@collective-intelligence/cli 0.2.4 → 0.2.6

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.
Files changed (2) hide show
  1. package/dist/cli.js +1 -1
  2. package/package.json +3 -3
package/dist/cli.js CHANGED
@@ -236,7 +236,7 @@ ${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()}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 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 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=empty2();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_=(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)=>map3(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 map3=dual(2,(self,f)=>new ContImpl(self,mapCont,f));var mapEager=dual(2,(self,f)=>effectIsExit(self)?exitMap(self,f):map3(self,f));var mapErrorEager=dual(2,(self,f)=>effectIsExit(self)?exitMapError(self,f):mapError(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 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?map3(all([self,that],{concurrency:2}),([a,a2])=>f(a,a2)):flatMap3(self,(a)=>map3(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 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 tapDefect=dual(2,(self,f)=>tapCauseFilter(self,findDefect,(_)=>f(_)));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 mapError=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 scope=scopeTag;var provideScope=provideService(scopeTag);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 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 acquireUseRelease=(acquire,use,release)=>uninterruptibleMask((restore)=>flatMap3(acquire,(a)=>onExitPrimitive(suspend(()=>restore(use(a))),(exit)=>release(a,exit),true)));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 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(()=>map3(forEach(Object.entries(arg),([key,effect])=>map3(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 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 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 runPromiseExit=runPromiseExitWith(empty());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 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 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 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 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)});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 map4=causeMap;var squash=causeSquash;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 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 _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 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 makeUnsafe3=scopeMakeUnsafe;var provide=provideScope;var addFinalizer=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(map3(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 succeed5=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(map3(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(map3((context)=>mergeAll(...context)))};var mergeAll2=(...layers)=>fromBuildMemo((memoMap,scope)=>mergeAllEffect(layers,memoMap,scope));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 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 promise2=promise;var tryPromise2=tryPromise;var succeed6=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_2=try_;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 map5=map3;var as2=as;var asVoid2=asVoid;var zipWith3=zipWith2;var catch_2=catch_;var catchTag2=catchTag;var catchReason2=catchReason;var catchCause2=catchCause;var catchIf2=catchIf;var mapError2=mapError;var orDie2=orDie;var tapError2=tapError;var tapDefect2=tapDefect;var ignore2=ignore;var orElseSucceed2=orElseSucceed;var timeout2=timeout;var timeoutOrElse2=timeoutOrElse;var delay2=delay;var sleep2=sleep;var raceFirst2=raceFirst;var matchEffect2=matchEffect;var context2=context;var provide3=provide2;var serviceOption2=serviceOption;var acquireRelease2=acquireRelease;var acquireUseRelease2=acquireUseRelease;var ensuring2=ensuring;var forever2=forever;var forkIn2=forkIn;var runFork2=runFork;var runPromise2=runPromise;var runPromiseWith2=runPromiseWith;var runPromiseExit2=runPromiseExit;var runSync2=runSync;var runSyncExit2=runSyncExit;var fnUntraced2=fnUntraced;var fn2=fn;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):succeed6(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 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)}}}return{nodes,initial:closure(nodes,starts),dot}};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",value:chars[i]})}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",value:char})}else{magic=true;tokens.push(parsed.token);i=parsed.end}}else{literal+=char;tokens.push({_tag:"Char",value:char})}}if(!magic){return{_tag:"Literal",value:literal}}const first=tokens[0];return{_tag:"Wildcard",tokens,leadingDot:first._tag==="Char"&&first.value==="."}};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,char)=>{switch(token._tag){case"Char":return token.value===char;case"Any":return true;case"Star":return false;case"Class":{const code=char.codePointAt(0);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 matchWildcard=(node,name,chars,dot)=>{if(name==="."||name===".."||name.startsWith(".")&&!dot&&!node.leadingDot){return false}const{tokens}=node;let t=0;let c=0;let star=-1;let resume=0;while(c<chars.length){if(tokens[t]?._tag==="Star"){star=t++;resume=c}else if(t<tokens.length&&matchToken(tokens[t],chars[c])){t++;c++}else if(star!==-1){t=star+1;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);let chars;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,chars??=Array.from(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 join=(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 byName=mapInput(String2,(entry)=>entry.name);var make8=(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:join(root,relative);const isUnlisted=(value)=>value==="."||value===".."||isRoot(value);const probe=(parent,name,named)=>{const path=toFsPath(join(parent,name));return fs.stat(path).pipe(map5((info)=>info.type),catchReason2("PlatformError","NotFound",()=>fs.readLink(path).pipe(as2("SymbolicLink"),catchIf2(isNotLink,()=>succeed6(undefined)))),catchIf2(named?isMissing:isIgnorable,()=>succeed6(undefined)),map5((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,()=>succeed6([])):succeed6([]),forEach2(probed,(name)=>probe(relative,name,named),{concurrency:16}),(listing,found)=>({entries:sort([...listing,...found.filter(isNotUndefined)],byName),named:named&&!listed}))};const visit=fnUntraced2(function*({name,type},parent,states,excluded){const result=step(compiled,states,name);const next=union(result);if(next.size===0){return}const relative=join(parent,name);const nextExcluded=union(step(excludes,excluded,name));const descend=canDescend(compiled,next);const isDirectory=!descend&&!needsDirectory(compiled,next)&&!excludeNeedsDirectory?false:type!=="Unknown"&&type!=="SymbolicLink"?type==="Directory":yield*fs.stat(toFsPath(relative)).pipe(map5((info)=>info.type==="Directory"),catchIf2(isIgnorable,()=>succeed6(false)));const accepted=accepts(compiled,next,isDirectory);if(!accepted&&(!isDirectory||!descend)||accepts(excludes,nextExcluded,isDirectory)){return}const child=(next)=>({relative,accepted,excluded:nextExcluded,next});if(!isDirectory||!descend){return child(undefined)}if(result.globstar.size===0){return child(next)}const followed=canDescend(compiled,result.explicit)?result.explicit:undefined;if(type!=="Unknown"){return child(type==="SymbolicLink"?followed:next)}return yield*fs.readLink(toFsPath(relative)).pipe(as2(child(followed)),catchIf2(isNotLink,()=>succeed6(child(next))))});const directory=fnUntraced2(function*(relative,states,excluded,named,out){const listing=yield*entries(relative,states,named);const children=yield*forEach2(listing.entries,(entry)=>visit(entry,relative,states,excluded),{concurrency:16});for(const child of children){if(child===undefined){continue}if(child.accepted){out.push(child.relative)}if(child.next!==undefined){yield*directory(child.relative,child.next,child.excluded,listing.named,out)}}});const out=[];yield*directory("",compiled.initial,excludes.initial,true,out);return out});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 interrupt2=fiberInterrupt;var Empty=Symbol.for("effect/MutableList/Empty");var make9=()=>({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 TypeId8="~effect/Queue";var EnqueueTypeId="~effect/Queue/Enqueue";var DequeueTypeId="~effect/Queue/Dequeue";var variance={_A:identity,_E:identity};var QueueProto={[TypeId8]:variance,[EnqueueTypeId]:variance,[DequeueTypeId]:variance,...PipeInspectableProto,toJSON(){return{_id:"effect/Queue",state:this.state._tag,size:sizeUnsafe(this)}}};var make10=(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=make9();self.scheduleRunning=false;self.state={_tag:"Open",takers:new Set,offers:new Set,awaiters:new Set};return succeed3(self)});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 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 TypeId9="~effect/Channel";var ChannelProto={[TypeId9]:{_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)=>succeed6(failCause3(cause)));return self};var fromPull=(effect)=>fromTransform((_,__)=>effect);var toTransform=(channel)=>channel.transform;var asyncQueue=(scope,f,options)=>make10({capacity:options?.bufferSize,strategy:options?.strategy}).pipe(tap2((queue)=>addFinalizer(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)=>map5(asyncQueue(scope,f,options),takeAll2));var unwrap=(channel)=>fromTransform((upstream,scope)=>{let pull;return succeed6(suspend2(()=>{if(pull)return pull;return channel.pipe(provide(scope),flatMap4((channel)=>toTransform(channel)(upstream,scope)),flatMap4((pull_)=>pull=pull_))}))});var TypeId10="~effect/Stream";var streamVariance={_R:identity,_E:identity,_A:identity};var Stream=function(channel){this.channel=channel};Stream.prototype={[TypeId10]:streamVariance,pipe(){return pipeArguments(this,arguments)}};var fromChannel=(channel)=>new Stream(channel);var TypeId11="~effect/Sink";var endVoid=succeed6([undefined]);var sinkVariance={_A:identity,_In:identity,_L:identity,_E:identity,_R:identity};var SinkProto={[TypeId11]:sinkVariance,pipe(){return pipeArguments(this,arguments)}};var fromChannel2=(channel)=>fromTransform2((upstream,scope)=>toTransform(channel)(upstream,scope).pipe(flatMap4(forever2({disableYield:true})),catchDone(succeed6)));var fromTransform2=(transform)=>{const self=Object.create(SinkProto);self.transform=transform;return self};var toChannel=(self)=>fromTransform((upstream,scope)=>succeed6(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(map5(effect,toChannel)));var fromChannel3=fromChannel;var fromPull2=(pull)=>fromChannel3(fromPull(pull));var toChannel2=(stream)=>stream.channel;var callback3=(f,options)=>fromChannel3(callbackArray(f,options));var unwrap3=(effect)=>fromChannel3(unwrap(map5(effect,toChannel2)));var TypeId12="~effect/FileSystem";var FileSystem=Service("effect/FileSystem");var make11=(impl)=>FileSystem.of({...impl,[TypeId12]:TypeId12,glob:make8(impl),exists:(path)=>pipe(impl.access(path),as2(true),catchTag2("PlatformError",(e)=>e.reason._tag==="NotFound"?succeed6(false):fail6(e))),readFileString:(path,encoding)=>flatMap4(impl.readFile(path),(_)=>try_2({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(succeed6(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 succeed6(of(buf))}}))))},unwrap3),sink:(path,options)=>pipe(impl.open(path,{...options,flag:options?.flag??"w"}),map5((file)=>forEach3((_)=>file.writeAll(_))),unwrap2),writeFileString:(path,data,options)=>flatMap4(try_2({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_2({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 succeed6(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))),map5((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 succeed6(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 map5(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 map5(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 map5(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?succeed6(undefined):positionToNumber(position,"write"),(nodePosition)=>map5(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?succeed6(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(map5((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(succeed6(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_2({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(map5(([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=map5(serviceOption2(WatchBackend),(backend)=>make11({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 TypeId13="~effect/Path";var Path2=Service("effect/Path");var make12=(impl)=>Path2.of({...impl,[TypeId13]:TypeId13,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)}});function normalizeStringPosix(path,allowAboveRoot){let res="";let lastSegmentLength=0;let lastSlash=-1;let dots=0;let code;for(let i=0;i<=path.length;++i){if(i<path.length){code=path.charCodeAt(i)}else if(code===47){break}else{code=47}if(code===47){if(lastSlash===i-1||dots===1){}else if(lastSlash!==i-1&&dots===2){if(res.length<2||lastSegmentLength!==2||res.charCodeAt(res.length-1)!==46||res.charCodeAt(res.length-2)!==46){if(res.length>2){const lastSlashIndex=res.lastIndexOf("/");if(lastSlashIndex!==res.length-1){if(lastSlashIndex===-1){res="";lastSegmentLength=0}else{res=res.slice(0,lastSlashIndex);lastSegmentLength=res.length-1-res.lastIndexOf("/")}lastSlash=i;dots=0;continue}}else if(res.length===2||res.length===1){res="";lastSegmentLength=0;lastSlash=i;dots=0;continue}}if(allowAboveRoot){if(res.length>0){res+="/.."}else{res=".."}lastSegmentLength=2}}else{if(res.length>0){res+="/"+path.slice(lastSlash+1,i)}else{res=path.slice(lastSlash+1,i)}lastSegmentLength=i-lastSlash-1}lastSlash=i;dots=0}else if(code===46&&dots!==-1){++dots}else{dots=-1}}return res}function _format(sep,pathObject){const dir=pathObject.dir||pathObject.root;const base=pathObject.base||(pathObject.name||"")+(pathObject.ext||"");if(!dir){return base}if(dir===pathObject.root){return dir+base}return dir+sep+base}function fromFileUrl(url){if(url.protocol!=="file:"){return fail6(new BadArgument({module:"Path",method:"fromFileUrl",description:"URL must be of scheme file"}))}else if(url.hostname!==""){return fail6(new BadArgument({module:"Path",method:"fromFileUrl",description:"Invalid file URL host"}))}const pathname=url.pathname;for(let n=0;n<pathname.length;n++){if(pathname[n]==="%"){const third=pathname.codePointAt(n+2)|32;if(pathname[n+1]==="2"&&third===102){return fail6(new BadArgument({module:"Path",method:"fromFileUrl",description:"must not include encoded / characters"}))}}}return try_2({try:()=>decodeURIComponent(pathname),catch:(cause)=>new BadArgument({module:"Path",method:"fromFileUrl",cause})})}var resolve2=function resolve(){let resolvedPath="";let resolvedAbsolute=false;let cwd=undefined;for(let i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){let path;if(i>=0){path=arguments[i]}else{const process2=globalThis.process;if(cwd===undefined&&"process"in globalThis&&typeof process2==="object"&&process2!==null&&typeof process2.cwd==="function"){cwd=process2.cwd()}path=cwd}if(path.length===0){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charCodeAt(0)===47}resolvedPath=normalizeStringPosix(resolvedPath,!resolvedAbsolute);if(resolvedAbsolute){if(resolvedPath.length>0){return"/"+resolvedPath}else{return"/"}}else if(resolvedPath.length>0){return resolvedPath}else{return"."}};var CHAR_FORWARD_SLASH=47;function toFileUrl(filepath){const outURL=new URL("file://");let resolved=resolve2(filepath);const filePathLast=filepath.charCodeAt(filepath.length-1);if(filePathLast===CHAR_FORWARD_SLASH&&resolved[resolved.length-1]!=="/"){resolved+="/"}outURL.pathname=encodePathChars(resolved);return succeed6(outURL)}var percentRegExp=/%/g;var backslashRegExp=/\\/g;var newlineRegExp=/\n/g;var carriageReturnRegExp=/\r/g;var tabRegExp=/\t/g;function encodePathChars(filepath){if(filepath.includes("%")){filepath=filepath.replace(percentRegExp,"%25")}if(filepath.includes("\\")){filepath=filepath.replace(backslashRegExp,"%5C")}if(filepath.includes(`
237
237
  `)){filepath=filepath.replace(newlineRegExp,"%0A")}if(filepath.includes("\r")){filepath=filepath.replace(carriageReturnRegExp,"%0D")}if(filepath.includes("\t")){filepath=filepath.replace(tabRegExp,"%09")}return filepath}var posixImpl=make12({resolve:resolve2,normalize(path){if(path.length===0)return".";const isAbsolute=path.charCodeAt(0)===47;const trailingSeparator=path.charCodeAt(path.length-1)===47;path=normalizeStringPosix(path,!isAbsolute);if(path.length===0&&!isAbsolute)path=".";if(path.length>0&&trailingSeparator)path+="/";if(isAbsolute)return"/"+path;return path},isAbsolute(path){return path.length>0&&path.charCodeAt(0)===47},join(){if(arguments.length===0){return"."}let joined;for(let i=0;i<arguments.length;++i){const arg=arguments[i];if(arg.length>0){if(joined===undefined){joined=arg}else{joined+="/"+arg}}}if(joined===undefined){return"."}return posixImpl.normalize(joined)},relative(from,to){if(from===to)return"";from=posixImpl.resolve(from);to=posixImpl.resolve(to);if(from===to)return"";let fromStart=1;for(;fromStart<from.length;++fromStart){if(from.charCodeAt(fromStart)!==47){break}}const fromEnd=from.length;const fromLen=fromEnd-fromStart;let toStart=1;for(;toStart<to.length;++toStart){if(to.charCodeAt(toStart)!==47){break}}const toEnd=to.length;const toLen=toEnd-toStart;const length=fromLen<toLen?fromLen:toLen;let lastCommonSep=-1;let i=0;for(;i<=length;++i){if(i===length){if(toLen>length){if(to.charCodeAt(toStart+i)===47){return to.slice(toStart+i+1)}else if(i===0){return to.slice(toStart+i)}}else if(fromLen>length){if(from.charCodeAt(fromStart+i)===47){lastCommonSep=i}else if(i===0){lastCommonSep=0}}break}const fromCode=from.charCodeAt(fromStart+i);const toCode=to.charCodeAt(toStart+i);if(fromCode!==toCode){break}else if(fromCode===47){lastCommonSep=i}}let out="";for(i=fromStart+lastCommonSep+1;i<=fromEnd;++i){if(i===fromEnd||from.charCodeAt(i)===47){if(out.length===0){out+=".."}else{out+="/.."}}}if(out.length>0){return out+to.slice(toStart+lastCommonSep)}else{toStart+=lastCommonSep;if(to.charCodeAt(toStart)===47){++toStart}return to.slice(toStart)}},dirname(path){if(path.length===0)return".";let code=path.charCodeAt(0);const hasRoot=code===47;let end=-1;let matchedSlash=true;for(let i=path.length-1;i>=1;--i){code=path.charCodeAt(i);if(code===47){if(!matchedSlash){end=i;break}}else{matchedSlash=false}}if(end===-1)return hasRoot?"/":".";if(hasRoot&&end===1)return"//";return path.slice(0,end)},basename(path,ext){let start=0;let end=-1;let matchedSlash=true;let i;if(ext!==undefined&&ext.length>0&&ext.length<=path.length){if(ext.length===path.length&&ext===path)return"";let extIdx=ext.length-1;let firstNonSlashEnd=-1;for(i=path.length-1;i>=0;--i){const code=path.charCodeAt(i);if(code===47){if(!matchedSlash){start=i+1;break}}else{if(firstNonSlashEnd===-1){matchedSlash=false;firstNonSlashEnd=i+1}if(extIdx>=0){if(code===ext.charCodeAt(extIdx)){if(--extIdx===-1){end=i}}else{extIdx=-1;end=firstNonSlashEnd}}}}if(start===end)end=firstNonSlashEnd;else if(end===-1)end=path.length;return path.slice(start,end)}else{for(i=path.length-1;i>=0;--i){if(path.charCodeAt(i)===47){if(!matchedSlash){start=i+1;break}}else if(end===-1){matchedSlash=false;end=i+1}}if(end===-1)return"";return path.slice(start,end)}},extname(path){let startDot=-1;let startPart=0;let end=-1;let matchedSlash=true;let preDotState=0;for(let i=path.length-1;i>=0;--i){const code=path.charCodeAt(i);if(code===47){if(!matchedSlash){startPart=i+1;break}continue}if(end===-1){matchedSlash=false;end=i+1}if(code===46){if(startDot===-1){startDot=i}else if(preDotState!==1){preDotState=1}}else if(startDot!==-1){preDotState=-1}}if(startDot===-1||end===-1||preDotState===0||preDotState===1&&startDot===end-1&&startDot===startPart+1){return""}return path.slice(startDot,end)},format:function format(pathObject){if(pathObject===null||typeof pathObject!=="object"){throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof pathObject)}return _format("/",pathObject)},parse(path){const ret={root:"",dir:"",base:"",ext:"",name:""};if(path.length===0)return ret;let code=path.charCodeAt(0);const isAbsolute=code===47;let start;if(isAbsolute){ret.root="/";start=1}else{start=0}let startDot=-1;let startPart=0;let end=-1;let matchedSlash=true;let i=path.length-1;let preDotState=0;for(;i>=start;--i){code=path.charCodeAt(i);if(code===47){if(!matchedSlash){startPart=i+1;break}continue}if(end===-1){matchedSlash=false;end=i+1}if(code===46){if(startDot===-1)startDot=i;else if(preDotState!==1)preDotState=1}else if(startDot!==-1){preDotState=-1}}if(startDot===-1||end===-1||preDotState===0||preDotState===1&&startDot===end-1&&startDot===startPart+1){if(end!==-1){if(startPart===0&&isAbsolute)ret.base=ret.name=path.slice(1,end);else ret.base=ret.name=path.slice(startPart,end)}}else{if(startPart===0&&isAbsolute){ret.name=path.slice(1,startDot);ret.base=path.slice(1,end)}else{ret.name=path.slice(startPart,startDot);ret.base=path.slice(startPart,end)}ret.ext=path.slice(startDot,end)}if(startPart>0)ret.dir=path.slice(0,startPart-1);else if(isAbsolute)ret.dir="/";return ret},sep:"/",fromFileUrl,toFileUrl,toNamespacedPath:identity});var layer3=succeed5(Path2)(posixImpl);import*as NodePath from"path";import*as NodeUrl from"url";var fileUrlOps=(windows)=>({fromFileUrl:(url)=>try_2({try:()=>NodeUrl.fileURLToPath(url,{windows}),catch:(cause)=>new BadArgument({module:"Path",method:"fromFileUrl",cause})}),toFileUrl:(path)=>try_2({try:()=>NodeUrl.pathToFileURL(path,{windows}),catch:(cause)=>new BadArgument({module:"Path",method:"toFileUrl",cause})})});var layerPosix=succeed5(Path2)(make12({...NodePath.posix,...fileUrlOps(false)}));var layerWin32=succeed5(Path2)(make12({...NodePath.win32,...fileUrlOps(true)}));var layer4=succeed5(Path2)(make12({...NodePath,...fileUrlOps(undefined)}));var layer5=layer4;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 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 TypeId14="~effect/Redacted";var isRedacted=(u)=>hasProperty(u,TypeId14);var make13=(value,options)=>{const self=Object.create(Proto2);if(options?.label){self.label=options.label}redactedRegistry.set(self,value);return self};var Proto2={[TypeId14]:{_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 makeEquivalence=(isEquivalent)=>make((x,y)=>isEquivalent(value2(x),value2(y)));function resolve3(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=resolve3(ast)?.identifier;if(typeof identifier==="string")return identifier;return ast.getExpected(getExpected)});var missing=Symbol();var succeed8=succeed4;var missingExit=succeed8(missing);var sameExit=succeed8(missing);var toOption=(value)=>value===missing?none2():some2(value);var fromOptionExit=(option)=>option._tag==="None"?missingExit:succeed8(option.value);var TypeId15="~effect/SchemaIssue/Issue";function isIssue(u){return hasProperty(u,TypeId15)&&u[TypeId15]===TypeId15}function hasInput(issue){return Object.hasOwn(issue,"input")}class IssueNodeImpl{[TypeId15]=TypeId15;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,map2(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(`
238
238
  `)}message=messageOverride??findMessage(issue)??getExpectedMessage(getExpected(issue.ast),issue);break}default:message=messageOverride??defaultLeafHook(issue);break}return path?`${message}
239
- 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_2({try:()=>JSON.parse(input,options?.reviver),catch:()=>new InvalidValue({expected:"a valid JSON string"},input,parseOptions)}))}function stringifyJson(options){return transformEffect((input,parseOptions)=>try_2({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 TypeId16="~effect/SchemaTransformation/Transformation";var Transformation=class extends Class{[TypeId16]=TypeId16;_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,TypeId16)&&u[TypeId16]===TypeId16}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)?succeed6(new URL(s)):fail6(new InvalidValue({expected:"a valid URL string"},s,options)),encode:(url)=>succeed6(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 TypeId17="~effect/Schema";class ASTNodeImpl{[TypeId17]=TypeId17;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 succeed8(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(map4(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)&&parameter.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=empty2();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=()=>succeed8(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 succeed8(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 succeed6(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 isFinite(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,[isFinite()]);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:succeed8(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(succeed8(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?succeed8(current):result;case"Transform":{const transform=(value)=>value===missing?missingExit:succeed8(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(()=>map4(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?succeed8(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 succeed6(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 succeed6(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?succeed8(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?succeed8(value):local})}}var invalid3=Symbol();var cache=new WeakMap;var compiler;var compilerAdaptersEnabled=false;var decodeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve4,ast,"parser"):resolve4(ast).parser;var makeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve4,ast,"makeEffect"):resolve4(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:succeed8(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 resolve4(ast){const cached=cache.get(ast);if(cached!==undefined)return cached;const entry=compiler===undefined?new InterpretedEntry(ast):new CompilerEntry(ast,compiler(ast,resolve4),resolve4);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 make14(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=resolve4(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 succeed6(value)};function run(ast){return runWithCompiler(normalCompiler,ast)}function parserResult(result,input){if(result===sameExit){return succeed6(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 succeed6(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??=resolve4(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=resolve4(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??resolve4)(descriptor.link.to),input,options);try{return construct(fields)}catch(error){throwConstructorDefect(error)}}var normalCompiler=(ast)=>resolve4(ast).parser;var constructorCompiler=(ast)=>resolve4(ast).makeEffect;var TypeId18="~effect/Schema/Schema";var RebuildOptions=Symbol();var SchemaProto={[TypeId18]:TypeId18,get make(){const value=make14(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 make15(ast,this[RebuildOptions])}};function make15(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 make15(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)=>make15(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 TypeId19=TypeId18;function declareConstructor(){return(typeParameters,run,annotations)=>{return make16(new Declaration(typeParameters.map(getAST),(typeParameters)=>run(typeParameters.map((ast)=>make16(ast))),annotations))}}function declare(is,annotations){return declareConstructor()([],()=>(input,ast,options)=>is(input)?succeed6(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(()=>map4(cause,(issue)=>new SchemaError(issue))))}function fromIssueExit(exit){return isSuccess3(exit)?exit:failCause2(map4(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 runSchemaErrorPromise(self){return runPromiseExit2(self).then((exit)=>{if(isSuccess3(exit)){return exit.value}throw getSchemaErrorOrThrow(exit.cause,"Promise adapter can only reject schema errors")})}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 decodeUnknownPromise(schema,options){const parser=decodeUnknownEffect2(schema,options);return(input,options)=>{return runSchemaErrorPromise(parser(input,options))}}var decodePromise=decodeUnknownPromise;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 make16=make15;function isSchema(u){return hasProperty(u,TypeId19)&&u[TypeId19]===TypeId19}var optionalKey2=lambda((schema)=>make16(optionalKey(schema.ast),{schema}));var optional2=lambda((self)=>{const schema=UndefinedOr(self);return make16(optional(self.ast),{schema})});function Literal2(literal){const out=make16(new Literal(literal),{literal,transform(to){return out.pipe(decodeTo2(Literal2(to),{decode:transform(()=>to),encode:transform(()=>literal)}))}});return out}var Unknown2=make16(unknown);var Null2=make16(null_);var Undefined2=make16(undefined_2);var String5=make16(string2);var Number5=make16(number2);var Boolean3=make16(boolean);function makeStruct(ast,fields){return make16(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 make16(record(key.ast,value.ast),{key,value})}var ArraySchema=lambda((schema)=>make16(new Arrays(false,[],[schema.ast]),{value:schema}));function makeUnion(ast,members){return make16(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 make16(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)=>make16(schema.ast,{schema,identifier})}function decodeTo2(to,transformation){return(from)=>{return make16(decodeTo(from.ast,to.ast,transformation?makeTransformation(transformation):passthrough2()),{from,to})}}function withConstructorDefault2(defaultValue){return(schema)=>make16(withConstructorDefault(schema.ast,defaultValue),{schema})}function tag(literal){return Literal2(literal).pipe(withConstructorDefault2(succeed6(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&&regExp.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=make16(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_2({try:()=>new globalThis.RegExp(e.source,e.flags),catch:()=>new InvalidValue({expected:"valid RegExp source and flags"},e,options)}),encode:(regExp)=>succeed6({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 succeed6(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)=>make13(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)=>make13(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])=>makeEquivalence(value)});return make16(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[TypeId19]=TypeId19;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=make16(new Declaration([from.ast],()=>(input,ast,options)=>{return isClassValue(input)?succeed6(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=make16(annotate(Json,{toCode:()=>({runtime:"Schema.Json",Type:"Schema.Json"})}));var JsonObject=Record(String5,Json2);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.4";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
+ 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_2({try:()=>JSON.parse(input,options?.reviver),catch:()=>new InvalidValue({expected:"a valid JSON string"},input,parseOptions)}))}function stringifyJson(options){return transformEffect((input,parseOptions)=>try_2({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 TypeId16="~effect/SchemaTransformation/Transformation";var Transformation=class extends Class{[TypeId16]=TypeId16;_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,TypeId16)&&u[TypeId16]===TypeId16}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)?succeed6(new URL(s)):fail6(new InvalidValue({expected:"a valid URL string"},s,options)),encode:(url)=>succeed6(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 TypeId17="~effect/Schema";class ASTNodeImpl{[TypeId17]=TypeId17;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 succeed8(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(map4(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)&&parameter.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=empty2();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=()=>succeed8(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 succeed8(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 succeed6(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 isFinite(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,[isFinite()]);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:succeed8(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(succeed8(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?succeed8(current):result;case"Transform":{const transform=(value)=>value===missing?missingExit:succeed8(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(()=>map4(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?succeed8(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 succeed6(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 succeed6(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?succeed8(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?succeed8(value):local})}}var invalid3=Symbol();var cache=new WeakMap;var compiler;var compilerAdaptersEnabled=false;var decodeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve4,ast,"parser"):resolve4(ast).parser;var makeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve4,ast,"makeEffect"):resolve4(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:succeed8(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 resolve4(ast){const cached=cache.get(ast);if(cached!==undefined)return cached;const entry=compiler===undefined?new InterpretedEntry(ast):new CompilerEntry(ast,compiler(ast,resolve4),resolve4);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 make14(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=resolve4(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 succeed6(value)};function run(ast){return runWithCompiler(normalCompiler,ast)}function parserResult(result,input){if(result===sameExit){return succeed6(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 succeed6(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??=resolve4(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=resolve4(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??resolve4)(descriptor.link.to),input,options);try{return construct(fields)}catch(error){throwConstructorDefect(error)}}var normalCompiler=(ast)=>resolve4(ast).parser;var constructorCompiler=(ast)=>resolve4(ast).makeEffect;var TypeId18="~effect/Schema/Schema";var RebuildOptions=Symbol();var SchemaProto={[TypeId18]:TypeId18,get make(){const value=make14(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 make15(ast,this[RebuildOptions])}};function make15(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 make15(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)=>make15(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 TypeId19=TypeId18;function declareConstructor(){return(typeParameters,run,annotations)=>{return make16(new Declaration(typeParameters.map(getAST),(typeParameters)=>run(typeParameters.map((ast)=>make16(ast))),annotations))}}function declare(is,annotations){return declareConstructor()([],()=>(input,ast,options)=>is(input)?succeed6(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(()=>map4(cause,(issue)=>new SchemaError(issue))))}function fromIssueExit(exit){return isSuccess3(exit)?exit:failCause2(map4(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 runSchemaErrorPromise(self){return runPromiseExit2(self).then((exit)=>{if(isSuccess3(exit)){return exit.value}throw getSchemaErrorOrThrow(exit.cause,"Promise adapter can only reject schema errors")})}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 decodeUnknownPromise(schema,options){const parser=decodeUnknownEffect2(schema,options);return(input,options)=>{return runSchemaErrorPromise(parser(input,options))}}var decodePromise=decodeUnknownPromise;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 make16=make15;function isSchema(u){return hasProperty(u,TypeId19)&&u[TypeId19]===TypeId19}var optionalKey2=lambda((schema)=>make16(optionalKey(schema.ast),{schema}));var optional2=lambda((self)=>{const schema=UndefinedOr(self);return make16(optional(self.ast),{schema})});function Literal2(literal){const out=make16(new Literal(literal),{literal,transform(to){return out.pipe(decodeTo2(Literal2(to),{decode:transform(()=>to),encode:transform(()=>literal)}))}});return out}var Unknown2=make16(unknown);var Null2=make16(null_);var Undefined2=make16(undefined_2);var String5=make16(string2);var Number5=make16(number2);var Boolean3=make16(boolean);function makeStruct(ast,fields){return make16(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 make16(record(key.ast,value.ast),{key,value})}var ArraySchema=lambda((schema)=>make16(new Arrays(false,[],[schema.ast]),{value:schema}));function makeUnion(ast,members){return make16(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 make16(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)=>make16(schema.ast,{schema,identifier})}function decodeTo2(to,transformation){return(from)=>{return make16(decodeTo(from.ast,to.ast,transformation?makeTransformation(transformation):passthrough2()),{from,to})}}function withConstructorDefault2(defaultValue){return(schema)=>make16(withConstructorDefault(schema.ast,defaultValue),{schema})}function tag(literal){return Literal2(literal).pipe(withConstructorDefault2(succeed6(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&&regExp.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=make16(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_2({try:()=>new globalThis.RegExp(e.source,e.flags),catch:()=>new InvalidValue({expected:"valid RegExp source and flags"},e,options)}),encode:(regExp)=>succeed6({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 succeed6(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)=>make13(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)=>make13(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])=>makeEquivalence(value)});return make16(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[TypeId19]=TypeId19;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=make16(new Declaration([from.ast],()=>(input,ast,options)=>{return isClassValue(input)?succeed6(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=make16(annotate(Json,{toCode:()=>({runtime:"Schema.Json",Type:"Schema.Json"})}));var JsonObject=Record(String5,Json2);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.6";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,`
240
240
  `);const chunks=buffer.split(`
241
241
 
242
242
  `);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.4",
3
+ "version": "0.2.6",
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.3",
13
+ "@collective-intelligence/extensions-sdk-backend": "0.2.4",
14
14
  "@module-federation/vite": "1.23.2",
15
15
  "@vitejs/plugin-react": "6.0.5",
16
16
  "acorn": "8.18.0",
@@ -53,5 +53,5 @@
53
53
  "ultracite": "7.10.7",
54
54
  "vitest": "5.0.2"
55
55
  },
56
- "gitHead": "854692172c956fe8f0bbc6a0fdf8bcaa6e2787ef"
56
+ "gitHead": "7868d119f10849855dc7301346908ab30a68f1db"
57
57
  }