@collective-intelligence/cli 0.2.23 → 0.2.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/package.json +5 -5
package/dist/cli.js
CHANGED
|
@@ -235,7 +235,7 @@ ${prefix}${lines[i]}`}if(cause.cause){stack+=` {
|
|
|
235
235
|
${renderErrorCause(cause.cause,`${prefix} `)}
|
|
236
236
|
${prefix}}`}return stack};var FiberTypeId="~effect/Fiber";var fiberVariance={_A:identity,_E:identity};var fiberIdStore={id:0};var AsyncResource=(()=>{try{return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource}catch{return}})();var captureAsyncContext=()=>AsyncResource===undefined?undefined:new AsyncResource("effect/Fiber");var getCurrentFiber=()=>globalThis[currentFiberTypeId];class FiberImpl{constructor(context,interruptible=true){this.setContext(context);this.id=++fiberIdStore.id;this.currentOpCount=0;this.interruptible=interruptible;this._stack=[];this._observers=undefined;this._exit=undefined;this._children=undefined;this._interruptedCause=undefined;this._yielded=undefined;this._running=false;this._deferredInterrupt=false;this._parent=undefined;this._asyncContext=undefined;this.cache.runtimeMetrics?.recordFiberStart(this.context)}get[FiberTypeId](){return fiberVariance}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(ref){return get(this.context,ref)}addObserver(cb){if(this._exit){cb(this._exit);return constVoid}if(this._observers===undefined){this._observers=[cb]}else{this._observers.push(cb)}return()=>this.removeObserver(cb)}removeObserver(cb){if(this._exit||this._observers===undefined)return;const index=this._observers.indexOf(cb);if(index>=0){this._observers.splice(index,1)}}interruptUnsafe(fiberId,annotations){if(this._exit){return}let cause=causeInterrupt(fiberId);if(this.cache.stackFrame){cause=causeAnnotate(cause,make4(StackTraceKey,this.cache.stackFrame))}if(annotations){cause=causeAnnotate(cause,annotations)}this._interruptedCause=this._interruptedCause?causeAddInterrupts(this._interruptedCause,cause):cause;if(this.interruptible){if(this._running){this._deferredInterrupt=true}else{this.evaluate(failCause(this._interruptedCause))}}}pollUnsafe(){return this._exit}evaluate(effect){if(this._exit){return}else if(this._asyncContext!==undefined){const asyncContext=this._asyncContext;this._asyncContext=undefined;try{return asyncContext.runInAsyncScope(this.evaluate,this,effect)}finally{asyncContext.emitDestroy()}}else if(this._yielded!==undefined){const yielded=this._yielded;this._yielded=undefined;yielded()}const exit=this.runLoop(effect);if(exit===Yield){this._asyncContext=captureAsyncContext();return}const interruptChildren=fiberMiddleware.interruptChildren&&fiberMiddleware.interruptChildren(this);if(interruptChildren!==undefined){return this.evaluate(flatMap3(interruptChildren,()=>exit))}this._exit=exit;this.cache.runtimeMetrics?.recordFiberEnd(this.context,this._exit);if(this._parent){this._parent._children?.delete(this);this._parent=undefined}if(this._observers!==undefined){const observers=this._observers;this._observers=undefined;for(let i=0;i<observers.length;i++){observers[i](exit)}}this._stack.length=0;this._children=undefined;this.context=empty();const cache=this.cache;if(cache.span!==undefined||cache.stackFrame!==undefined){this.cache={...cache,span:undefined,stackFrame:undefined}}}runLoop(effect){const prevFiber=globalThis[currentFiberTypeId];globalThis[currentFiberTypeId]=this;const prevRunning=this._running;this._running=true;let yielding=false;let current=effect;this.currentOpCount=0;try{while(true){try{if(this._deferredInterrupt){this._deferredInterrupt=false;current=failCause(this._interruptedCause)}this.currentOpCount++;const cache=this.cache;if(!yielding&&!cache.preventYield&&cache.scheduler.shouldYield(this)){yielding=true;const prev=current;current=flatMap3(yieldNow,()=>prev)}current=cache.tracerContext?cache.tracerContext(current,this):current[evaluate](this);if(current===Yield){const yielded=this._yielded;if(ExitTypeId in yielded){this._deferredInterrupt=false;this._yielded=undefined;return yielded}else if(this._deferredInterrupt){this._yielded=undefined;yielded();continue}return Yield}}catch(error){if(!hasProperty(current,evaluate)){return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`)}current=exitDie(error)}}}finally{this._running=prevRunning;globalThis[currentFiberTypeId]=prevFiber}}getCont(symbol){if(this._deferredInterrupt){this._deferredInterrupt=false;return deferredInterruptCont}while(true){const op=this._stack.pop();if(!op)return;const all=op[contAll];if(all!==undefined){const cont=all.call(op,this);if(cont){cont[symbol]=cont;return cont}}if(op[symbol])return op}}succeedWith(value){if((++this.currentOpCount&maxInlineSteps-1)===0){return exitSucceed(value)}const cont=this.getCont(contA);return cont?cont[contA](value,this):this.yieldWith(exitSucceed(value))}yieldWith(value){this._yielded=value;return Yield}children(){return this._children??=new Set}pipe(){return pipeArguments(this,arguments)}setContext(context){const previous=this.context;this.context=context;if(previous!==undefined&&hasSameCache(previous,context))return;const root=context.cacheRoot;const cache=root._fiberCache??=makeFiberContextCache(context);if(this.cache?.scheduler!==cache.scheduler){this._dispatcher=undefined}this.cache=cache}get currentSpanLocal(){const span=this.cache.span;return span?._tag==="Span"?span:undefined}}var makeFiberContextCache=(context)=>{const currentTracer=getOrUndefinedUnsafe(context,TracerKey);return{scheduler:get(context,Scheduler),tracer:currentTracer,tracerContext:currentTracer?currentTracer["context"]:undefined,tracerEnabled:get(context,TracerEnabled),span:getOrUndefinedUnsafe(context,ParentSpanKey),logLevel:get(context,CurrentLogLevel),minimumLogLevel:get(context,MinimumLogLevel),stackFrame:get(context,CurrentStackFrame),runtimeMetrics:getOrUndefinedUnsafe(context,FiberRuntimeMetricsKey),maxOpsBeforeYield:get(context,MaxOpsBeforeYield),preventYield:get(context,PreventSchedulerYield)}};var deferredInterruptCont={[contA](_value,fiber){return failCause(fiber._interruptedCause)},[contE](_cause,fiber){return failCause(fiber._interruptedCause)}};var maxInlineSteps=32;var fiberMiddleware={interruptChildren:undefined};var fiberStackAnnotations=(fiber)=>{if(!fiber.cache.stackFrame)return;const annotations=new Map;annotations.set(InterruptorStackTrace.key,fiber.cache.stackFrame);return makeUnsafe(annotations)};var fiberInterruptChildren=(fiber)=>{if(fiber._children===undefined||fiber._children.size===0){return}return fiberInterruptAll(fiber._children)};var fiberAwait=(self)=>{const impl=self;if(impl._exit)return succeed3(impl._exit);return callback((resume)=>{if(impl._exit)return resume(succeed3(impl._exit));return sync(self.addObserver((exit)=>resume(succeed3(exit))))})};var fiberAwaitAll=(self)=>callback((resume)=>{const iter=self[Symbol.iterator]();const exits=[];let cancel=undefined;function loop(){let result=iter.next();while(!result.done){if(result.value._exit){exits.push(result.value._exit);result=iter.next();continue}cancel=result.value.addObserver((exit)=>{exits.push(exit);loop()});return}resume(succeed3(exits))}loop();return sync(()=>cancel?.())});var fiberJoin=(self)=>{const impl=self;if(impl._exit)return impl._exit;return callback((resume)=>{if(impl._exit)return resume(impl._exit);return sync(self.addObserver(resume))})};var fiberInterrupt=(self)=>withFiber((fiber)=>fiberInterruptAs(self,fiber.id));var fiberInterruptAs=dual((args)=>hasProperty(args[0],FiberTypeId),(self,fiberId,annotations)=>withFiber((parent)=>{let ann=fiberStackAnnotations(parent);ann=ann&&annotations?merge(ann,annotations):ann??annotations;self.interruptUnsafe(fiberId,ann);return asVoid(fiberAwait(self))}));var fiberInterruptAll=(fibers)=>withFiber((parent)=>{const annotations=fiberStackAnnotations(parent);let fiberArr=empty3();for(const fiber of fibers){fiber.interruptUnsafe(parent.id,annotations);fiberArr.push(fiber)}return asVoid(fiberAwaitAll(fiberArr))});var succeed3=exitSucceed;var failCause=exitFailCause;var fail3=exitFail;var sync=makePrimitive({op:"Sync",[evaluate](fiber){const thunk=this[args];const value=thunk();const cont=fiber.getCont(contA);return cont?cont[contA](value,fiber):fiber.yieldWith(exitSucceed(value))}});var suspend=makePrimitive({op:"Suspend",[evaluate](_fiber){const thunk=this[args];return thunk()}});var fromResult=match2({onFailure:fail3,onSuccess:succeed3});var yieldNowWith=makePrimitive({op:"Yield",[evaluate](fiber){let resumed=false;fiber.currentDispatcher.scheduleTask(()=>{if(resumed)return;fiber.evaluate(exitVoid)},this[args]??0);return fiber.yieldWith(()=>{resumed=true})}});var yieldNow=yieldNowWith(0);var succeedNone=succeed3(none2());var failCauseSync=(evaluate)=>suspend(()=>failCause(evaluate()));var die=(defect)=>exitDie(defect);var void_=succeed3(undefined);var try_2=(options)=>{const evaluate=typeof options==="function"?options:options.try;const catcher=typeof options==="function"?(cause)=>new UnknownError(cause,"An error occurred in Effect.try"):options.catch;return suspend(()=>{try{return succeed3(evaluate())}catch(err){return fail3(catcher(err))}})};var promise=(evaluate)=>callbackOptions(function(resume,signal){evaluate(signal).then((a)=>resume(succeed3(a)),(e)=>resume(die(e)))},evaluate.length!==0);var tryPromise=(options)=>{const f=typeof options==="function"?options:options.try;const catcher=typeof options==="function"?(cause)=>new UnknownError(cause,"An error occurred in Effect.tryPromise"):options.catch;return callbackOptions(function(resume,signal){const failWithCatch=(cause)=>suspend(()=>{try{return fail3(internalCall(()=>catcher(cause)))}catch(err){return die(err)}});try{f(signal).then((a)=>resume(succeed3(a)),(e)=>resume(failWithCatch(e)))}catch(err){resume(failWithCatch(err))}},f.length!==0)};var callbackOptions=function(){const Proto=makePrimitiveProto({op:"Async",[evaluate](fiber){let resumed=false;let yielded=false;const controller=this.withSignal?new AbortController:undefined;const onCancel=this.register.call(fiber.cache.scheduler,(effect)=>{if(resumed)return;resumed=true;if(yielded){fiber.evaluate(effect)}else{yielded=effect}},controller?.signal);if(yielded!==false)return yielded;yielded=true;fiber.yieldWith(()=>{resumed=true});if(controller===undefined&&onCancel===undefined){return Yield}fiber._stack.push(asyncFinalizer(()=>{resumed=true;controller?.abort();return onCancel??exitVoid}));return Yield}});const AsyncImpl=function(register,withSignal){this.register=register;this.withSignal=withSignal};AsyncImpl.prototype=Proto;return function(register,withSignal){return new AsyncImpl(register,withSignal)}}();var asyncFinalizer=makePrimitive({op:"AsyncFinalizer",[contAll](fiber){if(fiber.interruptible){fiber.interruptible=false;fiber._stack.push(setInterruptibleTrue)}},[contE](cause,_fiber){return hasInterrupts(cause)?flatMap3(combineFinalizerCause(exitFailCause(cause),this[args]()),()=>failCause(cause)):failCause(cause)}});var callback=(register)=>callbackOptions(register,register.length>=2);var never=callback(constVoid);var gen=(...args)=>{if(args.length===1){const body=args[0];return suspend(()=>fromIteratorUnsafe(body()))}const[options,body]=args;return suspend(()=>fromIteratorUnsafe(body.call(options.self)))};var fnBody=(bodyOrOptions,pipeables)=>typeof bodyOrOptions==="function"?bodyOrOptions:pipeables.shift().bind(bodyOrOptions.self);var fnUntraced=(bodyOrOptions,...pipeables)=>{const body=fnBody(bodyOrOptions,pipeables);const fn=pipeables.length===0?function(){return suspend(()=>fromIteratorUnsafe(body.apply(this,arguments)))}:function(){let effect=suspend(()=>fromIteratorUnsafe(body.apply(this,arguments)));for(let i=0;i<pipeables.length;i++){effect=pipeables[i](effect,...arguments)}return effect};return defineFunctionLength(body.length,fn)};var defineFunctionLength=(length,fn)=>Object.defineProperty(fn,"length",{value:length,configurable:true});var fnStackCleaner=makeStackCleaner(2);var fn=function(){const nameFirst=typeof arguments[0]==="string";const name=nameFirst?arguments[0]:"Effect.fn";const spanOptions=nameFirst?arguments[1]:undefined;const prevLimit=getStackTraceLimit();let defError;if(prevLimit!==0){setStackTraceLimit(2);defError=new globalThis.Error;setStackTraceLimit(prevLimit)}if(nameFirst){return(body,...pipeables)=>makeFn(name,body,defError,pipeables,nameFirst,spanOptions)}return makeFn(name,arguments[0],defError,Array.prototype.slice.call(arguments,1),nameFirst,spanOptions)};var makeFn=(name,bodyOrOptions,defError,pipeables,addSpan,spanOptions)=>{const body=fnBody(bodyOrOptions,pipeables);const definitionName=`${name} (definition)`;const definitionStack=defError?fnStackCleaner(()=>defError.stack):constUndefined;const makeCallFrame=(callError)=>(prev)=>({name,stack:callError?fnStackCleaner(()=>callError.stack):constUndefined,parent:{name:definitionName,stack:definitionStack,parent:prev}});return defineFunctionLength(body.length,function(...args){let result=suspend(()=>{const iter=body.apply(this,arguments);return isEffect(iter)?iter:fromIteratorUnsafe(iter)});for(let i=0;i<pipeables.length;i++){result=pipeables[i](result,...args)}if(!isEffect(result)){return result}const prevLimit=getStackTraceLimit();let callError;if(prevLimit!==0){setStackTraceLimit(2);callError=new globalThis.Error;setStackTraceLimit(prevLimit)}return updateService(addSpan?useSpan(name,spanOptions,(span)=>provideParentSpan(result,span)):result,CurrentStackFrame,makeCallFrame(callError))})};var fnUntracedEager=(bodyOrOptions,...pipeables)=>{const body=fnBody(bodyOrOptions,pipeables);return defineFunctionLength(body.length,pipeables.length===0?function(){return fromIteratorEagerUnsafe(()=>body.apply(this,arguments))}:function(){let effect=fromIteratorEagerUnsafe(()=>body.apply(this,arguments));for(const pipeable of pipeables){effect=pipeable(effect,...arguments)}return effect})};var fromIteratorEagerUnsafe=(evaluate)=>{try{const iterator=evaluate();let value=undefined;while(true){const state=iterator.next(value);if(state.done){return succeed3(state.value)}const primitive=state.value;if(primitive&&primitive._tag==="Success"){value=primitive.value;continue}else if(primitive&&primitive._tag==="Failure"){return state.value}else{let isFirstExecution=true;return suspend(()=>{if(isFirstExecution){isFirstExecution=false;return flatMap3(state.value,(value)=>fromIteratorUnsafe(iterator,value))}else{return suspend(()=>fromIteratorUnsafe(evaluate()))}})}}}catch(error){return die(error)}};var fromIteratorUnsafe=function(){const Proto=makePrimitiveProto({op:"Iterator",[contA](value,fiber){const iter=this.iterator;while(true){const state=iter.next(value);if(state.done)return succeed3(state.value);if(!effectIsExit(state.value)){fiber._stack.push(this);return state.value}else if(state.value._tag==="Failure"){return state.value}value=state.value.value}},[evaluate](fiber){return this[contA](this.initial,fiber)}});const IteratorImpl=function(iterator,initial){this.iterator=iterator;this.initial=initial};IteratorImpl.prototype=Proto;return function(iterator,initial){return new IteratorImpl(iterator,initial)}}();var as=dual(2,(self,value)=>new ContImpl(self,returnPayload,succeed3(value)));var evaluateCont=function(fiber){fiber._stack.push(this);return this[args]};var OnSuccessProto=makePrimitiveProto({op:"OnSuccess",[evaluate]:evaluateCont});var ContImpl=function(self,cont,payload){this[args]=self;this[contA]=cont;this.payload=payload};ContImpl.prototype=OnSuccessProto;var returnPayload=function(){return this.payload};var succeedPayload=function(_value,fiber){return fiber.succeedWith(this.payload)};var continuationMarksStack=(()=>{const limit=getStackTraceLimit();if(limit===0)return false;const marker="~effect/Effect/stackProbe";const probe={[marker]:function stackProbe(){return new Error}};setStackTraceLimit(1);const error=probe[marker]();setStackTraceLimit(limit);return error.stack?.includes("[as "+marker+"]")===true})();var mapCont=function(value,fiber){const f=this.payload;return fiber.succeedWith(continuationMarksStack?f(value):internalCall(()=>f(value)))};var andThenCont=function(value){const f=this.payload;return f(value)};var tapCont=function(value){const f=this.payload;return new ContImpl(f(value),succeedPayload,value)};var tapEffectCont=function(value){return new ContImpl(this.payload,succeedPayload,value)};var asSome=(self)=>map4(self,some2);var andThen=dual(2,(self,f)=>new ContImpl(self,isEffect(f)?returnPayload:andThenCont,f));var tap=dual(2,(self,f)=>new ContImpl(self,isEffect(f)?tapEffectCont:tapCont,f));var asVoid=(self)=>new ContImpl(self,returnPayload,exitVoid);var raceAllFirst=(all,options)=>withFiber((parent)=>{const fibers=new Set;onExitUnsafe(parent,()=>fibers.size===0?undefined:fiberInterruptAll(fibers));return callback((resume)=>{let done=false;let i=0;for(const effect of all){if(done)break;const index=i++;const fiber=forkUnsafe(parent,effect,true,true,false);fibers.add(fiber);fiber.addObserver((exit)=>{fibers.delete(fiber);const isWinner=!done;done=true;resume(exit);if(isWinner&&options?.onWinner){options.onWinner({fiber,index,parentFiber:parent})}})}})});var raceFirst=dual((args)=>isEffect(args[1]),(self,that,options)=>raceAllFirst([self,that],options));var flatMap3=dual(2,(self,f)=>new ContImpl(self,andThenCont,f));var effectIsExit=(effect)=>effect[ExitTypeId]!==undefined;var flatMapEager=dual(2,(self,f)=>{if(effectIsExit(self)){return self._tag==="Success"?f(self.value):self}return flatMap3(self,f)});var flatten3=(self)=>flatMap3(self,identity);var map4=dual(2,(self,f)=>new ContImpl(self,mapCont,f));var mapEager=dual(2,(self,f)=>effectIsExit(self)?exitMap(self,f):map4(self,f));var mapErrorEager=dual(2,(self,f)=>effectIsExit(self)?exitMapError(self,f):mapError2(self,f));var mapBothEager=dual(2,(self,options)=>effectIsExit(self)?exitMapBoth(self,options):mapBoth(self,options));var catchEager=dual(2,(self,f)=>{if(effectIsExit(self)){if(self._tag==="Success")return self;const error=findRecoverableError(self.cause);if(isFailure2(error))return exitFailCause(error.failure);return f(error.success)}return catch_(self,f)});var exitInterrupt=(fiberId)=>exitFailCause(causeInterrupt(fiberId));var exitIsSuccess=(self)=>self._tag==="Success";var exitIsFailure=(self)=>self._tag==="Failure";var exitFilterCause=(self)=>self._tag==="Failure"?succeed2(self.cause):fail2(self);var exitHasInterrupts=(self)=>self._tag==="Failure"&&hasInterrupts(self.cause);var exitVoid=exitSucceed(undefined);var exitMap=dual(2,(self,f)=>self._tag==="Success"?exitSucceed(f(self.value)):self);var exitMapError=dual(2,(self,f)=>{if(self._tag==="Success")return self;return exitFailCause(causeMap(self.cause,f))});var exitMapBoth=dual(2,(self,options)=>{if(self._tag==="Success")return exitSucceed(options.onSuccess(self.value));return exitFailCause(causeMap(self.cause,options.onFailure))});var exitZipRight=dual(2,(self,that)=>exitIsSuccess(self)?that:self);var exitAsVoidAll=(exits)=>{const failures=[];for(const exit of exits){if(exit._tag==="Failure"){failures.push(...exit.cause.reasons)}}return failures.length===0?exitVoid:exitFailCause(causeFromReasons(failures))};var serviceOption=(service)=>withFiber((fiber)=>succeed3(getOption(fiber.context,service)));var updateContext=dual(2,(self,f)=>withFiber((fiber)=>{const prevContext=fiber.context;const nextContext=f(prevContext);if(prevContext===nextContext)return self;fiber.setContext(nextContext);onExitUnsafe(fiber,()=>{fiber.setContext(prevContext);return});return self}));var updateService=dual(3,(self,service,f)=>updateContext(self,(s)=>{const prev=getUnsafe(s,service);const next=f(prev);if(prev===next)return s;return add(s,service,next)}));var context=()=>getContext;var getContext=withFiber((fiber)=>succeed3(fiber.context));var contextWith=(f)=>withFiber((fiber)=>f(fiber.context));var provideContext=dual(2,(self,context)=>{if(effectIsExit(self))return self;return updateContext(self,merge(context))});var provideService=function(){if(arguments.length===1){return dual(2,(self,impl)=>provideServiceImpl(self,arguments[0],impl))}return dual(3,(self,service,impl)=>provideServiceImpl(self,service,impl)).apply(this,arguments)};var provideServiceImpl=(self,service,implementation)=>updateContext(self,add(service,implementation));var zipWith2=dual((args)=>isEffect(args[1]),(self,that,f,options)=>options?.concurrent?map4(all([self,that],{concurrency:2}),([a,a2])=>f(a,a2)):flatMap3(self,(a)=>map4(that,(a2)=>f(a,a2))));var forever=dual((args)=>isEffect(args[0]),(self,options)=>whileLoop({while:constTrue,body:constant(options?.disableYield?self:flatMap3(self,(_)=>yieldNow)),step:constVoid}));var catchCause=dual(2,(self,f)=>new OnFailureImpl(self,f.length!==1?(cause)=>f(cause):f));var OnFailureProto=makePrimitiveProto({op:"OnFailure",[evaluate]:evaluateCont});var OnFailureImpl=function(self,f){this[args]=self;this[contE]=f};OnFailureImpl.prototype=OnFailureProto;var catchCauseFilter=dual(3,(self,filter,f)=>catchCause(self,(cause)=>{const eb=filter(cause);return isFailure2(eb)?failCause(eb.failure):f(eb.success,cause)}));var catch_=dual(2,(self,f)=>catchCauseFilter(self,findRecoverableError,(e)=>f(e)));var catchDefect=dual(2,(self,f)=>catchCauseFilter(self,findDefect,f));var tapCause=dual(2,(self,f)=>catchCause(self,(cause)=>andThen(f(cause),failCause(cause))));var tapCauseFilter=dual(3,(self,filter,f)=>catchCause(self,(cause)=>{const result=filter(cause);if(isFailure2(result)){return failCause(cause)}return andThen(f(result.success,cause),failCause(cause))}));var tapError=dual(2,(self,f)=>tapCauseFilter(self,findError,(e)=>f(e)));var catchIf=dual((args)=>isEffect(args[0]),(self,predicate,f,orElse)=>catchCause(self,(cause)=>{const error=findRecoverableError(cause);if(isFailure2(error))return failCause(error.failure);if(!predicate(error.success)){return orElse?orElse(error.success):failCause(cause)}return f(error.success)}));var catchTag=dual((args)=>isEffect(args[0]),(self,k,f,orElse)=>{const pred=Array.isArray(k)?(e)=>hasProperty(e,"_tag")&&k.includes(e._tag):isTagged(k);return catchIf(self,pred,f,orElse)});var catchReason=dual((args)=>isEffect(args[0]),(self,errorTag,reasonTag,f,orElse)=>catchIf(self,(e)=>isTagged(e,errorTag)&&hasProperty(e,"reason")&&(orElse!==undefined||isTagged(e.reason,reasonTag)),(e)=>{const reason=e.reason;if(isTagged(reason,reasonTag))return f(reason,e);return orElse?orElse(reason,e):fail3(e)}));var mapError2=dual(2,(self,f)=>catchCause(self,(cause)=>failCause(causeMap(cause,f))));var mapBoth=dual(2,(self,options)=>matchCauseEffect(self,{onFailure:(cause)=>failCause(causeMap(cause,options.onFailure)),onSuccess:(a)=>sync(()=>options.onSuccess(a))}));var orDie=(self)=>catch_(self,die);var orElseSucceed=dual(2,(self,f)=>catch_(self,(error)=>sync(()=>f(error))));var ignoreCauseLogger=(log)=>log==="Unhandled"?(...message)=>withFiber((fiber)=>{const level=fiber.getRef(UnhandledLogLevel);return level===undefined?void_:logWithLevel(level)(...message)}):logWithLevel(log===true?undefined:log);var ignore=dual((args)=>isEffect(args[0]),(self,options)=>{if(!options?.log){return matchEffect(self,{onFailure:(_)=>void_,onSuccess:(_)=>void_})}const logEffect=ignoreCauseLogger(options.log);return matchCauseEffect(self,{onFailure(cause){const error=findRecoverableError(cause);return isFailure2(error)?failCause(error.failure):options.message===undefined?logEffect(cause):logEffect(options.message,cause)},onSuccess:(_)=>void_})});var option=(self)=>match4(self,{onFailure:none2,onSuccess:some2});var result=(self)=>matchEager(self,{onFailure:fail2,onSuccess:succeed2});var matchCauseEffect=dual(2,(self,options)=>new OnSuccessAndFailureImpl(self,options.onSuccess.length!==1?(a)=>options.onSuccess(a):options.onSuccess,options.onFailure.length!==1?(cause)=>options.onFailure(cause):options.onFailure));var OnSuccessAndFailureProto=makePrimitiveProto({op:"OnSuccessAndFailure",[evaluate]:evaluateCont});var OnSuccessAndFailureImpl=function(self,onSuccess,onFailure){this[args]=self;this[contA]=onSuccess;this[contE]=onFailure};OnSuccessAndFailureImpl.prototype=OnSuccessAndFailureProto;var matchSuccess=function(value,fiber){const handlers=this.payload;return fiber.succeedWith(continuationMarksStack?handlers.onSuccess(value):internalCall(()=>handlers.onSuccess(value)))};var makeMatch=(op,onFailure)=>{const Proto=makePrimitiveProto({op,[evaluate]:evaluateCont,[contA]:matchSuccess,[contE]:onFailure});const MatchImpl=function(self,handlers){this[args]=self;this.payload=handlers};MatchImpl.prototype=Proto;return MatchImpl};var MatchImpl=makeMatch("Match",function(cause,fiber){const error=findRecoverableError(cause);if(isFailure2(error))return failCause(error.failure);const handlers=this.payload;return fiber.succeedWith(continuationMarksStack?handlers.onFailure(error.success):internalCall(()=>handlers.onFailure(error.success)))});var matchEffect=dual(2,(self,options)=>matchCauseEffect(self,{onFailure:(cause)=>{const error=findRecoverableError(cause);return isFailure2(error)?failCause(error.failure):options.onFailure(error.success)},onSuccess:options.onSuccess}));var match4=dual(2,(self,options)=>new MatchImpl(self,options));var matchEager=dual(2,(self,options)=>{if(effectIsExit(self)){if(self._tag==="Success")return exitSucceed(options.onSuccess(self.value));const error=findRecoverableError(self.cause);if(isFailure2(error))return exitFailCause(error.failure);return exitSucceed(options.onFailure(error.success))}return match4(self,options)});var exit=(self)=>effectIsExit(self)?exitSucceed(self):exitPrimitive(self);var exitPrimitive=makePrimitive({op:"Exit",[evaluate](fiber){fiber._stack.push(this);return this[args]},[contA](value,fiber,exit){return fiber.succeedWith(exit??exitSucceed(value))},[contE](cause,fiber,exit){return fiber.succeedWith(exit??exitFailCause(cause))}});var delay=dual(2,(self,duration)=>andThen(sleep(duration),self));var timeoutOrElse=dual(2,(self,options)=>flatMap3(timeoutOption(self,options.duration),(option)=>isNone2(option)?options.orElse():succeed3(option.value)));var timeoutErrorFromDuration=(duration)=>new TimeoutError(`Operation timed out after '${format2(duration)}'`);var timeout=dual(2,(self,duration)=>{const decoded=fromInputUnsafe2(duration);return timeoutOrElse(self,{duration:decoded,orElse:()=>fail3(timeoutErrorFromDuration(decoded))})});var timeoutOption=dual(2,(self,duration)=>raceFirst(asSome(self),as(sleep(duration),none2())));var ScopeTypeId="~effect/Scope";var ScopeCloseableTypeId="~effect/Scope/Closeable";var scopeTag=Service("effect/Scope");var scopeClose=(self,exit_)=>withFiber((fiber)=>{fiberEnterUninterruptibleUnsafe(fiber);return scopeCloseUnsafe(self,exit_)??void_});var scopeCloseUnsafe=(self,exit_)=>{const state=self.state;if(state._tag==="Closed")return;self.state={_tag:"Closed",exit:exit_};if(self.parent!==undefined){scopeRemoveFinalizerUnsafe(self.parent,self)}if(state._tag==="Empty")return;if(state.finalizer!==undefined){return runFinalizer(state.finalizer,exit_)}const finalizers=state.finalizers;if(finalizers.size===1){return runFinalizer(finalizers.values().next().value,exit_)}return scopeCloseFinalizers(self,finalizers,exit_)};var runFinalizer=(finalizer,exit_)=>{try{return finalizer(exit_)}catch(defect){return exitDie(defect)}};var combineFinalizerCause=(exit_,finalizer)=>exitIsSuccess(exit_)?finalizer:catchCause(finalizer,(cause)=>failCause(causeElectDefects(causeCombine(exit_.cause,cause))));var scopeCloseFinalizers=fnUntraced(function*(self,finalizers,exit_){let exits=[];const fibers=[];const arr=Array.from(finalizers);const parent=getCurrentFiber();for(let i=arr.length-1;i>=0;i--){const[key,finalizer]=arr[i];if(self.strategy==="sequential"){exits.push(yield*exit(runFinalizer(finalizer,exit_)))}else if(key!==parent){fibers.push(forkUnsafe(parent,runFinalizer(finalizer,exit_),true,true,"inherit"))}}if(fibers.length>0){exits=yield*fiberAwaitAll(fibers)}return yield*exitAsVoidAll(exits)});var scopeForkUnsafe=(scope,finalizerStrategy)=>{const child=makeScope(finalizerStrategy,scope);if(scope.state._tag==="Closed"){child.state=scope.state;return child}scopeAddFinalizerUnsafe(scope,child,(exit)=>scopeClose(child,exit));return child};var scopeAddFinalizerExit=(scope,finalizer)=>{return suspend(()=>{if(scope.state._tag==="Closed"){return finalizer(scope.state.exit)}scopeAddFinalizerUnsafe(scope,{},finalizer);return void_})};var scopeAddFinalizer=(scope,finalizer)=>scopeAddFinalizerExit(scope,constant(finalizer));var scopeAddFinalizerUnsafe=(scope,key,finalizer)=>{if(scope.state._tag==="Empty"){scope.state={_tag:"Open",finalizerKey:key,finalizer,finalizers:undefined}}else if(scope.state._tag==="Open"){const state=scope.state;if(state.finalizer!==undefined){state.finalizers=new Map([[state.finalizerKey,state.finalizer]]);state.finalizerKey=undefined;state.finalizer=undefined;state.finalizers.set(key,finalizer)}else{state.finalizers.set(key,finalizer)}}};var scopeRemoveFinalizerUnsafe=(scope,key)=>{if(scope.state._tag!=="Open")return;const state=scope.state;if(state.finalizerKey===key){scope.state=constScopeEmpty}else if(state.finalizers!==undefined){state.finalizers.delete(key);if(state.finalizers.size===0){scope.state=constScopeEmpty}}};var scopeMakeUnsafe=(finalizerStrategy)=>makeScope(finalizerStrategy,undefined);var makeScope=(finalizerStrategy="sequential",parent)=>({[ScopeCloseableTypeId]:ScopeCloseableTypeId,[ScopeTypeId]:ScopeTypeId,strategy:finalizerStrategy,parent,state:constScopeEmpty});var constScopeEmpty={_tag:"Empty"};var scopeMake=(finalizerStrategy)=>sync(()=>scopeMakeUnsafe(finalizerStrategy));var scope=scopeTag;var provideScope=provideService(scopeTag);var scoped=(self)=>withFiber((fiber)=>{const prev=fiber.context;const scope=scopeMakeUnsafe();fiber.setContext(add(fiber.context,scopeTag,scope));onExitUnsafe(fiber,(exit)=>{fiber.setContext(prev);return scopeCloseUnsafe(scope,exit)});return self});var scopedWith=(f)=>suspend(()=>{const scope=scopeMakeUnsafe();return onExit(f(scope),(exit)=>suspend(()=>scopeCloseUnsafe(scope,exit)??void_))});var acquireRelease=(acquire,release,options)=>contextWith((context)=>uninterruptibleMask((restore)=>flatMap3(scope,(scope)=>tap(options?.interruptible?restore(acquire):acquire,(a)=>scopeAddFinalizerExit(scope,(exit)=>provideContext(release(a,exit),context))))));var addFinalizer=(finalizer)=>flatMap3(scope,(scope)=>contextWith((context)=>scopeAddFinalizerExit(scope,(exit)=>provideContext(finalizer(exit),context))));var OnExitImpl=function(){const Proto=makePrimitiveProto({op:"OnExit",[evaluate](fiber){fiber._stack.push(this);return this.effect},[contAll](fiber){if(fiber.interruptible&&this.interruptible!==true){fiber._stack.push(setInterruptibleTrue);fiber.interruptible=false}},[contA](value,_,exit){exit??=exitSucceed(value);let eff;try{eff=this.onExit(exit)}catch(defect){eff=exitDie(defect)}return eff?flatMap3(eff,(_)=>exit):exit},[contE](cause,_,exit){exit??=exitFailCause(cause);let eff;try{eff=this.onExit(exit)}catch(defect){eff=exitDie(defect)}return eff?flatMap3(combineFinalizerCause(exit,eff),(_)=>exit):exit}});const OnExitImpl=function(effect,onExit,interruptible){this.effect=effect;this.onExit=onExit;this.interruptible=interruptible};OnExitImpl.prototype=Proto;return OnExitImpl}();var onExitPrimitive=(effect,onExit,interruptible)=>new OnExitImpl(effect,onExit,interruptible);var onExitUnsafe=(fiber,f)=>{fiber._stack.push(new OnExitImpl(undefined,f,undefined))};var onExit=dual(2,onExitPrimitive);var ensuring=dual(2,(self,finalizer)=>onExit(self,(_)=>finalizer));var onExitFilter=dual(3,(self,filter,f)=>onExit(self,(exit)=>{const b=filter(exit);return isFailure2(b)?void_:f(b.success,exit)}));var onError=dual(2,(self,f)=>onExitFilter(self,exitFilterCause,f));var onErrorFilter=dual(3,(self,filter,f)=>onExit(self,(exit)=>{if(exit._tag!=="Failure"){return void_}const result=filter(exit.cause);return isFailure2(result)?void_:f(result.success,exit.cause)}));var onInterrupt=dual(2,(self,finalizer)=>onErrorFilter(causeFilterInterruptors,finalizer)(self));var acquireUseRelease=(acquire,use,release)=>uninterruptibleMask((restore)=>flatMap3(acquire,(a)=>onExitPrimitive(suspend(()=>restore(use(a))),(exit)=>release(a,exit),true)));var infiniteTTL=constant(Infinity);var makeCachedUnsafe=(self,ttlMillis)=>{let expiresAt=0;let exit;let current;const join=(fiber,run)=>{run.awaiters++;onExitUnsafe(fiber,()=>{if(--run.awaiters>0||run.done)return;if(current===run)current=undefined;return fiberInterrupt(run.fiber)});return fiberJoin(run.fiber)};return[withFiber((fiber)=>{if(current!==undefined){return fiber===current.fiber?fiberJoin(current.fiber):join(fiber,current)}if(exit!==undefined&&(expiresAt===Infinity||fiber.getRef(ClockRef).currentTimeMillisUnsafe()<expiresAt)){return exit}exit=undefined;const clock=fiber.getRef(ClockRef);const run={fiber:new FiberImpl(fiber.context),awaiters:0,done:false};current=run;const joined=join(fiber,run);run.fiber.evaluate(onExitPrimitive(self,(exit_)=>{run.done=true;if(current!==run)return;current=undefined;if(exitHasInterrupts(exit_))return;const duration=ttlMillis(exit_);expiresAt=duration===Infinity?Infinity:clock.currentTimeMillisUnsafe()+duration;exit=exit_}));return run.fiber._exit??joined}),sync(()=>{current=undefined;exit=undefined})]};var cached=(self)=>sync(()=>makeCachedUnsafe(self,infiniteTTL)[0]);var interrupt=withFiber((fiber)=>failCause(causeInterrupt(fiber.id)));var uninterruptible=(self)=>withFiber((fiber)=>{if(!fiber.interruptible)return self;fiber.interruptible=false;fiber._stack.push(setInterruptibleTrue);return self});var setInterruptible=makePrimitive({op:"SetInterruptible",[contAll](fiber){fiber.interruptible=this[args];if(fiber._interruptedCause&&fiber.interruptible){return()=>failCause(fiber._interruptedCause)}}});var setInterruptibleTrue=setInterruptible(true);var setInterruptibleFalse=setInterruptible(false);var setFiberInterruptible=(fiber)=>{fiber.interruptible=true;fiber._stack.push(setInterruptibleFalse);if(fiber._interruptedCause)return failCause(fiber._interruptedCause)};var fiberEnterUninterruptibleUnsafe=(fiber)=>{const impl=fiber;if(!impl.interruptible)return;impl.interruptible=false;impl._stack.push(setInterruptibleTrue)};var interruptible=(self)=>withFiber((fiber)=>{if(fiber.interruptible)return self;return setFiberInterruptible(fiber)??self});var uninterruptibleMask=(f)=>withFiber((fiber)=>{if(!fiber.interruptible)return f(identity);fiber.interruptible=false;fiber._stack.push(setInterruptibleTrue);return f(interruptible)});var abortSignal=map4(acquireRelease(sync(()=>new AbortController),(controller)=>sync(()=>controller.abort())),(_)=>_.signal);var all=(arg,options)=>{if(isIterable(arg)){return options?.mode==="result"?forEach(arg,result,options):forEach(arg,identity,options)}else if(options?.discard){return options.mode==="result"?forEach(Object.values(arg),result,options):forEach(Object.values(arg),identity,options)}return suspend(()=>map4(forEach(Object.entries(arg),([key,effect])=>map4(options?.mode==="result"?result(effect):effect,(value)=>[key,value]),{concurrency:options?.concurrency}),Object.fromEntries))};var whileLoop=makePrimitive({op:"While",[contA](value,fiber){this[args].step(value);if(this[args].while()){fiber._stack.push(this);return this[args].body()}return exitVoid},[evaluate](fiber){if(this[args].while()){fiber._stack.push(this);return this[args].body()}return exitVoid}});var forEach=dual((args)=>typeof args[1]==="function",(iterable,f,options)=>suspend(()=>{const concurrency=resolveConcurrency(options?.concurrency);if(concurrency===1){return forEachSequential(iterable,f,options)}const items=fromIterable(iterable);let length=items.length;if(length===0){return options?.discard?void_:succeed3([])}const out=options?.discard?undefined:new Array(length);const eff=forEachConcurrent({f,out},items,{concurrency});return eff?as(eff,out):succeed3(out)}));var forEachSequential=(iterable,f,options)=>suspend(()=>{const out=options?.discard?undefined:[];const iterator=iterable[Symbol.iterator]();let state=iterator.next();let index=0;return as(whileLoop({while:()=>!state.done,body:()=>f(state.value,index++),step:(b)=>{if(out)out.push(b);state=iterator.next()}}),out)});var resolveConcurrency=(concurrency)=>concurrency==="unbounded"?Number.POSITIVE_INFINITY:Math.max(1,concurrency??1);var iterateEager=()=>(options)=>{const onItem=options.onItem;const step=options.step;const resumeSequential=(state,items,index,end,effect)=>flatMap3(exit(effect),(itemExit)=>step(state,items[index],itemExit,index)??runSequential(state,items,index+1,end)??void_);const runSequential=(state,items,index=0,end=items.length)=>{for(;index<end;index++){const item=items[index];const effect=onItem(state,item,index);if(!effectIsExit(effect)){return resumeSequential(state,items,index,end,effect)}const terminal=step(state,item,effect,index);if(terminal)return terminal._tag==="Failure"?terminal:undefined}};return runSequential};var iterateConcurrentImpl=(options)=>{const onItem=options.onItem;const step=options.step;return(state,items,opts)=>{let index=0;const end=opts.end??items.length;const concurrency=opts.concurrency;let done=false;let parentFiber;let fibers;let resume;let terminal;let effect;const failDefect=(error)=>{const defect=exitDie(error);terminal=defect;done=true;return fibers&&fibers.size>0?flatMap3(uninterruptible(fiberInterruptAll(Array.from(fibers))),()=>terminal??defect):defect};const go=()=>{let paused=false;for(;!terminal&&index<end;index++){const item=items[index];const eff=effect??onItem(state,item,index);if(effectIsExit(eff)){terminal=step(state,item,eff,index);if(terminal)break}else if(!parentFiber){return callback((cb)=>{parentFiber=getCurrentFiber();fibers=new Set;effect=eff;resume=cb;let result;try{result=go()}catch(error){return cb(failDefect(error))}if(result)return cb(result);return suspend(()=>{terminal??=exitVoid;return flatMap3(fibers?fiberInterruptAll(fibers):void_,()=>terminal?._tag==="Failure"?terminal:void_)})})}else{effect=undefined;const fiber=forkUnsafe(parentFiber,eff,true,true,"inherit");if(fiber._exit){terminal=step(state,item,fiber._exit,index);if(terminal)break;continue}fibers.add(fiber);const currentIndex=index;fiber.addObserver((exit)=>{fibers.delete(fiber);try{if(terminal){if(exit._tag==="Failure"){const reasons=exit.cause.reasons.filter((reason)=>reason._tag!=="Interrupt");if(reasons.length>0){const cause=causeFromReasons(reasons);terminal=exitFailCause(terminal._tag==="Failure"?causeElectDefects(causeCombine(terminal.cause,cause)):cause)}}}else{const result=step(state,item,exit,currentIndex);if(result){terminal=result;go()}}if(paused){const eff=go();if(eff)resume(eff)}else if(done&&fibers.size===0){resume(terminal??void_)}}catch(error){resume(failDefect(error))}});if(fibers.size<concurrency)continue;paused=true;index++;return}}done=true;if(terminal){if(fibers&&fibers.size>0){const annotations=fiberStackAnnotations(parentFiber);fibers.forEach((f)=>f.interruptUnsafe(parentFiber.id,annotations));return}if(resume||terminal._tag==="Failure"){return terminal}}else if(resume){if(!fibers){return exitVoid}else if(fibers.size===0){resume(void_)}}};return go()}};var iterateConcurrent=()=>(options)=>iterateConcurrentImpl(options);var forEachConcurrent=iterateConcurrentImpl({onItem(state,item,index){return state.f(item,index)},step(state,_,exit,index){if(exit._tag==="Failure")return exit;else if(state.out){state.out[index]=exit.value}}});var forkChild=dual((args)=>isEffect(args[0]),(self,options)=>withFiber((fiber)=>{interruptChildrenPatch();return succeed3(forkUnsafe(fiber,self,options?.startImmediately,false,options?.uninterruptible??false))}));var forkUnsafe=(parent,effect,immediate=false,daemon=false,uninterruptible=false)=>{const parentRuntime=parent;const interruptible=uninterruptible==="inherit"?parentRuntime.interruptible:!uninterruptible;const child=new FiberImpl(parentRuntime.context,interruptible);if(!daemon){parentRuntime.children().add(child);child._parent=parentRuntime}if(immediate){child.evaluate(effect)}else{child._asyncContext=captureAsyncContext();parentRuntime.currentDispatcher.scheduleTask(()=>child.evaluate(effect),0)}return child};var fiberScopeFinalizer=(fiber)=>()=>withFiber((current)=>current===fiber?void_:fiberInterrupt(fiber));var forkIn=dual((args)=>isEffect(args[0]),(self,scope,options)=>withFiber((parent)=>{const fiber=scope.state._tag==="Closed"?new FiberImpl(parent.context):forkUnsafe(parent,self,options?.startImmediately,true,options?.uninterruptible);if(!fiber._exit){if(scope.state._tag!=="Closed"){scopeAddFinalizerUnsafe(scope,fiber,fiberScopeFinalizer(fiber));fiber.addObserver(()=>scopeRemoveFinalizerUnsafe(scope,fiber))}else{fiber.interruptUnsafe(parent.id,fiberStackAnnotations(parent))}}return succeed3(fiber)}));var forkScoped=dual((args)=>isEffect(args[0]),(self,options)=>flatMap3(scope,(scope)=>forkIn(self,scope,options)));var runForkWith=(context)=>(effect,options)=>{const fiber=new FiberImpl(options?.scheduler?add(context,Scheduler,options.scheduler):context,options?.uninterruptible!==true);fiber.evaluate(effect);if(fiber._exit)return fiber;if(options?.signal){if(options.signal.aborted){fiber.interruptUnsafe()}else{const abort=()=>fiber.interruptUnsafe();options.signal.addEventListener("abort",abort,{once:true});fiber.addObserver(()=>options.signal.removeEventListener("abort",abort))}}if(options?.onFiberStart){options.onFiberStart(fiber)}return fiber};var runFork=runForkWith(empty());var runPromiseExitWith=(context)=>{const runFork=runForkWith(context);return(effect,options)=>{const fiber=runFork(effect,options);return new Promise((resolve)=>{fiber.addObserver((exit)=>resolve(exit))})}};var runPromiseWith=(context)=>{const runPromiseExit=runPromiseExitWith(context);return(effect,options)=>runPromiseExit(effect,options).then((exit)=>{if(exit._tag==="Failure"){throw causeSquash(exit.cause)}return exit.value})};var runPromise=runPromiseWith(empty());var runSyncExitWith=(context)=>{const runFork=runForkWith(context);return(effect)=>{if(effectIsExit(effect))return effect;const scheduler=new MixedScheduler("sync");const fiber=runFork(effect,{scheduler});fiber._dispatcher?.flush();return fiber._exit??exitDie(new AsyncFiberError(fiber))}};var runSyncExit=runSyncExitWith(empty());var runSyncWith=(context)=>{const runSyncExit=runSyncExitWith(context);return(effect)=>{const exit=runSyncExit(effect);if(exit._tag==="Failure")throw causeSquash(exit.cause);return exit.value}};var runSync=runSyncWith(empty());var succeedTrue=succeed3(true);var succeedFalse=succeed3(false);class Latch{waiters=[];scheduled=undefined;_isOpen;constructor(isOpen){this._isOpen=isOpen}scheduleUnsafe(fiber){if(this.waiters.length===0){return succeedTrue}if(this.scheduled===undefined){this.scheduled=this.waiters;fiber.currentDispatcher.scheduleTask(this.flushScheduled,0)}else{for(let i=0;i<this.waiters.length;i++){this.scheduled.push(this.waiters[i])}}this.waiters=[];return succeedTrue}flushScheduled=()=>{if(this.scheduled===undefined)return;const waiters=this.scheduled;this.scheduled=undefined;for(let i=0;i<waiters.length;i++){waiters[i](exitVoid)}};flushWaiters(){const waiters=this.waiters;this.waiters=[];this.flushScheduled();for(let i=0;i<waiters.length;i++){waiters[i](exitVoid)}}open=withFiber((fiber)=>{if(this._isOpen)return succeedFalse;this._isOpen=true;return this.scheduleUnsafe(fiber)});release=withFiber((fiber)=>this._isOpen?succeedFalse:this.scheduleUnsafe(fiber));openUnsafe(){if(this._isOpen)return false;this._isOpen=true;this.flushWaiters();return true}await=callback((resume)=>{if(this._isOpen){return resume(void_)}this.waiters.push(resume);return sync(()=>{let index=this.waiters.indexOf(resume);if(index!==-1){this.waiters.splice(index,1)}else if(this.scheduled!==undefined){index=this.scheduled.indexOf(resume);if(index!==-1){this.scheduled.splice(index,1)}}})});closeUnsafe(){if(!this._isOpen)return false;this._isOpen=false;return true}close=sync(()=>this.closeUnsafe());whenOpen=(self)=>flatMap3(this.await,()=>self);isOpen(){return this._isOpen}}var makeLatchUnsafe=(open)=>new Latch(open??false);var bigint03=BigInt(0);var NoopSpanProto={_tag:"Span",spanId:"noop",traceId:"noop",sampled:false,status:{_tag:"Ended",startTime:bigint03,endTime:bigint03,exit:exitVoid},attributes:new Map,links:[],kind:"internal",attribute(){},event(){},end(){},addLinks(){}};var noopSpan=(options)=>Object.assign(Object.create(NoopSpanProto),options);var filterDisablePropagation=(span)=>{if(!span)return none2();return get(span.annotations,DisablePropagation)?span._tag==="Span"?filterDisablePropagation(getOrUndefined(span.parent)):none2():some2(span)};var makeSpanUnsafe=(fiber,name,options)=>{const disablePropagation=!fiber.cache.tracerEnabled||options?.annotations&&get(options.annotations,DisablePropagation);const parent=options?.parent!==undefined?some2(options.parent):options?.root?none2():filterDisablePropagation(fiber.cache.span);let span;if(disablePropagation){span=noopSpan({name,parent,annotations:add(options?.annotations??empty(),DisablePropagation,true)})}else{const tracer=fiber.cache.tracer??nativeTracer;const clock=fiber.getRef(ClockRef);const timingEnabled=fiber.getRef(TracerTimingEnabled);const annotationsFromEnv=fiber.getRef(TracerSpanAnnotations);const linksFromEnv=fiber.getRef(TracerSpanLinks);const level=options?.level??fiber.getRef(CurrentTraceLevel);const links=options?.links!==undefined?[...linksFromEnv,...options.links]:linksFromEnv.length===0?[]:linksFromEnv.slice();span=tracer.span({name,parent,annotations:options?.annotations??empty(),links,startTime:timingEnabled?clock.currentTimeNanosUnsafe():bigint03,kind:options?.kind??"internal",root:options?.root??false,sampled:options?.sampled??(isSome2(parent)&&parent.value.sampled===false?false:!isLogLevelGreaterThan(fiber.getRef(MinimumTraceLevel),level))});for(const key in annotationsFromEnv){span.attribute(key,annotationsFromEnv[key])}if(options?.attributes!==undefined){for(const key in options.attributes){span.attribute(key,options.attributes[key])}}}return span};var provideSpanStackFrame=(name,stack)=>{stack=typeof stack==="function"?stack:constUndefined;return updateService(CurrentStackFrame,(parent)=>({name,stack,parent}))};var endSpan=(span,exit,clock,timingEnabled)=>sync(()=>{if(span.status._tag==="Ended")return;span.end(timingEnabled?clock.currentTimeNanosUnsafe():bigint03,exit)});var useSpan=(name,...args)=>{const options=args.length===1?undefined:args[0];const evaluate=args[args.length-1];return withFiber((fiber)=>{const span=makeSpanUnsafe(fiber,name,options);const clock=fiber.getRef(ClockRef);const timingEnabled=fiber.getRef(TracerTimingEnabled);onExitUnsafe(fiber,(exit)=>endSpan(span,exit,clock,timingEnabled));return evaluate(span)})};var provideParentSpan=provideService(ParentSpan);var withParentSpan=function(){const dataFirst=isEffect(arguments[0]);const span=dataFirst?arguments[1]:arguments[0];let options=dataFirst?arguments[2]:arguments[1];let provideStackFrame=identity;if(span._tag==="Span"){options=addSpanStackTrace(options);provideStackFrame=provideSpanStackFrame(span.name,options?.captureStackTrace)}if(dataFirst){return provideParentSpan(provideStackFrame(arguments[0]),span)}return(self)=>provideParentSpan(provideStackFrame(self),span)};var ClockRef=Reference("effect/Clock",{defaultValue:()=>new ClockImpl});var MAX_TIMER_MILLIS=2**31-1;class ClockImpl{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=sync(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return wallTimeNanos()}currentTimeNanos=sync(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return monotonicNowNanos()}monotonicTimeNanos=sync(()=>this.monotonicTimeNanosUnsafe());sleep(duration){return this.sleepMillis(toMillis(duration))}sleepMillis(millis){if(millis<=0)return yieldNow;else if(!Number.isFinite(millis))return never;return callback((resume)=>{const continuation=millis>MAX_TIMER_MILLIS?this.sleepMillis(millis-MAX_TIMER_MILLIS):void_;const handle=setTimeout(()=>resume(continuation),Math.min(millis,MAX_TIMER_MILLIS));return sync(()=>clearTimeout(handle))})}}var nanosPerMilli=BigInt(1e6);var monotonicNowNanos=function(){const processHrtime=globalThis.process?.hrtime;if(typeof processHrtime?.bigint==="function"){return()=>processHrtime.bigint()}if(typeof performance!=="undefined"&&typeof performance.now==="function"){return()=>BigInt(Math.round(performance.now()*1e6))}let previous=BigInt(0);return()=>{const current=BigInt(Date.now())*nanosPerMilli;if(current>previous){previous=current}return previous}}();var wallTimeNanos=function(){const reanchorThresholdNanos=BigInt(1e9);let origin;return()=>{const monotonic=monotonicNowNanos();const wall=BigInt(Date.now())*nanosPerMilli;if(origin===undefined){origin=wall-monotonic}else{const projected=origin+monotonic;const skew=wall>projected?wall-projected:projected-wall;if(skew>reanchorThresholdNanos){origin=wall-monotonic}}return origin+monotonic}}();var clockWith=(f)=>withFiber((fiber)=>f(fiber.getRef(ClockRef)));var sleep=(duration)=>clockWith((clock)=>clock.sleep(fromInputUnsafe2(duration)));var currentTimeMillis=clockWith((clock)=>clock.currentTimeMillis);var TimeoutErrorTypeId="~effect/Cause/TimeoutError";class TimeoutError extends TaggedError("TimeoutError"){[TimeoutErrorTypeId]=TimeoutErrorTypeId;constructor(message){super({message})}}var AsyncFiberErrorTypeId="~effect/Cause/AsyncFiberError";class AsyncFiberError extends TaggedError("AsyncFiberError"){[AsyncFiberErrorTypeId]=AsyncFiberErrorTypeId;constructor(fiber){super({message:"An asynchronous Effect was executed with Effect.runSync",fiber})}}var UnknownErrorTypeId="~effect/Cause/UnknownError";class UnknownError extends TaggedError("UnknownError"){[UnknownErrorTypeId]=UnknownErrorTypeId;constructor(cause,message){super({message,cause})}}var ConsoleRef=Reference("effect/Console",{defaultValue:()=>globalThis.console});var logLevelToOrder=(level)=>{switch(level){case"All":return Number.MIN_SAFE_INTEGER;case"Fatal":return 50000;case"Error":return 40000;case"Warn":return 30000;case"Info":return 20000;case"Debug":return 1e4;case"Trace":return 0;case"None":return Number.MAX_SAFE_INTEGER}};var LogLevelOrder=mapInput(Number2,logLevelToOrder);var isLogLevelGreaterThan=isGreaterThan(LogLevelOrder);var CurrentLoggers=Reference("effect/Logger/CurrentLoggers",{defaultValue:()=>new Set([defaultLogger,tracerLogger])});var LogToStderr=Reference("effect/Logger/LogToStderr",{defaultValue:constFalse});var LoggerTypeId="~effect/Logger";var LoggerProto={[LoggerTypeId]:{_Message:identity,_Output:identity},pipe(){return pipeArguments(this,arguments)}};var loggerMake=(log)=>{const self=Object.create(LoggerProto);self.log=log;return self};var formatLabel=(key)=>key.replace(/[\s="]/g,"_");var formatLogSpan=(self,now)=>{const label=formatLabel(self[0]);return`${label}=${now-self[1]}ms`};var logWithLevel=(level)=>(...message)=>{let cause=undefined;for(let i=0,len=message.length;i<len;i++){const msg=message[i];if(isCause(msg)){if(cause){message.splice(i,1)}else{message=message.slice(0,i).concat(message.slice(i+1))}cause=cause?causeFromReasons(cause.reasons.concat(msg.reasons)):msg;i--}}if(cause===undefined){cause=causeEmpty}return withFiber((fiber)=>{const logLevel=level??fiber.cache.logLevel;if(isLogLevelGreaterThan(fiber.cache.minimumLogLevel,logLevel)){return void_}const clock=fiber.getRef(ClockRef);const loggers=fiber.getRef(CurrentLoggers);if(loggers.size>0){const date=new Date(clock.currentTimeMillisUnsafe());for(const logger of loggers){logger.log({cause,fiber,date,logLevel,message})}}return void_})};var colors={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"};var logLevelColors={None:[],All:[],Trace:[colors.gray],Debug:[colors.blue],Info:[colors.green],Warn:[colors.yellow],Error:[colors.red],Fatal:[colors.bgBrightRed,colors.black]};var 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")}`;var defaultLogger=loggerMake(({cause,date,fiber,logLevel,message})=>{const message_=Array.isArray(message)?message.slice():[message];if(cause.reasons.length>0){message_.push(causePretty(cause))}const now=date.getTime();const spans=fiber.getRef(CurrentLogSpans);let spanString="";for(const span of spans){spanString+=` ${formatLogSpan(span,now)}`}const annotations=fiber.getRef(CurrentLogAnnotations);if(Object.keys(annotations).length>0){message_.push(annotations)}const console2=fiber.getRef(ConsoleRef);const log=fiber.getRef(LogToStderr)?console2.error:console2.log;log(`[${defaultDateFormat(date)}] ${logLevel.toUpperCase()} (#${fiber.id})${spanString}:`,...message_)});var tracerLogger=loggerMake(({cause,fiber,logLevel,message})=>{const clock=fiber.getRef(ClockRef);const annotations=fiber.getRef(CurrentLogAnnotations);const span=fiber.cache.span;if(span===undefined||span._tag==="ExternalSpan"||span.status._tag==="Ended")return;const attributes={};for(const[key,value]of Object.entries(annotations)){assignProperty(attributes,key,value)}attributes["effect.fiberId"]=fiber.id;attributes["effect.logLevel"]=logLevel.toUpperCase();if(cause.reasons.length>0){attributes["effect.cause"]=causePretty(cause)}span.event(toStringUnknown(Array.isArray(message)&&message.length===1?message[0]:message),clock.currentTimeNanosUnsafe(),attributes)});function interruptChildrenPatch(){fiberMiddleware.interruptChildren??=fiberInterruptChildren}var isFailReason2=isFailReason;var isDieReason2=isDieReason;var fromReasons=causeFromReasons;var fail4=causeFail;var die2=causeDie;var makeFailReason=(error)=>new Fail(error);var makeDieReason=(defect)=>new Die(defect);var hasInterruptsOnly2=hasInterruptsOnly;var map5=causeMap;var squash=causeSquash;var hasInterrupts2=hasInterrupts;var filterInterruptors=causeFilterInterruptors;var isDone2=isDone;var done2=done;var reasonAnnotations2=reasonAnnotations;var succeed4=exitSucceed;var failCause2=exitFailCause;var fail5=exitFail;var void_2=exitVoid;var isSuccess3=exitIsSuccess;var isFailure3=exitIsFailure;var TypeId5="~effect/Deferred";var DeferredProto={[TypeId5]:{_A:identity,_E:identity},pipe(){return pipeArguments(this,arguments)}};var DeferredImpl=function(){this.resumes=undefined;this.effect=undefined};DeferredImpl.prototype=DeferredProto;var makeUnsafe2=()=>new DeferredImpl;var make8=()=>sync(()=>makeUnsafe2());var _await=(self)=>callback((resume)=>{if(self.effect)return resume(self.effect);self.resumes??=[];self.resumes.push(resume);return sync(()=>{const resumes=self.resumes;if(resumes===undefined)return;const index=resumes.indexOf(resume);if(index>=0)resumes.splice(index,1)})});var completeWith=dual(2,(self,effect)=>sync(()=>doneUnsafe(self,effect)));var done3=completeWith;var succeed5=dual(2,(self,value)=>done3(self,exitSucceed(value)));var doneUnsafe=(self,effect)=>{if(self.effect)return false;self.effect=effect;if(self.resumes){const resumes=self.resumes;self.resumes=undefined;for(let i=0;i<resumes.length;i++){resumes[i](effect)}}return true};var into=dual(2,(self,deferred)=>uninterruptibleMask((restore)=>flatMap3(exit(restore(self)),(exit)=>done3(deferred,exit))));var TracerTimingEnabled2=TracerTimingEnabled;var make9=scopeMake;var makeUnsafe3=scopeMakeUnsafe;var provide=provideScope;var addFinalizerExit=scopeAddFinalizerExit;var addFinalizer2=scopeAddFinalizer;var forkUnsafe2=scopeForkUnsafe;var close=scopeClose;var TypeId6="~effect/Layer";var MemoMapTypeId="~effect/Layer/MemoMap";var makeMemoMapEntry=(memoMap,layer)=>{const entry={observers:0,deferred:makeUnsafe2(),scope:makeUnsafe3(),finalizer:(exit)=>suspend(()=>{if(--entry.observers>0)return void_;memoMap.map.delete(layer);return close(entry.scope,exit)})};return entry};var memoMapObserve=(entry,scope)=>{if(scope.state._tag==="Closed")return false;entry.observers++;scopeAddFinalizerUnsafe(scope,{},entry.finalizer);return true};var LayerProto={[TypeId6]:{_ROut:identity,_E:identity,_RIn:identity},pipe(){return pipeArguments(this,arguments)}};var fromBuildUnsafe=(build)=>{const self=Object.create(LayerProto);self.build=build;return self};var fromBuild=(build)=>fromBuildUnsafe((memoMap,scope)=>{const layerScope=forkUnsafe2(scope);return onExit(build(memoMap,layerScope),(exit)=>exit._tag==="Failure"?close(layerScope,exit):void_)});var fromBuildMemo=(build)=>{const self=fromBuild((memoMap,scope)=>memoMap.getOrElseMemoize(self,scope,build));return self};class MemoMapImpl{get[MemoMapTypeId](){return MemoMapTypeId}parent;constructor(parent){this.parent=parent}map=new Map;get(layer,scope){const local=this.map.get(layer);if(local){memoMapObserve(local,scope);return local.deferred.effect??_await(local.deferred)}return this.parent?.get(layer,scope)}getOrElseMemoize(layer,scope,build){return suspend(()=>{let deferred;return onExitPrimitive(suspend(()=>{const existing=this.get(layer,scope);if(existing)return existing;const entry=makeMemoMapEntry(this,layer);if(!memoMapObserve(entry,scope))return build(this,scope);deferred=entry.deferred;this.map.set(layer,entry);return build(this,entry.scope)}),(exit)=>{if(deferred)doneUnsafe(deferred,exit)})})}}var makeMemoMapUnsafe=()=>new MemoMapImpl;var forkMemoMapUnsafe=(parent)=>new MemoMapImpl(parent);class CurrentMemoMap extends Service()("effect/Layer/CurrentMemoMap"){static forkOrCreate(self){const current=getOrUndefined2(self,CurrentMemoMap);return current?forkMemoMapUnsafe(current):makeMemoMapUnsafe()}}var buildWithMemoMap=dual(3,(self,memoMap,scope)=>provideService(map4(suspend(()=>self.build(memoMap,scope)),add(CurrentMemoMap,memoMap)),CurrentMemoMap,memoMap));var buildWithScope=dual(2,(self,scope)=>withFiber((fiber)=>buildWithMemoMap(self,CurrentMemoMap.forkOrCreate(fiber.context),scope)));var succeed6=function(){if(arguments.length===1){return(resource)=>succeedContext(make4(arguments[0],resource))}return succeedContext(make4(arguments[0],arguments[1]))};var succeedContext=(context)=>fromBuildUnsafe(constant(succeed3(context)));var effect=function(){if(arguments.length===1){return(effect)=>effectImpl(arguments[0],effect)}return effectImpl(arguments[0],arguments[1])};var effectImpl=(service,effect)=>effectContext(map4(effect,(value)=>make4(service,value)));var effectContext=(effect)=>fromBuildMemo((_,scope)=>provide(effect,scope));var mergeAllEffect=(layers,memoMap,scope)=>{const parentScope=forkUnsafe2(scope,"parallel");return forEach(layers,(layer)=>layer.build(memoMap,forkUnsafe2(parentScope,"sequential")),{concurrency:layers.length}).pipe(map4((context)=>mergeAll(...context)))};var mergeAll2=(...layers)=>fromBuildMemo((memoMap,scope)=>mergeAllEffect(layers,memoMap,scope));var Clock=ClockRef;var currentTimeMillis2=currentTimeMillis;var catchDone=dual(2,(effect,f)=>catchCauseFilter(effect,filterDoneLeftover,(l)=>f(l)));var isDoneCause=(cause)=>cause.reasons.some(isDoneFailure);var isDoneFailure=(failure)=>failure._tag==="Fail"&&isDone2(failure.error);var filterDone=(cause)=>{let done;let hasFailure=false;for(const reason of cause.reasons){if(isDoneFailure(reason)){done??=reason.error}else if(reason._tag!=="Interrupt"){hasFailure=true}}if(done===undefined)return fail2(cause);return hasFailure?fail2(fromReasons(cause.reasons.filter((reason)=>!isDoneFailure(reason)))):succeed2(done)};var filterDoneLeftover=(cause)=>{const done=filterDone(cause);return isFailure2(done)?done:succeed2(done.success.value)};var doneExitFromCause=(cause)=>{const halt=filterDone(cause);return!isFailure2(halt)?succeed4(halt.success.value):failCause2(halt.failure)};var provideLayer=(self,layer,options)=>scopedWith((scope)=>flatMap3(options?.local?buildWithMemoMap(layer,makeMemoMapUnsafe(),scope):buildWithScope(layer,scope),(context)=>provideContext(self,context)));var provide2=dual((args)=>isEffect(args[0]),(self,source,options)=>isContext(source)?provideContext(self,source):provideLayer(self,Array.isArray(source)?mergeAll2(...source):source,options));var isEffect2=isEffect;var all2=all;var forEach2=forEach;var whileLoop2=whileLoop;var promise2=promise;var tryPromise2=tryPromise;var succeed7=succeed3;var succeedNone2=succeedNone;var suspend2=suspend;var sync2=sync;var void_3=void_;var callback2=callback;var gen2=gen;var fail6=fail3;var failCause3=failCause;var failCauseSync2=failCauseSync;var die3=die;var try_3=try_2;var withFiber2=withFiber;var fromResult2=fromResult;var flatMap4=flatMap3;var flatten4=flatten3;var andThen2=andThen;var tap2=tap;var result2=result;var option2=option;var exit2=exit;var map6=map4;var as2=as;var asVoid2=asVoid;var zipWith3=zipWith2;var catch_2=catch_;var catchTag2=catchTag;var catchReason2=catchReason;var catchCause2=catchCause;var catchDefect2=catchDefect;var catchIf2=catchIf;var mapError3=mapError2;var orDie2=orDie;var tapError2=tapError;var tapCause2=tapCause;var ignore2=ignore;var orElseSucceed2=orElseSucceed;var timeout2=timeout;var timeoutOrElse2=timeoutOrElse;var delay2=delay;var sleep2=sleep;var raceFirst2=raceFirst;var matchCauseEffect2=matchCauseEffect;var matchEffect2=matchEffect;var context2=context;var contextWith2=contextWith;var provide3=provide2;var provideContext2=provideContext;var serviceOption2=serviceOption;var updateContext2=updateContext;var provideService2=provideService;var scoped2=scoped;var acquireRelease2=acquireRelease;var acquireUseRelease2=acquireUseRelease;var addFinalizer3=addFinalizer;var ensuring2=ensuring;var onError2=onError;var onExitPrimitive2=onExitPrimitive;var onExit2=onExit;var cached2=cached;var interrupt2=interrupt;var onInterrupt2=onInterrupt;var uninterruptibleMask2=uninterruptibleMask;var abortSignal2=abortSignal;var forever2=forever;var useSpan2=useSpan;var withParentSpan2=withParentSpan;var forkChild2=forkChild;var forkIn2=forkIn;var forkScoped2=forkScoped;var runFork2=runFork;var runForkWith2=runForkWith;var runPromise2=runPromise;var runSync2=runSync;var runSyncExit2=runSyncExit;var fnUntraced2=fnUntraced;var fn2=fn;var logError=logWithLevel("Error");var effectify=(fn,onError,onSyncError)=>(...args)=>callback2((resume)=>{let synchronous=true;let pending;try{fn(...args,(err,result)=>{const effect=err?onError?suspend2(()=>fail6(onError(err,args))):fail6(err):succeed7(result);if(synchronous){pending??=effect}else{resume(effect)}})}catch(err){pending=onSyncError?fail6(onSyncError(err,args)):die3(err)}synchronous=false;if(pending){resume(pending)}});var mapEager2=mapEager;var mapErrorEager2=mapErrorEager;var mapBothEager2=mapBothEager;var flatMapEager2=flatMapEager;var catchEager2=catchEager;var fnUntracedEager2=fnUntracedEager;var await_=fiberAwait;var join=fiberJoin;var interrupt3=fiberInterrupt;var interruptAll=fiberInterruptAll;var maxExpansions=1e4;var maxExpandedLength=2**22;var maxBraceDepth=64;var compile=(patterns,dot)=>{const nodes=[];const starts=new Set;for(const pattern of patterns){for(const expanded of expandBraces(pattern)){const start=nodes.length;if(compilePattern(expanded,nodes)){starts.add(start)}}}const initial=closure(nodes,starts);return{nodes,initial,dot,masks:nodes.length<=32?compileMasks(nodes,initial):undefined}};var compileMasks=(nodes,initial)=>{let start=0;for(const state of initial){start|=1<<state}let globstar=0;let end=0;let endFile=0;for(let i=0;i<nodes.length;i++){const node=nodes[i];const bit=1<<i;if(node._tag==="Globstar"){globstar|=bit}else if(node._tag==="End"){end|=bit;if(!node.directoryOnly){endFile|=bit}}}return{initial:start,globstar,end,endFile}};var isUnc=(path)=>path.startsWith("//")&&path[2]!==undefined&&path[2]!=="/";var compilePattern=(pattern,nodes)=>{if(pattern===""||isUnc(pattern)){return false}const raw=splitSegments(pattern);const globstar=raw.indexOf("**");if(globstar!==-1&&raw.some((segment,i)=>i>globstar&&(segment==="."||segment===".."))){return false}const{directory,segments}=normalize2(raw);if(segments.length===0){return false}for(const segment of segments){if(segment!=="**"){nodes.push(compileSegment(Array.from(segment)))}else if(nodes[nodes.length-1]!==globstarNode){nodes.push(globstarNode)}}nodes.push({_tag:"End",directoryOnly:directory});return true};var globstarNode={_tag:"Globstar"};var splitSegments=(pattern)=>{const segments=[];let start=0;for(let i=0;i<pattern.length;i++){if(pattern[i]==="\\"){i++}else if(pattern[i]==="/"){segments.push(pattern.slice(start,i));start=i+1}}segments.push(pattern.slice(start));return segments};var drive=/^[A-Za-z]:/;var isDrive=(segment)=>segment.length===2&&drive.test(segment);var isRoot=(name)=>name===""||name.length===3&&name[2]==="/"&&drive.test(name);var isAbsolute=(path)=>path.startsWith("/")||path[2]==="/"&&drive.test(path);var normalize2=(raw)=>{const segments=[];let i=0;if(raw.length>1&&(raw[0]===""||isDrive(raw[0]))){segments.push(raw[0]===""?"":`${raw[0]}/`);i=1}let directory=false;for(;i<raw.length;i++){const segment=raw[i];if(segment===""||segment==="."){directory=i===raw.length-1&&segments.length>0}else{segments.push(segment);directory=false}}if(segments.length===0&&raw.includes(".")){segments.push(".")}return{segments,directory}};var compileSegment=(chars)=>{const tokens=[];let literal="";let magic=false;let classes=true;for(let i=0;i<chars.length;i++){const char=chars[i];if(char==="\\"&&i+1<chars.length){literal+=chars[++i];tokens.push({_tag:"Char",code:chars[i].codePointAt(0)})}else if(char==="*"){magic=true;if(tokens[tokens.length-1]?._tag!=="Star"){tokens.push({_tag:"Star"})}}else if(char==="?"){magic=true;tokens.push({_tag:"Any"})}else if(char==="["&&classes){const parsed=parseClass(chars,i);if(parsed===undefined){classes=false;literal+=char;tokens.push({_tag:"Char",code:char.codePointAt(0)})}else{magic=true;tokens.push(parsed.token);i=parsed.end}}else{literal+=char;tokens.push({_tag:"Char",code:char.codePointAt(0)})}}if(!magic){return{_tag:"Literal",value:literal}}const first=tokens[0];return{_tag:"Wildcard",tokens,leadingDot:first._tag==="Char"&&first.code===46,affixes:compileAffixes(tokens)}};var compileAffixes=(tokens)=>{let prefix="";let suffix;for(const token of tokens){if(token._tag==="Star"&&suffix===undefined){suffix=""}else if(token._tag==="Char"&&(token.code<55296||token.code>57343)){const char=String.fromCodePoint(token.code);if(suffix===undefined){prefix+=char}else{suffix+=char}}else{return}}return suffix===undefined?undefined:{prefix,suffix}};var range=(from,to)=>[from.codePointAt(0),to.codePointAt(0)];var posixClasses={alnum:[...range("0","9"),...range("A","Z"),...range("a","z")],alpha:[...range("A","Z"),...range("a","z")],blank:[9,9,32,32],cntrl:[0,31,127,127],digit:range("0","9"),graph:[33,126],lower:range("a","z"),print:[32,126],punct:[33,47,58,64,91,96,123,126],space:[9,13,32,32],upper:range("A","Z"),word:[...range("0","9"),...range("A","Z"),95,95,...range("a","z")],xdigit:[...range("0","9"),...range("A","F"),...range("a","f")]};var parsePosixClass=(chars,open)=>{for(let i=open+2;i<chars.length&&i<=open+8;i++){if(chars[i]===":"&&chars[i+1]==="]"){const ranges=posixClasses[chars.slice(open+2,i).join("")];return ranges===undefined?undefined:{ranges,end:i+1}}}return};var parseClass=(chars,open)=>{let i=open+1;const negated=chars[i]==="!"||chars[i]==="^";if(negated){i++}const ranges=[];for(let first=true;i<chars.length;i++,first=false){let char=chars[i];if(char==="/"){return}if(char==="]"&&!first){return{token:{_tag:"Class",ranges,negated},end:i}}if(char==="["&&chars[i+1]===":"){const posix=parsePosixClass(chars,i);if(posix!==undefined){ranges.push(...posix.ranges);i=posix.end;continue}}if(char==="\\"&&i+1<chars.length){char=chars[++i]}if(chars[i+1]==="-"&&i+2<chars.length&&chars[i+2]!=="]"){let next=i+2;if(chars[next]==="/"){return}if(chars[next]==="\\"&&next+1<chars.length){next++}ranges.push(...range(char,chars[next]));i=next;continue}ranges.push(...range(char,char))}return};var expandBraces=(pattern)=>{const chars=Array.from(pattern);const groups=matchBraceGroups(chars);if(groups.size===0){return[pattern]}const sequence=parseBraceSequence(chars,0,chars.length,groups,0);if(sequence===undefined){return[pattern]}const count=countExpansions(sequence);return count>maxExpansions||count*pattern.length>maxExpandedLength?[pattern]:expandSequence(sequence)};var matchBraceGroups=(chars)=>{const groups=new Map;const stack=[];let classes=true;for(let i=0;i<chars.length;i++){const char=chars[i];if(char==="\\"){i++}else if(char==="/"){classes=true}else if(char==="["&&classes){const parsed=parseClass(chars,i);if(parsed===undefined){classes=false}else{i=parsed.end}}else if(char==="{"){stack.push({open:i,commas:[]})}else if(char===","){stack[stack.length-1]?.commas.push(i)}else if(char==="}"){const group=stack.pop();if(group!==undefined&&group.commas.length>0){groups.set(group.open,{commas:group.commas,close:i})}}}return groups};var parseBraceSequence=(chars,start,end,groups,depth)=>{if(depth>maxBraceDepth){return}const parts=[];let text="";for(let i=start;i<end;i++){const group=groups.get(i);if(group===undefined){if(chars[i]==="\\"&&i+1<end){text+=chars[i++]}text+=chars[i];continue}const alternatives=[];let from=i+1;for(const to of[...group.commas,group.close]){const alternative=parseBraceSequence(chars,from,to,groups,depth+1);if(alternative===undefined){return}alternatives.push(alternative);from=to+1}if(text!==""){parts.push(text);text=""}parts.push(alternatives);i=group.close}if(text!==""){parts.push(text)}return parts};var countExpansions=(sequence)=>{let count=1;for(const part of sequence){if(typeof part!=="string"){let sum=0;for(const alternative of part){sum+=countExpansions(alternative)}count*=sum;if(count>maxExpansions){return Infinity}}}return count};var expandSequence=(sequence)=>{let out=[""];for(const part of sequence){if(typeof part==="string"){out=out.map((prefix)=>prefix+part)}else{const alternatives=part.flatMap(expandSequence);out=out.flatMap((prefix)=>alternatives.map((alternative)=>prefix+alternative))}}return out};var matchToken=(token,code)=>{switch(token._tag){case"Char":return token.code===code;case"Any":return true;case"Star":return false;case"Class":{let found=false;for(let i=0;i<token.ranges.length&&!found;i+=2){found=code>=token.ranges[i]&&code<=token.ranges[i+1]}return found!==token.negated}}};var width=(code)=>code>65535?2:1;var matchWildcard=(node,name,dot)=>{if(name==="."||name===".."||name.startsWith(".")&&!dot&&!node.leadingDot){return false}if(node.affixes!==undefined){const{prefix,suffix}=node.affixes;return name.length>=prefix.length+suffix.length&&name.startsWith(prefix)&&name.endsWith(suffix)}const{tokens}=node;let t=0;let c=0;let star=-1;let resume=0;while(c<name.length){if(tokens[t]?._tag==="Star"){star=t++;resume=c;continue}const code=name.codePointAt(c);if(t<tokens.length&&matchToken(tokens[t],code)){t++;c+=width(code)}else if(star!==-1){t=star+1;resume+=width(name.codePointAt(resume));c=resume}else{return false}}while(tokens[t]?._tag==="Star"){t++}return t===tokens.length};var closure=(nodes,states)=>{for(const state of states){if(nodes[state]._tag==="Globstar"){states.add(state+1)}}return states};var step=(compiled,states,name)=>{const explicit=new Set;const viaGlobstar=new Set;const root=isRoot(name);for(const state of states){const node=compiled.nodes[state];switch(node._tag){case"Globstar":{if(!root&&name!=="."&&name!==".."&&(compiled.dot||!name.startsWith("."))){viaGlobstar.add(state)}break}case"Literal":{if(node.value===name){explicit.add(state+1)}break}case"Wildcard":{if(!root&&matchWildcard(node,name,compiled.dot)){explicit.add(state+1)}break}}}return{explicit:closure(compiled.nodes,explicit),globstar:closure(compiled.nodes,viaGlobstar)}};var union=(step)=>{if(step.globstar.size===0){return step.explicit}const states=new Set(step.explicit);for(const state of step.globstar){states.add(state)}return states};var accepts=(compiled,states,isDirectory)=>{for(const state of states){const node=compiled.nodes[state];if(node._tag==="End"&&(isDirectory||!node.directoryOnly)){return true}}return false};var canDescend=(compiled,states)=>{for(const state of states){if(compiled.nodes[state]._tag!=="End"){return true}}return false};var needsDirectory=(compiled,states)=>{for(const state of states){const node=compiled.nodes[state];if(node._tag==="End"&&node.directoryOnly){return true}}return false};var join2=(parent,name)=>{if(parent===""){return name===""?"/":name}return parent.endsWith("/")?parent+name:`${parent}/${name}`};var isMissing=(error)=>error.reason._tag==="NotFound"||error.reason._tag==="BadResource";var isIgnorable=(error)=>isMissing(error)||error.reason._tag==="PermissionDenied";var isNotLink=(error)=>isIgnorable(error)||error.reason._tag==="Unknown";var DIRECTORY_CONCURRENCY=16;var byName=mapInput(String2,(entry)=>entry.name);var make10=(fs)=>(pattern,options)=>walk(fs,compile([pattern],options?.dot??false),options);var walk=fnUntraced2(function*(fs,compiled,options){if(compiled.initial.size===0){return[]}const root=options?.root??"";const excludes=compile(options?.exclude??[],true);const excludeNeedsDirectory=excludes.nodes.some((node)=>node._tag==="End"&&node.directoryOnly);const toFsPath=(relative)=>isAbsolute(relative)?relative:relative===""?root===""?".":root:join2(root,relative);const isUnlisted=(value)=>value==="."||value===".."||isRoot(value);const probe=(parent,name,named)=>{const path=toFsPath(join2(parent,name));return fs.stat(path).pipe(map6((info)=>info.type),catchReason2("PlatformError","NotFound",()=>fs.readLink(path).pipe(as2("SymbolicLink"),catchIf2(isNotLink,()=>succeed7(undefined)))),catchIf2(named?isMissing:isIgnorable,()=>succeed7(undefined)),map6((type)=>type===undefined?undefined:{name,type}))};const entries=(relative,states,named)=>{const literals=new Set;let listed=!named;for(const state of states){const node=compiled.nodes[state];if(node._tag==="Literal"){literals.add(node.value)}else if(node._tag!=="End"){listed=true}}const probed=listed?[...literals].filter(isUnlisted):[...literals];return zipWith3(listed?catchIf2(fs.readDirectoryEntries(toFsPath(relative)),named?isMissing:isIgnorable,()=>succeed7([])):succeed7([]),forEach2(probed,(name)=>probe(relative,name,named),{concurrency:16}),(listing,found)=>({entries:sort([...listing,...found.filter(isNotUndefined)],byName),named:named&&!listed}))};const visit=({name,type},parent,states,excluded)=>{const result=step(compiled,states,name);const next=union(result);if(next.size===0){return}const relative=join2(parent,name);const nextExcluded=union(step(excludes,excluded,name));const descend=canDescend(compiled,next);const child=(isDirectory,link)=>{const accepted=accepts(compiled,next,isDirectory);if(!accepted&&(!isDirectory||!descend)||accepts(excludes,nextExcluded,isDirectory)){return}return{relative,accepted,excluded:nextExcluded,next:!isDirectory||!descend?undefined:!link||result.globstar.size===0?next:canDescend(compiled,result.explicit)?result.explicit:undefined}};if(!descend&&!needsDirectory(compiled,next)&&!excludeNeedsDirectory){return child(false,false)}if(type!=="Unknown"&&type!=="SymbolicLink"){return child(type==="Directory",false)}const path=toFsPath(relative);return fs.stat(path).pipe(map6((info)=>info.type==="Directory"),catchIf2(isIgnorable,()=>succeed7(false)),flatMap4((isDirectory)=>{const resolved=child(isDirectory,type==="SymbolicLink");if(type==="SymbolicLink"||resolved?.next===undefined||result.globstar.size===0){return succeed7(resolved)}return fs.readLink(path).pipe(as2(child(isDirectory,true)),catchIf2(isNotLink,()=>succeed7(resolved)))}))};let slots=DIRECTORY_CONCURRENCY;let finishing=false;const failed=makeUnsafe2();const fork=(walk)=>walk.pipe(onError2((cause)=>sync2(()=>{if(!finishing){doneUnsafe(failed,failCause3(cause))}})),ensuring2(sync2(()=>{slots++})),forkChild2);const directory=fnUntraced2(function*(relative,states,excluded,named){const listing=yield*entries(relative,states,named);const children=[];const pending=[];for(const entry of listing.entries){const child=visit(entry,relative,states,excluded);if(isEffect2(child)){const index=children.push(undefined)-1;pending.push(map6(child,(child)=>{children[index]=child}))}else{children.push(child)}}if(pending.length>0){yield*all2(pending,{concurrency:16,discard:true})}const subtrees=[];for(const child of children){if(child?.next!==undefined){const walk=directory(child.relative,child.next,child.excluded,listing.named);if(slots>0){slots--;subtrees.push(join(yield*fork(walk)))}else{subtrees.push(succeed7(yield*walk))}}}const out=[];let index=0;for(const child of children){if(child===undefined){continue}if(child.accepted){out.push(child.relative)}if(child.next!==undefined){for(const path of yield*subtrees[index++]){out.push(path)}}}return out});return yield*raceFirst2(ensuring2(directory("",compiled.initial,excludes.initial,true),sync2(()=>{finishing=true})),_await(failed))});var TypeId7="~effect/PlatformError";class BadArgument extends TaggedError2("BadArgument"){get message(){return`${this.module}.${this.method}${this.description?`: ${this.description}`:""}`}}class SystemError extends Error3{get message(){return`${this._tag}: ${this.module}.${this.method}${this.pathOrDescriptor!==undefined?` (${this.pathOrDescriptor})`:""}${this.description?`: ${this.description}`:""}`}}class PlatformError extends TaggedError2("PlatformError"){constructor(reason){if("cause"in reason){super({reason,cause:reason.cause})}else{super({reason})}}[TypeId7]=TypeId7;get message(){return this.reason.message}}var systemError=(options)=>new PlatformError(new SystemError(options));var badArgument=(options)=>new PlatformError(new BadArgument(options));var makeUnsafe4=makeLatchUnsafe;var TypeId8="~effect/MutableRef";var MutableRefProto={[TypeId8]:TypeId8,...PipeInspectableProto,toJSON(){return{_id:"MutableRef",current:toJson(this.current)}}};var make11=(value)=>{const ref=Object.create(MutableRefProto);ref.current=value;return ref};var Empty=Symbol.for("effect/MutableList/Empty");var make12=()=>({head:undefined,tail:undefined,length:0});var compactHead=(self)=>{const head=self.head;if(head.offset>=1024&&head===self.tail&&head.mutable&&(head.array.length-head.offset)*8<=head.offset){self.head=self.tail={array:head.array.slice(head.offset),mutable:true,offset:0,next:undefined}}};var emptyBucket=()=>({array:[],mutable:true,offset:0,next:undefined});var append2=(self,message)=>{if(!self.tail){self.head=self.tail=emptyBucket()}else if(!self.tail.mutable){self.tail.next=emptyBucket();self.tail=self.tail.next}self.tail.array.push(message);self.length++};var clear=(self)=>{self.head=self.tail=undefined;self.length=0};var takeN=(self,n)=>{n=normalize(n);if(n<=0||!self.head)return[];n=Math.min(n,self.length);if(n===self.length&&self.head?.offset===0&&!self.head.next){const array=self.head.array;clear(self);return array}const array=new Array(n);let index=0;let chunk=self.head;while(chunk){while(chunk.offset<chunk.array.length){array[index++]=chunk.array[chunk.offset];if(chunk.mutable)chunk.array[chunk.offset]=undefined;chunk.offset++;if(index===n){self.head=chunk.offset===chunk.array.length&&chunk.next?chunk.next:chunk;self.length-=n;if(self.length===0)clear(self);else compactHead(self);return array}}chunk=chunk.next}clear(self);return array};var take=(self)=>{if(!self.head)return Empty;const message=self.head.array[self.head.offset];if(self.head.mutable)self.head.array[self.head.offset]=undefined;self.head.offset++;self.length--;if(self.head.offset===self.head.array.length){if(self.head.next){self.head=self.head.next}else{clear(self)}}else{compactHead(self)}return message};var TypeId9="~effect/Queue";var EnqueueTypeId="~effect/Queue/Enqueue";var DequeueTypeId="~effect/Queue/Dequeue";var variance={_A:identity,_E:identity};var QueueProto={[TypeId9]:variance,[EnqueueTypeId]:variance,[DequeueTypeId]:variance,...PipeInspectableProto,toJSON(){return{_id:"effect/Queue",state:this.state._tag,size:sizeUnsafe(this)}}};var make13=(options)=>withFiber((fiber)=>{const self=Object.create(QueueProto);self.dispatcher=fiber.currentDispatcher;self.capacity=options?.capacity??Number.POSITIVE_INFINITY;self.strategy=options?.strategy??"suspend";self.messages=make12();self.scheduleRunning=false;self.state={_tag:"Open",takers:new Set,offers:new Set,awaiters:new Set};return succeed3(self)});var bounded=(capacity)=>make13({capacity});var offer=dual(2,(self,message)=>suspend(()=>offerUnsafe(self,message)?exitTrue:self.state._tag==="Open"&&self.strategy==="suspend"?offerOrWait(self,message):exitFalse));var offerUnsafe=(self,message)=>{if(self.state._tag!=="Open"){return false}else if(self.messages.length>=self.capacity){if(self.strategy==="sliding"){take(self.messages);append2(self.messages,message);return true}else if(self.capacity<=0&&self.state.takers.size>0){append2(self.messages,message);releaseTakers(self);return true}return false}append2(self.messages,message);scheduleReleaseTaker(self);return true};var failCause4=dual(2,(self,cause)=>sync(()=>failCauseUnsafe(self,cause)));var failCauseUnsafe=(self,cause)=>{if(self.state._tag!=="Open"){return false}const exit=exitFailCause(cause);const fail=exitZipRight(exit,exitFailDone);if(self.state.offers.size===0&&self.messages.length===0){finalize(self,fail);return true}self.state={...self.state,_tag:"Closing",exit:fail};scheduleReleaseTaker(self);return true};var endUnsafe=(self)=>failCauseUnsafe(self,causeFail(Done()));var shutdown=(self)=>sync(()=>shutdownUnsafe(self));var shutdownUnsafe=(self)=>{if(self.state._tag==="Done"){return false}clear(self.messages);const offers=self.state.offers;finalize(self,self.state._tag==="Open"?exitInterrupt2:self.state.exit);for(const entry of offers){resumeUnoffered(entry)}return true};var takeAll2=(self)=>takeBetween(self,1,Number.POSITIVE_INFINITY);var takeBetween=dual(3,(self,min,max)=>{min=normalize(min);max=normalize(max);return suspendTake(()=>takeBetweenUnsafe(self,min,max)??andThen(awaitTake(self,()=>canTake(self,min)),takeBetween(self,min,max)))});var take2=(self)=>suspendTake(()=>takeUnsafe(self)??andThen(awaitTake(self,()=>canTake(self,1)),take2(self)));var takeUnsafe=(self)=>{if(self.state._tag==="Done"){return self.state.exit}if(self.messages.length>0){const message=take(self.messages);releaseCapacity(self);return exitSucceed(message)}else if(self.capacity<=0&&self.state.offers.size>0){const message=takeOfferUnsafe(self.state.offers);releaseCapacity(self);return exitSucceed(message)}return};var sizeUnsafe=(self)=>self.state._tag==="Done"?0:self.messages.length;var exitFalse=exitSucceed(false);var exitTrue=exitSucceed(true);var exitFailDone=exitFail(Done());var exitInterrupt2=exitInterrupt();var releaseTakers=(self)=>{if(self.state._tag==="Done"||self.state.takers.size===0){return}for(const taker of self.state.takers){if(!taker.ready())continue;self.state.takers.delete(taker);taker.resume(exitVoid);if(self.messages.length===0){break}}};var scheduleReleaseTaker=(self)=>{if(self.scheduleRunning||self.state._tag==="Done"||self.state.takers.size===0){return}self.scheduleRunning=true;self.dispatcher.scheduleTask(()=>{self.scheduleRunning=false;releaseTakers(self)},0)};var takeBetweenUnsafe=(self,min,max)=>{if(self.state._tag==="Done"){return self.state.exit}else if(max<=0||min<=0){return exitSucceed([])}else if(!canTake(self,min)){return}const messages=self.messages.length>0?takeN(self.messages,max):[takeOfferUnsafe(self.state.offers)];releaseCapacity(self);return exitSucceed(messages)};var suspendTake=makePrimitive({op:"QueueTake",[evaluate](fiber){const effect=this[args]();return isExit(effect)?effect[evaluate](fiber):effect}});var canTake=(self,min)=>self.messages.length>=(self.state._tag==="Closing"?1:Math.min(min,self.capacity||1))||self.capacity<=0&&self.state._tag!=="Done"&&self.state.offers.size>0;var awaitTake=(self,ready)=>callback((resume)=>{if(self.state._tag==="Done")return resume(self.state.exit);if(ready())return resume(exitVoid);const taker={ready,resume};self.state.takers.add(taker);return sync(()=>{if(self.state._tag!=="Done")self.state.takers.delete(taker)})});var offerOrWait=(self,message)=>callback((resume)=>offerUnsafe(self,message)?resume(exitTrue):waitToOffer(self,{_tag:"Single",message,resume}));var waitToOffer=(self,entry)=>{if(self.state._tag!=="Open")return resumeUnoffered(entry);const offers=self.state.offers;offers.add(entry);return sync(()=>{if(self.state._tag==="Done")return;offers.delete(entry);if(self.state._tag==="Closing"&&offers.size===0&&self.messages.length===0){finalize(self,self.state.exit)}})};var resumeUnoffered=(entry)=>entry._tag==="Single"?entry.resume(exitFalse):entry.resume(exitSucceed(entry.remaining.slice(entry.offset)));var takeOfferUnsafe=(offers)=>{const entry=offers.values().next().value;if(entry._tag==="Single"){offers.delete(entry);entry.resume(exitTrue);return entry.message}const message=entry.remaining[entry.offset++];if(entry.offset===entry.remaining.length){offers.delete(entry);entry.resume(exitSucceed([]))}return message};var releaseCapacity=(self)=>{if(self.state._tag==="Done"){return isDoneCause(self.state.exit.cause)}else if(self.state.offers.size===0){if(self.state._tag==="Closing"&&self.messages.length===0){finalize(self,self.state.exit);return isDoneCause(self.state.exit.cause)}return false}for(const entry of self.state.offers){let n=self.capacity-self.messages.length;if(n<=0)break;else if(entry._tag==="Single"){append2(self.messages,entry.message);self.state.offers.delete(entry);entry.resume(exitTrue)}else{for(;entry.offset<entry.remaining.length;entry.offset++){if(n===0)return false;append2(self.messages,entry.remaining[entry.offset]);n--}self.state.offers.delete(entry);entry.resume(exitSucceed([]))}const state=self.state;if(state._tag==="Done"){return isDoneCause(state.exit.cause)}}return false};var finalize=(self,exit)=>{if(self.state._tag==="Done"){return}const openState=self.state;self.state={_tag:"Done",exit};for(const taker of openState.takers){taker.resume(exit)}openState.takers.clear();for(const awaiter of openState.awaiters){awaiter(exit)}openState.awaiters.clear()};var makeUnsafe5=(permits)=>new SemaphoreImpl(permits);var firstAvailableWaiter=(self)=>{for(const waiter of self.waiters){if(waiter.permits<=self.free)return waiter}};var takePermits=(self,n,onAcquire,restore=identity)=>withFiber((fiber)=>{if(self.free>=n&&firstAvailableWaiter(self)===undefined){self.taken+=n;return onAcquire()}const waiter={permits:n,resume:undefined};const remove=()=>{if(self.waiters.delete(waiter))self.releaseUnsafe(fiber,0);return};self.waiters.add(waiter);onExitUnsafe(fiber,remove);const wait=restore(callback((resume)=>{if(firstAvailableWaiter(self)===waiter){resume(void_)}else{waiter.resume=resume}}));const loop=flatMap3(wait,()=>{if(firstAvailableWaiter(self)!==waiter)return loop;self.taken+=n;remove();return onAcquire()});return loop});class SemaphoreImpl{waiters=new Set;taken=0;permits;constructor(permits){this.permits=permits}get free(){return this.permits-this.taken}take(n){return takePermits(this,n,()=>succeed3(n))}takeScoped(n){return uninterruptibleMask((restore)=>flatMap3(scope,(scope)=>takePermits(this,n,()=>scopeAddFinalizer(scope,this.release(n)),restore)))}takeIfAvailable(n){return suspend(()=>{if(this.free<n)return succeed3(false);this.taken+=n;return succeed3(true)})}releaseUnsafe(fiber,n){this.taken-=n;if(this.waiters.size>0){fiber.currentDispatcher.scheduleTask(()=>{let remaining=this.free;for(const waiter of Array.from(this.waiters)){if(!this.waiters.has(waiter)||waiter.permits>remaining)continue;remaining-=waiter.permits;const resume=waiter.resume;waiter.resume=undefined;resume?.(void_)}},0)}return this.free}resize(permits){return withFiber((fiber)=>{this.permits=permits;if(this.free<0)return void_;this.releaseUnsafe(fiber,0);return void_})}release(n){return withFiber((fiber)=>succeed3(this.releaseUnsafe(fiber,n)))}get releaseAll(){return withFiber((fiber)=>succeed3(this.releaseUnsafe(fiber,this.taken)))}withPermits(n){return(self)=>uninterruptibleMask((restore)=>takePermits(this,n,()=>onExitPrimitive(restore(self),()=>{this.releaseUnsafe(getCurrentFiber(),n);return},true),restore))}withPermit=this.withPermits(1);withPermitsIfAvailable(n){return(self)=>uninterruptibleMask((restore)=>{if(this.free<n)return succeedNone;this.taken+=n;return onExitPrimitive(restore(asSome(self)),()=>{this.releaseUnsafe(getCurrentFiber(),n);return},true)})}}var make14=(permits)=>sync(()=>new SemaphoreImpl(permits));var TypeId10="~effect/Channel";var isChannel=(u)=>hasProperty(u,TypeId10);var ChannelProto={[TypeId10]:{_Env:identity,_InErr:identity,_InElem:identity,_OutErr:identity,_OutElem:identity},pipe(){return pipeArguments(this,arguments)}};var fromTransform=(transform)=>{const self=Object.create(ChannelProto);self.transform=(upstream,scope)=>catchCause2(transform(upstream,scope),(cause)=>succeed7(failCause3(cause)));return self};var transformPull=(self,f)=>fromTransform((upstream,scope)=>flatMap4(toTransform(self)(upstream,scope),(pull)=>f(pull,scope)));var fromPull=(effect)=>fromTransform((_,__)=>effect);var fromTransformBracket=(f)=>fromTransform(fnUntraced2(function*(upstream,scope){const closableScope=forkUnsafe2(scope);const onCause=(cause)=>close(closableScope,doneExitFromCause(cause));const pull=yield*onError2(f(upstream,scope,closableScope),onCause);return onError2(pull,onCause)}));var toTransform=(channel)=>channel.transform;var asyncQueue=(scope,f,options)=>make13({capacity:options?.bufferSize,strategy:options?.strategy}).pipe(tap2((queue)=>addFinalizer2(scope,shutdown(queue))),tap2((queue)=>provide(f(queue),scope).pipe(catchCause2((cause)=>failCause4(queue,cause)),forkIn2(scope,{startImmediately:true}))));var callbackArray=(f,options)=>fromTransform((_,scope)=>map6(asyncQueue(scope,f,options),takeAll2));var suspend3=(evaluate)=>fromTransform((upstream,scope)=>suspend2(()=>toTransform(evaluate())(upstream,scope)));var fail7=(error)=>fromPull(succeed7(fail6(error)));var fromReadableStream=(options)=>fromTransform((_,scope)=>readableStreamToPullUnsafe({scope,readable:options.evaluate(),onError:options.onError,releaseLockOnEnd:options.releaseLockOnEnd}));var readableStreamToPullUnsafe=(options)=>{const reader=options.readable.getReader();const exit=options.exit??make11(undefined);const pull=suspend2(()=>{if(exit.current)return exit.current;return matchCauseEffect2(tryPromise2({try:()=>reader.read(),catch:options.onError}),{onFailure:(cause)=>exit.current??failCause3(cause),onSuccess:({done,value})=>{if(exit.current)return exit.current;return done?done2():succeed7(of(value))}})});return as2(addFinalizer2(options.scope,options.releaseLockOnEnd?sync2(()=>reader.releaseLock()):promise2(()=>reader.cancel().catch((error)=>reader.closed.then(()=>Promise.reject(error),constVoid))).pipe(ensuring2(sync2(()=>reader.releaseLock())))),pull)};var merge2=dual((args)=>isChannel(args[0])&&isChannel(args[1]),(left,right,options)=>fromTransformBracket(fnUntraced2(function*(upstream,_scope,forkedScope){const strategy=options?.haltStrategy??"both";const queue=yield*bounded(0);yield*addFinalizer2(forkedScope,shutdown(queue));let done=0;function onExit(side,cause){done++;if(!isDoneCause(cause)){return failCause4(queue,cause)}switch(strategy){case"both":{return done===2?failCause4(queue,cause):void_3}case"left":case"right":{return side===strategy?failCause4(queue,cause):void_3}case"either":{return failCause4(queue,cause)}}}const runSide=(side,channel,scope)=>toTransform(channel)(upstream,scope).pipe(flatMap4((pull)=>pull.pipe(flatMap4((value)=>offer(queue,value)),forever2)),onError2((cause)=>onExitPrimitive2(doneExitFromCause(cause),(exit)=>close(scope,exit)).pipe(matchCauseEffect2({onFailure:(cause)=>onExit(side,cause),onSuccess:()=>onExit(side,cause)}))),forkIn2(forkedScope));yield*runSide("left",left,forkUnsafe2(forkedScope));yield*runSide("right",right,forkUnsafe2(forkedScope));return take2(queue)})));var unwrap=(channel)=>fromTransform((upstream,scope)=>{let pull;return succeed7(suspend2(()=>{if(pull)return pull;return channel.pipe(provide(scope),flatMap4((channel)=>toTransform(channel)(upstream,scope)),flatMap4((pull_)=>pull=pull_))}))});var interruptWhen=dual(2,(self,effect)=>merge2(self,fromPull(succeed7(flatMap4(effect,done2))),{haltStrategy:"either"}));var onExit3=dual(2,(self,finalizer)=>fromTransformBracket((upstream,scope,forkedScope)=>addFinalizerExit(forkedScope,finalizer).pipe(andThen2(toTransform(self)(upstream,scope)))));var ensuring3=dual(2,(self,finalizer)=>onExit3(self,(_)=>finalizer));var runWith=(self,f,onHalt)=>suspend2(()=>{const scope=makeUnsafe3();const makePull=toTransform(self)(done2(),scope);return catchDone(flatMap4(makePull,f),onHalt?onHalt:succeed7).pipe(onExit2((exit)=>close(scope,exit)))});var runForEach=dual(2,(self,f)=>runWith(self,(pull)=>forever2(flatMap4(pull,f),{disableYield:true})));var mkUint8Array=(self)=>map6(runFold(self,()=>({bytes:0,arrays:[]}),(acc,chunk)=>{for(let i=0;i<chunk.length;i++){acc.bytes+=chunk[i].length;acc.arrays.push(chunk[i])}return acc}),({arrays,bytes})=>{const result=new Uint8Array(bytes);let offset=0;for(let i=0;i<arrays.length;i++){const array=arrays[i];result.set(array,offset);offset+=array.length}return result});var runFold=dual(3,(self,initial,f)=>suspend2(()=>{let state=initial();return runWith(self,(pull)=>whileLoop2({while:constTrue,body:()=>pull,step:(value)=>{state=f(state,value)}}),()=>succeed7(state))}));var TypeId11="~effect/Stream";var streamVariance={_R:identity,_E:identity,_A:identity};var Stream=function(channel){this.channel=channel};Stream.prototype={[TypeId11]:streamVariance,pipe(){return pipeArguments(this,arguments)}};var fromChannel=(channel)=>new Stream(channel);var TypeId12="~effect/Sink";var endVoid=succeed7([undefined]);var sinkVariance={_A:identity,_In:identity,_L:identity,_E:identity,_R:identity};var SinkProto={[TypeId12]:sinkVariance,pipe(){return pipeArguments(this,arguments)}};var fromChannel2=(channel)=>fromTransform2((upstream,scope)=>toTransform(channel)(upstream,scope).pipe(flatMap4(forever2({disableYield:true})),catchDone(succeed7)));var fromTransform2=(transform)=>{const self=Object.create(SinkProto);self.transform=transform;return self};var toChannel=(self)=>fromTransform((upstream,scope)=>succeed7(flatMap4(self.transform(upstream,scope),done2)));var forEach3=(f)=>forEachArray(forEach2((_)=>f(_),{discard:true}));var forEachArray=(f)=>fromTransform2((upstream)=>upstream.pipe(flatMap4(f),forever2({disableYield:true}),catchDone(()=>endVoid)));var unwrap2=(effect)=>fromChannel2(unwrap(map6(effect,toChannel)));var TypeId13="~effect/Stream";var isStream=(u)=>hasProperty(u,TypeId13);var fromChannel3=fromChannel;var fromPull2=(pull)=>fromChannel3(fromPull(pull));var toChannel2=(stream)=>stream.channel;var callback3=(f,options)=>fromChannel3(callbackArray(f,options));var suspend4=(stream)=>{const suspended=fromChannel3(suspend3(()=>stream().channel));suspendedStreams.set(suspended,stream);return suspended};var suspendedStreams=new WeakMap;var fail8=(error)=>fromChannel3(fail7(error));var fromReadableStream2=(options)=>fromChannel3(fromReadableStream(options));var unwrap3=(effect)=>fromChannel3(unwrap(map6(effect,toChannel2)));var interruptWhen2=dual(2,(self,effect)=>fromChannel3(interruptWhen(self.channel,effect)));var ensuring4=dual(2,(self,finalizer)=>fromChannel3(ensuring3(self.channel,finalizer)));var mkArrayBuffer=(self)=>map6(mkUint8Array(self.channel),(bytes)=>bytes.buffer);var toReadableStreamWith=dual((args)=>isStream(args[0]),(self,context,options)=>{let currentResolve=undefined;let fiber=undefined;let cancelled=false;const latch=makeUnsafe4(false);const signal=options?.signal;const onAbort=()=>fiber.interruptUnsafe();return new ReadableStream({start(controller){fiber=runFork2(provideContext2(runForEach(transformPull(self.channel,(pull)=>succeed7(latch.whenOpen(pull))),(chunk)=>sync2(()=>{latch.closeUnsafe();for(let i=0;i<chunk.length;i++){controller.enqueue(chunk[i])}currentResolve();currentResolve=undefined})),context));fiber.addObserver((exit)=>{signal?.removeEventListener("abort",onAbort);if(cancelled)return;if(exit._tag==="Failure"&&signal?.aborted!==true){controller.error(squash(exit.cause))}else{controller.close()}});if(signal!==undefined&&fiber.pollUnsafe()===undefined){if(signal.aborted)onAbort();else signal.addEventListener("abort",onAbort,{once:true})}},pull(){return new Promise((resolve)=>{currentResolve=resolve;latch.openUnsafe()})},cancel(){if(!fiber)return;cancelled=true;return runPromise2(asVoid2(interrupt3(fiber)))}},options?.strategy)});var toReadableStreamEffect=dual((args)=>isStream(args[0]),(self,options)=>map6(context2(),(context)=>toReadableStreamWith(self,context,options)));var TypeId14="~effect/FileSystem";var FileSystem=Service("effect/FileSystem");var make15=(impl)=>FileSystem.of({...impl,[TypeId14]:TypeId14,glob:make10(impl),exists:(path)=>pipe(impl.access(path),as2(true),catchTag2("PlatformError",(e)=>e.reason._tag==="NotFound"?succeed7(false):fail6(e))),readFileString:(path,encoding)=>flatMap4(impl.readFile(path),(_)=>try_3({try:()=>new TextDecoder(encoding).decode(_),catch:(cause)=>badArgument({module:"FileSystem",method:"readFileString",description:"invalid encoding",cause})})),stream:fnUntraced2(function*(path,options){const file=yield*impl.open(path,{flag:"r"});const offset=options?.offset===undefined?undefined:fromInputUnsafe(options.offset);if(offset){yield*file.seek(offset,"start")}const bytesToRead=options?.bytesToRead===undefined?undefined:fromInputUnsafe(options.bytesToRead);let totalBytesRead=BigInt(0);const chunkSize=Number(BigInt(options?.chunkSize??64*1024));const readChunk=file.readAlloc(chunkSize);return fromPull2(succeed7(flatMap4(suspend2(()=>{if(bytesToRead!==undefined&&bytesToRead<=totalBytesRead){return done2()}return bytesToRead!==undefined&&bytesToRead-totalBytesRead<chunkSize?file.readAlloc(Number(bytesToRead-totalBytesRead)):readChunk}),match({onNone:()=>done2(),onSome:(buf)=>{totalBytesRead+=BigInt(buf.length);return succeed7(of(buf))}}))))},unwrap3),sink:(path,options)=>pipe(impl.open(path,{...options,flag:options?.flag??"w"}),map6((file)=>forEach3((_)=>file.writeAll(_))),unwrap2),writeFileString:(path,data,options)=>flatMap4(try_3({try:()=>new TextEncoder().encode(data),catch:(cause)=>badArgument({module:"FileSystem",method:"writeFileString",description:"could not encode string",cause})}),(_)=>impl.writeFile(path,_,options))});var FileTypeId="~effect/FileSystem/File";class WatchBackend extends Service()("effect/FileSystem/WatchBackend"){}import*as Crypto from"crypto";import*as NFS from"fs";import*as OS from"os";import*as Path from"path";var handleErrnoException=(module,method)=>(err,[path])=>{let reason="Unknown";switch(err.code){case"ENOENT":reason="NotFound";break;case"EACCES":case"EPERM":reason="PermissionDenied";break;case"EEXIST":reason="AlreadyExists";break;case"EISDIR":reason="BadResource";break;case"ENOTDIR":reason="BadResource";break;case"EBUSY":reason="Busy";break;case"ELOOP":reason="BadResource";break}return systemError({_tag:reason,module,method,pathOrDescriptor:path,syscall:err.syscall,cause:err})};var handleBadArgument=(method)=>(err)=>badArgument({module:"FileSystem",method,description:err.message??String(err)});var bigintToNumber=(value,field)=>{const number=Number(value);if(!Number.isSafeInteger(number)){throw new RangeError(`${field} exceeds the safe integer range: ${value}`)}return number};var bigintToNumberOption=(value)=>flatMap(fromNullishOr(value),toNumber);var toUint64=(value)=>BigInt.asUintN(64,value);var toUint64Option=(value)=>map(fromNullishOr(value),toUint64);var positionToNumber=(position,method)=>try_3({try:()=>bigintToNumber(position,"position"),catch:handleBadArgument(method)});var access2=(()=>{const nodeAccess=effectify(NFS.access,handleErrnoException("FileSystem","access"),handleBadArgument("access"));return(path,options)=>{let mode=NFS.constants.F_OK;if(options?.readable){mode|=NFS.constants.R_OK}if(options?.writable){mode|=NFS.constants.W_OK}return nodeAccess(path,mode)}})();var copy=(()=>{const nodeCp=effectify(NFS.cp,handleErrnoException("FileSystem","copy"),handleBadArgument("copy"));return(fromPath,toPath,options)=>nodeCp(fromPath,toPath,{force:options?.overwrite??false,preserveTimestamps:options?.preserveTimestamps??false,recursive:true})})();var copyFile2=(()=>{const nodeCopyFile=effectify(NFS.copyFile,handleErrnoException("FileSystem","copyFile"),handleBadArgument("copyFile"));return(fromPath,toPath)=>nodeCopyFile(fromPath,toPath)})();var chmod2=(()=>{const nodeChmod=effectify(NFS.chmod,handleErrnoException("FileSystem","chmod"),handleBadArgument("chmod"));return(path,mode)=>nodeChmod(path,mode)})();var chown2=(()=>{const nodeChown=effectify(NFS.chown,handleErrnoException("FileSystem","chown"),handleBadArgument("chown"));return(path,uid,gid)=>nodeChown(path,uid,gid)})();var link2=(()=>{const nodeLink=effectify(NFS.link,handleErrnoException("FileSystem","link"),handleBadArgument("link"));return(existingPath,newPath)=>nodeLink(existingPath,newPath)})();var makeDirectory=(()=>{const nodeMkdir=effectify(NFS.mkdir,handleErrnoException("FileSystem","makeDirectory"),handleBadArgument("makeDirectory"));return(path,options)=>nodeMkdir(path,{recursive:options?.recursive??false,mode:options?.mode})})();var makeTempDirectoryFactory=(method)=>{const nodeMkdtemp=effectify(NFS.mkdtemp,handleErrnoException("FileSystem",method),handleBadArgument(method));return(options)=>suspend2(()=>{const prefix=options?.prefix??"";const directory=typeof options?.directory==="string"?Path.join(options.directory,"."):OS.tmpdir();return nodeMkdtemp(prefix?Path.join(directory,prefix):directory+"/")})};var makeTempDirectory=makeTempDirectoryFactory("makeTempDirectory");var removeFactory=(method)=>{const nodeRm=effectify(NFS.rm,handleErrnoException("FileSystem",method),handleBadArgument(method));return(path,options)=>nodeRm(path,{recursive:options?.recursive??false,force:options?.force??false})};var remove=removeFactory("remove");var makeTempDirectoryScoped=(()=>{const makeDirectory=makeTempDirectoryFactory("makeTempDirectoryScoped");const removeDirectory=removeFactory("makeTempDirectoryScoped");return(options)=>acquireRelease2(makeDirectory(options),(directory)=>orDie2(removeDirectory(directory,{recursive:true,force:true})))})();var openFlagBits=(flag)=>{const{O_APPEND,O_CREAT,O_EXCL,O_RDONLY,O_RDWR,O_TRUNC,O_WRONLY}=NFS.constants;switch(flag){case"r":return O_RDONLY;case"r+":return O_RDWR;case"w":return O_TRUNC|O_CREAT|O_WRONLY;case"wx":return O_TRUNC|O_CREAT|O_WRONLY|O_EXCL;case"w+":return O_TRUNC|O_CREAT|O_RDWR;case"wx+":return O_TRUNC|O_CREAT|O_RDWR|O_EXCL;case"a":return O_APPEND|O_CREAT|O_WRONLY;case"ax":return O_APPEND|O_CREAT|O_WRONLY|O_EXCL;case"a+":return O_APPEND|O_CREAT|O_RDWR;case"ax+":return O_APPEND|O_CREAT|O_RDWR|O_EXCL}};var noFollowFlags=(method,flag)=>suspend2(()=>{const{O_NOFOLLOW}=NFS.constants;if(process.platform==="win32"||typeof O_NOFOLLOW!=="number"||O_NOFOLLOW===0){return fail6(badArgument({module:"FileSystem",method,description:"noFollow is not supported on this platform"}))}return succeed7(openFlagBits(flag)|O_NOFOLLOW)});var openFactory=(method)=>{const nodeOpen=effectify(NFS.open,handleErrnoException("FileSystem",method),handleBadArgument(method));const nodeClose=effectify(NFS.close,handleErrnoException("FileSystem",method),handleBadArgument(method));return(path,options)=>pipe(acquireRelease2(options?.noFollow===true?flatMap4(noFollowFlags(method,options.flag??"r"),(flags)=>nodeOpen(path,flags,options.mode)):nodeOpen(path,options?.flag??"r",options?.mode),(fd)=>orDie2(nodeClose(fd))),map6((fd)=>makeFile(fd,options?.flag?.startsWith("a")??false)))};var open2=openFactory("open");var negativePosition=(method)=>badArgument({module:"FileSystem",method,description:"Cannot read before the start of the file"});var makeFile=(()=>{const nodeReadFactory=(method)=>effectify(NFS.read,handleErrnoException("FileSystem",method),handleBadArgument(method));const nodeRead=nodeReadFactory("read");const nodeReadAlloc=nodeReadFactory("readAlloc");const nodeStat=effectify(NFS.fstat,handleErrnoException("FileSystem","stat"),handleBadArgument("stat"));const nodeTruncate=effectify(NFS.ftruncate,handleErrnoException("FileSystem","truncate"),handleBadArgument("truncate"));const nodeSync=effectify(NFS.fsync,handleErrnoException("FileSystem","sync"),handleBadArgument("sync"));const nodeWriteFactory=(method)=>effectify(NFS.write,handleErrnoException("FileSystem",method),handleBadArgument(method));const nodeWrite=nodeWriteFactory("write");const nodeWriteAll=nodeWriteFactory("writeAll");class FileImpl{[FileTypeId];fd;append;position=BigInt(0);constructor(fd,append){this[FileTypeId]=FileTypeId;this.fd=fd;this.append=append}get stat(){return flatMap4(nodeStat(this.fd,{bigint:true}),makeFileInfo)}get sync(){return nodeSync(this.fd)}seek(offset,from){return suspend2(()=>{const position=from==="start"?offset:this.position+offset;if(position<BigInt(0)){return fail6(badArgument({module:"FileSystem",method:"seek",description:"Cannot seek before the start of the file"}))}this.position=position;return succeed7(position)})}read(buffer,options){return suspend2(()=>{const explicit=options?.position;if(explicit!==undefined){return explicit<BigInt(0)?fail6(negativePosition("read")):nodeRead(this.fd,{buffer,position:explicit})}const position=this.position;return map6(nodeRead(this.fd,{buffer,position}),(bytesRead)=>{this.position=position+BigInt(bytesRead);return bytesRead})})}readAlloc(size,options){return suspend2(()=>{try{if(!Number.isInteger(size)||size<0){throw new RangeError("size must be a non-negative integer")}const explicit=options?.position;if(explicit!==undefined&&explicit<BigInt(0)){return fail6(negativePosition("readAlloc"))}const buffer=Buffer.allocUnsafeSlow(size);const position=explicit??this.position;return map6(nodeReadAlloc(this.fd,{buffer,position}),(bytesRead)=>{if(bytesRead===0){return none2()}if(explicit===undefined){this.position=position+BigInt(bytesRead)}if(bytesRead===size){return some2(buffer)}const dst=Buffer.allocUnsafeSlow(bytesRead);buffer.copy(dst,0,0,bytesRead);return some2(dst)})}catch(cause){return fail6(handleBadArgument("readAlloc")(cause))}})}truncate(length){return map6(nodeTruncate(this.fd,length||undefined),()=>{if(!this.append){const len=BigInt(length??0);if(this.position>len){this.position=len}}})}write(buffer){return suspend2(()=>{const position=this.position;return flatMap4(this.append?succeed7(undefined):positionToNumber(position,"write"),(nodePosition)=>map6(nodeWrite(this.fd,buffer,undefined,undefined,nodePosition),(bytesWritten)=>{if(!this.append){this.position=position+BigInt(bytesWritten)}return bytesWritten}))})}writeAllChunk(buffer){return suspend2(()=>{const position=this.position;return flatMap4(this.append?succeed7(undefined):positionToNumber(position,"writeAll"),(nodePosition)=>flatMap4(nodeWriteAll(this.fd,buffer,undefined,undefined,nodePosition),(bytesWritten)=>{if(bytesWritten===0){return fail6(systemError({module:"FileSystem",method:"writeAll",_tag:"WriteZero",pathOrDescriptor:this.fd,description:"write returned 0 bytes written"}))}if(!this.append){this.position=position+BigInt(bytesWritten)}return bytesWritten<buffer.length?this.writeAllChunk(buffer.subarray(bytesWritten)):void_3}))})}writeAll(buffer){return buffer.length===0?void_3:this.writeAllChunk(buffer)}}return(fd,append)=>new FileImpl(fd,append)})();var makeTempFileFactory=(method)=>{const makeDirectory=makeTempDirectoryFactory(method);return fnUntraced2(function*(options){const directory=yield*makeDirectory(options);const random=Crypto.randomBytes(6).toString("hex");const name=Path.join(directory,options?.suffix?`${random}${options.suffix}`:random);yield*writeFile2(name,new Uint8Array(0));return name})};var makeTempFile=makeTempFileFactory("makeTempFile");var makeTempFileScoped=(()=>{const makeFile=makeTempFileFactory("makeTempFileScoped");const removeDirectory=removeFactory("makeTempFileScoped");return(options)=>acquireRelease2(makeFile(options),(file)=>orDie2(removeDirectory(Path.dirname(file),{recursive:true,force:true})))})();var readDirectory=(path,options)=>tryPromise2({try:()=>NFS.promises.readdir(path,options),catch:(err)=>handleErrnoException("FileSystem","readDirectory")(err,[path])});var readDirectoryEntries=(path)=>tryPromise2({try:()=>NFS.promises.readdir(path,{withFileTypes:true}),catch:(err)=>handleErrnoException("FileSystem","readDirectoryEntries")(err,[path])}).pipe(map6((entries)=>entries.map((entry)=>({name:entry.name,type:fileType(entry)}))));var readFile2=(path)=>callback2((resume,signal)=>{try{NFS.readFile(path,{signal},(err,data)=>{if(err){resume(fail6(handleErrnoException("FileSystem","readFile")(err,[path])))}else{resume(succeed7(data))}})}catch(err){resume(fail6(handleBadArgument("readFile")(err)))}});var readLink=(()=>{const nodeReadLink=effectify(NFS.readlink,handleErrnoException("FileSystem","readLink"),handleBadArgument("readLink"));return(path)=>nodeReadLink(path)})();var realPath=(()=>{const nodeRealPath=effectify(process.platform==="win32"?NFS.realpath.native:NFS.realpath,handleErrnoException("FileSystem","realPath"),handleBadArgument("realPath"));return(path)=>nodeRealPath(path)})();var rename2=(()=>{const nodeRename=effectify(NFS.rename,handleErrnoException("FileSystem","rename"),handleBadArgument("rename"));return(oldPath,newPath)=>nodeRename(oldPath,newPath)})();var fileType=(stat)=>stat.isFile()?"File":stat.isDirectory()?"Directory":stat.isSymbolicLink()?"SymbolicLink":stat.isBlockDevice()?"BlockDevice":stat.isCharacterDevice()?"CharacterDevice":stat.isFIFO()?"FIFO":stat.isSocket()?"Socket":"Unknown";var makeFileInfo=(stat,method="stat")=>try_3({try:()=>({type:fileType(stat),mtime:fromNullishOr(stat.mtime),atime:fromNullishOr(stat.atime),birthtime:fromNullishOr(stat.birthtime),dev:toUint64(stat.dev),rdev:toUint64Option(stat.rdev),ino:toUint64Option(stat.ino),mode:bigintToNumber(stat.mode,"mode"),nlink:toUint64Option(stat.nlink),uid:bigintToNumberOption(stat.uid),gid:bigintToNumberOption(stat.gid),size:bytes(stat.size),blksize:stat.blksize!==undefined?some2(bytes(stat.blksize)):none2(),blocks:fromNullishOr(stat.blocks)}),catch:handleBadArgument(method)});var statFactory=(method,nodeStatFn)=>{const nodeStat=effectify(nodeStatFn,handleErrnoException("FileSystem",method),handleBadArgument(method));return(path)=>flatMap4(nodeStat(path,{bigint:true}),(stat)=>makeFileInfo(stat,method))};var stat2=statFactory("stat",NFS.stat);var lstat2=statFactory("lstat",NFS.lstat);var symlink2=(()=>{const nodeSymlink=effectify(NFS.symlink,handleErrnoException("FileSystem","symlink"),handleBadArgument("symlink"));return(target,path)=>nodeSymlink(target,path)})();var truncate2=(()=>{const nodeTruncate=effectify(NFS.truncate,handleErrnoException("FileSystem","truncate"),handleBadArgument("truncate"));return(path,length)=>nodeTruncate(path,length)})();var utimes2=(()=>{const nodeUtimes=effectify(NFS.utimes,handleErrnoException("FileSystem","utime"),handleBadArgument("utime"));return(path,atime,mtime)=>nodeUtimes(path,atime,mtime)})();var watchNode=(path,info,options)=>callback3((queue)=>acquireRelease2(sync2(()=>{const directory=info.type==="Directory"?path:Path.dirname(path);const watcher=NFS.watch(path,{recursive:options?.recursive??false},(event,path)=>{if(!path)return;switch(event){case"rename":{runFork2(matchEffect2(stat2(Path.resolve(directory,path)),{onSuccess:(_)=>offer(queue,{_tag:"Create",path}),onFailure:(_)=>offer(queue,{_tag:"Remove",path})}));return}case"change":{offerUnsafe(queue,{_tag:"Update",path});return}}});watcher.on("error",(error)=>{failCauseUnsafe(queue,fail4(systemError({module:"FileSystem",_tag:"Unknown",method:"watch",pathOrDescriptor:path,cause:error})))});watcher.on("close",()=>{endUnsafe(queue)});return watcher}),(watcher)=>sync2(()=>watcher.close())).pipe(tap2(()=>sync2(()=>options?.onReady?.()))));var watch2=(backend,path,options)=>all2([stat2(path),serviceOption2(WatchBackend)]).pipe(map6(([stat,callerBackend])=>orElse(callerBackend,()=>backend).pipe(flatMap((_)=>_.register(path,stat,options)),getOrElse(()=>watchNode(path,stat,options)))),unwrap3);var writeFile2=(path,data,options)=>callback2((resume,signal)=>{try{NFS.writeFile(path,data,{signal,flag:options?.flag,mode:options?.mode},(err)=>{if(err){resume(fail6(handleErrnoException("FileSystem","writeFile")(err,[path])))}else{resume(void_3)}})}catch(err){resume(fail6(handleBadArgument("writeFile")(err)))}});var makeFileSystem=map6(serviceOption2(WatchBackend),(backend)=>make15({access:access2,chmod:chmod2,chown:chown2,copy,copyFile:copyFile2,link:link2,lstat:lstat2,makeDirectory,makeTempDirectory,makeTempDirectoryScoped,makeTempFile,makeTempFileScoped,open:open2,readDirectory,readDirectoryEntries,readFile:readFile2,readLink,realPath,remove,rename:rename2,stat:stat2,symlink:symlink2,truncate:truncate2,utimes:utimes2,watch(path,options){return watch2(backend,path,options)},writeFile:writeFile2}));var layer=effect(FileSystem)(makeFileSystem);var layer2=layer;var TypeId15="~effect/Path";var Path2=Service("effect/Path");var make16=(impl)=>Path2.of({...impl,[TypeId15]:TypeId15,resolveWithin(root,input){if(impl.parse(input).root!=="")return none2();const base=impl.resolve(root);const candidate=impl.resolve(base,input);const relative=impl.relative(base,candidate);return relative===".."||relative.startsWith(`..${impl.sep}`)||impl.isAbsolute(relative)?none2():some2(candidate)}});import*as NodePath from"path";import*as NodeUrl from"url";var fileUrlOps=(windows)=>({fromFileUrl:(url)=>try_3({try:()=>NodeUrl.fileURLToPath(url,{windows}),catch:(cause)=>new BadArgument({module:"Path",method:"fromFileUrl",cause})}),toFileUrl:(path)=>try_3({try:()=>NodeUrl.pathToFileURL(path,{windows}),catch:(cause)=>new BadArgument({module:"Path",method:"toFileUrl",cause})})});var layerPosix=succeed6(Path2)(make16({...NodePath.posix,...fileUrlOps(false)}));var layerWin32=succeed6(Path2)(make16({...NodePath.win32,...fileUrlOps(true)}));var layer3=succeed6(Path2)(make16({...NodePath,...fileUrlOps(undefined)}));var layer4=layer3;var defaultTeardown=(exit,onExit)=>{if(isSuccess3(exit))return onExit(0);if(hasInterruptsOnly2(exit.cause))return onExit(130);return onExit(getErrorExitCode(squash(exit.cause)))};var makeRunMain=(f)=>dual((args)=>isEffect2(args[0]),(effect,options)=>{const main=options?.disableErrorReporting===true?effect:tapCause2(effect,(cause)=>{if(hasInterruptsOnly2(cause))return void_3;const isReported=getErrorReported(squash(cause));return isReported?logError(cause):void_3});const teardown=options?.teardown??defaultTeardown;runFork2(withFiber2((fiber)=>{try{const keepAlive=globalThis.setInterval(constVoid,2147483647);fiber.addObserver(()=>{clearInterval(keepAlive)})}catch{}f({fiber,teardown});return main}))});var errorExitCode="~effect/Runtime/errorExitCode";var getErrorExitCode=(u)=>{if(typeof u==="object"&&u!==null&&errorExitCode in u){const code=u[errorExitCode];if(typeof code==="number"){return code}}return 1};var errorReported="~effect/Runtime/errorReported";var getErrorReported=(u)=>{if(typeof u==="object"&&u!==null&&errorReported in u){const isReported=u[errorReported];if(typeof isReported==="boolean"){return isReported}}return true};var runMain=makeRunMain(({fiber,teardown})=>{let receivedSignal=false;fiber.addObserver((exit)=>{process.removeListener("SIGINT",onSigint);process.removeListener("SIGTERM",onSigint);teardown(exit,(code)=>{if(receivedSignal||code!==0){process.exit(code)}})});function onSigint(){receivedSignal=true;fiber.interruptUnsafe(fiber.id)}process.on("SIGINT",onSigint);process.on("SIGTERM",onSigint)});var runMain2=runMain;var TypeId16="~effect/FiberSet";var isFiberSet=(u)=>hasProperty(u,TypeId16);var Proto2={[TypeId16]:TypeId16,[Symbol.iterator](){if(this.state._tag==="Closed"){return empty2()}return this.state.backing[Symbol.iterator]()},...PipeInspectableProto,toJSON(){return{_id:"FiberSet",state:this.state}}};var makeUnsafe6=(backing,deferred)=>{const self=Object.create(Proto2);self.state={_tag:"Open",backing};self.deferred=deferred;return self};var make17=()=>acquireRelease2(sync2(()=>makeUnsafe6(new Set,makeUnsafe2())),(set)=>suspend2(()=>{const state=set.state;if(state._tag==="Closed")return void_3;set.state={_tag:"Closed"};const fibers=state.backing;return interruptAll(fibers).pipe(into(set.deferred))}));var makeRuntimePromise=()=>flatMap4(make17(),(self)=>runtimePromise(self)());var internalFiberId=-1;var isInternalInterruption=toPredicate(compose(filterInterruptors,has2(internalFiberId)));var addUnsafe2=dual((args)=>isFiberSet(args[0]),(self,fiber,options)=>{if(self.state._tag==="Closed"){fiber.interruptUnsafe(internalFiberId);return}else if(self.state.backing.has(fiber)){return}self.state.backing.add(fiber);fiber.addObserver((exit)=>{if(self.state._tag==="Closed"){return}self.state.backing.delete(fiber);if(isFailure3(exit)&&(options?.propagateInterruption===true?!isInternalInterruption(exit.cause):!hasInterruptsOnly2(exit.cause))){doneUnsafe(self.deferred,exit)}})});var constInterruptedFiber=function(){let fiber=undefined;return()=>{if(fiber===undefined){fiber=runFork2(interrupt2)}return fiber}}();var runtime=(self)=>()=>map6(context2(),(services)=>{const runFork=runForkWith2(services);return(effect,options)=>{if(self.state._tag==="Closed"){return constInterruptedFiber()}const fiber=runFork(effect,options);addUnsafe2(self,fiber,options);return fiber}});var runtimePromise=(self)=>()=>map6(runtime(self)(),(runFork)=>(effect,options)=>new Promise((resolve,reject)=>runFork(effect,options).addObserver((exit)=>{if(isSuccess3(exit)){resolve(exit.value)}else{reject(squash(exit.cause))}})));var make18=()=>map6(makeRuntimePromise(),(run)=>({runPromise:(effect,options)=>run(options?.carrier===undefined?effect:withParentSpan2(effect,externalSpan({spanId:options.carrier.spanId,traceId:options.carrier.traceId})),{signal:options?.signal})}));var EdgeBridge={make:make18};var redactedRegistry=new WeakMap;var value=(self)=>{if(redactedRegistry.has(self)){return redactedRegistry.get(self)}else{throw new Error("Unable to get redacted value"+(self.label?` with label: "${self.label}"`:""))}};var TypeId17="~effect/Redacted";var isRedacted=(u)=>hasProperty(u,TypeId17);var make19=(value,options)=>{const self=Object.create(Proto3);if(options?.label){self.label=options.label}redactedRegistry.set(self,value);return self};var Proto3={[TypeId17]:{_A:(_)=>_},label:undefined,...PipeInspectableProto,toJSON(){return this.toString()},toString(){return`<redacted${isString(this.label)?":"+this.label:""}>`},[symbol](){return hash(redactedRegistry.get(this))},[symbol2](that){return isRedacted(that)&&equals(redactedRegistry.get(this),redactedRegistry.get(that))}};var value2=value;var makeEquivalence4=(isEquivalent)=>make((x,y)=>isEquivalent(value2(x),value2(y)));var TypeId18=Symbol.for("~effect/http/Headers");var Proto4=Object.defineProperties(Object.create(null),{[TypeId18]:{value:TypeId18},[symbolRedactable]:{value(context){return redact2(this,get(context,CurrentRedactedNames))}},toJSON:{value(){return redact(this)}},[symbol2]:{value(that){return Equivalence2(this,that)}},[symbol]:{value(){return structure(this)}},toString:{value:BaseProto.toString},[NodeInspectSymbol]:{value:BaseProto[NodeInspectSymbol]}});var make20=(input)=>Object.assign(Object.create(Proto4),input);var Equivalence2=makeEquivalence2(strictEqual());var empty5=Object.create(Proto4);var fromInput=(input)=>{if(input===undefined){return empty5}else if(Symbol.iterator in input){const out=Object.create(Proto4);for(const[k,v]of input){out[k.toLowerCase()]=v}return out}const out=Object.create(Proto4);for(const[k,v]of Object.entries(input)){if(Array.isArray(v)){out[k.toLowerCase()]=v.join(", ")}else if(v!==undefined){out[k.toLowerCase()]=v}}return out};var fromRecordUnsafe=(input)=>Object.setPrototypeOf(input,Proto4);var set=dual(3,(self,key,value)=>{const out=make20(self);out[key.toLowerCase()]=value;return out});var setAll=dual(2,(self,headers)=>make20({...self,...fromInput(headers)}));var merge3=dual(2,(self,headers)=>{const out=make20(self);Object.assign(out,headers);return out});var remove2=dual(2,(self,key)=>{const out=make20(self);delete out[key.toLowerCase()];return out});var redact2=dual(2,(self,key)=>{const out={...self};const modify=(key)=>{if(typeof key==="string"){const k=key.toLowerCase();if(k in self){out[k]=make19(self[k])}}else{for(const name in self){if(name.search(key)!==-1){out[name]=make19(self[name])}}}};if(Array.isArray(key)){for(let i=0;i<key.length;i++){modify(key[i])}}else{modify(key)}return out});var isRedactedName=(name,patterns)=>{const lowerName=name.toLowerCase();for(let i=0;i<patterns.length;i++){const pattern=patterns[i];if(typeof pattern==="string"){if(pattern.toLowerCase()===lowerName){return true}}else if(name.search(pattern)!==-1){return true}}return false};var CurrentRedactedNames=Reference("effect/Headers/CurrentRedactedNames",{defaultValue:()=>["authorization","cookie","set-cookie","x-api-key"]});var TypeId19="~effect/http/Cookies";var CookieTypeId="~effect/http/Cookies/Cookie";var Proto5={[TypeId19]:TypeId19,...BaseProto,toJSON(){return{_id:"effect/Cookies",cookies:map2(this.cookies,(cookie)=>cookie.toJSON())}},pipe(){return pipeArguments(this,arguments)}};var fromReadonlyRecord=(cookies)=>{const self=Object.create(Proto5);self.cookies=cookies;return self};var fromIterable2=(cookies)=>{const record={};for(const cookie of cookies){assignProperty(record,cookie.name,cookie)}return fromReadonlyRecord(record)};var fromSetCookie=(headers)=>{const arrayHeaders=typeof headers==="string"?[headers]:headers;const cookies=[];for(const header of arrayHeaders){const cookie=parseSetCookie(header.trim());if(cookie){cookies.push(cookie)}}return fromIterable2(cookies)};function parseSetCookie(header){const parts=header.split(";").map((_)=>_.trim()).filter((_)=>_!=="");if(parts.length===0){return}const firstEqual=parts[0].indexOf("=");if(firstEqual===-1){return}const name=parts[0].slice(0,firstEqual).replace(cookieWhitespaceRegExp,"");if(!cookieNameRegExp.test(name)){return}const valueEncoded=parts[0].slice(firstEqual+1).replace(cookieWhitespaceRegExp,"");const value=tryDecodeURIComponent(valueEncoded);if(parts.length===1){return Object.assign(Object.create(CookieProto),{name,value,valueEncoded})}const options={};for(let i=1;i<parts.length;i++){const part=parts[i];const equalIndex=part.indexOf("=");const key=equalIndex===-1?part:part.slice(0,equalIndex).trim();const value=equalIndex===-1?undefined:part.slice(equalIndex+1).trim();switch(key.toLowerCase()){case"domain":{if(value===undefined){break}const domain=value.trim().replace(/^\./,"");if(domain){options.domain=domain}break}case"expires":{if(value===undefined){break}const date=new Date(value);if(!isNaN(date.getTime())){options.expires=date}break}case"max-age":{if(value===undefined||!maxAgeRegExp.test(value)){break}options.maxAge=seconds(parseInt(value,10));break}case"path":{if(value===undefined){break}if(value[0]==="/"){options.path=value}break}case"priority":{if(value===undefined){break}switch(value.toLowerCase()){case"low":options.priority="low";break;case"medium":options.priority="medium";break;case"high":options.priority="high";break}break}case"httponly":{options.httpOnly=true;break}case"secure":{options.secure=true;break}case"partitioned":{options.partitioned=true;break}case"samesite":{if(value===undefined){break}switch(value.toLowerCase()){case"lax":options.sameSite="lax";break;case"strict":options.sameSite="strict";break;case"none":options.sameSite="none";break}break}}}return Object.assign(Object.create(CookieProto),{name,value,valueEncoded,options:Object.keys(options).length>0?options:undefined})}var cookieNameRegExp=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;var cookieWhitespaceRegExp=/^[\t ]+|[\t ]+$/g;var maxAgeRegExp=/^-?[0-9]+$/;var CookieProto={[CookieTypeId]:CookieTypeId,...BaseProto,toJSON(){return{_id:"effect/Cookies/Cookie",name:this.name,value:this.value,options:this.options}}};var tryDecodeURIComponent=(str)=>{try{return decodeURIComponent(str)}catch(_){return str}};var encode=(input)=>encodeBytes(typeof input==="string"?encoder.encode(input):input);var decode=(str)=>{const stripped=stripCrlf(str);const length=stripped.length;if(length%4!==0){return fail2(new EncodingError({kind:"Decode",module:"Base64",input:stripped,message:`Length must be a multiple of 4, but is ${length}`}))}const index=stripped.indexOf("=");if(index!==-1&&(index<length-2||index===length-2&&stripped[length-1]!=="=")){return fail2(new EncodingError({kind:"Decode",module:"Base64",input:stripped,message:"Found a '=' character, but it is not at the end"}))}try{const missingOctets=stripped.endsWith("==")?2:stripped.endsWith("=")?1:0;const result=new Uint8Array(3*(length/4)-missingOctets);for(let i=0,j=0;i<length;i+=4,j+=3){const buffer=getCode(stripped.charCodeAt(i))<<18|getCode(stripped.charCodeAt(i+1))<<12|getCode(stripped.charCodeAt(i+2))<<6|getCode(stripped.charCodeAt(i+3));result[j]=buffer>>16;result[j+1]=buffer>>8&255;result[j+2]=buffer&255}return succeed2(result)}catch(cause){return fail2(new EncodingError({kind:"Decode",module:"Base64",input:stripped,message:cause instanceof Error?cause.message:"Invalid input"}))}};var encodeBytes=(bytes)=>{const length=bytes.length;const toBase64=Uint8Array.prototype.toBase64;if(length>=32&&typeof toBase64==="function")return toBase64.call(bytes);return length<128?encodeShort(bytes):encodeLong(bytes)};var encodeShort=(bytes)=>{const length=bytes.length;let result="";let i;for(i=2;i<length;i+=3){result+=alphabet[bytes[i-2]>>2];result+=alphabet[(bytes[i-2]&3)<<4|bytes[i-1]>>4];result+=alphabet[(bytes[i-1]&15)<<2|bytes[i]>>6];result+=alphabet[bytes[i]&63]}if(i===length+1){result+=alphabet[bytes[i-2]>>2];result+=alphabet[(bytes[i-2]&3)<<4];result+="=="}if(i===length){result+=alphabet[bytes[i-2]>>2];result+=alphabet[(bytes[i-2]&3)<<4|bytes[i-1]>>4];result+=alphabet[(bytes[i-1]&15)<<2];result+="="}return result};var encodeLong=(bytes)=>{const length=bytes.length;const result=new Uint8Array(Math.ceil(length/3)*4);let i;let j=0;for(i=2;i<length;i+=3,j+=4){result[j]=alphabetCodes[bytes[i-2]>>2];result[j+1]=alphabetCodes[(bytes[i-2]&3)<<4|bytes[i-1]>>4];result[j+2]=alphabetCodes[(bytes[i-1]&15)<<2|bytes[i]>>6];result[j+3]=alphabetCodes[bytes[i]&63]}if(i===length+1){result[j]=alphabetCodes[bytes[i-2]>>2];result[j+1]=alphabetCodes[(bytes[i-2]&3)<<4];result[j+2]=paddingCode;result[j+3]=paddingCode}if(i===length){result[j]=alphabetCodes[bytes[i-2]>>2];result[j+1]=alphabetCodes[(bytes[i-2]&3)<<4|bytes[i-1]>>4];result[j+2]=alphabetCodes[(bytes[i-1]&15)<<2];result[j+3]=paddingCode}return decoder.decode(result)};var encoder=new TextEncoder;var decoder=new TextDecoder;var stripCrlf=(str)=>str.replace(/[\n\r]/g,"");var alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var alphabetCodes=encoder.encode(alphabet);var paddingCode=61;var codes=new Uint8Array(123).fill(255);for(let i=0;i<alphabet.length;i++)codes[alphabet.charCodeAt(i)]=i;codes[61]=0;var getCode=(charCode)=>{if(charCode>=codes.length||codes[charCode]===255){throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`)}return codes[charCode]};var unwrap4=(value)=>typeof value==="string"?value:value2(value);var bodyDecoder=new TextDecoder("utf-8",{ignoreBOM:true});var fromBody=(bytes)=>new URLSearchParams(bodyDecoder.decode(bytes).replace(/^\?/,"%3F"));var TypeId20="~effect/http/UrlParams";var isUrlParams=(u)=>hasProperty(u,TypeId20);var Proto6={...PipeInspectableProto,[TypeId20]:TypeId20,[Symbol.iterator](){return this.params[Symbol.iterator]()},[symbolRedactable](context){return{_id:"UrlParams",params:Object.fromEntries(redact3(this,get(context,CurrentRedactedNames2)))}},toJSON(){return redact(this)},[symbol2](that){return Equivalence3(this,that)},[symbol](){return array(this.params.flat())}};var make21=(params)=>{const self=Object.create(Proto6);self.params=params;return self};var fromInput2=(input)=>{if(isUrlParams(input)){return input}const parsed=fromInputNested(input);const out=[];for(let i=0;i<parsed.length;i++){if(Array.isArray(parsed[i][0])){const[keys,value]=parsed[i];out.push([`${keys[0]}[${keys.slice(1).join("][")}]`,value])}else{out.push(parsed[i])}}return make21(out)};var fromInputNested=(input)=>{const entries=typeof input[Symbol.iterator]==="function"?fromIterable(input):Object.entries(input);const out=[];for(const[key,value]of entries){if(Array.isArray(value)){for(let i=0;i<value.length;i++){if(value[i]!==undefined){out.push([key,coerce(value[i])])}}}else if(value!==null&&typeof value==="object"&&!isRedacted(value)){const nested=fromInputNested(value);for(const[k,v]of nested){out.push([[key,...typeof k==="string"?[k]:k],v])}}else if(value!==undefined){out.push([key,coerce(value)])}}return out};var coerce=(value)=>isRedacted(value)?value:String(value);var Equivalence3=make((a,b)=>arrayEquivalence(a.params,b.params));var arrayEquivalence=makeEquivalence3(makeEquivalence([strictEqual(),asEquivalence()]));var empty6=make21([]);var setAll2=dual(2,(self,input)=>{const params=fromInput2(input).params.slice();const keys=new Set;for(let i=0;i<params.length;i++){keys.add(params[i][0])}for(let i=0;i<self.params.length;i++){if(keys.has(self.params[i][0]))continue;params.push(self.params[i])}return make21(params)});var redact3=dual(2,(self,key)=>{const patterns=Array.isArray(key)?key:[key];return self.params.map(([name,value])=>[name,typeof value==="string"&&isRedactedName2(name,patterns)?make19(value):value])});var isRedactedName2=isRedactedName;var redactUrl=(url,redactedNames=currentRedactedNames())=>{if(url.includes("@"))url=redactUserinfo(url);const queryStart=url.indexOf("?");if(queryStart===-1||redactedNames.length===0)return url;const hashStart=url.indexOf("#");if(hashStart!==-1&&hashStart<queryStart)return url;const queryEnd=hashStart===-1?url.length:hashStart;return url.slice(0,queryStart+1)+redactQuery(url.slice(queryStart+1,queryEnd),redactedNames)+url.slice(queryEnd)};var authorityStart=/^(?:(https?|ftp|wss?):[/\\]*|[a-z][a-z\d+.-]*:\/\/|[/\\]{2,})/i;var specialAuthorityEnd=/[/\\?#]/;var authorityEnd=/[/?#]/;var redactUserinfo=(url)=>{let normalized="";const offsets=[];for(let i=0;i<url.length;i++){const code=url.charCodeAt(i);if(code===9||code===10||code===13||normalized===""&&code<=32)continue;normalized+=url[i];offsets.push(i)}const authority=authorityStart.exec(normalized);if(authority===null)return url;const start=authority[0].length;const special=authority[1]!==undefined||!authority[0].includes(":");const rest=normalized.slice(start);const end=rest.search(special?specialAuthorityEnd:authorityEnd);const userinfoEnd=(end===-1?rest:rest.slice(0,end)).lastIndexOf("@");return userinfoEnd===-1?url:url.slice(0,offsets[start])+"REDACTED:REDACTED"+url.slice(offsets[start+userinfoEnd])};var redactQuery=(query,redactedNames)=>query.split("&").map((part)=>{const index=part.indexOf("=");return index!==-1&&isRedactedName2(decodeQueryKey(part.slice(0,index)),redactedNames)?part.slice(0,index+1)+"REDACTED":part}).join("&");var decodeQueryKey=(key)=>{if(!key.includes("%")&&!key.includes("+"))return key;try{return decodeURIComponent(key.replace(/\+/g," "))}catch{return key}};var currentRedactedNames=()=>get(globalThis[currentFiberTypeId]?.context??empty(),CurrentRedactedNames2);var CurrentRedactedNames2=Reference("effect/http/UrlParams/CurrentRedactedNames",{defaultValue:()=>["X-Amz-Signature","X-Amz-Credential","X-Amz-Security-Token","AWSAccessKeyId","Signature","sig","X-Goog-Signature"]});function resolve2(ast){return ast.checks?ast.checks[ast.checks.length-1].annotations:ast.annotations}var STRUCTURAL_ANNOTATION_KEY="~structural";var SENTINELS_ANNOTATION_KEY="~sentinels";var CONSTRUCTOR_ANNOTATION_KEY="~constructor";var getExpected=memoize((ast)=>{const identifier=resolve2(ast)?.identifier;if(typeof identifier==="string")return identifier;return ast.getExpected(getExpected)});var missing=Symbol();var succeed9=succeed4;var missingExit=succeed9(missing);var sameExit=succeed9(missing);var toOption=(value)=>value===missing?none2():some2(value);var fromOptionExit=(option)=>option._tag==="None"?missingExit:succeed9(option.value);var TypeId21="~effect/SchemaIssue/Issue";function isIssue(u){return hasProperty(u,TypeId21)&&u[TypeId21]===TypeId21}function hasInput(issue){return Object.hasOwn(issue,"input")}class IssueNodeImpl{[TypeId21]=TypeId21;constructor(input,options){if(options?.reportInput===true&&input!==missing){this.input=input}}}var Filter=class extends IssueNodeImpl{_tag="Filter";filter;issue;constructor(filter,issue,input,options){super(input,options);this.filter=filter;this.issue=issue}};var Encoding=class extends IssueNodeImpl{_tag="Encoding";ast;issue;constructor(ast,issue,input,options){super(input,options);this.ast=ast;this.issue=issue}};var Pointer=class extends IssueNodeImpl{_tag="Pointer";path;issue;constructor(path,issue){super();this.path=path;this.issue=issue}};var MissingKey=class extends IssueNodeImpl{_tag="MissingKey";annotations;constructor(annotations){super();this.annotations=annotations}};var UnexpectedKey=class extends IssueNodeImpl{_tag="UnexpectedKey";ast;constructor(ast,input,options){super(input,options);this.ast=ast}};var Composite=class extends IssueNodeImpl{_tag="Composite";ast;issues;constructor(ast,issues,input,options){super(input,options);this.ast=ast;this.issues=issues}};var InvalidType=class extends IssueNodeImpl{_tag="InvalidType";ast;constructor(ast,input,options){super(input,options);this.ast=ast}};var InvalidValue=class extends IssueNodeImpl{_tag="InvalidValue";annotations;constructor(annotations,input,options){super(input,options);this.annotations=annotations}};var Forbidden=class extends IssueNodeImpl{_tag="Forbidden";annotations;constructor(annotations,input,options){super(input,options);this.annotations=annotations}};var AnyOf=class extends IssueNodeImpl{_tag="AnyOf";ast;issues;constructor(ast,issues,input,options){super(input,options);this.ast=ast;this.issues=issues}};var OneOf=class extends IssueNodeImpl{_tag="OneOf";ast;successes;constructor(ast,successes,input,options){super(input,options);this.ast=ast;this.successes=successes}};function makeFilterIssue(entry,input,options){if(isIssue(entry)){return entry}if(typeof entry==="string"){return new InvalidValue({message:entry},input,options)}const inner=typeof entry.issue==="string"?new InvalidValue({message:entry.issue},input,options):entry.issue;return new Pointer(entry.path,inner)}function makeSingle(out,input,options){if(out===undefined){return}if(typeof out==="boolean"){return out?undefined:new InvalidValue(undefined,input,options)}return makeFilterIssue(out,input,options)}function normalizeFilterOutput(ast,out,input,options){if(Array.isArray(out)){if(!isReadonlyArrayNonEmpty(out)){return}return out.length===1?makeFilterIssue(out[0],input,options):new Composite(ast,map3(out,(entry)=>makeFilterIssue(entry,input,options)),input,options)}return makeSingle(out,input,options)}var defaultLeafHook=(issue)=>{const message=findMessage(issue);if(message!==undefined)return message;switch(issue._tag){case"InvalidType":return getExpectedMessage(getExpected(issue.ast),issue);case"InvalidValue":{const expected=findExpected(issue);if(expected!==undefined)return getExpectedMessage(expected,issue);const input=formatInput(issue);return input===undefined?"Expected a valid value":`Invalid data ${input}`}case"MissingKey":return"Missing key";case"UnexpectedKey":{const input=formatInput(issue);return input===undefined?"Expected no excess property":`Unexpected key with value ${input}`}case"Forbidden":return"Forbidden operation";case"OneOf":{const input=formatInput(issue);return input===undefined?"Expected exactly one member to match":`Expected exactly one member to match the input ${input}`}}};var defaultCheckHook=(issue)=>findMessage(issue)??findMessage(issue.issue);function formatInput(issue){return hasInput(issue)?format(issue.input):undefined}function findExpected(issue){const expected=issue.annotations?.expected;return typeof expected==="string"?expected:undefined}function getExpectedMessage(expected,issue){const input=formatInput(issue);return input===undefined?`Expected ${expected}`:`Expected ${expected}, got ${input}`}function getFilterMessage(issue,checkHook){const message=checkHook(issue);if(message!==undefined||issue.issue._tag!=="InvalidValue")return message;const expected=findExpected(issue.issue);return expected===undefined?getExpectedMessage(formatCheck(issue.filter),issue):getExpectedMessage(expected,issue.issue)}function formatCheck(check){const expected=check.annotations?.expected;if(typeof expected==="string")return expected;switch(check._tag){case"Filter":return"<filter>";case"FilterGroup":return check.checks.map((check)=>formatCheck(check)).join(" & ")}}function makeFormatterDefault(){return(issue)=>formatIssue(issue,"")}var defaultFormatter=makeFormatterDefault();function formatIssue(issue,path,messageOverride){let message;switch(issue._tag){case"Filter":return formatIssue(issue.issue,path,messageOverride??getFilterMessage(issue,defaultCheckHook));case"Encoding":return formatIssue(issue.issue,path,messageOverride);case"Pointer":return formatIssue(issue.issue,path+formatPath(issue.path),messageOverride);case"Composite":case"AnyOf":{if(issue._tag==="Composite"||issue.issues.length>0){return issue.issues.map((issue)=>formatIssue(issue,path,messageOverride)).join(`
|
|
237
237
|
`)}message=messageOverride??findMessage(issue)??getExpectedMessage(getExpected(issue.ast),issue);break}default:message=messageOverride??defaultLeafHook(issue);break}return path?`${message}
|
|
238
|
-
at ${path}`:message}function findMessage(issue){if(issue._tag==="Pointer"||issue._tag==="Composite")return;if(issue._tag==="Encoding")return findMessage(issue.issue);const annotations=issue._tag==="Filter"?issue.filter.annotations:("annotations"in issue)?issue.annotations:issue.ast.annotations;const message=annotations?.[issue._tag==="MissingKey"?"messageMissingKey":issue._tag==="UnexpectedKey"?"messageUnexpectedKey":"message"];if(typeof message==="string")return message}function getSchemaIssue(cause){let issue;for(const reason of cause.reasons){if(!isFailReason2(reason)||!isIssue(reason.error)){return}issue??=reason.error}return issue}function getSchemaIssueOrThrow(cause,message){const issue=getSchemaIssue(cause);if(issue===undefined){throw new Error(message,{cause})}return issue}var makeGetter=(fields)=>Object.assign(Object.create(Prototype),fields);function fail10(f){return transformOptionalEffect((oe,options)=>fail6(f(oe,options)))}function forbidden(message){return fail10((oe,options)=>{const annotations={message:message(oe)};return isSome2(oe)?new Forbidden(annotations,oe.value,options):new Forbidden(annotations)})}var passthrough_=makeGetter({_tag:"Passthrough"});function passthrough(){return passthrough_}function transform(f){return makeGetter({_tag:"Transform",transform:f})}function transformEffect(f){return makeGetter({_tag:"TransformEffect",transform:f})}function transformOptionalEffect(f){return makeGetter({_tag:"TransformOptionalEffect",transform:f})}function String3(){return transform(globalThis.String)}function Number3(){return transform(globalThis.Number)}function parseJson(options){return transformEffect((input,parseOptions)=>try_3({try:()=>JSON.parse(input,options?.reviver),catch:()=>new InvalidValue({expected:"a valid JSON string"},input,parseOptions)}))}function stringifyJson(options){return transformEffect((input,parseOptions)=>try_3({try:()=>{const output=JSON.stringify(input,options?.replacer,options?.space);if(output===undefined){throw new TypeError("Value cannot be represented as JSON")}return output},catch:()=>new InvalidValue({expected:"a JSON-serializable value"},input,parseOptions)}))}function encodeBase64(){return transform(encode)}function decodeBase64(){return transformEffect((input,options)=>mapErrorEager2(fromResult2(decode(input)),()=>new InvalidValue({expected:"a valid Base64 string"},input,options)))}var ContentTypeId=Symbol.for("~effect/Schema/content");function setContent(operation,content){Object.defineProperty(operation,ContentTypeId,{value:content});return operation}var TypeId22="~effect/SchemaTransformation/Transformation";var Transformation=class extends Class{[TypeId22]=TypeId22;_tag="Transformation";decode;encode;constructor(decode,encode){super();this.decode=decode;this.encode=encode}flip(){return new Transformation(this.encode,this.decode)}};function isTransformation(u){return hasProperty(u,TypeId22)&&u[TypeId22]===TypeId22}var makeTransformation=(options)=>{if(isTransformation(options)){return options}return new Transformation(options.decode,options.encode)};function transformEffect2(options){return new Transformation(transformEffect(options.decode),transformEffect(options.encode))}function transform2(options){return new Transformation(transform(options.decode),transform(options.encode))}var passthrough_2=new Transformation(passthrough(),passthrough());function passthrough2(){return passthrough_2}var numberFromString=new Transformation(Number3(),String3());var urlFromString=transformEffect2({decode:(s,options)=>URL.canParse(s)?succeed7(new URL(s)):fail6(new InvalidValue({expected:"a valid URL string"},s,options)),encode:(url)=>succeed7(url.href)});var uint8ArrayFromBase64String=new Transformation(decodeBase64(),encodeBase64());function fromJsonString(options){return new Transformation(parseJson(options??{}),setContent(stringifyJson(options),{mediaType:"application/json",preserveSchema:options?.reviver===undefined&&options?.replacer===undefined}))}function makeGuard(tag){return(ast)=>ast._tag===tag}var isDeclaration=makeGuard("Declaration");var isNever2=makeGuard("Never");var isLiteral=makeGuard("Literal");var isUniqueSymbol=makeGuard("UniqueSymbol");var isArrays=makeGuard("Arrays");var isObjects=makeGuard("Objects");var isSuspend=makeGuard("Suspend");var Link=class{to;transformation;constructor(to,transformation){this.to=to;this.transformation=transformation}};var defaultParseOptions={};var Context=class{isOptional;isMutable;constructorDefault;annotations;constructor(isOptional,isMutable,constructorDefault=undefined,annotations=undefined){this.isOptional=isOptional;this.isMutable=isMutable;this.constructorDefault=constructorDefault;this.annotations=annotations}};var TypeId23="~effect/Schema";class ASTNodeImpl{[TypeId23]=TypeId23;annotations;checks;encoding;context;constructor(annotations=undefined,checks=undefined,encoding=undefined,context=undefined){this.annotations=annotations;this.checks=checks;this.encoding=encoding;this.context=context}toString(){return`<${this._tag}>`}}var Declaration=class extends ASTNodeImpl{_tag="Declaration";typeParameters;run;encodingChecks;encodingRun;constructor(typeParameters,run,annotations,checks,encoding,context,encodingChecks,encodingRun){super(annotations,checks,encoding,context);this.typeParameters=typeParameters;this.run=run;this.encodingChecks=encodingChecks;this.encodingRun=encodingRun}getParser(){let run;return(input,options)=>{if(input===missing)return missingExit;run??=this.run(this.typeParameters);try{return run(input,this,options)}catch(error){return die3(error)}}}_rebuild(recur,checks,encodingChecks,run,encodingRun){const tps=mapOrSame(this.typeParameters,recur);return tps===this.typeParameters&&checks===this.checks&&encodingChecks===this.encodingChecks&&run===this.run&&encodingRun===this.encodingRun?this:new Declaration(tps,run,this.annotations,checks,undefined,this.context,encodingChecks,encodingRun)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){const expected=this.annotations?.expected;if(typeof expected==="string")return expected;return"<Declaration>"}};var Null=class extends ASTNodeImpl{_tag="Null";getParser(){return fromConst(this,null)}getExpected(){return"null"}};var null_=new Null;var Undefined=class extends ASTNodeImpl{_tag="Undefined";getParser(){return fromConst(this,undefined)}toCodecJson(){return replaceEncoding(this,[undefinedToNull])}getExpected(){return"undefined"}};var undefinedToNull=new Link(null_,new Transformation(transform(()=>{return}),transform(()=>null)));var undefined_2=new Undefined;var Unknown=class extends ASTNodeImpl{_tag="Unknown";getParser(){return fromRefinement(this,isUnknown)}getExpected(){return"unknown"}};var unknown=new Unknown;var Literal=class extends ASTNodeImpl{_tag="Literal";literal;constructor(literal,annotations,checks,encoding,context){super(annotations,checks,encoding,context);if(typeof literal==="number"&&!globalThis.Number.isFinite(literal)){throw new Error(`A numeric literal must be finite, got ${format(literal)}`)}this.literal=literal}getParser(){return fromConst(this,this.literal)}matchPart(s,_options){return s===globalThis.String(this.literal)?this.literal:undefined}toCodecJson(){return typeof this.literal==="bigint"?literalToString(this):this}toCodecStringTree(){return typeof this.literal==="string"?this:literalToString(this)}getExpected(){return typeof this.literal==="string"?JSON.stringify(this.literal):globalThis.String(this.literal)}};function literalToString(ast){const literalAsString=globalThis.String(ast.literal);return replaceEncoding(ast,[new Link(new Literal(literalAsString),new Transformation(transform(()=>ast.literal),transform(()=>literalAsString)))])}var String4=class extends ASTNodeImpl{_tag="String";getParser(){return fromRefinement(this,isString)}matchPart(s,options){const checks=this.checks;return checks&&!options.disableChecks&&collectIssues(checks,s,undefined,this,options)?undefined:s}getExpected(){return"string"}};var string2=new String4;var Number4=class extends ASTNodeImpl{_tag="Number";getParser(){return fromRefinement(this,isNumber)}matchKey(s,options){return this._match(isStringNumberRegExp,s,options)}matchPart(s,options){return this._match(isStringFiniteRegExp,s,options)}_match(regexp,s,options){if(!regexp.test(s))return;const value=globalThis.Number(s);if(options.disableChecks||!this.checks)return value;return collectIssues(this.checks,value,undefined,this,options)?undefined:value}toCodecJson(){if(this.checks&&(hasCheck(this.checks,"effect/schema/isFinite")||hasCheck(this.checks,"effect/schema/isInt"))){return this}return replaceEncoding(this,[numberToJson])}toCodecStringTree(){if(this.toCodecJson()===this){return replaceEncoding(this,[finiteToString])}return replaceEncoding(this,[numberToString])}getExpected(){return"number"}};function hasCheck(checks,id){return checks.some((check)=>check.annotations?.representation?.id===id||check._tag==="FilterGroup"&&hasCheck(check.checks,id))}var number2=new Number4;var Boolean2=class extends ASTNodeImpl{_tag="Boolean";getParser(){return fromRefinement(this,isBoolean)}getExpected(){return"boolean"}};var boolean=new Boolean2;var Arrays=class extends ASTNodeImpl{_tag="Arrays";isMutable;elements;rest;encodingChecks;constructor(isMutable,elements,rest,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.isMutable=isMutable;this.elements=elements;this.rest=rest;this.encodingChecks=encodingChecks;let hasOptional=false;for(let i=0;i<elements.length;i++){if(isOptional(elements[i])){hasOptional=true}else if(hasOptional){throw new Error("A required element cannot follow an optional element. ts(1257)")}}if(hasOptional&&rest.length>1){throw new Error("A required element cannot follow an optional element. ts(1257)")}for(let i=1;i<rest.length;i++){if(isOptional(rest[i])){throw new Error("An optional element cannot follow a rest element. ts(1266)")}}}getParser(compile,compileField=compile){const ast=this;let elements;let rest;const elementLen=ast.elements.length;const tailLen=Math.max(0,ast.rest.length-1);function getParser(tailThreshold,index){if(index<elementLen){return elements[index]}else if(index>=tailThreshold){return rest[index-tailThreshold+1]}return rest[0]}const finish=(state)=>{const{input,len,options}=state;if(ast.rest.length===0&&len>elementLen){for(let i=elementLen;i<len;i++){const unexpected=new UnexpectedKey(ast,input[i],options);const issue=new Pointer([i],unexpected);if(options.errors==="all"){if(state.issues)state.issues.push(issue);else state.issues=[issue]}else{return fail6(new Composite(ast,[issue],input,options))}}}if(state.issues){return fail6(new Composite(ast,state.issues,input,options))}return succeed9(state.output)};const parse=(input,options)=>{const len=input.length;const state={ast,getParser,input,len,tailThreshold:Math.max(elementLen,len-tailLen),output:[],issues:undefined,options};const end=ast.rest.length===0?elementLen:Math.max(len,elementLen+tailLen);const concurrency=options.concurrency===undefined?1:resolveConcurrency(options.concurrency);const eff=concurrency===1?parseArray(state,input,0,end):parseArrayConcurrent(state,input,{concurrency,end});if(!eff)return finish(state);if(effectIsExit(eff))return flatMapEager2(eff,()=>finish(state));let first=true;return suspend2(()=>{if(!first)return parse(input,options);first=false;return flatMap4(eff,()=>finish(state))})};return(input,options)=>{if(input===missing)return missingExit;try{if(!Array.isArray(input)){return fail6(new InvalidType(ast,input,options))}if(!elements){elements=ast.elements.map((ast)=>({ast,parser:compileField(ast)}));rest=ast.rest.map((ast)=>({ast,parser:compileField(ast)}))}return parse(input,options)}catch(error){return die3(error)}}}_rebuild(recur,checks,encodingChecks){const elements=mapOrSame(this.elements,recur);const rest=mapOrSame(this.rest,recur);return elements===this.elements&&rest===this.rest&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Arrays(this.isMutable,elements,rest,this.annotations,checks,undefined,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}getExpected(){return"array"}};function stepArray(s,item,exit,i){if(exit._tag==="Failure"){return wrapPropertyKeyIssue(s,s.ast,i,exit)}const value=exit===sameExit?item:exit[args];if(value!==missing){s.output[i]=value}else{const p=s.getParser(s.tailThreshold,i);if(isOptional(p.ast))return;const issue=new Pointer([i],new MissingKey(p.ast.context?.annotations));if(s.options.errors==="all"){if(s.issues)s.issues.push(issue);else s.issues=[issue]}else{return fail5(new Composite(s.ast,[issue],s.input,s.options))}}}var parseArrayOptions={onItem(s,item,i){const value=i<s.len?item:missing;return s.getParser(s.tailThreshold,i).parser(value,s.options)},step:stepArray};var parseArray=iterateEager()(parseArrayOptions);var parseArrayConcurrent=iterateConcurrent()(parseArrayOptions);var wrapPropertyKeyIssue=(s,ast,key,exit)=>{if(exit.cause.reasons.length===0){return exit}const issue=getSchemaIssue(exit.cause);if(issue===undefined){return failCause2(map5(exit.cause,(issue)=>new Composite(ast,[new Pointer([key],issue)],s.input,s.options)))}const pointer=new Pointer([key],issue);if(s.options.errors==="all"){if(s.issues)s.issues.push(pointer);else s.issues=[pointer]}else{return fail5(new Composite(ast,[pointer],s.input,s.options))}};var FINITE_PATTERN="[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?";function getIndexSignatureKeys(input,parameter,options=defaultParseOptions){let stringKeys;let symbolKeys;function go(parameter){switch(parameter._tag){case"String":case"TemplateLiteral":return(stringKeys??=Object.keys(input)).filter((k)=>parameter.matchPart(k,options)!==undefined);case"Number":return(stringKeys??=Object.keys(input)).filter((k)=>parameter.matchKey(k,options)!==undefined);case"Symbol":return(symbolKeys??=Object.getOwnPropertySymbols(input)).filter((k)=>Object.prototype.propertyIsEnumerable.call(input,k)&¶meter.matchKey(k,options)!==undefined);case"Union":return[...new Set(parameter.types.flatMap(go))];default:return[]}}return go(parameterFromPropertyKey(toEncoded(parameter)))}var PropertySignature=class{name;type;constructor(name,type){this.name=name;this.type=type}};function isIndexSignatureParameterSide(ast){switch(ast._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return true;case"Union":return ast.types.every(isIndexSignatureParameterSide);default:return false}}function isIndexSignatureParameterEncodedSide(ast){const encoded=getLastEncoding(ast);switch(encoded._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return true;case"Union":return encoded.types.every(isIndexSignatureParameterEncodedSide);default:return false}}function isIndexSignatureParameter(ast){return isIndexSignatureParameterSide(ast)&&isIndexSignatureParameterEncodedSide(ast)}var IndexSignature=class{parameter;type;constructor(parameter,type){if(!isIndexSignatureParameter(parameter)){throw new Error(`Invalid index signature parameter ${parameter._tag}`)}this.parameter=parameter;this.type=type;if(isOptional(type)||type.encoding!==undefined&&isOptional(toEncoded(type))){throw new Error("Cannot use `Schema.optionalKey` or `Schema.optional` with index signatures. Index signatures already allow keys to be absent; use `Schema.UndefinedOr` to allow `undefined` values.")}}};var Objects=class extends ASTNodeImpl{_tag="Objects";propertySignatures;indexSignatures;encodingChecks;constructor(propertySignatures,indexSignatures,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.propertySignatures=propertySignatures;this.indexSignatures=indexSignatures;this.encodingChecks=encodingChecks}getParser(compile,compileField=compile){const ast=this;const hasProperties=ast.propertySignatures.length;const indexCount=ast.indexSignatures.length;if(!hasProperties&&!indexCount){return fromRefinement(ast,isNotNullish)}let properties;let indexes;const compileMembers=()=>{if(!properties){properties=ast.propertySignatures.map((ps)=>({parser:compileField(ps.type),name:ps.name,type:ps.type}));indexes=indexCount?ast.indexSignatures.map((is)=>({is,parserKey:compile(parameterFromPropertyKey(is.parameter)),parserValue:compileField(is.type)})):undefined}return properties};const makeFallback=()=>{const expectedKeys=new Set(ast.propertySignatures.map((ps)=>typeof ps.name==="number"?globalThis.String(ps.name):ps.name));const finishIndex=(s,key,k2,inputValue,exitValue)=>{if(exitValue._tag==="Failure"){return wrapPropertyKeyIssue(s,ast,key,exitValue)??void_2}const value=exitValue===sameExit?inputValue:exitValue[args];if(k2!==missing&&value!==missing){if(hasProperties&&(expectedKeys.has(key)||expectedKeys.has(typeof k2==="number"?globalThis.String(k2):k2)))return void_2;assignProperty(s.out,k2,value)}return void_2};const parseIndex=(s,key,index,exitKey)=>{if(!exitKey){const eff=index.parserKey(key,s.options);if(!effectIsExit(eff)){return flatMap4(exit2(eff),(exit)=>parseIndex(s,key,index,exit))}exitKey=eff}if(exitKey._tag==="Failure"){return wrapPropertyKeyIssue(s,ast,key,exitKey)??void_2}const k2=exitKey===sameExit?key:exitKey[args];const inputValue=s.input[key];const result=index.parserValue(inputValue,s.options);return effectIsExit(result)?finishIndex(s,key,k2,inputValue,result):flatMap4(exit2(result),(exit)=>finishIndex(s,key,k2,inputValue,exit))};const parseStringIndex=(s,key,index)=>{const inputValue=s.input[key];const result=index.parserValue(inputValue,s.options);return effectIsExit(result)?finishIndex(s,key,key,inputValue,result):flatMap4(exit2(result),(exit)=>finishIndex(s,key,key,inputValue,exit))};const parseIndexes=indexCount?iterateConcurrent()({onItem:(s,[key,index])=>index.is.parameter===string2?parseStringIndex(s,key,index):parseIndex(s,key,index),step:(_s,_item,exit)=>exit._tag==="Failure"?exit:undefined}):undefined;return fnUntracedEager2(function*(input,options){if(input===missing){return missing}if(!(typeof input==="object"&&input!==null&&!Array.isArray(input))){return yield*fail6(new InvalidType(ast,input,options))}compileMembers();const record=input;const out={};const state={ast,input:record,out,issues:undefined,options};const errorsAllOption=options.errors==="all";const onExcessPropertyError=options.onExcessProperty==="error";const concurrency=options.concurrency===undefined?1:resolveConcurrency(options.concurrency);const indexKeys=indexCount&&onExcessPropertyError?ast.indexSignatures.map((index)=>getIndexSignatureKeys(record,index.parameter,options)):undefined;if(onExcessPropertyError){const coveredKeys=indexKeys?new Set(expectedKeys):expectedKeys;if(indexKeys){for(const keys of indexKeys){for(const key of keys)coveredKeys.add(key)}}const inputKeys=Reflect.ownKeys(record);for(let i=0;i<inputKeys.length;i++){const key=inputKeys[i];if(!coveredKeys.has(key)&&Object.prototype.propertyIsEnumerable.call(record,key)){const unexpected=new UnexpectedKey(ast,record[key],options);const issue=new Pointer([key],unexpected);if(errorsAllOption){if(state.issues){state.issues.push(issue)}else{state.issues=[issue]}continue}else{return yield*fail6(new Composite(ast,[issue],input,options))}}}}if(hasProperties){const eff=concurrency===1?parseProperties(state,properties):parsePropertiesConcurrent(state,properties,{concurrency});if(eff)yield*eff}if(indexCount&&concurrency===1){for(let i=0;i<indexCount;i++){const index=indexes[i];const parse=index.is.parameter===string2?parseStringIndex:parseIndex;const keys=indexKeys?.[i]??(index.is.parameter===string2?Object.keys(record):getIndexSignatureKeys(record,index.is.parameter,options));for(let j=0;j<keys.length;j++){const eff=parse(state,keys[j],index);if(!effectIsExit(eff))yield*eff;else if(eff._tag==="Failure")return yield*eff}}}else if(parseIndexes){const keyPairs=empty3();for(let i=0;i<indexCount;i++){const index=indexes[i];const keys=indexKeys?.[i]??(index.is.parameter===string2?Object.keys(record):getIndexSignatureKeys(record,index.is.parameter,options));for(let j=0;j<keys.length;j++){keyPairs.push([keys[j],index])}}const eff=parseIndexes(state,keyPairs,{concurrency});if(eff)yield*eff}if(state.issues){return yield*fail6(new Composite(ast,state.issues,input,options))}return out})};if(indexCount)return makeFallback();let fallback;const resume=(snapshot,index,pending)=>{const property=properties[index];return flatMap4(exit2(pending),(exit)=>{const state={...snapshot,out:{...snapshot.out}};const terminal=stepProperty(state,property,exit);if(terminal)return terminal;const done=()=>succeed9(state.out);const eff=parseProperties(state,properties.slice(index+1));return eff?flatMapEager2(eff,done):done()})};return(input,options)=>{if(input===missing)return missingExit;if(options.errors==="all"||options.onExcessProperty!==undefined||options.concurrency!==undefined&&resolveConcurrency(options.concurrency)!==1){return(fallback??=makeFallback())(input,options)}if(!(typeof input==="object"&&input!==null&&!Array.isArray(input))){return fail6(new InvalidType(ast,input,options))}const props=compileMembers();const record=input;const out={};const state={ast,input:record,out,issues:undefined,options};try{for(let index=0;index<props.length;index++){const property=props[index];const name=property.name;const hasKey=hasPropertySignature(record,name);const value=hasKey?record[name]:missing;const exit=property.parser(value,options);if(!effectIsExit(exit)){return resume(state,index,exit)}if(exit===sameExit){if(hasKey)assignProperty(out,name,value);continue}const terminal=stepProperty(state,property,exit);if(terminal)return terminal}}catch(error){return die3(error)}return succeed9(out)}}_rebuild(recur,recurParameter,checks,encodingChecks){const props=mapOrSame(this.propertySignatures,(ps)=>{const t=recur(ps.type);return t===ps.type?ps:new PropertySignature(ps.name,t)});const indexes=mapOrSame(this.indexSignatures,(is)=>{const p=recurParameter(is.parameter);const t=recur(is.type);return p===is.parameter&&t===is.type?is:new IndexSignature(p,t)});return props===this.propertySignatures&&indexes===this.indexSignatures&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Objects(props,indexes,this.annotations,checks,undefined,this.context,encodingChecks)}flip(recur){return this._rebuild(recur,recur,this.encodingChecks,this.checks)}recur(recur,recurParameter=recur){return this._rebuild(recur,recurParameter,this.checks,this.encodingChecks)}getExpected(){if(this.propertySignatures.length===0&&this.indexSignatures.length===0)return"object | array";return"object"}};function stepProperty(s,p,exit){if(exit._tag==="Failure"){return wrapPropertyKeyIssue(s,s.ast,p.name,exit)}if(exit===sameExit)return;const value=exit[args];if(value!==missing){assignProperty(s.out,p.name,value);return}delete s.out[p.name];if(!isOptional(p.type)){const issue=new Pointer([p.name],new MissingKey(p.type.context?.annotations));if(s.options.errors==="all"){if(s.issues)s.issues.push(issue);else s.issues=[issue];return}else{return fail5(new Composite(s.ast,[issue],s.input,s.options))}}}var parsePropertiesOptions={onItem(s,p){if(!hasPropertySignature(s.input,p.name)){return p.parser(missing,s.options)}const value=s.input[p.name];assignProperty(s.out,p.name,value);return p.parser(value,s.options)},step:stepProperty};var parseProperties=iterateEager()(parsePropertiesOptions);var parsePropertiesConcurrent=iterateConcurrent()(parsePropertiesOptions);function combineChecks(a,b){if(!a)return b;if(!b)return a;return[...a,...b]}function struct(fields,checks,annotations){return new Objects(Reflect.ownKeys(fields).map((key)=>{return new PropertySignature(key,fields[key].ast)}),[],annotations,checks)}function getAST(self){return self.ast}function union2(members,options,checks){return new Union(members.map(getAST),options,undefined,checks)}var toCandidate=memoizeIdempotent((ast)=>{while(true){if(isSuspend(ast))return unknown;const encoding=ast.encoding;if(!encoding){return ast.recur?.(toCandidate,identity)??ast}if(encoding.some((link)=>link.transformation._tag==="Middleware"&&link.transformation.decode!==identity))return unknown;ast=encoding[encoding.length-1].to}});function getCandidateTypes(ast){switch(ast._tag){case"Null":return["null"];case"Undefined":return["undefined"];case"String":case"TemplateLiteral":return["string"];case"Number":return["number"];case"Boolean":return["boolean"];case"Symbol":case"UniqueSymbol":return["symbol"];case"BigInt":return["bigint"];case"Arrays":return["array"];case"ObjectKeyword":return["object","array","function"];case"Objects":return ast.propertySignatures.length||ast.indexSignatures.length?["object"]:["string","number","boolean","symbol","bigint","object","array","function"];case"Enum":return Array.from(new Set(ast.enums.map(([,v])=>typeof v)));case"Literal":return[typeof ast.literal];case"Union":return Array.from(new Set(ast.types.flatMap(getCandidateTypes)));default:return["null","undefined","string","number","boolean","symbol","bigint","object","array","function"]}}function collectSentinels(ast){switch(ast._tag){default:return[];case"Declaration":{const s=ast.annotations?.[SENTINELS_ANNOTATION_KEY];return Array.isArray(s)?s:[]}case"Objects":return ast.propertySignatures.flatMap((ps)=>{const type=ps.type;if(!isOptional(type)){if(isLiteral(type)){return[{key:ps.name,literal:type.literal}]}if(isUniqueSymbol(type)){return[{key:ps.name,literal:type.symbol}]}}return[]});case"Arrays":return ast.elements.flatMap((e,i)=>{if(!isOptional(e)){if(isLiteral(e)){return[{key:i,literal:e.literal}]}if(isUniqueSymbol(e)){return[{key:i,literal:e.symbol}]}}return[]});case"Union":{if(ast.types.length===0)return[];const members=ast.types.map((type)=>collectSentinels(toCandidate(type)));return members[0].filter((s)=>members.every((sentinels)=>sentinels.some((o)=>o.key===s.key&&o.literal===s.literal)))}case"Suspend":return collectSentinels(ast.thunk())}}var candidateIndexCache=new WeakMap;var emptyCandidates=Object.freeze([]);var getRuntimeType=(input)=>input===null?"null":Array.isArray(input)?"array":typeof input;var hasPropertySignature=(input,key)=>key==="__proto__"?Object.hasOwn(input,key):(key in input);function getCandidateIndex(types){let index=candidateIndexCache.get(types);if(index)return index;let bySentinel;let sentinelCandidateCount=0;let otherwise;let literalCandidates;let onlyLiterals=true;const literalOf=[];for(let i=0;i<types.length;i++){const a=types[i];const encoded=toCandidate(a);if(isNever2(encoded))continue;if(isLiteral(encoded)||isUniqueSymbol(encoded)){literalCandidates??=new Map;const literal=isLiteral(encoded)?encoded.literal:encoded.symbol;literalOf[i]=literal;let arr=literalCandidates.get(literal);if(!arr)literalCandidates.set(literal,arr=[]);arr.push(i)}else{onlyLiterals=false}const sentinels=collectSentinels(encoded);if(sentinels.length){bySentinel??=new Map;sentinelCandidateCount++;for(const{key,literal}of sentinels){let entry=bySentinel.get(key);if(!entry)bySentinel.set(key,entry=[new Map,new Set]);entry[1].add(i);let indexes=entry[0].get(literal);if(!indexes)entry[0].set(literal,indexes=new Set);indexes.add(i)}}else{otherwise??={};const candidateTypes=getCandidateTypes(encoded);for(const t of candidateTypes)(otherwise[t]??=[]).push(i)}}const fallbacks={};const getFallback=(type)=>fallbacks[type]??=Object.freeze(otherwise?.[type]??emptyCandidates);if(onlyLiterals&&literalCandidates){literalCandidates.forEach(Object.freeze);index=(input)=>literalCandidates.get(input)??emptyCandidates}else if(bySentinel?.size===1&&!otherwise){const[key,[byValue]]=bySentinel.entries().next().value;const candidates=new Map;for(const[literal,indexes]of byValue){candidates.set(literal,Object.freeze(Array.from(indexes)))}const all=Object.freeze(types.map((_,i)=>i));index=(input,isConstructor)=>{if(isObjectKeyword(input)){const value=hasPropertySignature(input,key)?input[key]:undefined;if(value!==undefined)return candidates.get(value)??emptyCandidates;if(isConstructor)return all}return emptyCandidates}}else if(bySentinel){let commonSentinel;for(const entry of bySentinel){if((!commonSentinel||entry[1][0].size>commonSentinel[1][0].size)&&entry[1][1].size===sentinelCandidateCount){commonSentinel=entry}}index=(input,isConstructor)=>{const runtimeType=getRuntimeType(input);if(!isObjectKeyword(input))return getFallback(runtimeType);const selected=new Set(otherwise?.[runtimeType]);let directKey;if(commonSentinel){const[key,[byValue]]=commonSentinel;const hasKey=hasPropertySignature(input,key);const value=hasKey?input[key]:undefined;if(hasKey&&(!isConstructor||value!==undefined)){const match=byValue.get(value);if(!match)return getFallback(runtimeType);for(const i of match)selected.add(i);directKey=key}}if(directKey===undefined){for(const[key,[byValue,all]]of bySentinel){const hasKey=hasPropertySignature(input,key);const value=hasKey?input[key]:undefined;if(hasKey&&(!isConstructor||value!==undefined)){const match=byValue.get(value);if(match){for(const i of match)selected.add(i)}}else if(isConstructor){for(const i of all)selected.add(i)}}}for(const[key,[byValue,all]]of bySentinel){if(key===directKey)continue;const hasKey=hasPropertySignature(input,key);const value=hasKey?input[key]:undefined;if(hasKey&&(!isConstructor||value!==undefined)){const match=byValue.get(value);for(const i of selected){if(all.has(i)&&!match?.has(i))selected.delete(i)}}}return Array.from(selected).sort((a,b)=>a-b)}}else{index=(input)=>{const fallback=getFallback(getRuntimeType(input));return literalCandidates?fallback.filter((i)=>literalOf[i]===undefined||literalOf[i]===input):fallback}}candidateIndexCache.set(types,index);return index}var Union=class extends ASTNodeImpl{_tag="Union";types;options;encodingChecks;constructor(types,options,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.types=types;this.options=options;this.encodingChecks=encodingChecks}getParser(compile,compileField){const ast=this;const isConstructor=compileField!==undefined;const parsers=[];const parser=(i)=>parsers[i]??=compile(ast.types[i]);let index;return(input,options)=>{if(input===missing){return missingExit}const candidates=(index??=getCandidateIndex(ast.types))(input,isConstructor);if(candidates.length===0){return fail6(new AnyOf(ast,[],input,options))}if(candidates.length===1){const result=parser(candidates[0])(input,options);if(result._tag==="Success")return result;return effectIsExit(result)?failSingleUnionCandidate(ast,result.cause,input,options):catchSingleUnionCandidate(ast,result,input,options)}return parseUnionCandidates(ast,parser,candidates,input,options)}}_rebuild(recur,checks,encodingChecks){const types=mapOrSame(this.types,recur);return types===this.types&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Union(types,this.options,this.annotations,checks,undefined,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}matchPart(s,options){for(const type of this.types){const out=type.matchPart(s,options);if(out!==undefined)return out}return}getExpected(getExpected){const expected=this.annotations?.expected;if(typeof expected==="string")return expected;if(this.types.length===0)return"never";const types=this.types.map((type)=>{const encoded=toEncoded(type);switch(encoded._tag){case"Arrays":{const literals=encoded.elements.filter(isLiteral);if(literals.length>0){return`${formatIsMutable(encoded.isMutable)}[ ${literals.map((e)=>getExpected(e)+formatIsOptional(e.context?.isOptional)).join(", ")}, ... ]`}break}case"Objects":{const literals=encoded.propertySignatures.filter((ps)=>isLiteral(ps.type));if(literals.length>0){return`{ ${literals.map((ps)=>`${formatIsMutable(ps.type.context?.isMutable)}${formatPropertyKey(ps.name)}${formatIsOptional(ps.type.context?.isOptional)}: ${getExpected(ps.type)}`).join(", ")}, ... }`}break}}return getExpected(encoded)});return Array.from(new Set(types)).join(" | ")}};function failSingleUnionCandidate(ast,cause,input,options){const issue=getSchemaIssue(cause);if(!issue)return failCause2(cause);return fail5(new AnyOf(ast,[issue],input,options))}function catchSingleUnionCandidate(ast,result,input,options){return catchCause2(result,(cause)=>failSingleUnionCandidate(ast,cause,input,options))}function parseUnionCandidates(ast,parser,candidates,input,options){const state={ast,parser,input,out:undefined,successes:ast.options?.mode==="oneOf"?[]:undefined,issues:undefined,options};const eff=parseUnion(state,candidates);if(!eff){if(state.out)return state.out;return fail6(new AnyOf(ast,state.issues??[],input,options))}if(effectIsExit(eff))return resumeUnion(eff,state);let first=true;return suspend2(()=>{if(!first)return parseUnionCandidates(ast,parser,candidates,input,options);first=false;return resumeUnion(eff,state)})}function resumeUnion(eff,state){return flatMapEager2(eff,(_)=>{if(state.out===sameExit)return succeed7(state.input);if(state.out)return state.out;return fail6(new AnyOf(state.ast,state.issues??[],state.input,state.options))})}var parseUnion=iterateEager()({onItem(s,i){return s.parser(i)(s.input,s.options)},step(s,i,exit){if(exit._tag==="Failure"){const issue=getSchemaIssue(exit.cause);if(issue===undefined){return exit}if(s.issues)s.issues.push(issue);else s.issues=[issue]}else{if(s.out&&s.successes){s.successes.push(s.ast.types[i]);return fail5(new OneOf(s.ast,s.successes,s.input,s.options))}s.out=exit;if(s.successes){s.successes.push(s.ast.types[i])}else{return void_2}}}});var nonFiniteLiterals=new Union([new Literal("Infinity"),new Literal("-Infinity"),new Literal("NaN")]);function formatIsMutable(isMutable){return isMutable?"":"readonly "}function formatIsOptional(isOptional){return isOptional?"?":""}var Filter2=class extends Class{_tag="Filter";run;annotations;aborted;constructor(run,annotations=undefined,aborted=false){super();this.run=run;this.annotations=annotations;this.aborted=aborted}annotate(annotations){return new Filter2(this.run,{...this.annotations,...annotations},this.aborted)}abort(){return new Filter2(this.run,this.annotations,true)}and(other,annotations){return new FilterGroup([this,other],annotations)}};var FilterGroup=class extends Class{_tag="FilterGroup";checks;annotations;constructor(checks,annotations=undefined){super();this.checks=checks;this.annotations=annotations}annotate(annotations){return new FilterGroup(this.checks,{...this.annotations,...annotations})}and(other,annotations){return new FilterGroup([this,other],annotations)}};function makeFilter(filter,annotations,aborted=false){return new Filter2((input,ast,options)=>normalizeFilterOutput(ast,filter(input,ast,options),input,options),annotations,aborted)}function isFinite2(annotations){return makeFilter((n)=>globalThis.Number.isFinite(n),{expected:"a finite number",representation:{id:"effect/schema/isFinite",payload:null},toJsonSchema:()=>({type:"number"}),toCode:()=>({runtime:"Schema.isFinite()"}),arbitraryConstraint:{number:"finite"},...annotations})}var finite=appendChecks(number2,[isFinite2()]);var numberToJson=new Link(new Union([finite,nonFiniteLiterals]),new Transformation(Number3(),transform((n)=>globalThis.Number.isFinite(n)?n:globalThis.String(n))));function isPattern(regExp,annotations){const copy=new globalThis.RegExp(regExp);const payload={source:copy.source,flags:copy.flags};return makeFilter((s)=>{copy.lastIndex=0;return copy.test(s)},{expected:`a string matching the RegExp ${payload.source}`,representation:{id:"effect/schema/isPattern",payload},toJsonSchema:()=>[{},true],arbitraryConstraint:{patterns:[payload]},...annotations})}var bodyOwners=new WeakMap;function copy2(ast,changes){const out=Object.assign(Object.create(Object.getPrototypeOf(ast)),ast,changes);if(Reflect.ownKeys(changes).every((key)=>key==="context"||key==="encoding")){bodyOwners.set(out,getContextOwner(ast))}return out}function getContextOwner(ast){const existing=bodyOwners.get(ast);if(existing!==undefined)return existing;if(ast.encoding===undefined)return ast;const owner=Object.assign(Object.create(Object.getPrototypeOf(ast)),ast,{encoding:undefined});bodyOwners.set(ast,owner);return owner}function replaceEncoding(ast,encoding){return ast.encoding===encoding?ast:copy2(ast,{encoding})}function replaceContext(ast,context){if(ast.context===context){return ast}const owner=getContextOwner(ast);if(owner.context===context&&owner.encoding===ast.encoding){return owner}return copy2(ast,{context})}function getLastEncoding(ast){return ast.encoding?getLastEncoding(ast.encoding[ast.encoding.length-1].to):ast}function annotate(ast,annotations){if(ast.checks){const last=ast.checks[ast.checks.length-1];return replaceChecks(ast,append(ast.checks.slice(0,-1),last.annotate(annotations)))}return copy2(ast,{annotations:{...ast.annotations,...annotations}})}function replaceChecks(ast,checks){if(ast._tag==="Suspend"&&checks){throw new Error("Cannot add checks to Suspend")}if(ast.checks===checks){return ast}return copy2(ast,{checks})}function appendChecks(ast,checks){return replaceChecks(ast,combineChecks(ast.checks,checks))}function mapLink(link,f){const to=f(link.to);return to===link.to?link:new Link(to,link.transformation)}function updateLastLink(encoding,f){const links=encoding;const last=links[links.length-1];const out=mapLink(last,f);return out===last?encoding:append(encoding.slice(0,encoding.length-1),out)}function applyToLastLink(f){return(ast)=>ast.encoding?replaceEncoding(ast,updateLastLink(ast.encoding,f)):ast}function replaceContextLastLink(ast,context){return applyToLastLink((ast)=>replaceContext(ast,context))(ast)}function applyToSelfOrLastLinkEncoding(f){function out(ast){return ast.encoding?replaceEncoding(ast,updateLastLink(ast.encoding,out)):f(ast)}return memoize(out)}function applyToSelfOrLastLinkEncodingIdempotent(f,options){function out(ast){if(ast.encoding){const last=ast.encoding[ast.encoding.length-1];return options?.stopAt?.(last)?ast:replaceEncoding(ast,updateLastLink(ast.encoding,out))}return f(ast)}return memoizeIdempotent(out)}function appendTransformation(from,transformation,to){const link=new Link(from,transformation);return replaceEncoding(to,to.encoding?[...to.encoding,link]:[link])}function mapOrSame(as,f){let out;for(let i=0;i<as.length;i++){const a=as[i];const fa=f(a);if(out){out[i]=fa}else if(fa!==a){out=new Array(as.length);for(let j=0;j<i;j++){out[j]=as[j]}out[i]=fa}}return out??as}function annotateKey(ast,annotations){const context=ast.context?new Context(ast.context.isOptional,ast.context.isMutable,ast.context.constructorDefault,{...ast.context.annotations,...annotations}):new Context(false,false,undefined,annotations);return replaceContext(ast,context)}var optionalKey=memoizeIdempotent((ast)=>{const context=ast.context?ast.context.isOptional===false?new Context(true,ast.context.isMutable,ast.context.constructorDefault,ast.context.annotations):ast.context:new Context(true,false);return optionalKeyLastLink(replaceContext(ast,context))});var optionalKeyLastLink=applyToLastLink(optionalKey);var optional=memoize((ast)=>optionalKey(new Union([ast,undefined_2])));function withConstructorDefault(ast,defaultValue){const context=ast.context?new Context(ast.context.isOptional,ast.context.isMutable,defaultValue,ast.context.annotations):new Context(false,false,defaultValue);return replaceContext(ast,context)}function decodeTo(from,to,transformation){return appendTransformation(from,transformation,to)}function parseParameter(ast){const literals=[];const parameters=[];function addLiteral(literal){if(!literals.includes(literal)){literals.push(literal)}}function go(ast){switch(ast._tag){case"Literal":if(isPropertyKey(ast.literal)){addLiteral(ast.literal)}return;case"UniqueSymbol":addLiteral(ast.symbol);return;case"Enum":for(const[,value]of ast.enums){addLiteral(value)}return;case"Never":return;case"Union":for(let i=0;i<ast.types.length;i++){go(ast.types[i])}return;default:parameters.push(ast)}}go(ast);return{literals,parameters}}function record(key,value){const{literals,parameters:indexSignatures}=parseParameter(key);return new Objects(literals.map((literal)=>new PropertySignature(literal,value)),indexSignatures.map((parameter)=>new IndexSignature(parameter,value)))}function isOptional(ast){return ast.context?.isOptional??false}function isStructuralCheck(check){return check.annotations?.[STRUCTURAL_ANNOTATION_KEY]===true||check._tag==="FilterGroup"&&check.checks.every(isStructuralCheck)}function extractStructuralChecks(checks){function extract(check){if(isStructuralCheck(check))return[check];return check._tag==="FilterGroup"?check.checks.flatMap(extract):[]}const out=checks.flatMap(extract);return isArrayNonEmpty2(out)?out:undefined}function canPreserveEncodingChecks(ast){let preserve=true;function visit(child){preserve=preserve&&!child.encoding&&!isSuspend(child);if(preserve&&"recur"in child)child.recur(visit);return child}if("recur"in ast)ast.recur(visit);return preserve}var toType=memoizeIdempotent((ast)=>{const owner=getContextOwner(ast);if(owner!==ast){const type=toType(owner);return type===owner&&ast.encoding===undefined?ast:replaceContext(type,ast.context)}const type="recur"in ast?ast.recur(toType):ast;if("encodingChecks"in type&&type.encodingChecks){const checks=canPreserveEncodingChecks(ast)?type.encodingChecks:isArrays(type)||isObjects(type)||isDeclaration(type)&&type.typeParameters.length>0?extractStructuralChecks(type.encodingChecks):undefined;return copy2(type,{encodingChecks:undefined,checks:combineChecks(type.checks,checks)})}return type});var toEncoded=memoizeIdempotent((ast)=>{return toType(flip2(ast))});function flipEncoding(ast,encoding){const links=encoding;const len=links.length;const last=links[len-1];const ls=[new Link(flip2(replaceEncoding(ast,undefined)),links[0].transformation.flip())];for(let i=1;i<len;i++){ls.unshift(new Link(flip2(links[i-1].to),links[i].transformation.flip()))}const to=flip2(last.to);if(to.encoding){return replaceEncoding(to,[...to.encoding,...ls])}else{return replaceEncoding(to,ls)}}var flip2=memoize((ast)=>{if(ast.encoding){return flipEncoding(ast,ast.encoding)}const owner=getContextOwner(ast);if(owner!==ast){const flipped=flip2(owner);return flipped===owner?ast:replaceContext(flipped,ast.context)}return"flip"in ast?ast.flip(flip2):("recur"in ast)?ast.recur(flip2):ast});function fromConst(ast,value){const succeed=value===0?sameExit:succeed9(value);return(input,options)=>{if(input===missing)return missingExit;if(input===value)return succeed;return fail6(new InvalidType(ast,input,options))}}function fromRefinement(ast,refinement){return(input,options)=>{if(input===missing)return missingExit;if(refinement(input))return sameExit;return fail6(new InvalidType(ast,input,options))}}var parameterFromPropertyKey=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{switch(ast._tag){default:return ast;case"Number":return ast.toCodecStringTree();case"Union":return ast.recur(parameterFromPropertyKey)}});var parameterFromString=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{switch(ast._tag){default:return ast;case"Symbol":case"UniqueSymbol":return ast.toCodecStringTree();case"Union":return ast.recur(parameterFromString)}});var isStringFiniteRegExp=new globalThis.RegExp(`^${FINITE_PATTERN}$`);var isStringNumberRegExp=new globalThis.RegExp(`^(?:${FINITE_PATTERN}|Infinity|-Infinity|NaN)$`);function isStringFinite(annotations){return isPattern(isStringFiniteRegExp,{expected:"a string representing a finite number",representation:{id:"effect/schema/isStringFinite",payload:null},toJsonSchema:()=>({pattern:isStringFiniteRegExp.source}),...annotations})}var finiteString=appendChecks(string2,[isStringFinite()]);var finiteToString=new Link(finiteString,numberFromString);var numberToString=new Link(new Union([finiteString,nonFiniteLiterals]),numberFromString);var BIGINT_PATTERN="-?\\d+";var isStringBigIntRegExp=new globalThis.RegExp(`^${BIGINT_PATTERN}$`);var REGEXP_PATTERN="Symbol\\(([\\s\\S]*)\\)";var isStringSymbolRegExp=new globalThis.RegExp(`^${REGEXP_PATTERN}$`);function collectIssues(checks,value,issues,ast,options){for(let i=0;i<checks.length;i++){const check=checks[i];if(check._tag==="FilterGroup"){issues=collectIssues(check.checks,value,issues,ast,options);if(issues&&(options.errors!=="all"||issues[issues.length-1].filter.aborted)){return issues}}else{const issue=check.run(value,ast,options);if(issue){const filter=new Filter(check,issue,value,options);if(issues)issues.push(filter);else issues=[filter];if(options.errors!=="all"||check.aborted){return issues}}}}return issues}function getConstructorDescriptor(ast){if(!isDeclaration(ast))return;const getDescriptor=ast.annotations?.[CONSTRUCTOR_ANNOTATION_KEY];return isFunction(getDescriptor)?getDescriptor(ast.typeParameters):undefined}function isJsonLeaf(u){return u===null||typeof u==="string"||typeof u==="boolean"||typeof u==="number"&&globalThis.Number.isFinite(u)}function isStringTreeLeaf(u){return u===undefined||typeof u==="string"}function isTree(u,isLeaf){const cache=new WeakMap;const stack=[];outer:while(true){if(typeof u!=="object"||u===null){if(!isLeaf(u)){return false}}else{const value=u;const cached=cache.get(value);if(cached===false){return false}if(cached===undefined){const isArray=Array.isArray(value);if(!isArray){const prototype=Object.getPrototypeOf(value);if(prototype!==null&&prototype!==Object.prototype&&Object.getPrototypeOf(prototype)!==null){return false}}cache.set(value,false);stack.push({value,keys:isArray?value.length:Object.keys(value),index:0})}}while(stack.length>0){const frame=stack[stack.length-1];const keys=frame.keys;if(typeof keys==="number"){if(frame.index<keys){u=frame.value[frame.index++];continue outer}}else if(frame.index<keys.length){u=frame.value[keys[frame.index++]];continue outer}cache.set(frame.value,true);stack.pop()}return true}}function isJson(u){return isTree(u,isJsonLeaf)}var Json=new Declaration([],()=>(input,ast,options)=>isJson(input)?sameExit:fail6(new InvalidType(ast,input,options)),{representation:{id:"effect/schema/Json",payload:null},expected:"JSON value",toCodecJson:()=>{return},toCodecStringTree:()=>unknownToStringTree});function isStringTree(u){return isTree(u,isStringTreeLeaf)}var StringTree=new Declaration([],()=>(input,ast,options)=>isStringTree(input)?sameExit:fail6(new InvalidType(ast,input,options)),{expected:"StringTree",toCodecStringTree:()=>{return}});var unknownToStringTree=new Link(StringTree,passthrough2());var flatMapTransformation=(result,current,f)=>result===sameExit?f(current):flatMapEager2(result,f);function compileTransformation(transformation){const apply=compileTransformationUnsafe(transformation);return(result,current,options)=>{try{return apply(result,current,options)}catch(error){return die3(error)}}}function compileTransformationUnsafe(transformation){if(transformation._tag==="Middleware"){return(result,current,options)=>{const transformed=result===sameExit?transformation.decode(succeed9(toOption(current)),options):transformation.decode(mapEager2(result,toOption),options);return fromOptionalEffect(transformed)}}const getter=transformation.decode;switch(getter._tag){case"Passthrough":return(result,current)=>result===sameExit?succeed9(current):result;case"Transform":{const transform=(value)=>value===missing?missingExit:succeed9(getter.transform(value));return(result,current)=>flatMapTransformation(result,current,transform)}case"TransformOptional":{const transform=(value)=>fromOptionExit(getter.transform(toOption(value)));return(result,current)=>flatMapTransformation(result,current,transform)}case"TransformEffect":return(result,current,options)=>flatMapTransformation(result,current,(value)=>value===missing?missingExit:getter.transform(value,options));case"TransformOptionalEffect":return(result,current,options)=>flatMapTransformation(result,current,(value)=>fromOptionalEffect(getter.transform(toOption(value),options)))}}var fromOptionalEffect=(effect)=>flatMapEager2(effect,fromOptionExit);var wrapEncoding=(ast,input,options,effect)=>catchCause2(effect,(cause)=>failCauseSync2(()=>map5(cause,(issue)=>new Encoding(ast,issue,input,options))));function makeConstructorParser(descriptor,compile){const transform=compileTransformation(descriptor.link.transformation);let sourceParser;return(input,options)=>{if(input===missing)return missingExit;if(descriptor.isConstructed(input))return sameExit;const result=(sourceParser??=compile(descriptor.link.to))(input,options);return transform(result,input,options)}}function withDefault(ast,parser){const defaultValue=ast.context.constructorDefault;return(input,options)=>{if(input!==missing&&input!==undefined)return parser(input,options);const result=defaultValue;if(effectIsExit(result)&&result._tag==="Success"){const local=parser(result[args],options);return local===sameExit?result:local}return flatMapEager2(wrapEncoding(ast,input,options,result),(value)=>{const local=parser(value,options);return local===sameExit?succeed9(value):local})}}function compileField(ast,compile){const parser=compile(ast);return ast.context?.constructorDefault===undefined?parser:withDefault(ast,parser)}function compile2(ast,compile,compileField,base,specialize){if(ast._tag==="Declaration"){for(const parameter of ast.typeParameters)compile(parameter)}const descriptor=compileField?getConstructorDescriptor(ast):undefined;const parser=descriptor?makeConstructorParser(descriptor,compile):base??ast.getParser(compile,compileField);const checks=ast.checks;const links=ast.encoding;const transformations=links?.map((link)=>compileTransformation(link.transformation));const encodingChecks=ast.encodingChecks;if(!links&&!checks&&!encodingChecks){return parser}let encodingParsers;const parseChecks=(input,options)=>{let result=parser(input,options);try{if(encodingChecks&&!options.disableChecks){if(effectIsExit(result)){if(result._tag==="Success"){const output=result===sameExit?input:result[args];if(input!==missing&&output!==missing){const issues=collectIssues(encodingChecks,input,undefined,ast,options);if(issues){result=fail6(new Composite(ast,issues,input,options))}}}}else{result=flatMap4(result,(value)=>{if(input!==missing&&value!==missing){const issues=collectIssues(encodingChecks,input,undefined,ast,options);if(issues){return fail6(new Composite(ast,issues,input,options))}}return succeed7(value)})}}if(checks&&!options.disableChecks){if(effectIsExit(result)){if(result._tag==="Success"){const value=result===sameExit?input:result[args];if(value===missing)return result;const issues=collectIssues(checks,value,undefined,ast,options);if(issues){result=fail6(new Composite(ast,issues,value,options))}}}else{result=flatMap4(result,(value)=>{if(value!==missing){const issues=collectIssues(checks,value,undefined,ast,options);if(issues){return fail6(new Composite(ast,issues,value,options))}}return succeed7(value)})}}return result}catch(error){return die3(error)}};const parseLocal=specialize===undefined?parseChecks:specialize(parseChecks);if(!links){return parseLocal}return(input,options)=>{const parsers=encodingParsers??=links.map((link)=>compile(link.to));let current=input;let result=parsers[parsers.length-1](input,options);for(let i=links.length-1;i>=0;i--){result=transformations[i](result,current,options);if(i!==0){const next=parsers[i-1];if(result._tag==="Success"){current=result[args];result=next(current,options)}else{result=flatMapEager2(result,(value)=>{const nextResult=next(value,options);return nextResult===sameExit?succeed9(value):nextResult})}}}if(result._tag==="Success"){const value=result[args];const local=parseLocal(value,options);return local===sameExit?result:local}result=wrapEncoding(ast,input,options,result);return flatMapEager2(result,(value)=>{const local=parseLocal(value,options);return local===sameExit?succeed9(value):local})}}var invalid3=Symbol();var cache=new WeakMap;var compiler;var compilerAdaptersEnabled=false;var decodeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve3,ast,"parser"):resolve3(ast).parser;var makeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve3,ast,"makeEffect"):resolve3(ast).makeEffect;var makeField=(ast)=>compileField(ast,makeChild);class InterpretedEntry{ast;constructor(ast){this.ast=ast}get decodeEffect(){return this.cachedDecodeEffect??=compile2(this.ast,decodeChild)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=compile2(this.ast,makeChild,makeField)}}class CompilerEntry extends InterpretedEntry{compiled;resolve;constructor(ast,compiled,resolve){super(ast);this.compiled=compiled;this.resolve=resolve}save(key,value){Object.defineProperty(this,key,{value});return value}operation(key){const compiled=this.compiled;return typeof compiled==="function"?compiled(this.ast,this.resolve,key):compiled?.[key]}get is(){return this.save("is",this.operation("is"))}get decode(){return this.save("decode",this.operation("decode"))}get make(){return this.save("make",this.operation("make"))}get compiledMakeEffect(){return this.save("compiledMakeEffect",this.operation("makeEffect"))}get decodeEffect(){return this.save("decodeEffect",this.operation("decodeEffect")??compile2(this.ast,(ast)=>lazyParser(this.resolve,ast,"parser")))}get parser(){const decode=this.decode;return decode===undefined?this.decodeEffect:this.save("parser",withDecode(decode,()=>this.decodeEffect))}get makeEffect(){const makeEffect=this.compiledMakeEffect;if(makeEffect!==undefined)return this.save("makeEffect",makeEffect);const child=(ast)=>lazyParser(this.resolve,ast,"makeEffect");return this.save("makeEffect",compile2(this.ast,child,(ast)=>compileField(ast,child)))}}function withDecode(fastDecode,decodeEffect){let detailed;return(input,options)=>{if(input!==missing){try{const value=fastDecode(input,options);if(value!==invalid3)return value===input?sameExit:succeed9(value)}catch(error){return die3(error)}}return(detailed??=decodeEffect())(input,options)}}function lazyParser(resolve,ast,operation){const entry=resolve(ast);if(entry.compiled===undefined||Object.hasOwn(entry,operation)){return entry[operation]}let parser;return(input,options)=>(parser??=entry[operation])(input,options)}function resolve3(ast){const cached=cache.get(ast);if(cached!==undefined)return cached;const entry=compiler===undefined?new InterpretedEntry(ast):new CompilerEntry(ast,compiler(ast,resolve3),resolve3);cache.set(ast,entry);return entry}function makeEffect(schema){const ast=schema.ast;let parser;return(input,options)=>{return(parser??=runWithCompiler(constructorCompiler,toType(ast)))(input,options?.disableChecks?options?.parseOptions?{...options.parseOptions,disableChecks:true}:{disableChecks:true}:options?.parseOptions)}}function makeOption(schema){const parser=makeEffect(schema);return(input,options)=>{const exit=runSyncExit2(parser(input,options));if(isSuccess3(exit)){return some2(exit.value)}getSchemaIssueOrThrow(exit.cause,"Option adapter can only return none for schema issues");return none2()}}function make22(schema){return makeConstructorSync(toType(schema.ast))}function is(schema){return _is(schema.ast)}function makeIs(ast){if(!compilerAdaptersEnabled){const parser=asExit(run(ast));return(input)=>{const exit=parser(input,defaultParseOptions);if(isSuccess3(exit))return true;getSchemaIssueOrThrow(exit.cause,"Type guard adapter can only return false for schema issues");return false}}const entry=resolve3(ast);const guard=entry.is;if(guard!==undefined){return(input)=>{try{return guard(input,defaultParseOptions)}catch(error){getSchemaIssueOrThrow(die2(error),"Type guard adapter can only return false for schema issues");return false}}}const parser=entry.parser;return(input)=>{const exit=runSyncExit2(parserResult(parser(input,defaultParseOptions),input));if(isSuccess3(exit))return true;getSchemaIssueOrThrow(exit.cause,"Type guard adapter can only return false for schema issues");return false}}function _is(ast){const typeAST=toType(ast);let guard=(input)=>{guard=makeIs(typeAST);return guard(input)};return(input)=>{return guard(input)}}function decodeUnknownEffect(schema,options){const parser=run(schema.ast);return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}function encodeUnknownEffect(schema,options){const parser=run(flip2(schema.ast));return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}var mergeParseOptions=(options,overrideOptions)=>overrideOptions?{...options,...overrideOptions}:options;var getValue=(value)=>{if(value===missing){return fail6(new InvalidValue)}return succeed7(value)};function run(ast){return runWithCompiler(normalCompiler,ast)}function parserResult(result,input){if(result===sameExit){return succeed7(input)}if(!effectIsExit(result)){return flatMapEager2(result,getValue)}return result[args]===missing?getValue(missing):result}function runWithCompiler(compiler,ast){let parser;return(input,options)=>{const result=(parser??=compiler(ast))(input,options??defaultParseOptions);if(result===sameExit){return succeed7(input)}if(!effectIsExit(result)){return flatMapEager2(result,getValue)}return result[args]===missing?getValue(missing):result}}function asExit(parser){return(input,options)=>runSyncExit2(parser(input,options))}function runSync3(effect,message){const exit=runSyncExit2(effect);if(isSuccess3(exit)){return exit.value}const issue=getSchemaIssueOrThrow(exit.cause,message);throw new Error("Schema validation failed",{cause:issue})}var constructorDefectMessage="Constructor adapter can only throw schema issues";function throwConstructorDefect(error){throw new Error(constructorDefectMessage,{cause:die2(error)})}function makeConstructorSync(ast){let entry;return(input,options)=>constructSync(entry??=resolve3(ast),input,options)}function constructSync(entry,input,options){const parseOptions=options?.disableChecks?options.parseOptions?{...options.parseOptions,disableChecks:true}:{disableChecks:true}:options?.parseOptions??defaultParseOptions;const make=entry.make;if(make!==undefined&&input!==missing){let output;try{output=make(input,parseOptions)}catch(error){throwConstructorDefect(error)}if(output!==invalid3&&output!==missing)return output}return runSync3(parserResult(entry.makeEffect(input,parseOptions),input),constructorDefectMessage)}function makeClassSync(ast,input,options,construct){const entry=resolve3(ast);const descriptor=getConstructorDescriptor(ast);if(descriptor===undefined||entry.make!==undefined||entry.compiledMakeEffect!==undefined){return constructSync(entry,input,options)}if(descriptor.isConstructed(input))return input;const fields=constructSync((entry.resolve??resolve3)(descriptor.link.to),input,options);try{return construct(fields)}catch(error){throwConstructorDefect(error)}}var normalCompiler=(ast)=>resolve3(ast).parser;var constructorCompiler=(ast)=>resolve3(ast).makeEffect;var TypeId24="~effect/Schema/Schema";var RebuildOptions=Symbol();var SchemaProto={[TypeId24]:TypeId24,get make(){const value=make22(this);Object.defineProperty(this,"make",{value,enumerable:true});return value},get makeEffect(){const value=makeEffect(this);Object.defineProperty(this,"makeEffect",{value,enumerable:true});return value},get makeOption(){const value=makeOption(this);Object.defineProperty(this,"makeOption",{value,enumerable:true});return value},pipe(){return pipeArguments(this,arguments)},annotate(annotations){return this.rebuild(annotate(this.ast,annotations))},annotateKey(annotations){return this.rebuild(annotateKey(this.ast,annotations))},check(...checks){return this.rebuild(appendChecks(this.ast,checks))},rebuild(ast){return make23(ast,this[RebuildOptions])}};function make23(ast,options){function Schema(){}const self=Object.setPrototypeOf(Schema,SchemaProto);if(options&&(Object.hasOwn(options,"name")||Object.hasOwn(options,"length")||Object.hasOwn(options,"__proto__"))){Object.defineProperties(self,Object.getOwnPropertyDescriptors({...options}))}else{Object.assign(self,options)}self[RebuildOptions]=options;self.ast=ast;return self}function makeCodecDerivation(step,options){const deriveBody=memoize((owner)=>{const body=replaceContext(owner,undefined);const out=step(body,recur);return out===body?null:out});const recur=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{const derived=deriveBody(getContextOwner(ast));if(derived===null)return ast;const out=replaceContext(derived,ast.context);return ast.context===undefined?out:replaceContextLastLink(out,withoutConstructorDefault(ast.context))},options);return recur}function withoutConstructorDefault(context){return context.constructorDefault===undefined?context:new Context(context.isOptional,context.isMutable,undefined,context.annotations)}function validateCanonicalObjectPropertyNames(ast){if(ast.propertySignatures.some((ps)=>typeof ps.name!=="string")){throw new globalThis.Error("Objects property names must be strings",{cause:ast})}}function makeReorder(getPriority){return(types)=>{const sortedTypes=[...types].sort((a,b)=>getPriority(toEncoded(a))-getPriority(toEncoded(b)));const orderChanged=sortedTypes.some((ast,index)=>ast!==types[index]);if(!orderChanged)return types;return sortedTypes}}function toCodecStringTree(schema){return make23(toCodecStringTreeAST(schema.ast),{schema})}var toStringTreeReorder=makeReorder((ast)=>{switch(ast._tag){case"Null":case"Boolean":case"Number":case"BigInt":case"Symbol":case"UniqueSymbol":return 0;default:return 1}});function toCodecStringTreeASTStep(ast,recur,onMissingAnnotation){switch(ast._tag){case"Declaration":{const typeParameters=ast.typeParameters.map((tp)=>make23(recur(toEncoded(tp))));const getStringTreeLink=ast.annotations?.toCodecStringTree;if(isFunction(getStringTreeLink)){const link=getStringTreeLink(typeParameters);if(link===undefined)return ast;return replaceEncoding(ast,[mapLink(link,recur)])}const getJsonLink=ast.annotations?.toCodecJson;const jsonLink=isFunction(getJsonLink)?getJsonLink(typeParameters):undefined;const getLink=jsonLink===undefined?ast.annotations?.toCodec:undefined;const link=jsonLink??(isFunction(getLink)?getLink(typeParameters):undefined);return link===undefined?onMissingAnnotation(ast):replaceEncoding(ast,[mapLink(link,recur)])}case"Null":return replaceEncoding(ast,[nullToString]);case"Boolean":return replaceEncoding(ast,[booleanToString]);case"Unknown":case"ObjectKeyword":return replaceEncoding(ast,[unknownToStringTree]);case"Enum":case"Number":case"Literal":case"UniqueSymbol":case"Symbol":case"BigInt":return ast.toCodecStringTree();case"Objects":{validateCanonicalObjectPropertyNames(ast);return ast.recur(recur,parameterFromString)}case"Union":{const sortedTypes=toStringTreeReorder(ast.types);if(sortedTypes!==ast.types){return new Union(sortedTypes,ast.options,ast.annotations,ast.checks,ast.encoding,ast.context,ast.encodingChecks).recur(recur)}return ast.recur(recur)}case"Arrays":case"Suspend":return ast.recur(recur)}return ast}var nullToString=new Link(new Literal("null"),new Transformation(transform(()=>null),transform(()=>"null")));var booleanToString=new Link(new Union([new Literal("true"),new Literal("false")]),new Transformation(transform((s)=>s==="true"),String3()));var arrayFromSingleTransformation=new Transformation(transform((input)=>typeof input==="string"?[input]:input),passthrough());var isCodecArrayFromSingleLink=(link)=>link.transformation===arrayFromSingleTransformation;var toCodecStringTreeAST=makeCodecDerivation((ast,recur)=>toCodecStringTreeASTStep(ast,recur,(ast)=>{throw new globalThis.Error("Missing structural codec for StringTree",{cause:ast})}),{stopAt:isCodecArrayFromSingleLink});var lambda=(f)=>f;var SchemaErrorTypeId="~effect/Schema/SchemaError";function isSchemaError(u){return hasProperty(u,SchemaErrorTypeId)&&u[SchemaErrorTypeId]===SchemaErrorTypeId}var TypeId25=TypeId24;function declareConstructor(){return(typeParameters,run,annotations)=>{return make24(new Declaration(typeParameters.map(getAST),(typeParameters)=>run(typeParameters.map((ast)=>make24(ast))),annotations))}}function declare(is,annotations){return declareConstructor()([],()=>(input,ast,options)=>is(input)?succeed7(input):fail6(new InvalidType(ast,input,options)),annotations)}class SchemaError extends TaggedError2("SchemaError"){[SchemaErrorTypeId]=SchemaErrorTypeId;constructor(issue){const stackTraceLimit=getStackTraceLimit();setStackTraceLimit(0);try{super({issue})}finally{setStackTraceLimit(stackTraceLimit)}}get message(){return defaultFormatter(this.issue)}toJSON(){return{_tag:this._tag,message:this.message}}[NodeInspectSymbol](){return this.toJSON()}toString(){return`SchemaError(${this.message})`}}function isSchemaError2(u){return isSchemaError(u)}function fromIssueEffect(self){if(effectIsExit(self)){return fromIssueExit(self)}return catchCause2(self,(cause)=>failCauseSync2(()=>map5(cause,(issue)=>new SchemaError(issue))))}function fromIssueExit(exit){return isSuccess3(exit)?exit:failCause2(map5(exit.cause,(issue)=>new SchemaError(issue)))}function getSchemaErrorOrThrow(cause,message){let schemaError;for(const reason of cause.reasons){if(!isFailReason2(reason)||!isSchemaError2(reason.error)){throw new globalThis.Error(message,{cause})}schemaError??=reason.error}if(schemaError===undefined){throw new globalThis.Error(message,{cause})}return schemaError}function runSchemaErrorSync(self){const exit=runSyncExit2(self);if(isSuccess3(exit)){return exit.value}throw getSchemaErrorOrThrow(exit.cause,"Sync adapter can only throw schema errors")}var is2=is;function decodeUnknownEffect2(schema,options){const parser=decodeUnknownEffect(schema,options);return(input,options)=>{return fromIssueEffect(parser(input,options))}}var decodeEffect2=decodeUnknownEffect2;function decodeUnknownSync(schema,options){const parser=decodeUnknownEffect2(schema,options);return(input,options)=>{return runSchemaErrorSync(parser(input,options))}}var decodeSync=decodeUnknownSync;function encodeUnknownEffect2(schema,options){const parser=encodeUnknownEffect(schema,options);return(input,options)=>{return fromIssueEffect(parser(input,options))}}var encodeEffect=encodeUnknownEffect2;function encodeUnknownSync(schema,options){const parser=encodeUnknownEffect2(schema,options);return(input,options)=>{return runSchemaErrorSync(parser(input,options))}}var encodeSync=encodeUnknownSync;var make24=make23;function isSchema(u){return hasProperty(u,TypeId25)&&u[TypeId25]===TypeId25}var optionalKey2=lambda((schema)=>make24(optionalKey(schema.ast),{schema}));var optional2=lambda((self)=>{const schema=UndefinedOr(self);return make24(optional(self.ast),{schema})});function Literal2(literal){const out=make24(new Literal(literal),{literal,transform(to){return out.pipe(decodeTo2(Literal2(to),{decode:transform(()=>to),encode:transform(()=>literal)}))}});return out}var Unknown2=make24(unknown);var Null2=make24(null_);var Undefined2=make24(undefined_2);var String5=make24(string2);var Number5=make24(number2);var Boolean3=make24(boolean);function makeStruct(ast,fields){return make24(ast,{fields,mapFields(f,options){const fields=f(this.fields);return makeStruct(struct(fields,options?.unsafePreserveChecks?this.ast.checks:undefined),fields)}})}function Struct(fields){return makeStruct(struct(fields,undefined),fields)}function Record(key,value){return make24(record(key.ast,value.ast),{key,value})}var ArraySchema=lambda((schema)=>make24(new Arrays(false,[],[schema.ast]),{value:schema}));function makeUnion(ast,members){return make24(ast,{members,mapMembers(f,options){const members=f(this.members);return makeUnion(union2(members,this.ast.options,options?.unsafePreserveChecks?this.ast.checks:undefined),members)}})}function Union2(members,options){return makeUnion(union2(members,options,undefined),members)}function Literals(literals){const members=literals.map(Literal2);return make24(union2(members,undefined,undefined),{literals,members,mapMembers(f){return Union2(f(this.members))},pick(literals){return Literals(literals)},transform(to){return Union2(members.map((member,index)=>member.transform(to[index])))}})}var NullOr=lambda((self)=>Union2([self,Null2]));var UndefinedOr=lambda((self)=>Union2([self,Undefined2]));function brand(identifier){return(schema)=>make24(schema.ast,{schema,identifier})}function decodeTo2(to,transformation){return(from)=>{return make24(decodeTo(from.ast,to.ast,transformation?makeTransformation(transformation):passthrough2()),{from,to})}}function withConstructorDefault2(defaultValue){return(schema)=>make24(withConstructorDefault(schema.ast,defaultValue),{schema})}function tag(literal){return Literal2(literal).pipe(withConstructorDefault2(succeed7(literal)))}function TaggedStruct(value,fields){return Struct({_tag:tag(value),...fields})}function instanceOf(constructor,annotations){return declare((u)=>u instanceof constructor,annotations)}function link3(){return(encodeTo,transformation)=>{return new Link(encodeTo.ast,makeTransformation(transformation))}}var makeFilter2=makeFilter;function isPattern2(regExp,annotations){const source=regExp.source;const flags=regExp.flags;const canExport=/^[dg]*uy?$/.test(flags);const runtimeRegExp=flags===""?`new globalThis.RegExp(${format(source)})`:`new globalThis.RegExp(${format(source)}, ${format(flags)})`;return isPattern(regExp,{toJsonSchema:()=>canExport?{pattern:flags.endsWith("y")?`^(?:${source})`:source}:[{},true],toCode:()=>({runtime:`Schema.isPattern(${runtimeRegExp})`}),...annotations})}function isBase64(annotations){const pattern="^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$";const regExp=/^[0-9a-zA-Z+/]*={0,2}$/;return makeFilter2((s)=>s.length%4===0&®Exp.test(s),{expected:"a base64 encoded string",representation:{id:"effect/schema/isBase64",payload:null},toJsonSchema:()=>({pattern}),arbitraryConstraint:{patterns:[{source:pattern,flags:""}]},toCode:()=>({runtime:"Schema.isBase64()"}),...annotations})}var Finite=make24(finite);function isInt(annotations){return makeFilter2((n)=>globalThis.Number.isSafeInteger(n),{expected:"an integer",representation:{id:"effect/schema/isInt",payload:null},toJsonSchema:()=>({type:"integer",minimum:globalThis.Number.MIN_SAFE_INTEGER,maximum:globalThis.Number.MAX_SAFE_INTEGER}),toCode:()=>({runtime:"Schema.isInt()"}),arbitraryConstraint:{number:"integer"},...annotations})}var Int=Number5.check(isInt());function isMinLength(minLength,annotations){minLength=normalizeCardinality(minLength);return makeIsMinLength(minLength,Math.ceil(minLength/2),annotations)}function makeIsMinLength(minLength,minCodePoints,annotations){return makeFilter2((input)=>input.length>=minLength,{expected:`a value with a length of at least ${minLength}`,representation:{id:"effect/schema/isMinLength",payload:{minLength}},toJsonSchema:({type})=>type==="string"?minLength<=1?{minLength:minCodePoints}:[{minLength:minCodePoints},true]:type==="array"?{minItems:minLength}:type===undefined?[{minLength:minCodePoints,minItems:minLength},true]:[{},true],toCode:()=>({runtime:`Schema.isMinLength(${minLength})`}),[STRUCTURAL_ANNOTATION_KEY]:true,arbitraryConstraint:{minLength},...annotations})}function isNonEmpty(annotations){return makeIsMinLength(1,1,annotations)}function isMaxLength(maxLength,annotations){maxLength=normalizeCardinality(maxLength);return makeFilter2((input)=>input.length<=maxLength,{expected:`a value with a length of at most ${maxLength}`,representation:{id:"effect/schema/isMaxLength",payload:{maxLength}},toJsonSchema:({type})=>type==="string"?maxLength===0?{maxLength}:[{maxLength},true]:type==="array"?{maxItems:maxLength}:type===undefined?[{maxLength,maxItems:maxLength},true]:[{},true],toCode:()=>({runtime:`Schema.isMaxLength(${maxLength})`}),[STRUCTURAL_ANNOTATION_KEY]:true,arbitraryConstraint:{maxLength},...annotations})}function normalizeCardinality(value){if(!globalThis.Number.isFinite(value)){throw new globalThis.RangeError(`Expected a finite number, got ${value}`)}return Math.max(0,Math.floor(value))}var NonEmptyString=String5.check(isNonEmpty());var RegExp2=instanceOf(globalThis.RegExp,{representation:{id:"effect/schema/RegExp",payload:null},toCode:()=>({runtime:`Schema.RegExp`,Type:`globalThis.RegExp`}),expected:"RegExp",toCodecJson:()=>link3()(Struct({source:String5,flags:String5}),transformEffect2({decode:(e,options)=>try_3({try:()=>new globalThis.RegExp(e.source,e.flags),catch:()=>new InvalidValue({expected:"valid RegExp source and flags"},e,options)}),encode:(regExp)=>succeed7({source:regExp.source,flags:regExp.flags})}))});var URLString=String5.annotate({expected:"a string that will be decoded as a URL"});var URL2=instanceOf(globalThis.URL,{representation:{id:"effect/schema/URL",payload:null},toCode:()=>({runtime:`Schema.URL`,Type:`globalThis.URL`}),expected:"URL",toCodecJson:()=>link3()(URLString,urlFromString)});var JsonString=String5.annotate({expected:"a string that will be decoded as JSON"});function fromJsonString2(schema,options){return JsonString.pipe(decodeTo2(schema,fromJsonString(options)))}var File=instanceOf(globalThis.File,{representation:{id:"effect/schema/File",payload:null},toCode:()=>({runtime:`Schema.File`,Type:`globalThis.File`}),expected:"File",toCodecJson:()=>link3()(Struct({data:String5.check(isBase64()),type:String5,name:String5,lastModified:Int}),transformEffect2({decode:(e,options)=>match2(decode(e.data),{onFailure:()=>fail6(new InvalidValue({expected:"a valid Base64 string"},e.data,options)),onSuccess:(bytes)=>{const buffer=new globalThis.Uint8Array(bytes);return succeed7(new globalThis.File([buffer],e.name,{type:e.type,lastModified:e.lastModified}))}}),encode:(file,options)=>tryPromise2({try:async()=>{const bytes=new globalThis.Uint8Array(await file.arrayBuffer());return{data:encode(bytes),type:file.type,name:file.name,lastModified:file.lastModified}},catch:()=>new InvalidValue({expected:"a readable File"},file,options)})}))});var URLSearchParams2=instanceOf(globalThis.URLSearchParams,{representation:{id:"effect/schema/URLSearchParams",payload:null},toCode:()=>({runtime:`Schema.URLSearchParams`,Type:`globalThis.URLSearchParams`}),expected:"URLSearchParams",toCodecJson:()=>link3()(String5.annotate({expected:"a query string that will be decoded as URLSearchParams"}),transform2({decode:(e)=>new globalThis.URLSearchParams(e),encode:(params)=>params.toString()}))});var Base64String=String5.annotate({expected:"a base64 encoded string that will be decoded as Uint8Array",format:"byte",contentEncoding:"base64"});var Uint8Array2=instanceOf(globalThis.Uint8Array,{representation:{id:"effect/schema/Uint8Array",payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:"Uint8Array",toCodecJson:()=>link3()(Base64String,uint8ArrayFromBase64String)});var arbitraryMinimumDateTimestamp=-8640000000000000;var arbitraryMaximumDateTimestamp=8640000000000000;var arbitraryMinimumZonedDateTimeTimestamp=arbitraryMinimumDateTimestamp+14*60*60*1000;var arbitraryMaximumZonedDateTimeTimestamp=arbitraryMaximumDateTimestamp-14*60*60*1000;var arbitraryMinimumTimeZoneOffset=-12*60*60*1000;var arbitraryMaximumTimeZoneOffset=14*60*60*1000;function Redacted(value,options){const label=typeof options?.label==="string"?options.label:undefined;const disallowJsonEncode=options?.disallowJsonEncode===true;const normalizedOptions=label!==undefined?disallowJsonEncode?{label,disallowJsonEncode:true}:{label}:disallowJsonEncode?{disallowJsonEncode:true}:undefined;const decodeLabel=label!==undefined?decodeUnknownEffect(Literal2(label)):undefined;const schema=declareConstructor()([value],([value])=>(input,ast,poptions)=>{if(isRedacted(input)){const label=decodeLabel!==undefined?mapErrorEager2(decodeLabel(input.label,poptions),(issue)=>new Pointer(["label"],issue)):void_3;return flatMapEager2(label,()=>mapBothEager2(decodeUnknownEffect(value)(value2(input),poptions),{onSuccess:(value)=>make19(value,{label:input.label}),onFailure:()=>{return new Composite(ast,[new Pointer(["value"],new InvalidValue(undefined,input,poptions))],input,poptions)}}))}return fail6(new InvalidType(ast,input,poptions))},{representation:{id:"effect/schema/Redacted",payload:normalizedOptions??null},toCode:({typeParameters})=>({runtime:normalizedOptions!==undefined?`Schema.Redacted(${typeParameters[0].runtime}, ${format(normalizedOptions)})`:`Schema.Redacted(${typeParameters[0].runtime})`,Type:`Redacted.Redacted<${typeParameters[0].Type}>`,importDeclarations:[`import * as Redacted from "effect/Redacted"`]}),expected:"Redacted",toCodecJson:([value])=>link3()(value,{decode:transform((e)=>make19(e,{label})),encode:disallowJsonEncode?forbidden((oe)=>"Cannot serialize Redacted"+(isSome2(oe)&&typeof oe.value.label==="string"?` with label: "${oe.value.label}"`:"")):transform(value2)}),toEquivalence:([value])=>makeEquivalence4(value)});return make24(schema.ast,{value})}var immerable=globalThis.Symbol.for("immer-draftable");var payloadToken={};function makeClass(Inherited,identifier,struct2,annotations,proto){const getClassSchema=getClassSchemaFactory(struct2,identifier,annotations);const ClassTypeId=getClassTypeId(identifier);const out=class extends Inherited{constructor(...[input,options]){const internalOptions=options;const payload=internalOptions?.["~payload"];const value=payload?.token===payloadToken?payload.value:struct2.make(input??{},options);super(value,{...options,disableChecks:true,"~payload":{token:payloadToken,value}})}static[TypeId25]=TypeId25;get[ClassTypeId](){return ClassTypeId}static[immerable]=true;static identifier=identifier;static fields=struct2.fields;static get ast(){return getClassSchema(this).ast}static pipe(){return pipeArguments(this,arguments)}static rebuild(ast){return getClassSchema(this).rebuild(ast)}static make(input,options){return makeClassSync(toType(getClassSchema(this).ast),input??{},options,(fields)=>makeClassTrusted(this,fields))}static makeOption(input,options){return makeOption(getClassSchema(this))(input??{},options)}static makeEffect(input,options){return getClassSchema(this).makeEffect(input??{},options)}static annotate(annotations){return this.rebuild(annotate(this.ast,annotations))}static annotateKey(annotations){return this.rebuild(annotateKey(this.ast,annotations))}static check(...checks){return this.rebuild(appendChecks(this.ast,checks))}static extend(identifier2){return(schema,annotations)=>{const extension=isStruct(schema)?schema:Struct(schema);const fields={...struct2.fields,...extension.fields};const ast=struct(fields,struct2.ast.checks,{identifier:identifier2});return makeClass(this,identifier2,makeStruct(appendChecks(ast,extension.ast.checks),fields),annotations,proto)}}static mapFields(f,options){return struct2.mapFields(f,options)}};if(proto!==undefined){Object.assign(out.prototype,proto(identifier))}return out}function makeClassTrusted(self,fields){return new self(fields,{"~payload":{token:payloadToken,value:fields}})}function getClassTransformation(self){return new Transformation(transform((input)=>makeClassTrusted(self,input)),passthrough())}function getClassTypeId(identifier){return`~effect/Schema/Class/${identifier}`}function getClassSchemaFactory(from,identifier,annotations){let memo;return(self)=>{if(memo!==undefined){return memo}const ClassTypeId=getClassTypeId(identifier);const isClassValue=(input)=>input instanceof self||hasProperty(input,ClassTypeId);const transformation=getClassTransformation(self);const to=make24(new Declaration([from.ast],()=>(input,ast,options)=>{return isClassValue(input)?succeed7(input):fail6(new InvalidType(ast,input,options))},{identifier,[CONSTRUCTOR_ANNOTATION_KEY]:([from])=>({isConstructed:isClassValue,link:new Link(from,transformation)}),toCodec:([from])=>new Link(from.ast,transformation),toEquivalence:([from])=>from,toFormatter:([from])=>(t)=>`${self.identifier}(${from(t)})`,[SENTINELS_ANNOTATION_KEY]:collectSentinels(from.ast),...annotations}));return memo=decodeTo2(to,transformation)(from)}}function isStruct(schema){return isSchema(schema)}var Error4=(identifier)=>(schema,annotations)=>{const struct=isStruct(schema)?schema:Struct(schema);const self=makeClass(Error2,identifier,struct,annotations,(identifier)=>({name:identifier}));return self};var TaggedError3=(identifier)=>{return(tagValue,schema,annotations)=>{const struct=isStruct(schema)?schema.mapFields((fields)=>({_tag:tag(tagValue),...fields}),{unsafePreserveChecks:true}):TaggedStruct(tagValue,schema);return Error4(identifier??tagValue)(struct,annotations)}};var toCodecStringTree2=toCodecStringTree;var Json2=make24(annotate(Json,{toCode:()=>({runtime:"Schema.Json",Type:"Schema.Json"})}));var JsonObject=Record(String5,Json2);var TypeId26="~effect/http/HttpBody";class Proto7{[TypeId26];constructor(){this[TypeId26]=TypeId26}[NodeInspectSymbol](){return this.toJSON()}toString(){return format(this,{ignoreToString:true})}}class Empty2 extends Proto7{_tag="Empty";toJSON(){return{_id:"effect/HttpBody",_tag:"Empty"}}}var empty7=new Empty2;var buffer2=globalThis.Buffer;var TypeId27="~effect/http/HttpClientError";class HttpClientError extends TaggedError2("HttpClientError"){constructor(props){if("cause"in props.reason){super({...props,cause:props.reason.cause})}else{super(props)}}[TypeId27]=TypeId27;get request(){return this.reason.request}get response(){return"response"in this.reason?this.reason.response:undefined}get message(){return this.reason.message}}var formatReason=(tag)=>tag.endsWith("Error")?tag.slice(0,-5):tag;var formatMessage=(reason,description,info)=>description?`${reason}: ${description} (${info})`:`${reason} error (${info})`;var formatMethodAndUrl=(request)=>`${request.method} ${redactUrl(request.url)}`;var reasonToJSON=(reason,json)=>({...json,request:{_id:"HttpClientRequest",method:reason.request.method,url:redactUrl(reason.request.url)},..."response"in reason?{response:{_id:"HttpClientResponse",status:reason.response.status}}:undefined});class TransportError extends TaggedError2("TransportError"){get methodAndUrl(){return formatMethodAndUrl(this.request)}get message(){return formatMessage(formatReason(this._tag),this.description,this.methodAndUrl)}toJSON(){return reasonToJSON(this,super.toJSON())}}class EncodeError extends TaggedError2("EncodeError"){get methodAndUrl(){return formatMethodAndUrl(this.request)}get message(){return formatMessage(formatReason(this._tag),this.description,this.methodAndUrl)}toJSON(){return reasonToJSON(this,super.toJSON())}}class InvalidUrlError extends TaggedError2("InvalidUrlError"){get methodAndUrl(){return formatMethodAndUrl(this.request)}get message(){return formatMessage(formatReason(this._tag),this.description,this.methodAndUrl)}toJSON(){return reasonToJSON(this,super.toJSON())}}class StatusCodeError extends TaggedError2("StatusCodeError"){get methodAndUrl(){return formatMethodAndUrl(this.request)}get message(){const info=`${this.response.status} ${this.methodAndUrl}`;return formatMessage(formatReason(this._tag),this.description,info)}toJSON(){return reasonToJSON(this,super.toJSON())}}class DecodeError extends TaggedError2("DecodeError"){get methodAndUrl(){return formatMethodAndUrl(this.request)}get message(){const info=`${this.response.status} ${this.methodAndUrl}`;return formatMessage(formatReason(this._tag),this.description,info)}toJSON(){return reasonToJSON(this,super.toJSON())}}class EmptyBodyError extends TaggedError2("EmptyBodyError"){get methodAndUrl(){return formatMethodAndUrl(this.request)}get message(){const info=`${this.response.status} ${this.methodAndUrl}`;return formatMessage(formatReason(this._tag),this.description,info)}toJSON(){return reasonToJSON(this,super.toJSON())}}var allShort=[["GET","get"],["POST","post"],["PUT","put"],["DELETE","del"],["PATCH","patch"],["HEAD","head"],["OPTIONS","options"],["TRACE","trace"],["QUERY","query"]];var updateHeaders=(headers,body)=>{if(body._tag==="Empty"||body._tag==="FormData"){return remove2(remove2(headers,"content-type"),"content-length")}headers=body.contentType===undefined?remove2(headers,"content-type"):set(headers,"content-type",body.contentType);return updateContentLength(headers,body)};var updateContentLength=(headers,body)=>{const contentLength=body._tag==="Empty"||body._tag==="FormData"?undefined:body.contentLength;return contentLength===undefined?remove2(headers,"content-length"):set(headers,"content-length",contentLength.toString())};class UrlError extends TaggedError2("UrlError"){}var make25=(url,params,hash)=>try_({try:()=>{const urlInstance=new URL(url,baseUrl());for(let i=0;i<params.params.length;i++){const[key,value]=params.params[i];if(value!==undefined){urlInstance.searchParams.append(key,unwrap4(value))}}if(hash!==undefined){urlInstance.hash=hash}return urlInstance},catch:(cause)=>new UrlError({cause})});var baseUrl=()=>{if("location"in globalThis&&globalThis.location!==undefined&&globalThis.location.origin!==undefined&&globalThis.location.pathname!==undefined){const base=location.origin+location.pathname;try{return new URL(base).href}catch{return}}return};var TypeId28="~effect/http/HttpClientRequest";var Proto8={[TypeId28]:TypeId28,...BaseProto,toJSON(){return{_id:"HttpClientRequest",method:this.method,url:redactUrl(this.url),urlParams:this.urlParams,hash:this.hash,headers:redact(this.headers),body:this.body.toJSON()}},pipe(){return pipeArguments(this,arguments)}};function makeWith(method,url,urlParams,hash,headers,body){const self=Object.create(Proto8);self.method=method;self.url=url;self.urlParams=urlParams;self.hash=hash;self.headers=headers;self.body=body;return self}var empty8=makeWith("GET","",empty6,none2(),empty5,empty7);var make26=(method)=>(url,options)=>modify(empty8,{method,url,...options??undefined});var modify=dual(2,(self,options)=>{let result=self;if(options.method){result=setMethod(result,options.method)}if(options.url){result=setUrl(result,options.url)}if(options.headers){result=setHeaders(result,options.headers)}if(options.urlParams){result=setUrlParams(result,options.urlParams)}if(options.hash){result=setHash(result,options.hash)}if(options.body){result=setBody(result,options.body)}if(options.accept){result=accept(result,options.accept)}if(options.acceptJson){result=acceptJson(result)}return result});var setMethod=dual(2,(self,method)=>makeWith(method,self.url,self.urlParams,self.hash,self.headers,self.body));var setHeader=dual(3,(self,key,value)=>makeWith(self.method,self.url,self.urlParams,self.hash,set(self.headers,key,value),self.body));var setHeaders=dual(2,(self,input)=>makeWith(self.method,self.url,self.urlParams,self.hash,setAll(self.headers,input),self.body));var accept=dual(2,(self,mediaType)=>setHeader(self,"Accept",mediaType));var acceptJson=accept("application/json");var setUrl=dual(2,(self,url)=>{if(typeof url==="string"){return makeWith(self.method,url,self.urlParams,self.hash,self.headers,self.body)}const clone=new URL(url.toString());const urlParams=fromInput2(clone.searchParams);const hash=fromNullishOr(clone.hash===""?undefined:clone.hash.slice(1));clone.search="";clone.hash="";return makeWith(self.method,clone.toString(),urlParams,hash,self.headers,self.body)});var setUrlParams=dual(2,(self,input)=>makeWith(self.method,self.url,setAll2(self.urlParams,input),self.hash,self.headers,self.body));var setHash=dual(2,(self,hash)=>makeWith(self.method,self.url,self.urlParams,some2(hash),self.headers,self.body));var setBody=dual(2,(self,body)=>{return makeWith(self.method,self.url,self.urlParams,self.hash,updateHeaders(self.headers,body),body)});function toUrl(self){const r=make25(self.url,self.urlParams,getOrUndefined(self.hash));if(isSuccess2(r)){return some2(r.success)}return none2()}var TypeId29="~effect/http/HttpIncomingMessage";var inspect=(self,that)=>{return{...that,headers:redact(self.headers),remoteAddress:self.remoteAddress}};var WebSourceSymbol="~effect/http/HttpClientResponse/WebSource";var getWebSource=(self)=>self[WebSourceSymbol]?.();var TypeId30="~effect/http/HttpClientResponse";var fromWeb=(request,source)=>new WebHttpClientResponse(request,source);class WebHttpClientResponse extends Class2{[TypeId29];[TypeId30];request;source;constructor(request,source){super();this.request=request;this.source=source;this[TypeId29]=TypeId29;this[TypeId30]=TypeId30}toJSON(){return inspect(this,{_id:"HttpClientResponse",request:this.request.toJSON(),status:this.status})}get status(){return this.source.status}get url(){if(this.source.url)return this.source.url.split("#")[0];const url=toUrl(this.request);if(isNone2(url))return"";url.value.hash="";return url.value.href}get headers(){return fromInput(this.source.headers)}cachedCookies;get cookies(){if(this.cachedCookies){return this.cachedCookies}return this.cachedCookies=fromSetCookie(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return none2()}[WebSourceSymbol](){return this.source}get stream(){return this.source.body?fromReadableStream2({evaluate:()=>this.source.body,onError:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}):fail8(new HttpClientError({reason:new EmptyBodyError({request:this.request,response:this,description:"can not create stream from empty body"})}))}get json(){return flatMap4(this.text,(text)=>try_3({try:()=>text===""?null:JSON.parse(text),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}))}textBody;get text(){return this.textBody??=map6(this.arrayBuffer,(_)=>new TextDecoder().decode(_))}get urlParamsBody(){return flatMap4(this.arrayBuffer,(bytes)=>try_3({try:()=>fromInput2(fromBody(bytes)),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}))}formDataBody;get formData(){return this.formDataBody??=tryPromise2({try:()=>this.source.formData(),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}).pipe(cached2,runSync2)}arrayBufferBody;get arrayBuffer(){if(this.arrayBufferBody){return this.arrayBufferBody}this.arrayBufferBody=tryPromise2({try:()=>this.source.arrayBuffer(),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}).pipe(cached2,runSync2);return this.arrayBufferBody}get upgrade(){return fail6(new HttpClientError({reason:new StatusCodeError({request:this.request,response:this,description:"fetch cannot hand over the connection of an HTTP upgrade"})}))}pipe(){return pipeArguments(this,arguments)}}var toHeaders=(span)=>fromRecordUnsafe({b3:`${span.traceId}-${span.spanId}-${span.sampled?"1":"0"}${match(span.parent,{onNone:()=>"",onSome:(parent)=>`-${parent.spanId}`})}`,traceparent:`00-${span.traceId.padStart(32,"0")}-${span.spanId}-${span.sampled?"01":"00"}`});var defaultPorts={"http:":80,"https:":443,"ws:":80,"wss:":443};var addUrlAttributes=(span,url,redactedNames)=>{const query=redactUrl(url.search,redactedNames).slice(1);span.attribute("url.full",redactUrl(url.href,redactedNames));span.attribute("url.path",url.pathname);if(query!==""){span.attribute("url.query",query)}span.attribute("url.scheme",url.protocol.slice(0,-1));if(url.hostname!==""){span.attribute("server.address",url.hostname.startsWith("[")?url.hostname.slice(1,-1):url.hostname);const port=url.port===""?defaultPorts[url.protocol]:Number(url.port);if(port!==undefined){span.attribute("server.port",port)}}};var redactedNames=(urlParams,redactedNames)=>{const keys=urlParams.params.filter(([,value])=>typeof value!=="string").map(([key])=>key);return keys.length===0?redactedNames:[...redactedNames,...new URLSearchParams(keys.map((key)=>[key,""])).keys()]};var addHeaderAttributes=(span,phase,headers,filter,redactedNames)=>{for(const name in headers){if(!filter(name,phase))continue;span.attribute(`http.${phase}.header.${name}`,isRedactedName(name,redactedNames)?"<redacted>":headers[name])}};var TypeId31="~effect/http/HttpClient";var HttpClient=Service("effect/HttpClient");var transform3=dual(2,(self,f)=>makeWith2(flatMap4((request)=>f(self.postprocess(succeed7(request)),request)),self.preprocess));var transformResponse=dual(2,(self,f)=>makeWith2((request)=>f(self.postprocess(request)),self.preprocess));var makeWith2=(postprocess,preprocess)=>{const self=Object.create(Proto9);self.preprocess=preprocess;self.postprocess=postprocess;self.execute=function(request){return postprocess(preprocess(request))};return self};var Proto9={[TypeId31]:TypeId31,pipe(){return pipeArguments(this,arguments)},...BaseProto,toJSON(){return{_id:"effect/HttpClient"}},...Object.fromEntries(allShort.map(([fullMethod,method])=>[method,function(url,options){return this.execute(make26(fullMethod)(url,options))}]))};var make27=(f)=>makeWith2((effect)=>flatMap4(effect,(request)=>withFiber2((fiber)=>{const scopedController=scopedRequests.get(request);const controller=scopedController??new AbortController;const urlResult=make25(request.url,request.urlParams,getOrUndefined(request.hash));if(isFailure2(urlResult)){return fail6(new HttpClientError({reason:new InvalidUrlError({request,cause:urlResult.failure})}))}const url=urlResult.success;const tracerDisabled=fiber.getRef(DisablePropagation)||fiber.getRef(TracerDisabledWhen)(request);if(tracerDisabled){const effect=f(request,url,controller.signal,fiber);if(scopedController)return map6(effect,(response)=>trackResponse(response,controller,true));return uninterruptibleMask2((restore)=>matchCauseEffect2(restore(effect),{onSuccess(response){return succeed7(trackResponse(response,controller,false))},onFailure(cause){if(hasInterrupts2(cause)){controller.abort()}return failCause3(cause)}}))}return useSpan2(fiber.getRef(SpanNameGenerator)(request),{kind:"client"},(span)=>{span.attribute("http.request.method",request.method);const redactedHeaderNames=fiber.getRef(CurrentRedactedNames);addUrlAttributes(span,url,redactedNames(request.urlParams,fiber.getRef(CurrentRedactedNames2)));const headerFilter=fiber.getRef(TracerHeaderFilter);addHeaderAttributes(span,"request",request.headers,headerFilter,redactedHeaderNames);request=fiber.getRef(TracerPropagationEnabled)?setHeaders(request,toHeaders(span)):request;return uninterruptibleMask2((restore)=>restore(f(request,url,controller.signal,fiber)).pipe(withParentSpan2(span,{captureStackTrace:false}),matchCauseEffect2({onSuccess:(response)=>{span.attribute("http.response.status_code",response.status);addHeaderAttributes(span,"response",response.headers,headerFilter,redactedHeaderNames);if(response.status>=400&&response.status<600){span.attribute("error.type",String(response.status));endSpanWithStatusError(fiber,span,request,response)}return succeed7(trackResponse(response,controller,scopedController!==undefined))},onFailure(cause){if(!scopedController&&hasInterrupts2(cause)){controller.abort()}return failCause3(cause)}})))})})),succeed7);var endSpanWithStatusError=(fiber,span,request,response)=>{const stackTraceLimit=getStackTraceLimit();setStackTraceLimit(0);let exit;try{exit=fail5(new HttpClientError({reason:new StatusCodeError({request,response})}))}finally{setStackTraceLimit(stackTraceLimit)}span.end(fiber.getRef(TracerTimingEnabled2)?fiber.getRef(Clock).currentTimeNanosUnsafe():BigInt(0),exit)};var withScope=(self)=>transform3(self,(effect,request)=>{const controller=new AbortController;scopedRequests.set(request,controller);return andThen2(addFinalizer3(()=>sync2(()=>controller.abort())),effect)});var TracerDisabledWhen=Reference("effect/http/HttpClient/TracerDisabledWhen",{defaultValue:()=>constFalse});var TracerHeaderFilter=Reference("effect/http/HttpClient/TracerHeaderFilter",{defaultValue:()=>constFalse});var TracerPropagationEnabled=Reference("effect/http/HttpClient/TracerPropagationEnabled",{defaultValue:constTrue});var SpanNameGenerator=Reference("effect/http/HttpClient/SpanNameGenerator",{defaultValue:()=>(request)=>request.method});var layerMergedContext=(effect2)=>effect(HttpClient)(contextWith2((context)=>map6(effect2,(client)=>transformResponse(client,updateContext2((input)=>merge(context,input))))));var responseRegistry=(()=>{if("FinalizationRegistry"in globalThis&&globalThis.FinalizationRegistry){const registry=new FinalizationRegistry((controller)=>{try{controller.abort()}catch{}});return{register(response,controller){registry.register(response,controller,response)},unregister(response){registry.unregister(response)}}}const timers=new WeakMap;return{register(response,controller){timers.set(response,setTimeout(()=>controller.abort(),5000))},unregister(response){const timer=timers.get(response);if(timer===undefined)return;clearTimeout(timer);timers.delete(response)}}})();var scopedRequests=new WeakMap;var responseControllers=new WeakMap;var trackResponse=(response,controller,scoped)=>{if(!scoped){responseRegistry.register(response,controller);response=new InterruptibleResponse(response,controller)}responseControllers.set(response,controller);return response};class InterruptibleResponse{original;controller;constructor(original,controller){this.original=original;this.controller=controller}[TypeId30]=TypeId30;[TypeId29]=TypeId29;applyInterrupt(effect){return suspend2(()=>{responseRegistry.unregister(this.original);return onInterrupt2(effect,()=>sync2(()=>{this.controller.abort()}))})}get request(){return this.original.request}get url(){return this.original.url}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get upgrade(){return this.applyInterrupt(this.original.upgrade)}[WebSourceSymbol](){const source=getWebSource(this.original);if(source!==undefined)responseRegistry.unregister(this.original);return source}get stream(){return suspend4(()=>{responseRegistry.unregister(this.original);return ensuring4(this.original.stream,sync2(()=>{this.controller.abort()}))})}toJSON(){return this.original.toJSON()}[NodeInspectSymbol](){return this.original[NodeInspectSymbol]()}pipe(){return pipeArguments(this,arguments)}}var Fetch=Reference("effect/http/FetchHttpClient/Fetch",{defaultValue:()=>globalThis.fetch});var StreamBodyFallback=Reference("effect/http/FetchHttpClient/StreamBodyFallback",{defaultValue:()=>"error"});class RequestInit extends Service()("effect/http/FetchHttpClient/RequestInit"){}var supportsStreamBody;var detectStreamBodySupport=()=>{try{let duplexAccessed=false;const body=new ReadableStream;const request=new Request("https://example.com",{method:"POST",body,get duplex(){duplexAccessed=true;return"half"}});return(duplexAccessed||request.body===body)&&!request.headers.has("Content-Type")}catch{return false}};var fetch2=make27((request,url,signal,fiber)=>{if(request.headers.upgrade!==undefined){return fail6(new HttpClientError({reason:new TransportError({request,description:"fetch cannot send an HTTP upgrade request"})}))}const fetch2=fiber.getRef(Fetch);const options=getOrUndefined2(fiber.context,RequestInit)??{};let headers=options.headers?merge3(fromInput(options.headers),request.headers):request.headers;if(headers["content-length"]){headers=remove2(headers,"content-length")}let uploadController;const stopUpload=sync2(()=>uploadController?.abort());const send=(body)=>map6(tryPromise2({try:()=>fetch2(url,{...options,method:request.method,headers,body,duplex:typeof ReadableStream!=="undefined"&&body instanceof ReadableStream?"half":undefined,signal:uploadController?AbortSignal.any([signal,uploadController.signal]):signal}),catch:(cause)=>new HttpClientError({reason:new TransportError({request,cause})})}),(response)=>{const original=fromWeb(request,response);if(!uploadController)return original;if(response.body===null)uploadController.abort();return Object.create(original,{...Object.fromEntries(["arrayBuffer","text","json","formData","urlParamsBody"].map((key)=>[key,{get:()=>ensuring2(original[key],stopUpload)}])),stream:{get:()=>ensuring4(original.stream,stopUpload)}})}).pipe(onError2(()=>stopUpload));switch(request.body._tag){case"Raw":case"Uint8Array":return send(request.body.body);case"FormData":return send(request.body.formData);case"Stream":{supportsStreamBody??=detectStreamBodySupport();if(supportsStreamBody){uploadController=new AbortController;const uploadSignal=AbortSignal.any([signal,uploadController.signal]);const stopped=callback2((resume)=>{const onAbort=()=>resume(interrupt2);if(uploadSignal.aborted){onAbort();return}uploadSignal.addEventListener("abort",onAbort,{once:true});return sync2(()=>uploadSignal.removeEventListener("abort",onAbort))});return flatMap4(toReadableStreamEffect(interruptWhen2(request.body.stream,stopped)),send)}if(fiber.getRef(StreamBodyFallback)==="error"){return fail6(new HttpClientError({reason:new EncodeError({request,description:"Streaming request bodies are not supported in this runtime"})}))}return mkArrayBuffer(request.body.stream).pipe(mapError3((cause)=>new HttpClientError({reason:new EncodeError({request,cause})})),flatMap4(send))}}return send(undefined)});var layer5=layerMergedContext(succeed7(fetch2));import{chmodSync as chmodSync2,existsSync as existsSync10,readFileSync as readFileSync9,realpathSync as realpathSync5,renameSync as renameSync2,statSync as statSync3,writeFileSync as writeFileSync7}from"fs";import{rename as rename4}from"fs/promises";import{homedir,hostname}from"os";import{createInterface}from"readline/promises";import{pathToFileURL as pathToFileURL5}from"url";var name="@collective-intelligence/cli";var version="0.2.23";var jsonBodySerializer={bodySerializer:(body)=>JSON.stringify(body,(_key,value)=>typeof value==="bigint"?value.toString():value)};function createSseClient({onRequest,onSseError,onSseEvent,responseTransformer,responseValidator,sseDefaultRetryDelay,sseMaxRetryAttempts,sseMaxRetryDelay,sseSleepFn,url,...options}){let lastEventId;const sleep=sseSleepFn??((ms)=>new Promise((resolve)=>setTimeout(resolve,ms)));const createStream=async function*(){let retryDelay=sseDefaultRetryDelay??3000;let attempt=0;const signal=options.signal??new AbortController().signal;while(true){if(signal.aborted)break;attempt++;const headers=options.headers instanceof Headers?options.headers:new Headers(options.headers);if(lastEventId!==undefined){headers.set("Last-Event-ID",lastEventId)}try{const requestInit={redirect:"follow",...options,body:options.serializedBody??null,headers,signal};let request=new Request(url,requestInit);if(onRequest){request=await onRequest(url,requestInit)}const _fetch=options.fetch??globalThis.fetch;const response=await _fetch(request);if(!response.ok)throw new Error(`SSE failed: ${response.status} ${response.statusText}`);if(!response.body)throw new Error("No body in SSE response");const reader=response.body.pipeThrough(new TextDecoderStream).getReader();let buffer="";const abortHandler=()=>{try{reader.cancel()}catch{}};signal.addEventListener("abort",abortHandler);try{while(true){const{done,value}=await reader.read();if(done)break;buffer+=value;buffer=buffer.replace(/\r\n?/g,`
|
|
238
|
+
at ${path}`:message}function findMessage(issue){if(issue._tag==="Pointer"||issue._tag==="Composite")return;if(issue._tag==="Encoding")return findMessage(issue.issue);const annotations=issue._tag==="Filter"?issue.filter.annotations:("annotations"in issue)?issue.annotations:issue.ast.annotations;const message=annotations?.[issue._tag==="MissingKey"?"messageMissingKey":issue._tag==="UnexpectedKey"?"messageUnexpectedKey":"message"];if(typeof message==="string")return message}function getSchemaIssue(cause){let issue;for(const reason of cause.reasons){if(!isFailReason2(reason)||!isIssue(reason.error)){return}issue??=reason.error}return issue}function getSchemaIssueOrThrow(cause,message){const issue=getSchemaIssue(cause);if(issue===undefined){throw new Error(message,{cause})}return issue}var makeGetter=(fields)=>Object.assign(Object.create(Prototype),fields);function fail10(f){return transformOptionalEffect((oe,options)=>fail6(f(oe,options)))}function forbidden(message){return fail10((oe,options)=>{const annotations={message:message(oe)};return isSome2(oe)?new Forbidden(annotations,oe.value,options):new Forbidden(annotations)})}var passthrough_=makeGetter({_tag:"Passthrough"});function passthrough(){return passthrough_}function transform(f){return makeGetter({_tag:"Transform",transform:f})}function transformEffect(f){return makeGetter({_tag:"TransformEffect",transform:f})}function transformOptionalEffect(f){return makeGetter({_tag:"TransformOptionalEffect",transform:f})}function String3(){return transform(globalThis.String)}function Number3(){return transform(globalThis.Number)}function parseJson(options){return transformEffect((input,parseOptions)=>try_3({try:()=>JSON.parse(input,options?.reviver),catch:()=>new InvalidValue({expected:"a valid JSON string"},input,parseOptions)}))}function stringifyJson(options){return transformEffect((input,parseOptions)=>try_3({try:()=>{const output=JSON.stringify(input,options?.replacer,options?.space);if(output===undefined){throw new TypeError("Value cannot be represented as JSON")}return output},catch:()=>new InvalidValue({expected:"a JSON-serializable value"},input,parseOptions)}))}function encodeBase64(){return transform(encode)}function decodeBase64(){return transformEffect((input,options)=>mapErrorEager2(fromResult2(decode(input)),()=>new InvalidValue({expected:"a valid Base64 string"},input,options)))}var ContentTypeId=Symbol.for("~effect/Schema/content");function setContent(operation,content){Object.defineProperty(operation,ContentTypeId,{value:content});return operation}var TypeId22="~effect/SchemaTransformation/Transformation";var Transformation=class extends Class{[TypeId22]=TypeId22;_tag="Transformation";decode;encode;constructor(decode,encode){super();this.decode=decode;this.encode=encode}flip(){return new Transformation(this.encode,this.decode)}};function isTransformation(u){return hasProperty(u,TypeId22)&&u[TypeId22]===TypeId22}var makeTransformation=(options)=>{if(isTransformation(options)){return options}return new Transformation(options.decode,options.encode)};function transformEffect2(options){return new Transformation(transformEffect(options.decode),transformEffect(options.encode))}function transform2(options){return new Transformation(transform(options.decode),transform(options.encode))}var passthrough_2=new Transformation(passthrough(),passthrough());function passthrough2(){return passthrough_2}var numberFromString=new Transformation(Number3(),String3());var urlFromString=transformEffect2({decode:(s,options)=>URL.canParse(s)?succeed7(new URL(s)):fail6(new InvalidValue({expected:"a valid URL string"},s,options)),encode:(url)=>succeed7(url.href)});var uint8ArrayFromBase64String=new Transformation(decodeBase64(),encodeBase64());function fromJsonString(options){return new Transformation(parseJson(options??{}),setContent(stringifyJson(options),{mediaType:"application/json",preserveSchema:options?.reviver===undefined&&options?.replacer===undefined}))}function makeGuard(tag){return(ast)=>ast._tag===tag}var isDeclaration=makeGuard("Declaration");var isNever2=makeGuard("Never");var isLiteral=makeGuard("Literal");var isUniqueSymbol=makeGuard("UniqueSymbol");var isArrays=makeGuard("Arrays");var isObjects=makeGuard("Objects");var isSuspend=makeGuard("Suspend");var Link=class{to;transformation;constructor(to,transformation){this.to=to;this.transformation=transformation}};var defaultParseOptions={};var Context=class{isOptional;isMutable;constructorDefault;annotations;constructor(isOptional,isMutable,constructorDefault=undefined,annotations=undefined){this.isOptional=isOptional;this.isMutable=isMutable;this.constructorDefault=constructorDefault;this.annotations=annotations}};var TypeId23="~effect/Schema";class ASTNodeImpl{[TypeId23]=TypeId23;annotations;checks;encoding;context;constructor(annotations=undefined,checks=undefined,encoding=undefined,context=undefined){this.annotations=annotations;this.checks=checks;this.encoding=encoding;this.context=context}toString(){return`<${this._tag}>`}}var Declaration=class extends ASTNodeImpl{_tag="Declaration";typeParameters;run;encodingChecks;encodingRun;constructor(typeParameters,run,annotations,checks,encoding,context,encodingChecks,encodingRun){super(annotations,checks,encoding,context);this.typeParameters=typeParameters;this.run=run;this.encodingChecks=encodingChecks;this.encodingRun=encodingRun}getParser(){let run;return(input,options)=>{if(input===missing)return missingExit;run??=this.run(this.typeParameters);try{return run(input,this,options)}catch(error){return die3(error)}}}_rebuild(recur,checks,encodingChecks,run,encodingRun){const tps=mapOrSame(this.typeParameters,recur);return tps===this.typeParameters&&checks===this.checks&&encodingChecks===this.encodingChecks&&run===this.run&&encodingRun===this.encodingRun?this:new Declaration(tps,run,this.annotations,checks,undefined,this.context,encodingChecks,encodingRun)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){const expected=this.annotations?.expected;if(typeof expected==="string")return expected;return"<Declaration>"}};var Null=class extends ASTNodeImpl{_tag="Null";getParser(){return fromConst(this,null)}getExpected(){return"null"}};var null_=new Null;var Undefined=class extends ASTNodeImpl{_tag="Undefined";getParser(){return fromConst(this,undefined)}toCodecJson(){return replaceEncoding(this,[undefinedToNull])}getExpected(){return"undefined"}};var undefinedToNull=new Link(null_,new Transformation(transform(()=>{return}),transform(()=>null)));var undefined_2=new Undefined;var Unknown=class extends ASTNodeImpl{_tag="Unknown";getParser(){return fromRefinement(this,isUnknown)}getExpected(){return"unknown"}};var unknown=new Unknown;var Literal=class extends ASTNodeImpl{_tag="Literal";literal;constructor(literal,annotations,checks,encoding,context){super(annotations,checks,encoding,context);if(typeof literal==="number"&&!globalThis.Number.isFinite(literal)){throw new Error(`A numeric literal must be finite, got ${format(literal)}`)}this.literal=literal}getParser(){return fromConst(this,this.literal)}matchPart(s,_options){return s===globalThis.String(this.literal)?this.literal:undefined}toCodecJson(){return typeof this.literal==="bigint"?literalToString(this):this}toCodecStringTree(){return typeof this.literal==="string"?this:literalToString(this)}getExpected(){return typeof this.literal==="string"?JSON.stringify(this.literal):globalThis.String(this.literal)}};function literalToString(ast){const literalAsString=globalThis.String(ast.literal);return replaceEncoding(ast,[new Link(new Literal(literalAsString),new Transformation(transform(()=>ast.literal),transform(()=>literalAsString)))])}var String4=class extends ASTNodeImpl{_tag="String";getParser(){return fromRefinement(this,isString)}matchPart(s,options){const checks=this.checks;return checks&&!options.disableChecks&&collectIssues(checks,s,undefined,this,options)?undefined:s}getExpected(){return"string"}};var string2=new String4;var Number4=class extends ASTNodeImpl{_tag="Number";getParser(){return fromRefinement(this,isNumber)}matchKey(s,options){return this._match(isStringNumberRegExp,s,options)}matchPart(s,options){return this._match(isStringFiniteRegExp,s,options)}_match(regexp,s,options){if(!regexp.test(s))return;const value=globalThis.Number(s);if(options.disableChecks||!this.checks)return value;return collectIssues(this.checks,value,undefined,this,options)?undefined:value}toCodecJson(){if(this.checks&&(hasCheck(this.checks,"effect/schema/isFinite")||hasCheck(this.checks,"effect/schema/isInt"))){return this}return replaceEncoding(this,[numberToJson])}toCodecStringTree(){if(this.toCodecJson()===this){return replaceEncoding(this,[finiteToString])}return replaceEncoding(this,[numberToString])}getExpected(){return"number"}};function hasCheck(checks,id){return checks.some((check)=>check.annotations?.representation?.id===id||check._tag==="FilterGroup"&&hasCheck(check.checks,id))}var number2=new Number4;var Boolean2=class extends ASTNodeImpl{_tag="Boolean";getParser(){return fromRefinement(this,isBoolean)}getExpected(){return"boolean"}};var boolean=new Boolean2;var Arrays=class extends ASTNodeImpl{_tag="Arrays";isMutable;elements;rest;encodingChecks;constructor(isMutable,elements,rest,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.isMutable=isMutable;this.elements=elements;this.rest=rest;this.encodingChecks=encodingChecks;let hasOptional=false;for(let i=0;i<elements.length;i++){if(isOptional(elements[i])){hasOptional=true}else if(hasOptional){throw new Error("A required element cannot follow an optional element. ts(1257)")}}if(hasOptional&&rest.length>1){throw new Error("A required element cannot follow an optional element. ts(1257)")}for(let i=1;i<rest.length;i++){if(isOptional(rest[i])){throw new Error("An optional element cannot follow a rest element. ts(1266)")}}}getParser(compile,compileField=compile){const ast=this;let elements;let rest;const elementLen=ast.elements.length;const tailLen=Math.max(0,ast.rest.length-1);function getParser(tailThreshold,index){if(index<elementLen){return elements[index]}else if(index>=tailThreshold){return rest[index-tailThreshold+1]}return rest[0]}const finish=(state)=>{const{input,len,options}=state;if(ast.rest.length===0&&len>elementLen){for(let i=elementLen;i<len;i++){const unexpected=new UnexpectedKey(ast,input[i],options);const issue=new Pointer([i],unexpected);if(options.errors==="all"){if(state.issues)state.issues.push(issue);else state.issues=[issue]}else{return fail6(new Composite(ast,[issue],input,options))}}}if(state.issues){return fail6(new Composite(ast,state.issues,input,options))}return succeed9(state.output)};const parse=(input,options)=>{const len=input.length;const state={ast,getParser,input,len,tailThreshold:Math.max(elementLen,len-tailLen),output:[],issues:undefined,options};const end=ast.rest.length===0?elementLen:Math.max(len,elementLen+tailLen);const concurrency=options.concurrency===undefined?1:resolveConcurrency(options.concurrency);const eff=concurrency===1?parseArray(state,input,0,end):parseArrayConcurrent(state,input,{concurrency,end});if(!eff)return finish(state);if(effectIsExit(eff))return flatMapEager2(eff,()=>finish(state));let first=true;return suspend2(()=>{if(!first)return parse(input,options);first=false;return flatMap4(eff,()=>finish(state))})};return(input,options)=>{if(input===missing)return missingExit;try{if(!Array.isArray(input)){return fail6(new InvalidType(ast,input,options))}if(!elements){elements=ast.elements.map((ast)=>({ast,parser:compileField(ast)}));rest=ast.rest.map((ast)=>({ast,parser:compileField(ast)}))}return parse(input,options)}catch(error){return die3(error)}}}_rebuild(recur,checks,encodingChecks){const elements=mapOrSame(this.elements,recur);const rest=mapOrSame(this.rest,recur);return elements===this.elements&&rest===this.rest&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Arrays(this.isMutable,elements,rest,this.annotations,checks,undefined,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}getExpected(){return"array"}};function stepArray(s,item,exit,i){if(exit._tag==="Failure"){return wrapPropertyKeyIssue(s,s.ast,i,exit)}const value=exit===sameExit?item:exit[args];if(value!==missing){s.output[i]=value}else{const p=s.getParser(s.tailThreshold,i);if(isOptional(p.ast))return;const issue=new Pointer([i],new MissingKey(p.ast.context?.annotations));if(s.options.errors==="all"){if(s.issues)s.issues.push(issue);else s.issues=[issue]}else{return fail5(new Composite(s.ast,[issue],s.input,s.options))}}}var parseArrayOptions={onItem(s,item,i){const value=i<s.len?item:missing;return s.getParser(s.tailThreshold,i).parser(value,s.options)},step:stepArray};var parseArray=iterateEager()(parseArrayOptions);var parseArrayConcurrent=iterateConcurrent()(parseArrayOptions);var wrapPropertyKeyIssue=(s,ast,key,exit)=>{if(exit.cause.reasons.length===0){return exit}const issue=getSchemaIssue(exit.cause);if(issue===undefined){return failCause2(map5(exit.cause,(issue)=>new Composite(ast,[new Pointer([key],issue)],s.input,s.options)))}const pointer=new Pointer([key],issue);if(s.options.errors==="all"){if(s.issues)s.issues.push(pointer);else s.issues=[pointer]}else{return fail5(new Composite(ast,[pointer],s.input,s.options))}};var FINITE_PATTERN="[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?";function getIndexSignatureKeys(input,parameter,options=defaultParseOptions){let stringKeys;let symbolKeys;function go(parameter){switch(parameter._tag){case"String":case"TemplateLiteral":return(stringKeys??=Object.keys(input)).filter((k)=>parameter.matchPart(k,options)!==undefined);case"Number":return(stringKeys??=Object.keys(input)).filter((k)=>parameter.matchKey(k,options)!==undefined);case"Symbol":return(symbolKeys??=Object.getOwnPropertySymbols(input)).filter((k)=>Object.prototype.propertyIsEnumerable.call(input,k)&¶meter.matchKey(k,options)!==undefined);case"Union":return[...new Set(parameter.types.flatMap(go))];default:return[]}}return go(parameterFromPropertyKey(toEncoded(parameter)))}var PropertySignature=class{name;type;constructor(name,type){this.name=name;this.type=type}};function isIndexSignatureParameterSide(ast){switch(ast._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return true;case"Union":return ast.types.every(isIndexSignatureParameterSide);default:return false}}function isIndexSignatureParameterEncodedSide(ast){const encoded=getLastEncoding(ast);switch(encoded._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return true;case"Union":return encoded.types.every(isIndexSignatureParameterEncodedSide);default:return false}}function isIndexSignatureParameter(ast){return isIndexSignatureParameterSide(ast)&&isIndexSignatureParameterEncodedSide(ast)}var IndexSignature=class{parameter;type;constructor(parameter,type){if(!isIndexSignatureParameter(parameter)){throw new Error(`Invalid index signature parameter ${parameter._tag}`)}this.parameter=parameter;this.type=type;if(isOptional(type)||type.encoding!==undefined&&isOptional(toEncoded(type))){throw new Error("Cannot use `Schema.optionalKey` or `Schema.optional` with index signatures. Index signatures already allow keys to be absent; use `Schema.UndefinedOr` to allow `undefined` values.")}}};var Objects=class extends ASTNodeImpl{_tag="Objects";propertySignatures;indexSignatures;encodingChecks;constructor(propertySignatures,indexSignatures,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.propertySignatures=propertySignatures;this.indexSignatures=indexSignatures;this.encodingChecks=encodingChecks}getParser(compile,compileField=compile){const ast=this;const hasProperties=ast.propertySignatures.length;const indexCount=ast.indexSignatures.length;if(!hasProperties&&!indexCount){return fromRefinement(ast,isNotNullish)}let properties;let indexes;const compileMembers=()=>{if(!properties){properties=ast.propertySignatures.map((ps)=>({parser:compileField(ps.type),name:ps.name,type:ps.type}));indexes=indexCount?ast.indexSignatures.map((is)=>({is,parserKey:compile(parameterFromPropertyKey(is.parameter)),parserValue:compileField(is.type)})):undefined}return properties};const makeFallback=()=>{const expectedKeys=new Set(ast.propertySignatures.map((ps)=>typeof ps.name==="number"?globalThis.String(ps.name):ps.name));const finishIndex=(s,key,k2,inputValue,exitValue)=>{if(exitValue._tag==="Failure"){return wrapPropertyKeyIssue(s,ast,key,exitValue)??void_2}const value=exitValue===sameExit?inputValue:exitValue[args];if(k2!==missing&&value!==missing){if(hasProperties&&(expectedKeys.has(key)||expectedKeys.has(typeof k2==="number"?globalThis.String(k2):k2)))return void_2;assignProperty(s.out,k2,value)}return void_2};const parseIndex=(s,key,index,exitKey)=>{if(!exitKey){const eff=index.parserKey(key,s.options);if(!effectIsExit(eff)){return flatMap4(exit2(eff),(exit)=>parseIndex(s,key,index,exit))}exitKey=eff}if(exitKey._tag==="Failure"){return wrapPropertyKeyIssue(s,ast,key,exitKey)??void_2}const k2=exitKey===sameExit?key:exitKey[args];const inputValue=s.input[key];const result=index.parserValue(inputValue,s.options);return effectIsExit(result)?finishIndex(s,key,k2,inputValue,result):flatMap4(exit2(result),(exit)=>finishIndex(s,key,k2,inputValue,exit))};const parseStringIndex=(s,key,index)=>{const inputValue=s.input[key];const result=index.parserValue(inputValue,s.options);return effectIsExit(result)?finishIndex(s,key,key,inputValue,result):flatMap4(exit2(result),(exit)=>finishIndex(s,key,key,inputValue,exit))};const parseIndexes=indexCount?iterateConcurrent()({onItem:(s,[key,index])=>index.is.parameter===string2?parseStringIndex(s,key,index):parseIndex(s,key,index),step:(_s,_item,exit)=>exit._tag==="Failure"?exit:undefined}):undefined;return fnUntracedEager2(function*(input,options){if(input===missing){return missing}if(!(typeof input==="object"&&input!==null&&!Array.isArray(input))){return yield*fail6(new InvalidType(ast,input,options))}compileMembers();const record=input;const out={};const state={ast,input:record,out,issues:undefined,options};const errorsAllOption=options.errors==="all";const onExcessPropertyError=options.onExcessProperty==="error";const concurrency=options.concurrency===undefined?1:resolveConcurrency(options.concurrency);const indexKeys=indexCount&&onExcessPropertyError?ast.indexSignatures.map((index)=>getIndexSignatureKeys(record,index.parameter,options)):undefined;if(onExcessPropertyError){const coveredKeys=indexKeys?new Set(expectedKeys):expectedKeys;if(indexKeys){for(const keys of indexKeys){for(const key of keys)coveredKeys.add(key)}}const inputKeys=Reflect.ownKeys(record);for(let i=0;i<inputKeys.length;i++){const key=inputKeys[i];if(!coveredKeys.has(key)&&Object.prototype.propertyIsEnumerable.call(record,key)){const unexpected=new UnexpectedKey(ast,record[key],options);const issue=new Pointer([key],unexpected);if(errorsAllOption){if(state.issues){state.issues.push(issue)}else{state.issues=[issue]}continue}else{return yield*fail6(new Composite(ast,[issue],input,options))}}}}if(hasProperties){const eff=concurrency===1?parseProperties(state,properties):parsePropertiesConcurrent(state,properties,{concurrency});if(eff)yield*eff}if(indexCount&&concurrency===1){for(let i=0;i<indexCount;i++){const index=indexes[i];const parse=index.is.parameter===string2?parseStringIndex:parseIndex;const keys=indexKeys?.[i]??(index.is.parameter===string2?Object.keys(record):getIndexSignatureKeys(record,index.is.parameter,options));for(let j=0;j<keys.length;j++){const eff=parse(state,keys[j],index);if(!effectIsExit(eff))yield*eff;else if(eff._tag==="Failure")return yield*eff}}}else if(parseIndexes){const keyPairs=empty3();for(let i=0;i<indexCount;i++){const index=indexes[i];const keys=indexKeys?.[i]??(index.is.parameter===string2?Object.keys(record):getIndexSignatureKeys(record,index.is.parameter,options));for(let j=0;j<keys.length;j++){keyPairs.push([keys[j],index])}}const eff=parseIndexes(state,keyPairs,{concurrency});if(eff)yield*eff}if(state.issues){return yield*fail6(new Composite(ast,state.issues,input,options))}return out})};if(indexCount)return makeFallback();let fallback;const resume=(snapshot,index,pending)=>{const property=properties[index];return flatMap4(exit2(pending),(exit)=>{const state={...snapshot,out:{...snapshot.out}};const terminal=stepProperty(state,property,exit);if(terminal)return terminal;const done=()=>succeed9(state.out);const eff=parseProperties(state,properties.slice(index+1));return eff?flatMapEager2(eff,done):done()})};return(input,options)=>{if(input===missing)return missingExit;if(options.errors==="all"||options.onExcessProperty!==undefined||options.concurrency!==undefined&&resolveConcurrency(options.concurrency)!==1){return(fallback??=makeFallback())(input,options)}if(!(typeof input==="object"&&input!==null&&!Array.isArray(input))){return fail6(new InvalidType(ast,input,options))}const props=compileMembers();const record=input;const out={};const state={ast,input:record,out,issues:undefined,options};try{for(let index=0;index<props.length;index++){const property=props[index];const name=property.name;const hasKey=hasPropertySignature(record,name);const value=hasKey?record[name]:missing;const exit=property.parser(value,options);if(!effectIsExit(exit)){return resume(state,index,exit)}if(exit===sameExit){if(hasKey)assignProperty(out,name,value);continue}const terminal=stepProperty(state,property,exit);if(terminal)return terminal}}catch(error){return die3(error)}return succeed9(out)}}_rebuild(recur,recurParameter,checks,encodingChecks){const props=mapOrSame(this.propertySignatures,(ps)=>{const t=recur(ps.type);return t===ps.type?ps:new PropertySignature(ps.name,t)});const indexes=mapOrSame(this.indexSignatures,(is)=>{const p=recurParameter(is.parameter);const t=recur(is.type);return p===is.parameter&&t===is.type?is:new IndexSignature(p,t)});return props===this.propertySignatures&&indexes===this.indexSignatures&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Objects(props,indexes,this.annotations,checks,undefined,this.context,encodingChecks)}flip(recur){return this._rebuild(recur,recur,this.encodingChecks,this.checks)}recur(recur,recurParameter=recur){return this._rebuild(recur,recurParameter,this.checks,this.encodingChecks)}getExpected(){if(this.propertySignatures.length===0&&this.indexSignatures.length===0)return"object | array";return"object"}};function stepProperty(s,p,exit){if(exit._tag==="Failure"){return wrapPropertyKeyIssue(s,s.ast,p.name,exit)}if(exit===sameExit)return;const value=exit[args];if(value!==missing){assignProperty(s.out,p.name,value);return}delete s.out[p.name];if(!isOptional(p.type)){const issue=new Pointer([p.name],new MissingKey(p.type.context?.annotations));if(s.options.errors==="all"){if(s.issues)s.issues.push(issue);else s.issues=[issue];return}else{return fail5(new Composite(s.ast,[issue],s.input,s.options))}}}var parsePropertiesOptions={onItem(s,p){if(!hasPropertySignature(s.input,p.name)){return p.parser(missing,s.options)}const value=s.input[p.name];assignProperty(s.out,p.name,value);return p.parser(value,s.options)},step:stepProperty};var parseProperties=iterateEager()(parsePropertiesOptions);var parsePropertiesConcurrent=iterateConcurrent()(parsePropertiesOptions);function combineChecks(a,b){if(!a)return b;if(!b)return a;return[...a,...b]}function struct(fields,checks,annotations){return new Objects(Reflect.ownKeys(fields).map((key)=>{return new PropertySignature(key,fields[key].ast)}),[],annotations,checks)}function getAST(self){return self.ast}function union2(members,options,checks){return new Union(members.map(getAST),options,undefined,checks)}var toCandidate=memoizeIdempotent((ast)=>{while(true){if(isSuspend(ast))return unknown;const encoding=ast.encoding;if(!encoding){return ast.recur?.(toCandidate,identity)??ast}if(encoding.some((link)=>link.transformation._tag==="Middleware"&&link.transformation.decode!==identity))return unknown;ast=encoding[encoding.length-1].to}});function getCandidateTypes(ast){switch(ast._tag){case"Null":return["null"];case"Undefined":return["undefined"];case"String":case"TemplateLiteral":return["string"];case"Number":return["number"];case"Boolean":return["boolean"];case"Symbol":case"UniqueSymbol":return["symbol"];case"BigInt":return["bigint"];case"Arrays":return["array"];case"ObjectKeyword":return["object","array","function"];case"Objects":return ast.propertySignatures.length||ast.indexSignatures.length?["object"]:["string","number","boolean","symbol","bigint","object","array","function"];case"Enum":return Array.from(new Set(ast.enums.map(([,v])=>typeof v)));case"Literal":return[typeof ast.literal];case"Union":return Array.from(new Set(ast.types.flatMap(getCandidateTypes)));default:return["null","undefined","string","number","boolean","symbol","bigint","object","array","function"]}}function collectSentinels(ast){switch(ast._tag){default:return[];case"Declaration":{const s=ast.annotations?.[SENTINELS_ANNOTATION_KEY];return Array.isArray(s)?s:[]}case"Objects":return ast.propertySignatures.flatMap((ps)=>{const type=ps.type;if(!isOptional(type)){if(isLiteral(type)){return[{key:ps.name,literal:type.literal}]}if(isUniqueSymbol(type)){return[{key:ps.name,literal:type.symbol}]}}return[]});case"Arrays":return ast.elements.flatMap((e,i)=>{if(!isOptional(e)){if(isLiteral(e)){return[{key:i,literal:e.literal}]}if(isUniqueSymbol(e)){return[{key:i,literal:e.symbol}]}}return[]});case"Union":{if(ast.types.length===0)return[];const members=ast.types.map((type)=>collectSentinels(toCandidate(type)));return members[0].filter((s)=>members.every((sentinels)=>sentinels.some((o)=>o.key===s.key&&o.literal===s.literal)))}case"Suspend":return collectSentinels(ast.thunk())}}var candidateIndexCache=new WeakMap;var emptyCandidates=Object.freeze([]);var getRuntimeType=(input)=>input===null?"null":Array.isArray(input)?"array":typeof input;var hasPropertySignature=(input,key)=>key==="__proto__"?Object.hasOwn(input,key):(key in input);function getCandidateIndex(types){let index=candidateIndexCache.get(types);if(index)return index;let bySentinel;let sentinelCandidateCount=0;let otherwise;let literalCandidates;let onlyLiterals=true;const literalOf=[];for(let i=0;i<types.length;i++){const a=types[i];const encoded=toCandidate(a);if(isNever2(encoded))continue;if(isLiteral(encoded)||isUniqueSymbol(encoded)){literalCandidates??=new Map;const literal=isLiteral(encoded)?encoded.literal:encoded.symbol;literalOf[i]=literal;let arr=literalCandidates.get(literal);if(!arr)literalCandidates.set(literal,arr=[]);arr.push(i)}else{onlyLiterals=false}const sentinels=collectSentinels(encoded);if(sentinels.length){bySentinel??=new Map;sentinelCandidateCount++;for(const{key,literal}of sentinels){let entry=bySentinel.get(key);if(!entry)bySentinel.set(key,entry=[new Map,new Set]);entry[1].add(i);let indexes=entry[0].get(literal);if(!indexes)entry[0].set(literal,indexes=new Set);indexes.add(i)}}else{otherwise??={};const candidateTypes=getCandidateTypes(encoded);for(const t of candidateTypes)(otherwise[t]??=[]).push(i)}}const fallbacks={};const getFallback=(type)=>fallbacks[type]??=Object.freeze(otherwise?.[type]??emptyCandidates);if(onlyLiterals&&literalCandidates){literalCandidates.forEach(Object.freeze);index=(input)=>literalCandidates.get(input)??emptyCandidates}else if(bySentinel?.size===1&&!otherwise){const[key,[byValue]]=bySentinel.entries().next().value;const candidates=new Map;for(const[literal,indexes]of byValue){candidates.set(literal,Object.freeze(Array.from(indexes)))}const all=Object.freeze(types.map((_,i)=>i));index=(input,isConstructor)=>{if(isObjectKeyword(input)){const value=hasPropertySignature(input,key)?input[key]:undefined;if(value!==undefined)return candidates.get(value)??emptyCandidates;if(isConstructor)return all}return emptyCandidates}}else if(bySentinel){let commonSentinel;for(const entry of bySentinel){if((!commonSentinel||entry[1][0].size>commonSentinel[1][0].size)&&entry[1][1].size===sentinelCandidateCount){commonSentinel=entry}}index=(input,isConstructor)=>{const runtimeType=getRuntimeType(input);if(!isObjectKeyword(input))return getFallback(runtimeType);const selected=new Set(otherwise?.[runtimeType]);let directKey;if(commonSentinel){const[key,[byValue]]=commonSentinel;const hasKey=hasPropertySignature(input,key);const value=hasKey?input[key]:undefined;if(hasKey&&(!isConstructor||value!==undefined)){const match=byValue.get(value);if(!match)return getFallback(runtimeType);for(const i of match)selected.add(i);directKey=key}}if(directKey===undefined){for(const[key,[byValue,all]]of bySentinel){const hasKey=hasPropertySignature(input,key);const value=hasKey?input[key]:undefined;if(hasKey&&(!isConstructor||value!==undefined)){const match=byValue.get(value);if(match){for(const i of match)selected.add(i)}}else if(isConstructor){for(const i of all)selected.add(i)}}}for(const[key,[byValue,all]]of bySentinel){if(key===directKey)continue;const hasKey=hasPropertySignature(input,key);const value=hasKey?input[key]:undefined;if(hasKey&&(!isConstructor||value!==undefined)){const match=byValue.get(value);for(const i of selected){if(all.has(i)&&!match?.has(i))selected.delete(i)}}}return Array.from(selected).sort((a,b)=>a-b)}}else{index=(input)=>{const fallback=getFallback(getRuntimeType(input));return literalCandidates?fallback.filter((i)=>literalOf[i]===undefined||literalOf[i]===input):fallback}}candidateIndexCache.set(types,index);return index}var Union=class extends ASTNodeImpl{_tag="Union";types;options;encodingChecks;constructor(types,options,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.types=types;this.options=options;this.encodingChecks=encodingChecks}getParser(compile,compileField){const ast=this;const isConstructor=compileField!==undefined;const parsers=[];const parser=(i)=>parsers[i]??=compile(ast.types[i]);let index;return(input,options)=>{if(input===missing){return missingExit}const candidates=(index??=getCandidateIndex(ast.types))(input,isConstructor);if(candidates.length===0){return fail6(new AnyOf(ast,[],input,options))}if(candidates.length===1){const result=parser(candidates[0])(input,options);if(result._tag==="Success")return result;return effectIsExit(result)?failSingleUnionCandidate(ast,result.cause,input,options):catchSingleUnionCandidate(ast,result,input,options)}return parseUnionCandidates(ast,parser,candidates,input,options)}}_rebuild(recur,checks,encodingChecks){const types=mapOrSame(this.types,recur);return types===this.types&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Union(types,this.options,this.annotations,checks,undefined,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}matchPart(s,options){for(const type of this.types){const out=type.matchPart(s,options);if(out!==undefined)return out}return}getExpected(getExpected){const expected=this.annotations?.expected;if(typeof expected==="string")return expected;if(this.types.length===0)return"never";const types=this.types.map((type)=>{const encoded=toEncoded(type);switch(encoded._tag){case"Arrays":{const literals=encoded.elements.filter(isLiteral);if(literals.length>0){return`${formatIsMutable(encoded.isMutable)}[ ${literals.map((e)=>getExpected(e)+formatIsOptional(e.context?.isOptional)).join(", ")}, ... ]`}break}case"Objects":{const literals=encoded.propertySignatures.filter((ps)=>isLiteral(ps.type));if(literals.length>0){return`{ ${literals.map((ps)=>`${formatIsMutable(ps.type.context?.isMutable)}${formatPropertyKey(ps.name)}${formatIsOptional(ps.type.context?.isOptional)}: ${getExpected(ps.type)}`).join(", ")}, ... }`}break}}return getExpected(encoded)});return Array.from(new Set(types)).join(" | ")}};function failSingleUnionCandidate(ast,cause,input,options){const issue=getSchemaIssue(cause);if(!issue)return failCause2(cause);return fail5(new AnyOf(ast,[issue],input,options))}function catchSingleUnionCandidate(ast,result,input,options){return catchCause2(result,(cause)=>failSingleUnionCandidate(ast,cause,input,options))}function parseUnionCandidates(ast,parser,candidates,input,options){const state={ast,parser,input,out:undefined,successes:ast.options?.mode==="oneOf"?[]:undefined,issues:undefined,options};const eff=parseUnion(state,candidates);if(!eff){if(state.out)return state.out;return fail6(new AnyOf(ast,state.issues??[],input,options))}if(effectIsExit(eff))return resumeUnion(eff,state);let first=true;return suspend2(()=>{if(!first)return parseUnionCandidates(ast,parser,candidates,input,options);first=false;return resumeUnion(eff,state)})}function resumeUnion(eff,state){return flatMapEager2(eff,(_)=>{if(state.out===sameExit)return succeed7(state.input);if(state.out)return state.out;return fail6(new AnyOf(state.ast,state.issues??[],state.input,state.options))})}var parseUnion=iterateEager()({onItem(s,i){return s.parser(i)(s.input,s.options)},step(s,i,exit){if(exit._tag==="Failure"){const issue=getSchemaIssue(exit.cause);if(issue===undefined){return exit}if(s.issues)s.issues.push(issue);else s.issues=[issue]}else{if(s.out&&s.successes){s.successes.push(s.ast.types[i]);return fail5(new OneOf(s.ast,s.successes,s.input,s.options))}s.out=exit;if(s.successes){s.successes.push(s.ast.types[i])}else{return void_2}}}});var nonFiniteLiterals=new Union([new Literal("Infinity"),new Literal("-Infinity"),new Literal("NaN")]);function formatIsMutable(isMutable){return isMutable?"":"readonly "}function formatIsOptional(isOptional){return isOptional?"?":""}var Filter2=class extends Class{_tag="Filter";run;annotations;aborted;constructor(run,annotations=undefined,aborted=false){super();this.run=run;this.annotations=annotations;this.aborted=aborted}annotate(annotations){return new Filter2(this.run,{...this.annotations,...annotations},this.aborted)}abort(){return new Filter2(this.run,this.annotations,true)}and(other,annotations){return new FilterGroup([this,other],annotations)}};var FilterGroup=class extends Class{_tag="FilterGroup";checks;annotations;constructor(checks,annotations=undefined){super();this.checks=checks;this.annotations=annotations}annotate(annotations){return new FilterGroup(this.checks,{...this.annotations,...annotations})}and(other,annotations){return new FilterGroup([this,other],annotations)}};function makeFilter(filter,annotations,aborted=false){return new Filter2((input,ast,options)=>normalizeFilterOutput(ast,filter(input,ast,options),input,options),annotations,aborted)}function isFinite2(annotations){return makeFilter((n)=>globalThis.Number.isFinite(n),{expected:"a finite number",representation:{id:"effect/schema/isFinite",payload:null},toJsonSchema:()=>({type:"number"}),toCode:()=>({runtime:"Schema.isFinite()"}),arbitraryConstraint:{number:"finite"},...annotations})}var finite=appendChecks(number2,[isFinite2()]);var numberToJson=new Link(new Union([finite,nonFiniteLiterals]),new Transformation(Number3(),transform((n)=>globalThis.Number.isFinite(n)?n:globalThis.String(n))));function isPattern(regExp,annotations){const copy=new globalThis.RegExp(regExp);const payload={source:copy.source,flags:copy.flags};return makeFilter((s)=>{copy.lastIndex=0;return copy.test(s)},{expected:`a string matching the RegExp ${payload.source}`,representation:{id:"effect/schema/isPattern",payload},toJsonSchema:()=>[{},true],arbitraryConstraint:{patterns:[payload]},...annotations})}var bodyOwners=new WeakMap;function copy2(ast,changes){const out=Object.assign(Object.create(Object.getPrototypeOf(ast)),ast,changes);if(Reflect.ownKeys(changes).every((key)=>key==="context"||key==="encoding")){bodyOwners.set(out,getContextOwner(ast))}return out}function getContextOwner(ast){const existing=bodyOwners.get(ast);if(existing!==undefined)return existing;if(ast.encoding===undefined)return ast;const owner=Object.assign(Object.create(Object.getPrototypeOf(ast)),ast,{encoding:undefined});bodyOwners.set(ast,owner);return owner}function replaceEncoding(ast,encoding){return ast.encoding===encoding?ast:copy2(ast,{encoding})}function replaceContext(ast,context){if(ast.context===context){return ast}const owner=getContextOwner(ast);if(owner.context===context&&owner.encoding===ast.encoding){return owner}return copy2(ast,{context})}function getLastEncoding(ast){return ast.encoding?getLastEncoding(ast.encoding[ast.encoding.length-1].to):ast}function annotate(ast,annotations){if(ast.checks){const last=ast.checks[ast.checks.length-1];return replaceChecks(ast,append(ast.checks.slice(0,-1),last.annotate(annotations)))}return copy2(ast,{annotations:{...ast.annotations,...annotations}})}function replaceChecks(ast,checks){if(ast._tag==="Suspend"&&checks){throw new Error("Cannot add checks to Suspend")}if(ast.checks===checks){return ast}return copy2(ast,{checks})}function appendChecks(ast,checks){return replaceChecks(ast,combineChecks(ast.checks,checks))}function mapLink(link,f){const to=f(link.to);return to===link.to?link:new Link(to,link.transformation)}function updateLastLink(encoding,f){const links=encoding;const last=links[links.length-1];const out=mapLink(last,f);return out===last?encoding:append(encoding.slice(0,encoding.length-1),out)}function applyToLastLink(f){return(ast)=>ast.encoding?replaceEncoding(ast,updateLastLink(ast.encoding,f)):ast}function replaceContextLastLink(ast,context){return applyToLastLink((ast)=>replaceContext(ast,context))(ast)}function applyToSelfOrLastLinkEncoding(f){function out(ast){return ast.encoding?replaceEncoding(ast,updateLastLink(ast.encoding,out)):f(ast)}return memoize(out)}function applyToSelfOrLastLinkEncodingIdempotent(f,options){function out(ast){if(ast.encoding){const last=ast.encoding[ast.encoding.length-1];return options?.stopAt?.(last)?ast:replaceEncoding(ast,updateLastLink(ast.encoding,out))}return f(ast)}return memoizeIdempotent(out)}function appendTransformation(from,transformation,to){const link=new Link(from,transformation);return replaceEncoding(to,to.encoding?[...to.encoding,link]:[link])}function mapOrSame(as,f){let out;for(let i=0;i<as.length;i++){const a=as[i];const fa=f(a);if(out){out[i]=fa}else if(fa!==a){out=new Array(as.length);for(let j=0;j<i;j++){out[j]=as[j]}out[i]=fa}}return out??as}function annotateKey(ast,annotations){const context=ast.context?new Context(ast.context.isOptional,ast.context.isMutable,ast.context.constructorDefault,{...ast.context.annotations,...annotations}):new Context(false,false,undefined,annotations);return replaceContext(ast,context)}var optionalKey=memoizeIdempotent((ast)=>{const context=ast.context?ast.context.isOptional===false?new Context(true,ast.context.isMutable,ast.context.constructorDefault,ast.context.annotations):ast.context:new Context(true,false);return optionalKeyLastLink(replaceContext(ast,context))});var optionalKeyLastLink=applyToLastLink(optionalKey);var optional=memoize((ast)=>optionalKey(new Union([ast,undefined_2])));function withConstructorDefault(ast,defaultValue){const context=ast.context?new Context(ast.context.isOptional,ast.context.isMutable,defaultValue,ast.context.annotations):new Context(false,false,defaultValue);return replaceContext(ast,context)}function decodeTo(from,to,transformation){return appendTransformation(from,transformation,to)}function parseParameter(ast){const literals=[];const parameters=[];function addLiteral(literal){if(!literals.includes(literal)){literals.push(literal)}}function go(ast){switch(ast._tag){case"Literal":if(isPropertyKey(ast.literal)){addLiteral(ast.literal)}return;case"UniqueSymbol":addLiteral(ast.symbol);return;case"Enum":for(const[,value]of ast.enums){addLiteral(value)}return;case"Never":return;case"Union":for(let i=0;i<ast.types.length;i++){go(ast.types[i])}return;default:parameters.push(ast)}}go(ast);return{literals,parameters}}function record(key,value){const{literals,parameters:indexSignatures}=parseParameter(key);return new Objects(literals.map((literal)=>new PropertySignature(literal,value)),indexSignatures.map((parameter)=>new IndexSignature(parameter,value)))}function isOptional(ast){return ast.context?.isOptional??false}function isStructuralCheck(check){return check.annotations?.[STRUCTURAL_ANNOTATION_KEY]===true||check._tag==="FilterGroup"&&check.checks.every(isStructuralCheck)}function extractStructuralChecks(checks){function extract(check){if(isStructuralCheck(check))return[check];return check._tag==="FilterGroup"?check.checks.flatMap(extract):[]}const out=checks.flatMap(extract);return isArrayNonEmpty2(out)?out:undefined}function canPreserveEncodingChecks(ast){let preserve=true;function visit(child){preserve=preserve&&!child.encoding&&!isSuspend(child);if(preserve&&"recur"in child)child.recur(visit);return child}if("recur"in ast)ast.recur(visit);return preserve}var toType=memoizeIdempotent((ast)=>{const owner=getContextOwner(ast);if(owner!==ast){const type=toType(owner);return type===owner&&ast.encoding===undefined?ast:replaceContext(type,ast.context)}const type="recur"in ast?ast.recur(toType):ast;if("encodingChecks"in type&&type.encodingChecks){const checks=canPreserveEncodingChecks(ast)?type.encodingChecks:isArrays(type)||isObjects(type)||isDeclaration(type)&&type.typeParameters.length>0?extractStructuralChecks(type.encodingChecks):undefined;return copy2(type,{encodingChecks:undefined,checks:combineChecks(type.checks,checks)})}return type});var toEncoded=memoizeIdempotent((ast)=>{return toType(flip2(ast))});function flipEncoding(ast,encoding){const links=encoding;const len=links.length;const last=links[len-1];const ls=[new Link(flip2(replaceEncoding(ast,undefined)),links[0].transformation.flip())];for(let i=1;i<len;i++){ls.unshift(new Link(flip2(links[i-1].to),links[i].transformation.flip()))}const to=flip2(last.to);if(to.encoding){return replaceEncoding(to,[...to.encoding,...ls])}else{return replaceEncoding(to,ls)}}var flip2=memoize((ast)=>{if(ast.encoding){return flipEncoding(ast,ast.encoding)}const owner=getContextOwner(ast);if(owner!==ast){const flipped=flip2(owner);return flipped===owner?ast:replaceContext(flipped,ast.context)}return"flip"in ast?ast.flip(flip2):("recur"in ast)?ast.recur(flip2):ast});function fromConst(ast,value){const succeed=value===0?sameExit:succeed9(value);return(input,options)=>{if(input===missing)return missingExit;if(input===value)return succeed;return fail6(new InvalidType(ast,input,options))}}function fromRefinement(ast,refinement){return(input,options)=>{if(input===missing)return missingExit;if(refinement(input))return sameExit;return fail6(new InvalidType(ast,input,options))}}var parameterFromPropertyKey=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{switch(ast._tag){default:return ast;case"Number":return ast.toCodecStringTree();case"Union":return ast.recur(parameterFromPropertyKey)}});var parameterFromString=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{switch(ast._tag){default:return ast;case"Symbol":case"UniqueSymbol":return ast.toCodecStringTree();case"Union":return ast.recur(parameterFromString)}});var isStringFiniteRegExp=new globalThis.RegExp(`^${FINITE_PATTERN}$`);var isStringNumberRegExp=new globalThis.RegExp(`^(?:${FINITE_PATTERN}|Infinity|-Infinity|NaN)$`);function isStringFinite(annotations){return isPattern(isStringFiniteRegExp,{expected:"a string representing a finite number",representation:{id:"effect/schema/isStringFinite",payload:null},toJsonSchema:()=>({pattern:isStringFiniteRegExp.source}),...annotations})}var finiteString=appendChecks(string2,[isStringFinite()]);var finiteToString=new Link(finiteString,numberFromString);var numberToString=new Link(new Union([finiteString,nonFiniteLiterals]),numberFromString);var BIGINT_PATTERN="-?\\d+";var isStringBigIntRegExp=new globalThis.RegExp(`^${BIGINT_PATTERN}$`);var REGEXP_PATTERN="Symbol\\(([\\s\\S]*)\\)";var isStringSymbolRegExp=new globalThis.RegExp(`^${REGEXP_PATTERN}$`);function collectIssues(checks,value,issues,ast,options){for(let i=0;i<checks.length;i++){const check=checks[i];if(check._tag==="FilterGroup"){issues=collectIssues(check.checks,value,issues,ast,options);if(issues&&(options.errors!=="all"||issues[issues.length-1].filter.aborted)){return issues}}else{const issue=check.run(value,ast,options);if(issue){const filter=new Filter(check,issue,value,options);if(issues)issues.push(filter);else issues=[filter];if(options.errors!=="all"||check.aborted){return issues}}}}return issues}function getConstructorDescriptor(ast){if(!isDeclaration(ast))return;const getDescriptor=ast.annotations?.[CONSTRUCTOR_ANNOTATION_KEY];return isFunction(getDescriptor)?getDescriptor(ast.typeParameters):undefined}function isJsonLeaf(u){return u===null||typeof u==="string"||typeof u==="boolean"||typeof u==="number"&&globalThis.Number.isFinite(u)}function isStringTreeLeaf(u){return u===undefined||typeof u==="string"}function isTree(u,isLeaf){const cache=new WeakMap;const stack=[];outer:while(true){if(typeof u!=="object"||u===null){if(!isLeaf(u)){return false}}else{const value=u;const cached=cache.get(value);if(cached===false){return false}if(cached===undefined){const isArray=Array.isArray(value);if(!isArray){const prototype=Object.getPrototypeOf(value);if(prototype!==null&&prototype!==Object.prototype&&Object.getPrototypeOf(prototype)!==null){return false}}cache.set(value,false);stack.push({value,keys:isArray?value.length:Object.keys(value),index:0})}}while(stack.length>0){const frame=stack[stack.length-1];const keys=frame.keys;if(typeof keys==="number"){if(frame.index<keys){u=frame.value[frame.index++];continue outer}}else if(frame.index<keys.length){u=frame.value[keys[frame.index++]];continue outer}cache.set(frame.value,true);stack.pop()}return true}}function isJson(u){return isTree(u,isJsonLeaf)}var Json=new Declaration([],()=>(input,ast,options)=>isJson(input)?sameExit:fail6(new InvalidType(ast,input,options)),{representation:{id:"effect/schema/Json",payload:null},expected:"JSON value",toCodecJson:()=>{return},toCodecStringTree:()=>unknownToStringTree});function isStringTree(u){return isTree(u,isStringTreeLeaf)}var StringTree=new Declaration([],()=>(input,ast,options)=>isStringTree(input)?sameExit:fail6(new InvalidType(ast,input,options)),{expected:"StringTree",toCodecStringTree:()=>{return}});var unknownToStringTree=new Link(StringTree,passthrough2());var flatMapTransformation=(result,current,f)=>result===sameExit?f(current):flatMapEager2(result,f);function compileTransformation(transformation){const apply=compileTransformationUnsafe(transformation);return(result,current,options)=>{try{return apply(result,current,options)}catch(error){return die3(error)}}}function compileTransformationUnsafe(transformation){if(transformation._tag==="Middleware"){return(result,current,options)=>{const transformed=result===sameExit?transformation.decode(succeed9(toOption(current)),options):transformation.decode(mapEager2(result,toOption),options);return fromOptionalEffect(transformed)}}const getter=transformation.decode;switch(getter._tag){case"Passthrough":return(result,current)=>result===sameExit?succeed9(current):result;case"Transform":{const transform=(value)=>value===missing?missingExit:succeed9(getter.transform(value));return(result,current)=>flatMapTransformation(result,current,transform)}case"TransformOptional":{const transform=(value)=>fromOptionExit(getter.transform(toOption(value)));return(result,current)=>flatMapTransformation(result,current,transform)}case"TransformEffect":return(result,current,options)=>flatMapTransformation(result,current,(value)=>value===missing?missingExit:getter.transform(value,options));case"TransformOptionalEffect":return(result,current,options)=>flatMapTransformation(result,current,(value)=>fromOptionalEffect(getter.transform(toOption(value),options)))}}var fromOptionalEffect=(effect)=>flatMapEager2(effect,fromOptionExit);var wrapEncoding=(ast,input,options,effect)=>catchCause2(effect,(cause)=>failCauseSync2(()=>map5(cause,(issue)=>new Encoding(ast,issue,input,options))));function makeConstructorParser(descriptor,compile){const transform=compileTransformation(descriptor.link.transformation);let sourceParser;return(input,options)=>{if(input===missing)return missingExit;if(descriptor.isConstructed(input))return sameExit;const result=(sourceParser??=compile(descriptor.link.to))(input,options);return transform(result,input,options)}}function withDefault(ast,parser){const defaultValue=ast.context.constructorDefault;return(input,options)=>{if(input!==missing&&input!==undefined)return parser(input,options);const result=defaultValue;if(effectIsExit(result)&&result._tag==="Success"){const local=parser(result[args],options);return local===sameExit?result:local}return flatMapEager2(wrapEncoding(ast,input,options,result),(value)=>{const local=parser(value,options);return local===sameExit?succeed9(value):local})}}function compileField(ast,compile){const parser=compile(ast);return ast.context?.constructorDefault===undefined?parser:withDefault(ast,parser)}function compile2(ast,compile,compileField,base,specialize){if(ast._tag==="Declaration"){for(const parameter of ast.typeParameters)compile(parameter)}const descriptor=compileField?getConstructorDescriptor(ast):undefined;const parser=descriptor?makeConstructorParser(descriptor,compile):base??ast.getParser(compile,compileField);const checks=ast.checks;const links=ast.encoding;const transformations=links?.map((link)=>compileTransformation(link.transformation));const encodingChecks=ast.encodingChecks;if(!links&&!checks&&!encodingChecks){return parser}let encodingParsers;const parseChecks=(input,options)=>{let result=parser(input,options);try{if(encodingChecks&&!options.disableChecks){if(effectIsExit(result)){if(result._tag==="Success"){const output=result===sameExit?input:result[args];if(input!==missing&&output!==missing){const issues=collectIssues(encodingChecks,input,undefined,ast,options);if(issues){result=fail6(new Composite(ast,issues,input,options))}}}}else{result=flatMap4(result,(value)=>{if(input!==missing&&value!==missing){const issues=collectIssues(encodingChecks,input,undefined,ast,options);if(issues){return fail6(new Composite(ast,issues,input,options))}}return succeed7(value)})}}if(checks&&!options.disableChecks){if(effectIsExit(result)){if(result._tag==="Success"){const value=result===sameExit?input:result[args];if(value===missing)return result;const issues=collectIssues(checks,value,undefined,ast,options);if(issues){result=fail6(new Composite(ast,issues,value,options))}}}else{result=flatMap4(result,(value)=>{if(value!==missing){const issues=collectIssues(checks,value,undefined,ast,options);if(issues){return fail6(new Composite(ast,issues,value,options))}}return succeed7(value)})}}return result}catch(error){return die3(error)}};const parseLocal=specialize===undefined?parseChecks:specialize(parseChecks);if(!links){return parseLocal}return(input,options)=>{const parsers=encodingParsers??=links.map((link)=>compile(link.to));let current=input;let result=parsers[parsers.length-1](input,options);for(let i=links.length-1;i>=0;i--){result=transformations[i](result,current,options);if(i!==0){const next=parsers[i-1];if(result._tag==="Success"){current=result[args];result=next(current,options)}else{result=flatMapEager2(result,(value)=>{const nextResult=next(value,options);return nextResult===sameExit?succeed9(value):nextResult})}}}if(result._tag==="Success"){const value=result[args];const local=parseLocal(value,options);return local===sameExit?result:local}result=wrapEncoding(ast,input,options,result);return flatMapEager2(result,(value)=>{const local=parseLocal(value,options);return local===sameExit?succeed9(value):local})}}var invalid3=Symbol();var cache=new WeakMap;var compiler;var compilerAdaptersEnabled=false;var decodeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve3,ast,"parser"):resolve3(ast).parser;var makeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve3,ast,"makeEffect"):resolve3(ast).makeEffect;var makeField=(ast)=>compileField(ast,makeChild);class InterpretedEntry{ast;constructor(ast){this.ast=ast}get decodeEffect(){return this.cachedDecodeEffect??=compile2(this.ast,decodeChild)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=compile2(this.ast,makeChild,makeField)}}class CompilerEntry extends InterpretedEntry{compiled;resolve;constructor(ast,compiled,resolve){super(ast);this.compiled=compiled;this.resolve=resolve}save(key,value){Object.defineProperty(this,key,{value});return value}operation(key){const compiled=this.compiled;return typeof compiled==="function"?compiled(this.ast,this.resolve,key):compiled?.[key]}get is(){return this.save("is",this.operation("is"))}get decode(){return this.save("decode",this.operation("decode"))}get make(){return this.save("make",this.operation("make"))}get compiledMakeEffect(){return this.save("compiledMakeEffect",this.operation("makeEffect"))}get decodeEffect(){return this.save("decodeEffect",this.operation("decodeEffect")??compile2(this.ast,(ast)=>lazyParser(this.resolve,ast,"parser")))}get parser(){const decode=this.decode;return decode===undefined?this.decodeEffect:this.save("parser",withDecode(decode,()=>this.decodeEffect))}get makeEffect(){const makeEffect=this.compiledMakeEffect;if(makeEffect!==undefined)return this.save("makeEffect",makeEffect);const child=(ast)=>lazyParser(this.resolve,ast,"makeEffect");return this.save("makeEffect",compile2(this.ast,child,(ast)=>compileField(ast,child)))}}function withDecode(fastDecode,decodeEffect){let detailed;return(input,options)=>{if(input!==missing){try{const value=fastDecode(input,options);if(value!==invalid3)return value===input?sameExit:succeed9(value)}catch(error){return die3(error)}}return(detailed??=decodeEffect())(input,options)}}function lazyParser(resolve,ast,operation){const entry=resolve(ast);if(entry.compiled===undefined||Object.hasOwn(entry,operation)){return entry[operation]}let parser;return(input,options)=>(parser??=entry[operation])(input,options)}function resolve3(ast){const cached=cache.get(ast);if(cached!==undefined)return cached;const entry=compiler===undefined?new InterpretedEntry(ast):new CompilerEntry(ast,compiler(ast,resolve3),resolve3);cache.set(ast,entry);return entry}function makeEffect(schema){const ast=schema.ast;let parser;return(input,options)=>{return(parser??=runWithCompiler(constructorCompiler,toType(ast)))(input,options?.disableChecks?options?.parseOptions?{...options.parseOptions,disableChecks:true}:{disableChecks:true}:options?.parseOptions)}}function makeOption(schema){const parser=makeEffect(schema);return(input,options)=>{const exit=runSyncExit2(parser(input,options));if(isSuccess3(exit)){return some2(exit.value)}getSchemaIssueOrThrow(exit.cause,"Option adapter can only return none for schema issues");return none2()}}function make22(schema){return makeConstructorSync(toType(schema.ast))}function is(schema){return _is(schema.ast)}function makeIs(ast){if(!compilerAdaptersEnabled){const parser=asExit(run(ast));return(input)=>{const exit=parser(input,defaultParseOptions);if(isSuccess3(exit))return true;getSchemaIssueOrThrow(exit.cause,"Type guard adapter can only return false for schema issues");return false}}const entry=resolve3(ast);const guard=entry.is;if(guard!==undefined){return(input)=>{try{return guard(input,defaultParseOptions)}catch(error){getSchemaIssueOrThrow(die2(error),"Type guard adapter can only return false for schema issues");return false}}}const parser=entry.parser;return(input)=>{const exit=runSyncExit2(parserResult(parser(input,defaultParseOptions),input));if(isSuccess3(exit))return true;getSchemaIssueOrThrow(exit.cause,"Type guard adapter can only return false for schema issues");return false}}function _is(ast){const typeAST=toType(ast);let guard=(input)=>{guard=makeIs(typeAST);return guard(input)};return(input)=>{return guard(input)}}function decodeUnknownEffect(schema,options){const parser=run(schema.ast);return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}function encodeUnknownEffect(schema,options){const parser=run(flip2(schema.ast));return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}var mergeParseOptions=(options,overrideOptions)=>overrideOptions?{...options,...overrideOptions}:options;var getValue=(value)=>{if(value===missing){return fail6(new InvalidValue)}return succeed7(value)};function run(ast){return runWithCompiler(normalCompiler,ast)}function parserResult(result,input){if(result===sameExit){return succeed7(input)}if(!effectIsExit(result)){return flatMapEager2(result,getValue)}return result[args]===missing?getValue(missing):result}function runWithCompiler(compiler,ast){let parser;return(input,options)=>{const result=(parser??=compiler(ast))(input,options??defaultParseOptions);if(result===sameExit){return succeed7(input)}if(!effectIsExit(result)){return flatMapEager2(result,getValue)}return result[args]===missing?getValue(missing):result}}function asExit(parser){return(input,options)=>runSyncExit2(parser(input,options))}function runSync3(effect,message){const exit=runSyncExit2(effect);if(isSuccess3(exit)){return exit.value}const issue=getSchemaIssueOrThrow(exit.cause,message);throw new Error("Schema validation failed",{cause:issue})}var constructorDefectMessage="Constructor adapter can only throw schema issues";function throwConstructorDefect(error){throw new Error(constructorDefectMessage,{cause:die2(error)})}function makeConstructorSync(ast){let entry;return(input,options)=>constructSync(entry??=resolve3(ast),input,options)}function constructSync(entry,input,options){const parseOptions=options?.disableChecks?options.parseOptions?{...options.parseOptions,disableChecks:true}:{disableChecks:true}:options?.parseOptions??defaultParseOptions;const make=entry.make;if(make!==undefined&&input!==missing){let output;try{output=make(input,parseOptions)}catch(error){throwConstructorDefect(error)}if(output!==invalid3&&output!==missing)return output}return runSync3(parserResult(entry.makeEffect(input,parseOptions),input),constructorDefectMessage)}function makeClassSync(ast,input,options,construct){const entry=resolve3(ast);const descriptor=getConstructorDescriptor(ast);if(descriptor===undefined||entry.make!==undefined||entry.compiledMakeEffect!==undefined){return constructSync(entry,input,options)}if(descriptor.isConstructed(input))return input;const fields=constructSync((entry.resolve??resolve3)(descriptor.link.to),input,options);try{return construct(fields)}catch(error){throwConstructorDefect(error)}}var normalCompiler=(ast)=>resolve3(ast).parser;var constructorCompiler=(ast)=>resolve3(ast).makeEffect;var TypeId24="~effect/Schema/Schema";var RebuildOptions=Symbol();var SchemaProto={[TypeId24]:TypeId24,get make(){const value=make22(this);Object.defineProperty(this,"make",{value,enumerable:true});return value},get makeEffect(){const value=makeEffect(this);Object.defineProperty(this,"makeEffect",{value,enumerable:true});return value},get makeOption(){const value=makeOption(this);Object.defineProperty(this,"makeOption",{value,enumerable:true});return value},pipe(){return pipeArguments(this,arguments)},annotate(annotations){return this.rebuild(annotate(this.ast,annotations))},annotateKey(annotations){return this.rebuild(annotateKey(this.ast,annotations))},check(...checks){return this.rebuild(appendChecks(this.ast,checks))},rebuild(ast){return make23(ast,this[RebuildOptions])}};function make23(ast,options){function Schema(){}const self=Object.setPrototypeOf(Schema,SchemaProto);if(options&&(Object.hasOwn(options,"name")||Object.hasOwn(options,"length")||Object.hasOwn(options,"__proto__"))){Object.defineProperties(self,Object.getOwnPropertyDescriptors({...options}))}else{Object.assign(self,options)}self[RebuildOptions]=options;self.ast=ast;return self}function makeCodecDerivation(step,options){const deriveBody=memoize((owner)=>{const body=replaceContext(owner,undefined);const out=step(body,recur);return out===body?null:out});const recur=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{const derived=deriveBody(getContextOwner(ast));if(derived===null)return ast;const out=replaceContext(derived,ast.context);return ast.context===undefined?out:replaceContextLastLink(out,withoutConstructorDefault(ast.context))},options);return recur}function withoutConstructorDefault(context){return context.constructorDefault===undefined?context:new Context(context.isOptional,context.isMutable,undefined,context.annotations)}function validateCanonicalObjectPropertyNames(ast){if(ast.propertySignatures.some((ps)=>typeof ps.name!=="string")){throw new globalThis.Error("Objects property names must be strings",{cause:ast})}}function makeReorder(getPriority){return(types)=>{const sortedTypes=[...types].sort((a,b)=>getPriority(toEncoded(a))-getPriority(toEncoded(b)));const orderChanged=sortedTypes.some((ast,index)=>ast!==types[index]);if(!orderChanged)return types;return sortedTypes}}function toCodecStringTree(schema){return make23(toCodecStringTreeAST(schema.ast),{schema})}var toStringTreeReorder=makeReorder((ast)=>{switch(ast._tag){case"Null":case"Boolean":case"Number":case"BigInt":case"Symbol":case"UniqueSymbol":return 0;default:return 1}});function toCodecStringTreeASTStep(ast,recur,onMissingAnnotation){switch(ast._tag){case"Declaration":{const typeParameters=ast.typeParameters.map((tp)=>make23(recur(toEncoded(tp))));const getStringTreeLink=ast.annotations?.toCodecStringTree;if(isFunction(getStringTreeLink)){const link=getStringTreeLink(typeParameters);if(link===undefined)return ast;return replaceEncoding(ast,[mapLink(link,recur)])}const getJsonLink=ast.annotations?.toCodecJson;const jsonLink=isFunction(getJsonLink)?getJsonLink(typeParameters):undefined;const getLink=jsonLink===undefined?ast.annotations?.toCodec:undefined;const link=jsonLink??(isFunction(getLink)?getLink(typeParameters):undefined);return link===undefined?onMissingAnnotation(ast):replaceEncoding(ast,[mapLink(link,recur)])}case"Null":return replaceEncoding(ast,[nullToString]);case"Boolean":return replaceEncoding(ast,[booleanToString]);case"Unknown":case"ObjectKeyword":return replaceEncoding(ast,[unknownToStringTree]);case"Enum":case"Number":case"Literal":case"UniqueSymbol":case"Symbol":case"BigInt":return ast.toCodecStringTree();case"Objects":{validateCanonicalObjectPropertyNames(ast);return ast.recur(recur,parameterFromString)}case"Union":{const sortedTypes=toStringTreeReorder(ast.types);if(sortedTypes!==ast.types){return new Union(sortedTypes,ast.options,ast.annotations,ast.checks,ast.encoding,ast.context,ast.encodingChecks).recur(recur)}return ast.recur(recur)}case"Arrays":case"Suspend":return ast.recur(recur)}return ast}var nullToString=new Link(new Literal("null"),new Transformation(transform(()=>null),transform(()=>"null")));var booleanToString=new Link(new Union([new Literal("true"),new Literal("false")]),new Transformation(transform((s)=>s==="true"),String3()));var arrayFromSingleTransformation=new Transformation(transform((input)=>typeof input==="string"?[input]:input),passthrough());var isCodecArrayFromSingleLink=(link)=>link.transformation===arrayFromSingleTransformation;var toCodecStringTreeAST=makeCodecDerivation((ast,recur)=>toCodecStringTreeASTStep(ast,recur,(ast)=>{throw new globalThis.Error("Missing structural codec for StringTree",{cause:ast})}),{stopAt:isCodecArrayFromSingleLink});var lambda=(f)=>f;var SchemaErrorTypeId="~effect/Schema/SchemaError";function isSchemaError(u){return hasProperty(u,SchemaErrorTypeId)&&u[SchemaErrorTypeId]===SchemaErrorTypeId}var TypeId25=TypeId24;function declareConstructor(){return(typeParameters,run,annotations)=>{return make24(new Declaration(typeParameters.map(getAST),(typeParameters)=>run(typeParameters.map((ast)=>make24(ast))),annotations))}}function declare(is,annotations){return declareConstructor()([],()=>(input,ast,options)=>is(input)?succeed7(input):fail6(new InvalidType(ast,input,options)),annotations)}class SchemaError extends TaggedError2("SchemaError"){[SchemaErrorTypeId]=SchemaErrorTypeId;constructor(issue){const stackTraceLimit=getStackTraceLimit();setStackTraceLimit(0);try{super({issue})}finally{setStackTraceLimit(stackTraceLimit)}}get message(){return defaultFormatter(this.issue)}toJSON(){return{_tag:this._tag,message:this.message}}[NodeInspectSymbol](){return this.toJSON()}toString(){return`SchemaError(${this.message})`}}function isSchemaError2(u){return isSchemaError(u)}function fromIssueEffect(self){if(effectIsExit(self)){return fromIssueExit(self)}return catchCause2(self,(cause)=>failCauseSync2(()=>map5(cause,(issue)=>new SchemaError(issue))))}function fromIssueExit(exit){return isSuccess3(exit)?exit:failCause2(map5(exit.cause,(issue)=>new SchemaError(issue)))}function getSchemaErrorOrThrow(cause,message){let schemaError;for(const reason of cause.reasons){if(!isFailReason2(reason)||!isSchemaError2(reason.error)){throw new globalThis.Error(message,{cause})}schemaError??=reason.error}if(schemaError===undefined){throw new globalThis.Error(message,{cause})}return schemaError}function runSchemaErrorSync(self){const exit=runSyncExit2(self);if(isSuccess3(exit)){return exit.value}throw getSchemaErrorOrThrow(exit.cause,"Sync adapter can only throw schema errors")}var is2=is;function decodeUnknownEffect2(schema,options){const parser=decodeUnknownEffect(schema,options);return(input,options)=>{return fromIssueEffect(parser(input,options))}}var decodeEffect2=decodeUnknownEffect2;function decodeUnknownSync(schema,options){const parser=decodeUnknownEffect2(schema,options);return(input,options)=>{return runSchemaErrorSync(parser(input,options))}}var decodeSync=decodeUnknownSync;function encodeUnknownEffect2(schema,options){const parser=encodeUnknownEffect(schema,options);return(input,options)=>{return fromIssueEffect(parser(input,options))}}var encodeEffect=encodeUnknownEffect2;function encodeUnknownSync(schema,options){const parser=encodeUnknownEffect2(schema,options);return(input,options)=>{return runSchemaErrorSync(parser(input,options))}}var encodeSync=encodeUnknownSync;var make24=make23;function isSchema(u){return hasProperty(u,TypeId25)&&u[TypeId25]===TypeId25}var optionalKey2=lambda((schema)=>make24(optionalKey(schema.ast),{schema}));var optional2=lambda((self)=>{const schema=UndefinedOr(self);return make24(optional(self.ast),{schema})});function Literal2(literal){const out=make24(new Literal(literal),{literal,transform(to){return out.pipe(decodeTo2(Literal2(to),{decode:transform(()=>to),encode:transform(()=>literal)}))}});return out}var Unknown2=make24(unknown);var Null2=make24(null_);var Undefined2=make24(undefined_2);var String5=make24(string2);var Number5=make24(number2);var Boolean3=make24(boolean);function makeStruct(ast,fields){return make24(ast,{fields,mapFields(f,options){const fields=f(this.fields);return makeStruct(struct(fields,options?.unsafePreserveChecks?this.ast.checks:undefined),fields)}})}function Struct(fields){return makeStruct(struct(fields,undefined),fields)}function Record(key,value){return make24(record(key.ast,value.ast),{key,value})}var ArraySchema=lambda((schema)=>make24(new Arrays(false,[],[schema.ast]),{value:schema}));function makeUnion(ast,members){return make24(ast,{members,mapMembers(f,options){const members=f(this.members);return makeUnion(union2(members,this.ast.options,options?.unsafePreserveChecks?this.ast.checks:undefined),members)}})}function Union2(members,options){return makeUnion(union2(members,options,undefined),members)}function Literals(literals){const members=literals.map(Literal2);return make24(union2(members,undefined,undefined),{literals,members,mapMembers(f){return Union2(f(this.members))},pick(literals){return Literals(literals)},transform(to){return Union2(members.map((member,index)=>member.transform(to[index])))}})}var NullOr=lambda((self)=>Union2([self,Null2]));var UndefinedOr=lambda((self)=>Union2([self,Undefined2]));function brand(identifier){return(schema)=>make24(schema.ast,{schema,identifier})}function decodeTo2(to,transformation){return(from)=>{return make24(decodeTo(from.ast,to.ast,transformation?makeTransformation(transformation):passthrough2()),{from,to})}}function withConstructorDefault2(defaultValue){return(schema)=>make24(withConstructorDefault(schema.ast,defaultValue),{schema})}function tag(literal){return Literal2(literal).pipe(withConstructorDefault2(succeed7(literal)))}function TaggedStruct(value,fields){return Struct({_tag:tag(value),...fields})}function instanceOf(constructor,annotations){return declare((u)=>u instanceof constructor,annotations)}function link3(){return(encodeTo,transformation)=>{return new Link(encodeTo.ast,makeTransformation(transformation))}}var makeFilter2=makeFilter;function isPattern2(regExp,annotations){const source=regExp.source;const flags=regExp.flags;const canExport=/^[dg]*uy?$/.test(flags);const runtimeRegExp=flags===""?`new globalThis.RegExp(${format(source)})`:`new globalThis.RegExp(${format(source)}, ${format(flags)})`;return isPattern(regExp,{toJsonSchema:()=>canExport?{pattern:flags.endsWith("y")?`^(?:${source})`:source}:[{},true],toCode:()=>({runtime:`Schema.isPattern(${runtimeRegExp})`}),...annotations})}function isBase64(annotations){const pattern="^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$";const regExp=/^[0-9a-zA-Z+/]*={0,2}$/;return makeFilter2((s)=>s.length%4===0&®Exp.test(s),{expected:"a base64 encoded string",representation:{id:"effect/schema/isBase64",payload:null},toJsonSchema:()=>({pattern}),arbitraryConstraint:{patterns:[{source:pattern,flags:""}]},toCode:()=>({runtime:"Schema.isBase64()"}),...annotations})}var Finite=make24(finite);function isInt(annotations){return makeFilter2((n)=>globalThis.Number.isSafeInteger(n),{expected:"an integer",representation:{id:"effect/schema/isInt",payload:null},toJsonSchema:()=>({type:"integer",minimum:globalThis.Number.MIN_SAFE_INTEGER,maximum:globalThis.Number.MAX_SAFE_INTEGER}),toCode:()=>({runtime:"Schema.isInt()"}),arbitraryConstraint:{number:"integer"},...annotations})}var Int=Number5.check(isInt());function isMinLength(minLength,annotations){minLength=normalizeCardinality(minLength);return makeIsMinLength(minLength,Math.ceil(minLength/2),annotations)}function makeIsMinLength(minLength,minCodePoints,annotations){return makeFilter2((input)=>input.length>=minLength,{expected:`a value with a length of at least ${minLength}`,representation:{id:"effect/schema/isMinLength",payload:{minLength}},toJsonSchema:({type})=>type==="string"?minLength<=1?{minLength:minCodePoints}:[{minLength:minCodePoints},true]:type==="array"?{minItems:minLength}:type===undefined?[{minLength:minCodePoints,minItems:minLength},true]:[{},true],toCode:()=>({runtime:`Schema.isMinLength(${minLength})`}),[STRUCTURAL_ANNOTATION_KEY]:true,arbitraryConstraint:{minLength},...annotations})}function isNonEmpty(annotations){return makeIsMinLength(1,1,annotations)}function isMaxLength(maxLength,annotations){maxLength=normalizeCardinality(maxLength);return makeFilter2((input)=>input.length<=maxLength,{expected:`a value with a length of at most ${maxLength}`,representation:{id:"effect/schema/isMaxLength",payload:{maxLength}},toJsonSchema:({type})=>type==="string"?maxLength===0?{maxLength}:[{maxLength},true]:type==="array"?{maxItems:maxLength}:type===undefined?[{maxLength,maxItems:maxLength},true]:[{},true],toCode:()=>({runtime:`Schema.isMaxLength(${maxLength})`}),[STRUCTURAL_ANNOTATION_KEY]:true,arbitraryConstraint:{maxLength},...annotations})}function normalizeCardinality(value){if(!globalThis.Number.isFinite(value)){throw new globalThis.RangeError(`Expected a finite number, got ${value}`)}return Math.max(0,Math.floor(value))}var NonEmptyString=String5.check(isNonEmpty());var RegExp2=instanceOf(globalThis.RegExp,{representation:{id:"effect/schema/RegExp",payload:null},toCode:()=>({runtime:`Schema.RegExp`,Type:`globalThis.RegExp`}),expected:"RegExp",toCodecJson:()=>link3()(Struct({source:String5,flags:String5}),transformEffect2({decode:(e,options)=>try_3({try:()=>new globalThis.RegExp(e.source,e.flags),catch:()=>new InvalidValue({expected:"valid RegExp source and flags"},e,options)}),encode:(regExp)=>succeed7({source:regExp.source,flags:regExp.flags})}))});var URLString=String5.annotate({expected:"a string that will be decoded as a URL"});var URL2=instanceOf(globalThis.URL,{representation:{id:"effect/schema/URL",payload:null},toCode:()=>({runtime:`Schema.URL`,Type:`globalThis.URL`}),expected:"URL",toCodecJson:()=>link3()(URLString,urlFromString)});var JsonString=String5.annotate({expected:"a string that will be decoded as JSON"});function fromJsonString2(schema,options){return JsonString.pipe(decodeTo2(schema,fromJsonString(options)))}var File=instanceOf(globalThis.File,{representation:{id:"effect/schema/File",payload:null},toCode:()=>({runtime:`Schema.File`,Type:`globalThis.File`}),expected:"File",toCodecJson:()=>link3()(Struct({data:String5.check(isBase64()),type:String5,name:String5,lastModified:Int}),transformEffect2({decode:(e,options)=>match2(decode(e.data),{onFailure:()=>fail6(new InvalidValue({expected:"a valid Base64 string"},e.data,options)),onSuccess:(bytes)=>{const buffer=new globalThis.Uint8Array(bytes);return succeed7(new globalThis.File([buffer],e.name,{type:e.type,lastModified:e.lastModified}))}}),encode:(file,options)=>tryPromise2({try:async()=>{const bytes=new globalThis.Uint8Array(await file.arrayBuffer());return{data:encode(bytes),type:file.type,name:file.name,lastModified:file.lastModified}},catch:()=>new InvalidValue({expected:"a readable File"},file,options)})}))});var URLSearchParams2=instanceOf(globalThis.URLSearchParams,{representation:{id:"effect/schema/URLSearchParams",payload:null},toCode:()=>({runtime:`Schema.URLSearchParams`,Type:`globalThis.URLSearchParams`}),expected:"URLSearchParams",toCodecJson:()=>link3()(String5.annotate({expected:"a query string that will be decoded as URLSearchParams"}),transform2({decode:(e)=>new globalThis.URLSearchParams(e),encode:(params)=>params.toString()}))});var Base64String=String5.annotate({expected:"a base64 encoded string that will be decoded as Uint8Array",format:"byte",contentEncoding:"base64"});var Uint8Array2=instanceOf(globalThis.Uint8Array,{representation:{id:"effect/schema/Uint8Array",payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:"Uint8Array",toCodecJson:()=>link3()(Base64String,uint8ArrayFromBase64String)});var arbitraryMinimumDateTimestamp=-8640000000000000;var arbitraryMaximumDateTimestamp=8640000000000000;var arbitraryMinimumZonedDateTimeTimestamp=arbitraryMinimumDateTimestamp+14*60*60*1000;var arbitraryMaximumZonedDateTimeTimestamp=arbitraryMaximumDateTimestamp-14*60*60*1000;var arbitraryMinimumTimeZoneOffset=-12*60*60*1000;var arbitraryMaximumTimeZoneOffset=14*60*60*1000;function Redacted(value,options){const label=typeof options?.label==="string"?options.label:undefined;const disallowJsonEncode=options?.disallowJsonEncode===true;const normalizedOptions=label!==undefined?disallowJsonEncode?{label,disallowJsonEncode:true}:{label}:disallowJsonEncode?{disallowJsonEncode:true}:undefined;const decodeLabel=label!==undefined?decodeUnknownEffect(Literal2(label)):undefined;const schema=declareConstructor()([value],([value])=>(input,ast,poptions)=>{if(isRedacted(input)){const label=decodeLabel!==undefined?mapErrorEager2(decodeLabel(input.label,poptions),(issue)=>new Pointer(["label"],issue)):void_3;return flatMapEager2(label,()=>mapBothEager2(decodeUnknownEffect(value)(value2(input),poptions),{onSuccess:(value)=>make19(value,{label:input.label}),onFailure:()=>{return new Composite(ast,[new Pointer(["value"],new InvalidValue(undefined,input,poptions))],input,poptions)}}))}return fail6(new InvalidType(ast,input,poptions))},{representation:{id:"effect/schema/Redacted",payload:normalizedOptions??null},toCode:({typeParameters})=>({runtime:normalizedOptions!==undefined?`Schema.Redacted(${typeParameters[0].runtime}, ${format(normalizedOptions)})`:`Schema.Redacted(${typeParameters[0].runtime})`,Type:`Redacted.Redacted<${typeParameters[0].Type}>`,importDeclarations:[`import * as Redacted from "effect/Redacted"`]}),expected:"Redacted",toCodecJson:([value])=>link3()(value,{decode:transform((e)=>make19(e,{label})),encode:disallowJsonEncode?forbidden((oe)=>"Cannot serialize Redacted"+(isSome2(oe)&&typeof oe.value.label==="string"?` with label: "${oe.value.label}"`:"")):transform(value2)}),toEquivalence:([value])=>makeEquivalence4(value)});return make24(schema.ast,{value})}var immerable=globalThis.Symbol.for("immer-draftable");var payloadToken={};function makeClass(Inherited,identifier,struct2,annotations,proto){const getClassSchema=getClassSchemaFactory(struct2,identifier,annotations);const ClassTypeId=getClassTypeId(identifier);const out=class extends Inherited{constructor(...[input,options]){const internalOptions=options;const payload=internalOptions?.["~payload"];const value=payload?.token===payloadToken?payload.value:struct2.make(input??{},options);super(value,{...options,disableChecks:true,"~payload":{token:payloadToken,value}})}static[TypeId25]=TypeId25;get[ClassTypeId](){return ClassTypeId}static[immerable]=true;static identifier=identifier;static fields=struct2.fields;static get ast(){return getClassSchema(this).ast}static pipe(){return pipeArguments(this,arguments)}static rebuild(ast){return getClassSchema(this).rebuild(ast)}static make(input,options){return makeClassSync(toType(getClassSchema(this).ast),input??{},options,(fields)=>makeClassTrusted(this,fields))}static makeOption(input,options){return makeOption(getClassSchema(this))(input??{},options)}static makeEffect(input,options){return getClassSchema(this).makeEffect(input??{},options)}static annotate(annotations){return this.rebuild(annotate(this.ast,annotations))}static annotateKey(annotations){return this.rebuild(annotateKey(this.ast,annotations))}static check(...checks){return this.rebuild(appendChecks(this.ast,checks))}static extend(identifier2){return(schema,annotations)=>{const extension=isStruct(schema)?schema:Struct(schema);const fields={...struct2.fields,...extension.fields};const ast=struct(fields,struct2.ast.checks,{identifier:identifier2});return makeClass(this,identifier2,makeStruct(appendChecks(ast,extension.ast.checks),fields),annotations,proto)}}static mapFields(f,options){return struct2.mapFields(f,options)}};if(proto!==undefined){Object.assign(out.prototype,proto(identifier))}return out}function makeClassTrusted(self,fields){return new self(fields,{"~payload":{token:payloadToken,value:fields}})}function getClassTransformation(self){return new Transformation(transform((input)=>makeClassTrusted(self,input)),passthrough())}function getClassTypeId(identifier){return`~effect/Schema/Class/${identifier}`}function getClassSchemaFactory(from,identifier,annotations){let memo;return(self)=>{if(memo!==undefined){return memo}const ClassTypeId=getClassTypeId(identifier);const isClassValue=(input)=>input instanceof self||hasProperty(input,ClassTypeId);const transformation=getClassTransformation(self);const to=make24(new Declaration([from.ast],()=>(input,ast,options)=>{return isClassValue(input)?succeed7(input):fail6(new InvalidType(ast,input,options))},{identifier,[CONSTRUCTOR_ANNOTATION_KEY]:([from])=>({isConstructed:isClassValue,link:new Link(from,transformation)}),toCodec:([from])=>new Link(from.ast,transformation),toEquivalence:([from])=>from,toFormatter:([from])=>(t)=>`${self.identifier}(${from(t)})`,[SENTINELS_ANNOTATION_KEY]:collectSentinels(from.ast),...annotations}));return memo=decodeTo2(to,transformation)(from)}}function isStruct(schema){return isSchema(schema)}var Error4=(identifier)=>(schema,annotations)=>{const struct=isStruct(schema)?schema:Struct(schema);const self=makeClass(Error2,identifier,struct,annotations,(identifier)=>({name:identifier}));return self};var TaggedError3=(identifier)=>{return(tagValue,schema,annotations)=>{const struct=isStruct(schema)?schema.mapFields((fields)=>({_tag:tag(tagValue),...fields}),{unsafePreserveChecks:true}):TaggedStruct(tagValue,schema);return Error4(identifier??tagValue)(struct,annotations)}};var toCodecStringTree2=toCodecStringTree;var Json2=make24(annotate(Json,{toCode:()=>({runtime:"Schema.Json",Type:"Schema.Json"})}));var JsonObject=Record(String5,Json2);var TypeId26="~effect/http/HttpBody";class Proto7{[TypeId26];constructor(){this[TypeId26]=TypeId26}[NodeInspectSymbol](){return this.toJSON()}toString(){return format(this,{ignoreToString:true})}}class Empty2 extends Proto7{_tag="Empty";toJSON(){return{_id:"effect/HttpBody",_tag:"Empty"}}}var empty7=new Empty2;var buffer2=globalThis.Buffer;var TypeId27="~effect/http/HttpClientError";class HttpClientError extends TaggedError2("HttpClientError"){constructor(props){if("cause"in props.reason){super({...props,cause:props.reason.cause})}else{super(props)}}[TypeId27]=TypeId27;get request(){return this.reason.request}get response(){return"response"in this.reason?this.reason.response:undefined}get message(){return this.reason.message}}var formatReason=(tag)=>tag.endsWith("Error")?tag.slice(0,-5):tag;var formatMessage=(reason,description,info)=>description?`${reason}: ${description} (${info})`:`${reason} error (${info})`;var formatMethodAndUrl=(request)=>`${request.method} ${redactUrl(request.url)}`;var reasonToJSON=(reason,json)=>({...json,request:{_id:"HttpClientRequest",method:reason.request.method,url:redactUrl(reason.request.url)},..."response"in reason?{response:{_id:"HttpClientResponse",status:reason.response.status}}:undefined});class TransportError extends TaggedError2("TransportError"){get methodAndUrl(){return formatMethodAndUrl(this.request)}get message(){return formatMessage(formatReason(this._tag),this.description,this.methodAndUrl)}toJSON(){return reasonToJSON(this,super.toJSON())}}class EncodeError extends TaggedError2("EncodeError"){get methodAndUrl(){return formatMethodAndUrl(this.request)}get message(){return formatMessage(formatReason(this._tag),this.description,this.methodAndUrl)}toJSON(){return reasonToJSON(this,super.toJSON())}}class InvalidUrlError extends TaggedError2("InvalidUrlError"){get methodAndUrl(){return formatMethodAndUrl(this.request)}get message(){return formatMessage(formatReason(this._tag),this.description,this.methodAndUrl)}toJSON(){return reasonToJSON(this,super.toJSON())}}class StatusCodeError extends TaggedError2("StatusCodeError"){get methodAndUrl(){return formatMethodAndUrl(this.request)}get message(){const info=`${this.response.status} ${this.methodAndUrl}`;return formatMessage(formatReason(this._tag),this.description,info)}toJSON(){return reasonToJSON(this,super.toJSON())}}class DecodeError extends TaggedError2("DecodeError"){get methodAndUrl(){return formatMethodAndUrl(this.request)}get message(){const info=`${this.response.status} ${this.methodAndUrl}`;return formatMessage(formatReason(this._tag),this.description,info)}toJSON(){return reasonToJSON(this,super.toJSON())}}class EmptyBodyError extends TaggedError2("EmptyBodyError"){get methodAndUrl(){return formatMethodAndUrl(this.request)}get message(){const info=`${this.response.status} ${this.methodAndUrl}`;return formatMessage(formatReason(this._tag),this.description,info)}toJSON(){return reasonToJSON(this,super.toJSON())}}var allShort=[["GET","get"],["POST","post"],["PUT","put"],["DELETE","del"],["PATCH","patch"],["HEAD","head"],["OPTIONS","options"],["TRACE","trace"],["QUERY","query"]];var updateHeaders=(headers,body)=>{if(body._tag==="Empty"||body._tag==="FormData"){return remove2(remove2(headers,"content-type"),"content-length")}headers=body.contentType===undefined?remove2(headers,"content-type"):set(headers,"content-type",body.contentType);return updateContentLength(headers,body)};var updateContentLength=(headers,body)=>{const contentLength=body._tag==="Empty"||body._tag==="FormData"?undefined:body.contentLength;return contentLength===undefined?remove2(headers,"content-length"):set(headers,"content-length",contentLength.toString())};class UrlError extends TaggedError2("UrlError"){}var make25=(url,params,hash)=>try_({try:()=>{const urlInstance=new URL(url,baseUrl());for(let i=0;i<params.params.length;i++){const[key,value]=params.params[i];if(value!==undefined){urlInstance.searchParams.append(key,unwrap4(value))}}if(hash!==undefined){urlInstance.hash=hash}return urlInstance},catch:(cause)=>new UrlError({cause})});var baseUrl=()=>{if("location"in globalThis&&globalThis.location!==undefined&&globalThis.location.origin!==undefined&&globalThis.location.pathname!==undefined){const base=location.origin+location.pathname;try{return new URL(base).href}catch{return}}return};var TypeId28="~effect/http/HttpClientRequest";var Proto8={[TypeId28]:TypeId28,...BaseProto,toJSON(){return{_id:"HttpClientRequest",method:this.method,url:redactUrl(this.url),urlParams:this.urlParams,hash:this.hash,headers:redact(this.headers),body:this.body.toJSON()}},pipe(){return pipeArguments(this,arguments)}};function makeWith(method,url,urlParams,hash,headers,body){const self=Object.create(Proto8);self.method=method;self.url=url;self.urlParams=urlParams;self.hash=hash;self.headers=headers;self.body=body;return self}var empty8=makeWith("GET","",empty6,none2(),empty5,empty7);var make26=(method)=>(url,options)=>modify(empty8,{method,url,...options??undefined});var modify=dual(2,(self,options)=>{let result=self;if(options.method){result=setMethod(result,options.method)}if(options.url){result=setUrl(result,options.url)}if(options.headers){result=setHeaders(result,options.headers)}if(options.urlParams){result=setUrlParams(result,options.urlParams)}if(options.hash){result=setHash(result,options.hash)}if(options.body){result=setBody(result,options.body)}if(options.accept){result=accept(result,options.accept)}if(options.acceptJson){result=acceptJson(result)}return result});var setMethod=dual(2,(self,method)=>makeWith(method,self.url,self.urlParams,self.hash,self.headers,self.body));var setHeader=dual(3,(self,key,value)=>makeWith(self.method,self.url,self.urlParams,self.hash,set(self.headers,key,value),self.body));var setHeaders=dual(2,(self,input)=>makeWith(self.method,self.url,self.urlParams,self.hash,setAll(self.headers,input),self.body));var accept=dual(2,(self,mediaType)=>setHeader(self,"Accept",mediaType));var acceptJson=accept("application/json");var setUrl=dual(2,(self,url)=>{if(typeof url==="string"){return makeWith(self.method,url,self.urlParams,self.hash,self.headers,self.body)}const clone=new URL(url.toString());const urlParams=fromInput2(clone.searchParams);const hash=fromNullishOr(clone.hash===""?undefined:clone.hash.slice(1));clone.search="";clone.hash="";return makeWith(self.method,clone.toString(),urlParams,hash,self.headers,self.body)});var setUrlParams=dual(2,(self,input)=>makeWith(self.method,self.url,setAll2(self.urlParams,input),self.hash,self.headers,self.body));var setHash=dual(2,(self,hash)=>makeWith(self.method,self.url,self.urlParams,some2(hash),self.headers,self.body));var setBody=dual(2,(self,body)=>{return makeWith(self.method,self.url,self.urlParams,self.hash,updateHeaders(self.headers,body),body)});function toUrl(self){const r=make25(self.url,self.urlParams,getOrUndefined(self.hash));if(isSuccess2(r)){return some2(r.success)}return none2()}var TypeId29="~effect/http/HttpIncomingMessage";var inspect=(self,that)=>{return{...that,headers:redact(self.headers),remoteAddress:self.remoteAddress}};var WebSourceSymbol="~effect/http/HttpClientResponse/WebSource";var getWebSource=(self)=>self[WebSourceSymbol]?.();var TypeId30="~effect/http/HttpClientResponse";var fromWeb=(request,source)=>new WebHttpClientResponse(request,source);class WebHttpClientResponse extends Class2{[TypeId29];[TypeId30];request;source;constructor(request,source){super();this.request=request;this.source=source;this[TypeId29]=TypeId29;this[TypeId30]=TypeId30}toJSON(){return inspect(this,{_id:"HttpClientResponse",request:this.request.toJSON(),status:this.status})}get status(){return this.source.status}get url(){if(this.source.url)return this.source.url.split("#")[0];const url=toUrl(this.request);if(isNone2(url))return"";url.value.hash="";return url.value.href}get headers(){return fromInput(this.source.headers)}cachedCookies;get cookies(){if(this.cachedCookies){return this.cachedCookies}return this.cachedCookies=fromSetCookie(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return none2()}[WebSourceSymbol](){return this.source}get stream(){return this.source.body?fromReadableStream2({evaluate:()=>this.source.body,onError:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}):fail8(new HttpClientError({reason:new EmptyBodyError({request:this.request,response:this,description:"can not create stream from empty body"})}))}get json(){return flatMap4(this.text,(text)=>try_3({try:()=>text===""?null:JSON.parse(text),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}))}textBody;get text(){return this.textBody??=map6(this.arrayBuffer,(_)=>new TextDecoder().decode(_))}get urlParamsBody(){return flatMap4(this.arrayBuffer,(bytes)=>try_3({try:()=>fromInput2(fromBody(bytes)),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}))}formDataBody;get formData(){return this.formDataBody??=tryPromise2({try:()=>this.source.formData(),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}).pipe(cached2,runSync2)}arrayBufferBody;get arrayBuffer(){if(this.arrayBufferBody){return this.arrayBufferBody}this.arrayBufferBody=tryPromise2({try:()=>this.source.arrayBuffer(),catch:(cause)=>new HttpClientError({reason:new DecodeError({request:this.request,response:this,cause})})}).pipe(cached2,runSync2);return this.arrayBufferBody}get upgrade(){return fail6(new HttpClientError({reason:new StatusCodeError({request:this.request,response:this,description:"fetch cannot hand over the connection of an HTTP upgrade"})}))}pipe(){return pipeArguments(this,arguments)}}var toHeaders=(span)=>fromRecordUnsafe({b3:`${span.traceId}-${span.spanId}-${span.sampled?"1":"0"}${match(span.parent,{onNone:()=>"",onSome:(parent)=>`-${parent.spanId}`})}`,traceparent:`00-${span.traceId.padStart(32,"0")}-${span.spanId}-${span.sampled?"01":"00"}`});var defaultPorts={"http:":80,"https:":443,"ws:":80,"wss:":443};var addUrlAttributes=(span,url,redactedNames)=>{const query=redactUrl(url.search,redactedNames).slice(1);span.attribute("url.full",redactUrl(url.href,redactedNames));span.attribute("url.path",url.pathname);if(query!==""){span.attribute("url.query",query)}span.attribute("url.scheme",url.protocol.slice(0,-1));if(url.hostname!==""){span.attribute("server.address",url.hostname.startsWith("[")?url.hostname.slice(1,-1):url.hostname);const port=url.port===""?defaultPorts[url.protocol]:Number(url.port);if(port!==undefined){span.attribute("server.port",port)}}};var redactedNames=(urlParams,redactedNames)=>{const keys=urlParams.params.filter(([,value])=>typeof value!=="string").map(([key])=>key);return keys.length===0?redactedNames:[...redactedNames,...new URLSearchParams(keys.map((key)=>[key,""])).keys()]};var addHeaderAttributes=(span,phase,headers,filter,redactedNames)=>{for(const name in headers){if(!filter(name,phase))continue;span.attribute(`http.${phase}.header.${name}`,isRedactedName(name,redactedNames)?"<redacted>":headers[name])}};var TypeId31="~effect/http/HttpClient";var HttpClient=Service("effect/HttpClient");var transform3=dual(2,(self,f)=>makeWith2(flatMap4((request)=>f(self.postprocess(succeed7(request)),request)),self.preprocess));var transformResponse=dual(2,(self,f)=>makeWith2((request)=>f(self.postprocess(request)),self.preprocess));var makeWith2=(postprocess,preprocess)=>{const self=Object.create(Proto9);self.preprocess=preprocess;self.postprocess=postprocess;self.execute=function(request){return postprocess(preprocess(request))};return self};var Proto9={[TypeId31]:TypeId31,pipe(){return pipeArguments(this,arguments)},...BaseProto,toJSON(){return{_id:"effect/HttpClient"}},...Object.fromEntries(allShort.map(([fullMethod,method])=>[method,function(url,options){return this.execute(make26(fullMethod)(url,options))}]))};var make27=(f)=>makeWith2((effect)=>flatMap4(effect,(request)=>withFiber2((fiber)=>{const scopedController=scopedRequests.get(request);const controller=scopedController??new AbortController;const urlResult=make25(request.url,request.urlParams,getOrUndefined(request.hash));if(isFailure2(urlResult)){return fail6(new HttpClientError({reason:new InvalidUrlError({request,cause:urlResult.failure})}))}const url=urlResult.success;const tracerDisabled=fiber.getRef(DisablePropagation)||fiber.getRef(TracerDisabledWhen)(request);if(tracerDisabled){const effect=f(request,url,controller.signal,fiber);if(scopedController)return map6(effect,(response)=>trackResponse(response,controller,true));return uninterruptibleMask2((restore)=>matchCauseEffect2(restore(effect),{onSuccess(response){return succeed7(trackResponse(response,controller,false))},onFailure(cause){if(hasInterrupts2(cause)){controller.abort()}return failCause3(cause)}}))}return useSpan2(fiber.getRef(SpanNameGenerator)(request),{kind:"client"},(span)=>{span.attribute("http.request.method",request.method);const redactedHeaderNames=fiber.getRef(CurrentRedactedNames);addUrlAttributes(span,url,redactedNames(request.urlParams,fiber.getRef(CurrentRedactedNames2)));const headerFilter=fiber.getRef(TracerHeaderFilter);addHeaderAttributes(span,"request",request.headers,headerFilter,redactedHeaderNames);request=fiber.getRef(TracerPropagationEnabled)?setHeaders(request,toHeaders(span)):request;return uninterruptibleMask2((restore)=>restore(f(request,url,controller.signal,fiber)).pipe(withParentSpan2(span,{captureStackTrace:false}),matchCauseEffect2({onSuccess:(response)=>{span.attribute("http.response.status_code",response.status);addHeaderAttributes(span,"response",response.headers,headerFilter,redactedHeaderNames);if(response.status>=400&&response.status<600){span.attribute("error.type",String(response.status));endSpanWithStatusError(fiber,span,request,response)}return succeed7(trackResponse(response,controller,scopedController!==undefined))},onFailure(cause){if(!scopedController&&hasInterrupts2(cause)){controller.abort()}return failCause3(cause)}})))})})),succeed7);var endSpanWithStatusError=(fiber,span,request,response)=>{const stackTraceLimit=getStackTraceLimit();setStackTraceLimit(0);let exit;try{exit=fail5(new HttpClientError({reason:new StatusCodeError({request,response})}))}finally{setStackTraceLimit(stackTraceLimit)}span.end(fiber.getRef(TracerTimingEnabled2)?fiber.getRef(Clock).currentTimeNanosUnsafe():BigInt(0),exit)};var withScope=(self)=>transform3(self,(effect,request)=>{const controller=new AbortController;scopedRequests.set(request,controller);return andThen2(addFinalizer3(()=>sync2(()=>controller.abort())),effect)});var TracerDisabledWhen=Reference("effect/http/HttpClient/TracerDisabledWhen",{defaultValue:()=>constFalse});var TracerHeaderFilter=Reference("effect/http/HttpClient/TracerHeaderFilter",{defaultValue:()=>constFalse});var TracerPropagationEnabled=Reference("effect/http/HttpClient/TracerPropagationEnabled",{defaultValue:constTrue});var SpanNameGenerator=Reference("effect/http/HttpClient/SpanNameGenerator",{defaultValue:()=>(request)=>request.method});var layerMergedContext=(effect2)=>effect(HttpClient)(contextWith2((context)=>map6(effect2,(client)=>transformResponse(client,updateContext2((input)=>merge(context,input))))));var responseRegistry=(()=>{if("FinalizationRegistry"in globalThis&&globalThis.FinalizationRegistry){const registry=new FinalizationRegistry((controller)=>{try{controller.abort()}catch{}});return{register(response,controller){registry.register(response,controller,response)},unregister(response){registry.unregister(response)}}}const timers=new WeakMap;return{register(response,controller){timers.set(response,setTimeout(()=>controller.abort(),5000))},unregister(response){const timer=timers.get(response);if(timer===undefined)return;clearTimeout(timer);timers.delete(response)}}})();var scopedRequests=new WeakMap;var responseControllers=new WeakMap;var trackResponse=(response,controller,scoped)=>{if(!scoped){responseRegistry.register(response,controller);response=new InterruptibleResponse(response,controller)}responseControllers.set(response,controller);return response};class InterruptibleResponse{original;controller;constructor(original,controller){this.original=original;this.controller=controller}[TypeId30]=TypeId30;[TypeId29]=TypeId29;applyInterrupt(effect){return suspend2(()=>{responseRegistry.unregister(this.original);return onInterrupt2(effect,()=>sync2(()=>{this.controller.abort()}))})}get request(){return this.original.request}get url(){return this.original.url}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get upgrade(){return this.applyInterrupt(this.original.upgrade)}[WebSourceSymbol](){const source=getWebSource(this.original);if(source!==undefined)responseRegistry.unregister(this.original);return source}get stream(){return suspend4(()=>{responseRegistry.unregister(this.original);return ensuring4(this.original.stream,sync2(()=>{this.controller.abort()}))})}toJSON(){return this.original.toJSON()}[NodeInspectSymbol](){return this.original[NodeInspectSymbol]()}pipe(){return pipeArguments(this,arguments)}}var Fetch=Reference("effect/http/FetchHttpClient/Fetch",{defaultValue:()=>globalThis.fetch});var StreamBodyFallback=Reference("effect/http/FetchHttpClient/StreamBodyFallback",{defaultValue:()=>"error"});class RequestInit extends Service()("effect/http/FetchHttpClient/RequestInit"){}var supportsStreamBody;var detectStreamBodySupport=()=>{try{let duplexAccessed=false;const body=new ReadableStream;const request=new Request("https://example.com",{method:"POST",body,get duplex(){duplexAccessed=true;return"half"}});return(duplexAccessed||request.body===body)&&!request.headers.has("Content-Type")}catch{return false}};var fetch2=make27((request,url,signal,fiber)=>{if(request.headers.upgrade!==undefined){return fail6(new HttpClientError({reason:new TransportError({request,description:"fetch cannot send an HTTP upgrade request"})}))}const fetch2=fiber.getRef(Fetch);const options=getOrUndefined2(fiber.context,RequestInit)??{};let headers=options.headers?merge3(fromInput(options.headers),request.headers):request.headers;if(headers["content-length"]){headers=remove2(headers,"content-length")}let uploadController;const stopUpload=sync2(()=>uploadController?.abort());const send=(body)=>map6(tryPromise2({try:()=>fetch2(url,{...options,method:request.method,headers,body,duplex:typeof ReadableStream!=="undefined"&&body instanceof ReadableStream?"half":undefined,signal:uploadController?AbortSignal.any([signal,uploadController.signal]):signal}),catch:(cause)=>new HttpClientError({reason:new TransportError({request,cause})})}),(response)=>{const original=fromWeb(request,response);if(!uploadController)return original;if(response.body===null)uploadController.abort();return Object.create(original,{...Object.fromEntries(["arrayBuffer","text","json","formData","urlParamsBody"].map((key)=>[key,{get:()=>ensuring2(original[key],stopUpload)}])),stream:{get:()=>ensuring4(original.stream,stopUpload)}})}).pipe(onError2(()=>stopUpload));switch(request.body._tag){case"Raw":case"Uint8Array":return send(request.body.body);case"FormData":return send(request.body.formData);case"Stream":{supportsStreamBody??=detectStreamBodySupport();if(supportsStreamBody){uploadController=new AbortController;const uploadSignal=AbortSignal.any([signal,uploadController.signal]);const stopped=callback2((resume)=>{const onAbort=()=>resume(interrupt2);if(uploadSignal.aborted){onAbort();return}uploadSignal.addEventListener("abort",onAbort,{once:true});return sync2(()=>uploadSignal.removeEventListener("abort",onAbort))});return flatMap4(toReadableStreamEffect(interruptWhen2(request.body.stream,stopped)),send)}if(fiber.getRef(StreamBodyFallback)==="error"){return fail6(new HttpClientError({reason:new EncodeError({request,description:"Streaming request bodies are not supported in this runtime"})}))}return mkArrayBuffer(request.body.stream).pipe(mapError3((cause)=>new HttpClientError({reason:new EncodeError({request,cause})})),flatMap4(send))}}return send(undefined)});var layer5=layerMergedContext(succeed7(fetch2));import{chmodSync as chmodSync2,existsSync as existsSync10,readFileSync as readFileSync9,realpathSync as realpathSync5,renameSync as renameSync2,statSync as statSync3,writeFileSync as writeFileSync7}from"fs";import{rename as rename4}from"fs/promises";import{homedir,hostname}from"os";import{createInterface}from"readline/promises";import{pathToFileURL as pathToFileURL5}from"url";var name="@collective-intelligence/cli";var version="0.2.32";var jsonBodySerializer={bodySerializer:(body)=>JSON.stringify(body,(_key,value)=>typeof value==="bigint"?value.toString():value)};function createSseClient({onRequest,onSseError,onSseEvent,responseTransformer,responseValidator,sseDefaultRetryDelay,sseMaxRetryAttempts,sseMaxRetryDelay,sseSleepFn,url,...options}){let lastEventId;const sleep=sseSleepFn??((ms)=>new Promise((resolve)=>setTimeout(resolve,ms)));const createStream=async function*(){let retryDelay=sseDefaultRetryDelay??3000;let attempt=0;const signal=options.signal??new AbortController().signal;while(true){if(signal.aborted)break;attempt++;const headers=options.headers instanceof Headers?options.headers:new Headers(options.headers);if(lastEventId!==undefined){headers.set("Last-Event-ID",lastEventId)}try{const requestInit={redirect:"follow",...options,body:options.serializedBody??null,headers,signal};let request=new Request(url,requestInit);if(onRequest){request=await onRequest(url,requestInit)}const _fetch=options.fetch??globalThis.fetch;const response=await _fetch(request);if(!response.ok)throw new Error(`SSE failed: ${response.status} ${response.statusText}`);if(!response.body)throw new Error("No body in SSE response");const reader=response.body.pipeThrough(new TextDecoderStream).getReader();let buffer="";const abortHandler=()=>{try{reader.cancel()}catch{}};signal.addEventListener("abort",abortHandler);try{while(true){const{done,value}=await reader.read();if(done)break;buffer+=value;buffer=buffer.replace(/\r\n?/g,`
|
|
239
239
|
`);const chunks=buffer.split(`
|
|
240
240
|
|
|
241
241
|
`);buffer=chunks.pop()??"";for(const chunk of chunks){const lines=chunk.split(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@collective-intelligence/cli",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.32",
|
|
4
4
|
"description": "Distributable command-line tooling for Collective Intelligence Extension Packages.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
"ci": "./dist/cli.js"
|
|
11
11
|
},
|
|
12
12
|
"dependencies": {
|
|
13
|
-
"@collective-intelligence/extensions-sdk-backend": "0.2.
|
|
13
|
+
"@collective-intelligence/extensions-sdk-backend": "0.2.32",
|
|
14
14
|
"@module-federation/vite": "1.23.2",
|
|
15
15
|
"@vitejs/plugin-react": "6.0.5",
|
|
16
16
|
"acorn": "8.18.0",
|
|
@@ -32,8 +32,8 @@
|
|
|
32
32
|
"type-check": "bun check"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
|
-
"@collective-intelligence/extensions-sdk": "0.2.
|
|
36
|
-
"@collective-intelligence/schema-codegen": "0.
|
|
35
|
+
"@collective-intelligence/extensions-sdk": "0.2.32",
|
|
36
|
+
"@collective-intelligence/schema-codegen": "0.2.32",
|
|
37
37
|
"@effect/eslint-plugin": "latest",
|
|
38
38
|
"@effect/platform-bun": "4.1.2",
|
|
39
39
|
"@effect/platform-node": "4.1.2",
|
|
@@ -55,5 +55,5 @@
|
|
|
55
55
|
"ultracite": "7.10.7",
|
|
56
56
|
"vitest": "5.0.2"
|
|
57
57
|
},
|
|
58
|
-
"gitHead": "
|
|
58
|
+
"gitHead": "0c9b280b3237d4aaeb664ee0bace01d2cb06daf2"
|
|
59
59
|
}
|