@collective-intelligence/cli 0.1.31 → 0.1.33

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 (3) hide show
  1. package/README.md +54 -6
  2. package/dist/cli.js +11 -8
  3. package/package.json +4 -4
package/dist/cli.js CHANGED
@@ -236,12 +236,12 @@ ${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 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.1.31";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 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.1.33";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(`
243
243
  `);const dataLines=[];let eventName;for(const line of lines){if(line.startsWith("data:")){dataLines.push(line.replace(/^data:\s*/,""))}else if(line.startsWith("event:")){eventName=line.replace(/^event:\s*/,"")}else if(line.startsWith("id:")){lastEventId=line.replace(/^id:\s*/,"")}else if(line.startsWith("retry:")){const parsed=Number.parseInt(line.replace(/^retry:\s*/,""),10);if(!Number.isNaN(parsed)){retryDelay=parsed}}}let data;let parsedJson=false;if(dataLines.length){const rawData=dataLines.join(`
244
- `);try{data=JSON.parse(rawData);parsedJson=true}catch{data=rawData}}if(parsedJson){if(responseValidator){await responseValidator(data)}if(responseTransformer){data=await responseTransformer(data)}}onSseEvent?.({data,event:eventName,id:lastEventId,retry:retryDelay});if(dataLines.length){yield data}}}}finally{signal.removeEventListener("abort",abortHandler);reader.releaseLock()}break}catch(error){onSseError?.(error);if(sseMaxRetryAttempts!==undefined&&attempt>=sseMaxRetryAttempts){break}const backoff=Math.min(retryDelay*2**(attempt-1),sseMaxRetryDelay??30000);await sleep(backoff)}}};const stream=createStream();return{stream}}var separatorArrayExplode=(style)=>{switch(style){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}};var separatorArrayNoExplode=(style)=>{switch(style){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}};var separatorObjectExplode=(style)=>{switch(style){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}};var serializeArrayParam=({allowReserved,explode,name,style,value})=>{if(!explode){const joinedValues=(allowReserved?value:value.map((v)=>encodeURIComponent(v))).join(separatorArrayNoExplode(style));switch(style){case"label":return`.${joinedValues}`;case"matrix":return`;${name}=${joinedValues}`;case"simple":return joinedValues;default:return`${name}=${joinedValues}`}}const separator=separatorArrayExplode(style);const joinedValues=value.map((v)=>{if(style==="label"||style==="simple"){return allowReserved?v:encodeURIComponent(v)}return serializePrimitiveParam({allowReserved,name,value:v})}).join(separator);return style==="label"||style==="matrix"?separator+joinedValues:joinedValues};var serializePrimitiveParam=({allowReserved,name,value})=>{if(value===undefined||value===null){return""}if(typeof value==="object"){throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.")}return`${name}=${allowReserved?value:encodeURIComponent(value)}`};var serializeObjectParam=({allowReserved,explode,name,style,value,valueOnly})=>{if(value instanceof Date){return valueOnly?value.toISOString():`${name}=${value.toISOString()}`}if(style!=="deepObject"&&!explode){let values=[];Object.entries(value).forEach(([key,v])=>{values=[...values,key,allowReserved?v:encodeURIComponent(v)]});const joinedValues=values.join(",");switch(style){case"form":return`${name}=${joinedValues}`;case"label":return`.${joinedValues}`;case"matrix":return`;${name}=${joinedValues}`;default:return joinedValues}}const separator=separatorObjectExplode(style);const joinedValues=Object.entries(value).map(([key,v])=>serializePrimitiveParam({allowReserved,name:style==="deepObject"?`${name}[${key}]`:key,value:v})).join(separator);return style==="label"||style==="matrix"?separator+joinedValues:joinedValues};var PATH_PARAM_RE=/\{[^{}]+\}/g;var defaultPathSerializer=({path,url:_url})=>{let url=_url;const matches=_url.match(PATH_PARAM_RE);if(matches){for(const match of matches){let explode=false;let name=match.substring(1,match.length-1);let style="simple";if(name.endsWith("*")){explode=true;name=name.substring(0,name.length-1)}if(name.startsWith(".")){name=name.substring(1);style="label"}else if(name.startsWith(";")){name=name.substring(1);style="matrix"}const value=path[name];if(value===undefined||value===null){continue}if(Array.isArray(value)){url=url.replace(match,serializeArrayParam({explode,name,style,value}));continue}if(typeof value==="object"){url=url.replace(match,serializeObjectParam({explode,name,style,value,valueOnly:true}));continue}if(style==="matrix"){url=url.replace(match,`;${serializePrimitiveParam({name,value})}`);continue}const replaceValue=encodeURIComponent(style==="label"?`.${value}`:value);url=url.replace(match,replaceValue)}}return url};var getUrl=({baseUrl,path,query,querySerializer,url:_url})=>{const pathUrl=_url.startsWith("/")?_url:`/${_url}`;let url=(baseUrl??"")+pathUrl;if(path){url=defaultPathSerializer({path,url})}let search=query?querySerializer(query):"";if(search.startsWith("?")){search=search.substring(1)}if(search){url+=`?${search}`}return url};function getValidRequestBody(options){const hasBody=options.body!==undefined;const isSerializedBody=hasBody&&options.bodySerializer;if(isSerializedBody){if("serializedBody"in options){const hasSerializedBody=options.serializedBody!==undefined&&options.serializedBody!=="";return hasSerializedBody?options.serializedBody:null}return options.body!==""?options.body:null}if(hasBody){return options.body}return}var getAuthToken=async(auth,callback)=>{const token=typeof callback==="function"?await callback(auth):callback;if(!token){return}if(auth.scheme==="bearer"){return`Bearer ${token}`}if(auth.scheme==="basic"){return`Basic ${btoa(token)}`}return token};var createQuerySerializer=({parameters={},...args}={})=>{const querySerializer=(queryParams)=>{const search=[];if(queryParams&&typeof queryParams==="object"){for(const name in queryParams){const value=queryParams[name];if(value===undefined||value===null){continue}const options=parameters[name]||args;if(Array.isArray(value)){const serializedArray=serializeArrayParam({allowReserved:options.allowReserved,explode:true,name,style:"form",value,...options.array});if(serializedArray)search.push(serializedArray)}else if(typeof value==="object"){const serializedObject=serializeObjectParam({allowReserved:options.allowReserved,explode:true,name,style:"deepObject",value,...options.object});if(serializedObject)search.push(serializedObject)}else{const serializedPrimitive=serializePrimitiveParam({allowReserved:options.allowReserved,name,value});if(serializedPrimitive)search.push(serializedPrimitive)}}}return search.join("&")};return querySerializer};var getParseAs=(contentType)=>{if(!contentType){return"stream"}const cleanContent=contentType.split(";")[0]?.trim();if(!cleanContent){return}if(cleanContent.startsWith("application/json")||cleanContent.endsWith("+json")){return"json"}if(cleanContent==="multipart/form-data"){return"formData"}if(["application/","audio/","image/","video/"].some((type)=>cleanContent.startsWith(type))){return"blob"}if(cleanContent.startsWith("text/")){return"text"}return};var checkForExistence=(options,name)=>{if(!name){return false}if(options.headers.has(name)||options.query?.[name]||options.headers.get("Cookie")?.includes(`${name}=`)){return true}return false};var setAuthParams=async({security,...options})=>{for(const auth of security){if(checkForExistence(options,auth.name)){continue}const token=await getAuthToken(auth,options.auth);if(!token){continue}const name=auth.name??"Authorization";switch(auth.in){case"query":if(!options.query){options.query={}}options.query[name]=token;break;case"cookie":options.headers.append("Cookie",`${name}=${token}`);break;case"header":default:options.headers.set(name,token);break}}};var buildUrl=(options)=>getUrl({baseUrl:options.baseUrl,path:options.path,query:options.query,querySerializer:typeof options.querySerializer==="function"?options.querySerializer:createQuerySerializer(options.querySerializer),url:options.url});var mergeConfigs=(a,b)=>{const config={...a,...b};if(config.baseUrl?.endsWith("/")){config.baseUrl=config.baseUrl.substring(0,config.baseUrl.length-1)}config.headers=mergeHeaders(a.headers,b.headers);return config};var headersEntries=(headers)=>{const entries=[];headers.forEach((value,key)=>{entries.push([key,value])});return entries};var mergeHeaders=(...headers)=>{const mergedHeaders=new Headers;for(const header of headers){if(!header){continue}const iterator=header instanceof Headers?headersEntries(header):Object.entries(header);for(const[key,value]of iterator){if(value===null){mergedHeaders.delete(key)}else if(Array.isArray(value)){for(const v of value){mergedHeaders.append(key,v)}}else if(value!==undefined){mergedHeaders.set(key,typeof value==="object"?JSON.stringify(value):value)}}}return mergedHeaders};class Interceptors{fns=[];clear(){this.fns=[]}eject(id){const index=this.getInterceptorIndex(id);if(this.fns[index]){this.fns[index]=null}}exists(id){const index=this.getInterceptorIndex(id);return Boolean(this.fns[index])}getInterceptorIndex(id){if(typeof id==="number"){return this.fns[id]?id:-1}return this.fns.indexOf(id)}update(id,fn){const index=this.getInterceptorIndex(id);if(this.fns[index]){this.fns[index]=fn;return id}return false}use(fn){this.fns.push(fn);return this.fns.length-1}}var createInterceptors=()=>({error:new Interceptors,request:new Interceptors,response:new Interceptors});var defaultQuerySerializer=createQuerySerializer({allowReserved:false,array:{explode:true,style:"form"},object:{explode:true,style:"deepObject"}});var defaultHeaders={"Content-Type":"application/json"};var createConfig=(override={})=>({...jsonBodySerializer,headers:defaultHeaders,parseAs:"auto",querySerializer:defaultQuerySerializer,...override});var createClient=(config={})=>{let _config=mergeConfigs(createConfig(),config);const getConfig=()=>({..._config});const setConfig=(config)=>{_config=mergeConfigs(_config,config);return getConfig()};const interceptors=createInterceptors();const beforeRequest=async(options)=>{const opts={..._config,...options,fetch:options.fetch??_config.fetch??globalThis.fetch,headers:mergeHeaders(_config.headers,options.headers),serializedBody:undefined};if(opts.security){await setAuthParams({...opts,security:opts.security})}if(opts.requestValidator){await opts.requestValidator(opts)}if(opts.body!==undefined&&opts.bodySerializer){opts.serializedBody=opts.bodySerializer(opts.body)}if(opts.body===undefined||opts.serializedBody===""){opts.headers.delete("Content-Type")}const resolvedOpts=opts;const url=buildUrl(resolvedOpts);return{opts:resolvedOpts,url}};const request=async(options)=>{const{opts,url}=await beforeRequest(options);const requestInit={redirect:"follow",...opts,body:getValidRequestBody(opts)};let request=new Request(url,requestInit);for(const fn of interceptors.request.fns){if(fn){request=await fn(request,opts)}}const _fetch=opts.fetch;let response;try{response=await _fetch(request)}catch(error){let finalError=error;for(const fn of interceptors.error.fns){if(fn){finalError=await fn(error,undefined,request,opts)}}finalError=finalError||{};if(opts.throwOnError){throw finalError}return opts.responseStyle==="data"?undefined:{error:finalError,request,response:undefined}}for(const fn of interceptors.response.fns){if(fn){response=await fn(response,request,opts)}}const result={request,response};if(response.ok){const parseAs=(opts.parseAs==="auto"?getParseAs(response.headers.get("Content-Type")):opts.parseAs)??"json";if(response.status===204||response.headers.get("Content-Length")==="0"){let emptyData;switch(parseAs){case"arrayBuffer":case"blob":case"text":emptyData=await response[parseAs]();break;case"formData":emptyData=new FormData;break;case"stream":emptyData=response.body;break;case"json":default:emptyData={};break}return opts.responseStyle==="data"?emptyData:{data:emptyData,...result}}let data;switch(parseAs){case"arrayBuffer":case"blob":case"formData":case"text":data=await response[parseAs]();break;case"json":{const text=await response.text();data=text?JSON.parse(text):{};break}case"stream":return opts.responseStyle==="data"?response.body:{data:response.body,...result}}if(parseAs==="json"){if(opts.responseValidator){await opts.responseValidator(data)}if(opts.responseTransformer){data=await opts.responseTransformer(data)}}return opts.responseStyle==="data"?data:{data,...result}}const textError=await response.text();let jsonError;try{jsonError=JSON.parse(textError)}catch{}const error=jsonError??textError;let finalError=error;for(const fn of interceptors.error.fns){if(fn){finalError=await fn(error,response,request,opts)}}finalError=finalError||{};if(opts.throwOnError){throw finalError}return opts.responseStyle==="data"?undefined:{error:finalError,...result}};const makeMethodFn=(method)=>(options)=>request({...options,method});const makeSseFn=(method)=>async(options)=>{const{opts,url}=await beforeRequest(options);return createSseClient({...opts,body:opts.body,headers:opts.headers,method,onRequest:async(url,init)=>{let request=new Request(url,init);for(const fn of interceptors.request.fns){if(fn){request=await fn(request,opts)}}return request},serializedBody:getValidRequestBody(opts),url})};const _buildUrl=(options)=>buildUrl({..._config,...options});return{buildUrl:_buildUrl,connect:makeMethodFn("CONNECT"),delete:makeMethodFn("DELETE"),get:makeMethodFn("GET"),getConfig,head:makeMethodFn("HEAD"),interceptors,options:makeMethodFn("OPTIONS"),patch:makeMethodFn("PATCH"),post:makeMethodFn("POST"),put:makeMethodFn("PUT"),request,setConfig,sse:{connect:makeSseFn("CONNECT"),delete:makeSseFn("DELETE"),get:makeSseFn("GET"),head:makeSseFn("HEAD"),options:makeSseFn("OPTIONS"),patch:makeSseFn("PATCH"),post:makeSseFn("POST"),put:makeSseFn("PUT"),trace:makeSseFn("TRACE")},trace:makeMethodFn("TRACE")}};var client=createClient(createConfig());var authLogout=(options)=>(options?.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/auth/logout",...options});var authMe=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/auth/me",...options});var authMeOrganizations=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/auth/me/organizations",...options});var authStartCliDevice=(options)=>(options.client??client).post({url:"/auth/cli/device",...options,headers:{"Content-Type":"application/json",...options.headers}});var authExchangeCliToken=(options)=>(options.client??client).post({url:"/auth/cli/token",...options,headers:{"Content-Type":"application/json",...options.headers}});var aiModelPresetsList=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/ai/model-presets",...options});var aiModelPresetsDefault=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/ai/model-presets/default",...options});var developmentSessionsCreate=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions",...options,headers:{"Content-Type":"application/json",...options.headers}});var developmentSessionsTerminate=(options)=>(options.client??client).delete({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions/{sessionId}",...options});var developmentSessionsHeartbeat=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions/{sessionId}/heartbeat",...options});var developmentSessionsUpdateLocalManifest=(options)=>(options.client??client).put({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions/{sessionId}/local-manifest",...options,headers:{"Content-Type":"application/json",...options.headers}});var hostedExtensionDiagnosticsReadTrace=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/hosted-extension-diagnostics/{diagnosticId}/trace",...options});var packageOperationsSnapshot=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-operations/{operationId}",...options});var packageOperationsEvents=(options)=>(options.client??client).sse.get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-operations/{operationId}/events",...options});var packageOperationsContinueOperation=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-operations/{operationId}/continuations",...options});var packageReleasesUpdateInstallation=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-installations/update",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesRollbackInstallation=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-installations/rollback",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesPromote=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-releases/promote",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesPublish=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-releases/publish",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesLookupPublished=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-releases/lookup",...options,headers:{"Content-Type":"application/json",...options.headers}});var extensionPackagesListInstalled=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/installed",...options});var extensionPackagesListReleases=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/{fqn}/releases",...options});var extensionPackagesInstall=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/{fqn}/install",...options,headers:{"Content-Type":"application/json",...options.headers}});var extensionPackagesSync=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/{fqn}/sync",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationsSearch=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organizations/search",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationSetupCatalog=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/setup/catalog",...options});var organizationSetupSetup=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/setup",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferPreview=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/preview",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferExports=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/exports",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferImports=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/imports",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferRollbacks=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/rollbacks",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferRuns=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs",...options});var organizationTransferRun=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}",...options});var organizationTransferCancel=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/cancel",...options});var organizationTransferResume=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/resume",...options});var organizationTransferPurge=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/purge",...options});var organizationTransferEvents=(options)=>(options.client??client).sse.get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/events",...options});var organizationTransferReport=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/report",...options});var organizationTransferUploadUrls=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/archives/{archiveId}/upload-urls",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferDownloadUrls=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/archives/{archiveId}/download-urls",...options});var organizationCredentialsUpsert=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/upsert",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsList=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/list",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsGet=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/get",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsRotate=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/rotate",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsRevoke=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/revoke",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationServicePrincipalsList=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/service-principals",...options});var organizationExternalAppsList=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps",...options});var organizationExternalAppsEnroll=(options)=>(options.client??client).put({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/by-fqn/{fqn}",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationExternalAppsGet=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}",...options});var organizationExternalAppsUpdate=(options)=>(options.client??client).put({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationExternalAppsDisable=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}/disable",...options});var organizationExternalAppsRotateCredential=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}/credential/rotate",...options});var normalizedBackendUrl=(value)=>value.replace(/\/$/u,"");var makeBackendManagementClient=(config)=>createClient({baseUrl:normalizedBackendUrl(config.backendUrl),fetch:config.fetch,headers:config.token===undefined?{}:{authorization:`Bearer ${config.token}`}});function makeValue(value){return{_tag:"Value",value}}function makeRecord(keys,value){return{_tag:"Record",keys,value}}function makeArray(length,value){return{_tag:"Array",length,value}}var ConfigProvider=Reference("effect/ConfigProvider",{defaultValue:()=>fromEnv()});var Proto3={...PipeInspectableProto,toJSON(){return{_id:"ConfigProvider"}}};var identityPath=(path)=>path;function makeProvider(load,mapInput){const self=Object.create(Proto3);self.load=load;self.mapInput=mapInput;return self}function makeSource(get,transform){return makeProvider((path)=>get(transform(path)),(f)=>makeSource(get,(path)=>f(transform(path))))}function make17(get){return makeSource(get,identityPath)}var layer6=(self)=>isEffect2(self)?effect(ConfigProvider)(self):succeed5(ConfigProvider)(self);function fromUnknown(root,options){const preserveEmptyStrings=options?.preserveEmptyStrings===true;return make17((path)=>succeed6(nodeAtJson(root,path,preserveEmptyStrings)))}function nodeAtJson(root,path,preserveEmptyStrings){let cur=root;for(const seg of path){if(cur===null||cur===undefined)return;if(Array.isArray(cur)){if(typeof seg!=="number"||!Number.isInteger(seg)||seg<0||seg>=cur.length)return;cur=cur[seg];continue}if(isObject(cur)){if(typeof seg!=="string")return;if(!Object.hasOwn(cur,seg))return;cur=cur[seg];continue}return}return describeUnknown(cur,preserveEmptyStrings)}function describeUnknown(u,preserveEmptyStrings){if(u===undefined||u===null)return;if(typeof u==="string")return stringNode(u,preserveEmptyStrings);if(typeof u==="number"||typeof u==="boolean"||typeof u==="bigint"){return makeValue(String(u))}if(Array.isArray(u))return makeArray(u.length);if(isObject(u)){return makeRecord(new Set(Object.keys(u)))}return makeValue(format(u))}function stringNode(value,preserveEmptyStrings){const normalized=emptyStringAsMissing(value,preserveEmptyStrings);return normalized===undefined?undefined:makeValue(normalized)}function emptyStringAsMissing(value,preserveEmptyStrings){return value===""&&!preserveEmptyStrings?undefined:value}function fromEnvRecord(env,options){const preserveEmptyStrings=options?.preserveEmptyStrings===true;const trie=buildEnvTrie(env);return make17((path)=>succeed6(nodeAtEnv(trie,env,path,preserveEmptyStrings)))}function fromEnv(options){const env=options?.env??{...globalThis.process?.env,...import.meta?.env};return fromEnvRecord(env,{preserveEmptyStrings:options?.preserveEmptyStrings})}function buildEnvTrie(env){const trie={};for(const[name,value]of Object.entries(env)){if(value===undefined)continue;const segments=name.split("_");let node=trie;for(const seg of segments){const children=node.children??=Object.create(null);node=children[seg]??={}}}return trie}function nodeAtEnv(trie,env,path,preserveEmptyStrings){const key=path.map(String).join("_");const leafValue=emptyStringAsMissing(Object.hasOwn(env,key)?env[key]:undefined,preserveEmptyStrings);const trieNode=trieNodeAt(trie,path);const children=trieNode?.children?Object.keys(trieNode.children):[];if(children.length===0){return leafValue===undefined?undefined:makeValue(leafValue)}const allNumeric=children.every(isCanonicalArrayIndex);if(allNumeric){const length=Math.max(...children.map((k)=>parseInt(k,10)))+1;return makeArray(length,leafValue)}return makeRecord(new Set(children),leafValue)}function trieNodeAt(root,path){if(path.length===0)return root;let node=root;for(const seg of path){node=node?.children?.[String(seg)];if(!node)return}return node}var TypeId20="~effect/Config";class ConfigError{_tag="ConfigError";name="ConfigError";cause;constructor(cause){this.cause=cause}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}}var Proto4={...Prototype2({label:"Config",evaluate(fiber){return this.parse(fiber.getRef(ConfigProvider))}}),[TypeId20]:TypeId20,toJSON(){return{_id:"Config"}}};function make18(evaluator){const self=Object.create(Proto4);self.evaluator=evaluator;self.parse=(provider)=>flatMapEager2(evaluator(provider,[]),fromResult2);return self}var isSourceError=(u)=>isTagged(u,"SourceError");var cursorToString=()=>"<configuration>";var mapReasons=(f)=>(self)=>catchCause2(self,(cause)=>failCause3(fromReasons(cause.reasons.map(f))));var loadCursor=(provider,path)=>provider.load(path).pipe(mapReasons((reason)=>isFailReason2(reason)?makeDieReason(reason.error).annotate(reasonAnnotations2(reason)):reason),mapEager2((node)=>({provider,path,node,toString:cursorToString})));var loadChildCursor=(cursor,segment)=>loadCursor(cursor.provider,[...cursor.path,segment]);var decodeFromCursor=(ast,decode)=>decodeTo(unknown,ast,new Transformation(transformEffect((input)=>decode(input)),passthrough()));var isScalarInput=(ast)=>{switch(ast._tag){case"Union":return ast.types.every(isScalarInput);case"Objects":case"Arrays":case"Suspend":return false;default:return true}};var hasProviderInput=(ast,node)=>{switch(ast._tag){case"Objects":return node?._tag==="Record";case"Arrays":return node?._tag==="Array";case"Union":return ast.types.some((ast)=>hasProviderInput(ast,node));case"Suspend":return hasProviderInput(ast.thunk(),node);default:return node?.value!==undefined}};var toConfigCursorAST=memoize((root)=>{const seen=new WeakSet;const recur=applyToSelfOrLastLinkEncoding((ast)=>{seen.add(ast);switch(ast._tag){case"Objects":{const materialize=fnUntraced2(function*(cursor){if(cursor.node?._tag!=="Record"){return}const node=cursor.node;const keys=new Set;for(const property of ast.propertySignatures){if(typeof property.name==="string")keys.add(property.name)}if(ast.indexSignatures.length>0){const input={};for(const key of node.keys){assignProperty(input,key,undefined)}for(const is of ast.indexSignatures){for(const key of getIndexSignatureKeys(input,is.parameter)){if(typeof key==="string")keys.add(key)}}}const out={};for(const key of keys){const child=yield*loadChildCursor(cursor,key);if(child.node!==undefined)assignProperty(out,key,child)}return out});return decodeFromCursor(ast.recur(recur,(ast)=>ast),materialize)}case"Arrays":{const materialize=fnUntraced2(function*(cursor){if(cursor.node?._tag!=="Array"){return}const out=[];for(let i=0;i<cursor.node.length;i++){out.push(yield*loadChildCursor(cursor,i))}return out});return decodeFromCursor(ast.recur(recur),materialize)}case"Union":for(const member of ast.types){recur(member)}if(!isScalarInput(ast))return ast.recur(recur);break;case"Suspend":{const target=ast.thunk();if(!seen.has(target))recur(target);return ast.recur(recur)}case"Declaration":case"Any":throw new globalThis.Error("Config.schema does not support opaque StringTree encodings",{cause:ast})}return decodeFromCursor(ast,(cursor)=>succeed6(cursor.node?.value))});return recur(root)});function schema(codec,path){const codecStringTree=toCodecStringTree2(codec);const encodedAst=toEncoded(codecStringTree.ast);const decodeCursor=decodeUnknownEffect(make16(toConfigCursorAST(codecStringTree.ast)));const localPath=typeof path==="string"?[path]:path??[];return make18((provider,pathPrefix)=>{const fullPath=[...pathPrefix,...localPath];return loadCursor(provider,fullPath).pipe(flatMapEager2((cursor)=>decodeCursor(cursor).pipe(mapEager2(succeed2),catchEager2((issue)=>{const error=new ConfigError(new SchemaError(fullPath.length>0?new Pointer(fullPath,issue):issue));return hasProviderInput(encodedAst,cursor.node)?fail6(error):succeed6(fail2(error))}))),mapReasons((reason)=>isDieReason2(reason)&&isSourceError(reason.defect)?makeFailReason(new ConfigError(reason.defect)).annotate(reasonAnnotations2(reason)):reason))})}class BackendManagementConfigurationError extends TaggedError3()("BackendManagementConfigurationError",{message:String5}){}var tryConfiguration=(evaluate)=>try_2({catch:(cause)=>is2(BackendManagementConfigurationError)(cause)?cause:new BackendManagementConfigurationError({message:cause instanceof Error?cause.message:"CLI configuration step failed"}),try:evaluate});import{chmodSync,existsSync,mkdirSync,readFileSync,renameSync,writeFileSync}from"fs";import path from"path";var ProfileSchema=Struct({apiOrigin:String5,currentOrganizationId:optionalKey2(String5),session:optionalKey2(Struct({expiresAt:optionalKey2(String5),token:String5}))});var ProfileStoreSchema=Struct({current:optionalKey2(String5),profiles:Record(String5,ProfileSchema)});var profileStoreJson=fromJsonString2(ProfileStoreSchema);var decodeProfileStore=decodeUnknownSync(profileStoreJson);var encodeProfileStore=encodeSync(profileStoreJson);var nonEmpty=(value)=>value===""?undefined:value;var profileDirectory=(environment)=>{const configHome=nonEmpty(environment.XDG_CONFIG_HOME);if(configHome!==undefined){return path.join(configHome,"ci")}const home=nonEmpty(environment.HOME);return home===undefined?undefined:path.join(home,".config","ci")};var profileName=(apiOrigin)=>new URL(apiOrigin).host;var readProfileStore=(environment)=>{const directory=profileDirectory(environment);if(directory===undefined){return{profiles:{}}}const file=path.join(directory,"profiles.json");if(!existsSync(file)){return{profiles:{}}}try{return decodeProfileStore(readFileSync(file,"utf-8"))}catch{throw new BackendManagementConfigurationError({message:`CLI Profile file ${file} is invalid; fix or remove it, then run ci login`})}};var writeProfileStore=(environment,store)=>{const directory=profileDirectory(environment);if(directory===undefined){throw new BackendManagementConfigurationError({message:"Cannot locate the CLI configuration directory; set XDG_CONFIG_HOME or HOME"})}mkdirSync(directory,{mode:448,recursive:true});chmodSync(directory,448);const file=path.join(directory,"profiles.json");const temporary=`${file}.${process.pid}.tmp`;writeFileSync(temporary,`${encodeProfileStore(store)}
244
+ `);try{data=JSON.parse(rawData);parsedJson=true}catch{data=rawData}}if(parsedJson){if(responseValidator){await responseValidator(data)}if(responseTransformer){data=await responseTransformer(data)}}onSseEvent?.({data,event:eventName,id:lastEventId,retry:retryDelay});if(dataLines.length){yield data}}}}finally{signal.removeEventListener("abort",abortHandler);reader.releaseLock()}break}catch(error){onSseError?.(error);if(sseMaxRetryAttempts!==undefined&&attempt>=sseMaxRetryAttempts){break}const backoff=Math.min(retryDelay*2**(attempt-1),sseMaxRetryDelay??30000);await sleep(backoff)}}};const stream=createStream();return{stream}}var separatorArrayExplode=(style)=>{switch(style){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}};var separatorArrayNoExplode=(style)=>{switch(style){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}};var separatorObjectExplode=(style)=>{switch(style){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}};var serializeArrayParam=({allowReserved,explode,name,style,value})=>{if(!explode){const joinedValues=(allowReserved?value:value.map((v)=>encodeURIComponent(v))).join(separatorArrayNoExplode(style));switch(style){case"label":return`.${joinedValues}`;case"matrix":return`;${name}=${joinedValues}`;case"simple":return joinedValues;default:return`${name}=${joinedValues}`}}const separator=separatorArrayExplode(style);const joinedValues=value.map((v)=>{if(style==="label"||style==="simple"){return allowReserved?v:encodeURIComponent(v)}return serializePrimitiveParam({allowReserved,name,value:v})}).join(separator);return style==="label"||style==="matrix"?separator+joinedValues:joinedValues};var serializePrimitiveParam=({allowReserved,name,value})=>{if(value===undefined||value===null){return""}if(typeof value==="object"){throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.")}return`${name}=${allowReserved?value:encodeURIComponent(value)}`};var serializeObjectParam=({allowReserved,explode,name,style,value,valueOnly})=>{if(value instanceof Date){return valueOnly?value.toISOString():`${name}=${value.toISOString()}`}if(style!=="deepObject"&&!explode){let values=[];Object.entries(value).forEach(([key,v])=>{values=[...values,key,allowReserved?v:encodeURIComponent(v)]});const joinedValues=values.join(",");switch(style){case"form":return`${name}=${joinedValues}`;case"label":return`.${joinedValues}`;case"matrix":return`;${name}=${joinedValues}`;default:return joinedValues}}const separator=separatorObjectExplode(style);const joinedValues=Object.entries(value).map(([key,v])=>serializePrimitiveParam({allowReserved,name:style==="deepObject"?`${name}[${key}]`:key,value:v})).join(separator);return style==="label"||style==="matrix"?separator+joinedValues:joinedValues};var PATH_PARAM_RE=/\{[^{}]+\}/g;var defaultPathSerializer=({path,url:_url})=>{let url=_url;const matches=_url.match(PATH_PARAM_RE);if(matches){for(const match of matches){let explode=false;let name=match.substring(1,match.length-1);let style="simple";if(name.endsWith("*")){explode=true;name=name.substring(0,name.length-1)}if(name.startsWith(".")){name=name.substring(1);style="label"}else if(name.startsWith(";")){name=name.substring(1);style="matrix"}const value=path[name];if(value===undefined||value===null){continue}if(Array.isArray(value)){url=url.replace(match,serializeArrayParam({explode,name,style,value}));continue}if(typeof value==="object"){url=url.replace(match,serializeObjectParam({explode,name,style,value,valueOnly:true}));continue}if(style==="matrix"){url=url.replace(match,`;${serializePrimitiveParam({name,value})}`);continue}const replaceValue=encodeURIComponent(style==="label"?`.${value}`:value);url=url.replace(match,replaceValue)}}return url};var getUrl=({baseUrl,path,query,querySerializer,url:_url})=>{const pathUrl=_url.startsWith("/")?_url:`/${_url}`;let url=(baseUrl??"")+pathUrl;if(path){url=defaultPathSerializer({path,url})}let search=query?querySerializer(query):"";if(search.startsWith("?")){search=search.substring(1)}if(search){url+=`?${search}`}return url};function getValidRequestBody(options){const hasBody=options.body!==undefined;const isSerializedBody=hasBody&&options.bodySerializer;if(isSerializedBody){if("serializedBody"in options){const hasSerializedBody=options.serializedBody!==undefined&&options.serializedBody!=="";return hasSerializedBody?options.serializedBody:null}return options.body!==""?options.body:null}if(hasBody){return options.body}return}var getAuthToken=async(auth,callback)=>{const token=typeof callback==="function"?await callback(auth):callback;if(!token){return}if(auth.scheme==="bearer"){return`Bearer ${token}`}if(auth.scheme==="basic"){return`Basic ${btoa(token)}`}return token};var createQuerySerializer=({parameters={},...args}={})=>{const querySerializer=(queryParams)=>{const search=[];if(queryParams&&typeof queryParams==="object"){for(const name in queryParams){const value=queryParams[name];if(value===undefined||value===null){continue}const options=parameters[name]||args;if(Array.isArray(value)){const serializedArray=serializeArrayParam({allowReserved:options.allowReserved,explode:true,name,style:"form",value,...options.array});if(serializedArray)search.push(serializedArray)}else if(typeof value==="object"){const serializedObject=serializeObjectParam({allowReserved:options.allowReserved,explode:true,name,style:"deepObject",value,...options.object});if(serializedObject)search.push(serializedObject)}else{const serializedPrimitive=serializePrimitiveParam({allowReserved:options.allowReserved,name,value});if(serializedPrimitive)search.push(serializedPrimitive)}}}return search.join("&")};return querySerializer};var getParseAs=(contentType)=>{if(!contentType){return"stream"}const cleanContent=contentType.split(";")[0]?.trim();if(!cleanContent){return}if(cleanContent.startsWith("application/json")||cleanContent.endsWith("+json")){return"json"}if(cleanContent==="multipart/form-data"){return"formData"}if(["application/","audio/","image/","video/"].some((type)=>cleanContent.startsWith(type))){return"blob"}if(cleanContent.startsWith("text/")){return"text"}return};var checkForExistence=(options,name)=>{if(!name){return false}if(options.headers.has(name)||options.query?.[name]||options.headers.get("Cookie")?.includes(`${name}=`)){return true}return false};var setAuthParams=async({security,...options})=>{for(const auth of security){if(checkForExistence(options,auth.name)){continue}const token=await getAuthToken(auth,options.auth);if(!token){continue}const name=auth.name??"Authorization";switch(auth.in){case"query":if(!options.query){options.query={}}options.query[name]=token;break;case"cookie":options.headers.append("Cookie",`${name}=${token}`);break;case"header":default:options.headers.set(name,token);break}}};var buildUrl=(options)=>getUrl({baseUrl:options.baseUrl,path:options.path,query:options.query,querySerializer:typeof options.querySerializer==="function"?options.querySerializer:createQuerySerializer(options.querySerializer),url:options.url});var mergeConfigs=(a,b)=>{const config={...a,...b};if(config.baseUrl?.endsWith("/")){config.baseUrl=config.baseUrl.substring(0,config.baseUrl.length-1)}config.headers=mergeHeaders(a.headers,b.headers);return config};var headersEntries=(headers)=>{const entries=[];headers.forEach((value,key)=>{entries.push([key,value])});return entries};var mergeHeaders=(...headers)=>{const mergedHeaders=new Headers;for(const header of headers){if(!header){continue}const iterator=header instanceof Headers?headersEntries(header):Object.entries(header);for(const[key,value]of iterator){if(value===null){mergedHeaders.delete(key)}else if(Array.isArray(value)){for(const v of value){mergedHeaders.append(key,v)}}else if(value!==undefined){mergedHeaders.set(key,typeof value==="object"?JSON.stringify(value):value)}}}return mergedHeaders};class Interceptors{fns=[];clear(){this.fns=[]}eject(id){const index=this.getInterceptorIndex(id);if(this.fns[index]){this.fns[index]=null}}exists(id){const index=this.getInterceptorIndex(id);return Boolean(this.fns[index])}getInterceptorIndex(id){if(typeof id==="number"){return this.fns[id]?id:-1}return this.fns.indexOf(id)}update(id,fn){const index=this.getInterceptorIndex(id);if(this.fns[index]){this.fns[index]=fn;return id}return false}use(fn){this.fns.push(fn);return this.fns.length-1}}var createInterceptors=()=>({error:new Interceptors,request:new Interceptors,response:new Interceptors});var defaultQuerySerializer=createQuerySerializer({allowReserved:false,array:{explode:true,style:"form"},object:{explode:true,style:"deepObject"}});var defaultHeaders={"Content-Type":"application/json"};var createConfig=(override={})=>({...jsonBodySerializer,headers:defaultHeaders,parseAs:"auto",querySerializer:defaultQuerySerializer,...override});var createClient=(config={})=>{let _config=mergeConfigs(createConfig(),config);const getConfig=()=>({..._config});const setConfig=(config)=>{_config=mergeConfigs(_config,config);return getConfig()};const interceptors=createInterceptors();const beforeRequest=async(options)=>{const opts={..._config,...options,fetch:options.fetch??_config.fetch??globalThis.fetch,headers:mergeHeaders(_config.headers,options.headers),serializedBody:undefined};if(opts.security){await setAuthParams({...opts,security:opts.security})}if(opts.requestValidator){await opts.requestValidator(opts)}if(opts.body!==undefined&&opts.bodySerializer){opts.serializedBody=opts.bodySerializer(opts.body)}if(opts.body===undefined||opts.serializedBody===""){opts.headers.delete("Content-Type")}const resolvedOpts=opts;const url=buildUrl(resolvedOpts);return{opts:resolvedOpts,url}};const request=async(options)=>{const{opts,url}=await beforeRequest(options);const requestInit={redirect:"follow",...opts,body:getValidRequestBody(opts)};let request=new Request(url,requestInit);for(const fn of interceptors.request.fns){if(fn){request=await fn(request,opts)}}const _fetch=opts.fetch;let response;try{response=await _fetch(request)}catch(error){let finalError=error;for(const fn of interceptors.error.fns){if(fn){finalError=await fn(error,undefined,request,opts)}}finalError=finalError||{};if(opts.throwOnError){throw finalError}return opts.responseStyle==="data"?undefined:{error:finalError,request,response:undefined}}for(const fn of interceptors.response.fns){if(fn){response=await fn(response,request,opts)}}const result={request,response};if(response.ok){const parseAs=(opts.parseAs==="auto"?getParseAs(response.headers.get("Content-Type")):opts.parseAs)??"json";if(response.status===204||response.headers.get("Content-Length")==="0"){let emptyData;switch(parseAs){case"arrayBuffer":case"blob":case"text":emptyData=await response[parseAs]();break;case"formData":emptyData=new FormData;break;case"stream":emptyData=response.body;break;case"json":default:emptyData={};break}return opts.responseStyle==="data"?emptyData:{data:emptyData,...result}}let data;switch(parseAs){case"arrayBuffer":case"blob":case"formData":case"text":data=await response[parseAs]();break;case"json":{const text=await response.text();data=text?JSON.parse(text):{};break}case"stream":return opts.responseStyle==="data"?response.body:{data:response.body,...result}}if(parseAs==="json"){if(opts.responseValidator){await opts.responseValidator(data)}if(opts.responseTransformer){data=await opts.responseTransformer(data)}}return opts.responseStyle==="data"?data:{data,...result}}const textError=await response.text();let jsonError;try{jsonError=JSON.parse(textError)}catch{}const error=jsonError??textError;let finalError=error;for(const fn of interceptors.error.fns){if(fn){finalError=await fn(error,response,request,opts)}}finalError=finalError||{};if(opts.throwOnError){throw finalError}return opts.responseStyle==="data"?undefined:{error:finalError,...result}};const makeMethodFn=(method)=>(options)=>request({...options,method});const makeSseFn=(method)=>async(options)=>{const{opts,url}=await beforeRequest(options);return createSseClient({...opts,body:opts.body,headers:opts.headers,method,onRequest:async(url,init)=>{let request=new Request(url,init);for(const fn of interceptors.request.fns){if(fn){request=await fn(request,opts)}}return request},serializedBody:getValidRequestBody(opts),url})};const _buildUrl=(options)=>buildUrl({..._config,...options});return{buildUrl:_buildUrl,connect:makeMethodFn("CONNECT"),delete:makeMethodFn("DELETE"),get:makeMethodFn("GET"),getConfig,head:makeMethodFn("HEAD"),interceptors,options:makeMethodFn("OPTIONS"),patch:makeMethodFn("PATCH"),post:makeMethodFn("POST"),put:makeMethodFn("PUT"),request,setConfig,sse:{connect:makeSseFn("CONNECT"),delete:makeSseFn("DELETE"),get:makeSseFn("GET"),head:makeSseFn("HEAD"),options:makeSseFn("OPTIONS"),patch:makeSseFn("PATCH"),post:makeSseFn("POST"),put:makeSseFn("PUT"),trace:makeSseFn("TRACE")},trace:makeMethodFn("TRACE")}};var client=createClient(createConfig());var authLogout=(options)=>(options?.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/auth/logout",...options});var authMe=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/auth/me",...options});var authMeOrganizations=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/auth/me/organizations",...options});var authStartCliDevice=(options)=>(options.client??client).post({url:"/auth/cli/device",...options,headers:{"Content-Type":"application/json",...options.headers}});var authExchangeCliToken=(options)=>(options.client??client).post({url:"/auth/cli/token",...options,headers:{"Content-Type":"application/json",...options.headers}});var aiModelPresetsList=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/ai/model-presets",...options});var aiModelPresetsDefault=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/ai/model-presets/default",...options});var developmentSessionsCreate=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions",...options,headers:{"Content-Type":"application/json",...options.headers}});var developmentSessionsTerminate=(options)=>(options.client??client).delete({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions/{sessionId}",...options});var developmentSessionsHeartbeat=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions/{sessionId}/heartbeat",...options});var developmentSessionsUpdateLocalManifest=(options)=>(options.client??client).put({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions/{sessionId}/local-manifest",...options,headers:{"Content-Type":"application/json",...options.headers}});var hostedExtensionDiagnosticsReadTrace=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/hosted-extension-diagnostics/{diagnosticId}/trace",...options});var packageOperationsSnapshot=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-operations/{operationId}",...options});var packageOperationsEvents=(options)=>(options.client??client).sse.get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-operations/{operationId}/events",...options});var packageOperationsContinueOperation=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-operations/{operationId}/continuations",...options});var packageReleasesUpdateInstallation=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-installations/update",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesRollbackInstallation=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-installations/rollback",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesPromote=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-releases/promote",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesPublish=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-releases/publish",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesLookupPublished=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-releases/lookup",...options,headers:{"Content-Type":"application/json",...options.headers}});var extensionPackagesListInstalled=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/installed",...options});var extensionPackagesListReleases=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/{fqn}/releases",...options});var extensionPackagesInstall=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/{fqn}/install",...options,headers:{"Content-Type":"application/json",...options.headers}});var extensionPackagesSync=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/{fqn}/sync",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationsSearch=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organizations/search",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationSetupCatalog=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/setup/catalog",...options});var organizationSetupSetup=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/setup",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferMappings=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/mappings",...options});var organizationTransferValidateConfiguration=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/configuration/validate",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferPreview=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/preview",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferExports=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/exports",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferImports=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/imports",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferRollbacks=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/rollbacks",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferRuns=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs",...options});var organizationTransferRun=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}",...options});var organizationTransferCancel=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/cancel",...options});var organizationTransferResume=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/resume",...options});var organizationTransferPurge=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/purge",...options});var organizationTransferEvents=(options)=>(options.client??client).sse.get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/events",...options});var organizationTransferReport=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/report",...options});var organizationTransferUploadUrls=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/archives/{archiveId}/upload-urls",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferDownloadUrls=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/archives/{archiveId}/download-urls",...options});var organizationCredentialsUpsert=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/upsert",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsList=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/list",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsGet=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/get",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsRotate=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/rotate",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsRevoke=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/revoke",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationServicePrincipalsList=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/service-principals",...options});var organizationExternalAppsList=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps",...options});var organizationExternalAppsEnroll=(options)=>(options.client??client).put({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/by-fqn/{fqn}",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationExternalAppsGet=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}",...options});var organizationExternalAppsUpdate=(options)=>(options.client??client).put({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationExternalAppsDisable=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}/disable",...options});var organizationExternalAppsRotateCredential=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}/credential/rotate",...options});var normalizedBackendUrl=(value)=>value.replace(/\/$/u,"");var makeBackendManagementClient=(config)=>createClient({baseUrl:normalizedBackendUrl(config.backendUrl),fetch:config.fetch,headers:config.token===undefined?{}:{authorization:`Bearer ${config.token}`}});function makeValue(value){return{_tag:"Value",value}}function makeRecord(keys,value){return{_tag:"Record",keys,value}}function makeArray(length,value){return{_tag:"Array",length,value}}var ConfigProvider=Reference("effect/ConfigProvider",{defaultValue:()=>fromEnv()});var Proto3={...PipeInspectableProto,toJSON(){return{_id:"ConfigProvider"}}};var identityPath=(path)=>path;function makeProvider(load,mapInput){const self=Object.create(Proto3);self.load=load;self.mapInput=mapInput;return self}function makeSource(get,transform){return makeProvider((path)=>get(transform(path)),(f)=>makeSource(get,(path)=>f(transform(path))))}function make17(get){return makeSource(get,identityPath)}var layer6=(self)=>isEffect2(self)?effect(ConfigProvider)(self):succeed5(ConfigProvider)(self);function fromUnknown(root,options){const preserveEmptyStrings=options?.preserveEmptyStrings===true;return make17((path)=>succeed6(nodeAtJson(root,path,preserveEmptyStrings)))}function nodeAtJson(root,path,preserveEmptyStrings){let cur=root;for(const seg of path){if(cur===null||cur===undefined)return;if(Array.isArray(cur)){if(typeof seg!=="number"||!Number.isInteger(seg)||seg<0||seg>=cur.length)return;cur=cur[seg];continue}if(isObject(cur)){if(typeof seg!=="string")return;if(!Object.hasOwn(cur,seg))return;cur=cur[seg];continue}return}return describeUnknown(cur,preserveEmptyStrings)}function describeUnknown(u,preserveEmptyStrings){if(u===undefined||u===null)return;if(typeof u==="string")return stringNode(u,preserveEmptyStrings);if(typeof u==="number"||typeof u==="boolean"||typeof u==="bigint"){return makeValue(String(u))}if(Array.isArray(u))return makeArray(u.length);if(isObject(u)){return makeRecord(new Set(Object.keys(u)))}return makeValue(format(u))}function stringNode(value,preserveEmptyStrings){const normalized=emptyStringAsMissing(value,preserveEmptyStrings);return normalized===undefined?undefined:makeValue(normalized)}function emptyStringAsMissing(value,preserveEmptyStrings){return value===""&&!preserveEmptyStrings?undefined:value}function fromEnvRecord(env,options){const preserveEmptyStrings=options?.preserveEmptyStrings===true;const trie=buildEnvTrie(env);return make17((path)=>succeed6(nodeAtEnv(trie,env,path,preserveEmptyStrings)))}function fromEnv(options){const env=options?.env??{...globalThis.process?.env,...import.meta?.env};return fromEnvRecord(env,{preserveEmptyStrings:options?.preserveEmptyStrings})}function buildEnvTrie(env){const trie={};for(const[name,value]of Object.entries(env)){if(value===undefined)continue;const segments=name.split("_");let node=trie;for(const seg of segments){const children=node.children??=Object.create(null);node=children[seg]??={}}}return trie}function nodeAtEnv(trie,env,path,preserveEmptyStrings){const key=path.map(String).join("_");const leafValue=emptyStringAsMissing(Object.hasOwn(env,key)?env[key]:undefined,preserveEmptyStrings);const trieNode=trieNodeAt(trie,path);const children=trieNode?.children?Object.keys(trieNode.children):[];if(children.length===0){return leafValue===undefined?undefined:makeValue(leafValue)}const allNumeric=children.every(isCanonicalArrayIndex);if(allNumeric){const length=Math.max(...children.map((k)=>parseInt(k,10)))+1;return makeArray(length,leafValue)}return makeRecord(new Set(children),leafValue)}function trieNodeAt(root,path){if(path.length===0)return root;let node=root;for(const seg of path){node=node?.children?.[String(seg)];if(!node)return}return node}var TypeId20="~effect/Config";class ConfigError{_tag="ConfigError";name="ConfigError";cause;constructor(cause){this.cause=cause}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}}var Proto4={...Prototype2({label:"Config",evaluate(fiber){return this.parse(fiber.getRef(ConfigProvider))}}),[TypeId20]:TypeId20,toJSON(){return{_id:"Config"}}};function make18(evaluator){const self=Object.create(Proto4);self.evaluator=evaluator;self.parse=(provider)=>flatMapEager2(evaluator(provider,[]),fromResult2);return self}var isSourceError=(u)=>isTagged(u,"SourceError");var cursorToString=()=>"<configuration>";var mapReasons=(f)=>(self)=>catchCause2(self,(cause)=>failCause3(fromReasons(cause.reasons.map(f))));var loadCursor=(provider,path)=>provider.load(path).pipe(mapReasons((reason)=>isFailReason2(reason)?makeDieReason(reason.error).annotate(reasonAnnotations2(reason)):reason),mapEager2((node)=>({provider,path,node,toString:cursorToString})));var loadChildCursor=(cursor,segment)=>loadCursor(cursor.provider,[...cursor.path,segment]);var decodeFromCursor=(ast,decode)=>decodeTo(unknown,ast,new Transformation(transformEffect((input)=>decode(input)),passthrough()));var isScalarInput=(ast)=>{switch(ast._tag){case"Union":return ast.types.every(isScalarInput);case"Objects":case"Arrays":case"Suspend":return false;default:return true}};var hasProviderInput=(ast,node)=>{switch(ast._tag){case"Objects":return node?._tag==="Record";case"Arrays":return node?._tag==="Array";case"Union":return ast.types.some((ast)=>hasProviderInput(ast,node));case"Suspend":return hasProviderInput(ast.thunk(),node);default:return node?.value!==undefined}};var toConfigCursorAST=memoize((root)=>{const seen=new WeakSet;const recur=applyToSelfOrLastLinkEncoding((ast)=>{seen.add(ast);switch(ast._tag){case"Objects":{const materialize=fnUntraced2(function*(cursor){if(cursor.node?._tag!=="Record"){return}const node=cursor.node;const keys=new Set;for(const property of ast.propertySignatures){if(typeof property.name==="string")keys.add(property.name)}if(ast.indexSignatures.length>0){const input={};for(const key of node.keys){assignProperty(input,key,undefined)}for(const is of ast.indexSignatures){for(const key of getIndexSignatureKeys(input,is.parameter)){if(typeof key==="string")keys.add(key)}}}const out={};for(const key of keys){const child=yield*loadChildCursor(cursor,key);if(child.node!==undefined)assignProperty(out,key,child)}return out});return decodeFromCursor(ast.recur(recur,(ast)=>ast),materialize)}case"Arrays":{const materialize=fnUntraced2(function*(cursor){if(cursor.node?._tag!=="Array"){return}const out=[];for(let i=0;i<cursor.node.length;i++){out.push(yield*loadChildCursor(cursor,i))}return out});return decodeFromCursor(ast.recur(recur),materialize)}case"Union":for(const member of ast.types){recur(member)}if(!isScalarInput(ast))return ast.recur(recur);break;case"Suspend":{const target=ast.thunk();if(!seen.has(target))recur(target);return ast.recur(recur)}case"Declaration":case"Any":throw new globalThis.Error("Config.schema does not support opaque StringTree encodings",{cause:ast})}return decodeFromCursor(ast,(cursor)=>succeed6(cursor.node?.value))});return recur(root)});function schema(codec,path){const codecStringTree=toCodecStringTree2(codec);const encodedAst=toEncoded(codecStringTree.ast);const decodeCursor=decodeUnknownEffect(make16(toConfigCursorAST(codecStringTree.ast)));const localPath=typeof path==="string"?[path]:path??[];return make18((provider,pathPrefix)=>{const fullPath=[...pathPrefix,...localPath];return loadCursor(provider,fullPath).pipe(flatMapEager2((cursor)=>decodeCursor(cursor).pipe(mapEager2(succeed2),catchEager2((issue)=>{const error=new ConfigError(new SchemaError(fullPath.length>0?new Pointer(fullPath,issue):issue));return hasProviderInput(encodedAst,cursor.node)?fail6(error):succeed6(fail2(error))}))),mapReasons((reason)=>isDieReason2(reason)&&isSourceError(reason.defect)?makeFailReason(new ConfigError(reason.defect)).annotate(reasonAnnotations2(reason)):reason))})}class BackendManagementConfigurationError extends TaggedError3()("BackendManagementConfigurationError",{message:String5}){}var tryConfiguration=(evaluate)=>try_2({catch:(cause)=>is2(BackendManagementConfigurationError)(cause)?cause:new BackendManagementConfigurationError({message:cause instanceof Error?cause.message:"CLI configuration step failed"}),try:evaluate});import{chmodSync,existsSync,mkdirSync,readFileSync,renameSync,writeFileSync}from"fs";import path from"path";var ProfileSchema=Struct({apiOrigin:String5,currentOrganizationId:optionalKey2(String5),session:optionalKey2(Struct({expiresAt:optionalKey2(String5),token:String5}))});var ProfileStoreSchema=Struct({current:optionalKey2(String5),profiles:Record(String5,ProfileSchema)});var profileStoreJson=fromJsonString2(ProfileStoreSchema);var decodeProfileStore=decodeUnknownSync(profileStoreJson);var encodeProfileStore=encodeSync(profileStoreJson);var nonEmpty=(value)=>value===""?undefined:value;var profileDirectory=(environment)=>{const configHome=nonEmpty(environment.XDG_CONFIG_HOME);if(configHome!==undefined){return path.join(configHome,"ci")}const home=nonEmpty(environment.HOME);return home===undefined?undefined:path.join(home,".config","ci")};var profileName=(apiOrigin)=>new URL(apiOrigin).host;var readProfileStore=(environment)=>{const directory=profileDirectory(environment);if(directory===undefined){return{profiles:{}}}const file=path.join(directory,"profiles.json");if(!existsSync(file)){return{profiles:{}}}try{return decodeProfileStore(readFileSync(file,"utf-8"))}catch{throw new BackendManagementConfigurationError({message:`CLI Profile file ${file} is invalid; fix or remove it, then run ci login`})}};var writeProfileStore=(environment,store)=>{const directory=profileDirectory(environment);if(directory===undefined){throw new BackendManagementConfigurationError({message:"Cannot locate the CLI configuration directory; set XDG_CONFIG_HOME or HOME"})}mkdirSync(directory,{mode:448,recursive:true});chmodSync(directory,448);const file=path.join(directory,"profiles.json");const temporary=`${file}.${process.pid}.tmp`;writeFileSync(temporary,`${encodeProfileStore(store)}
245
245
  `,{mode:384});chmodSync(temporary,384);renameSync(temporary,file)};var updateProfile=(environment,name,update)=>{const store=readProfileStore(environment);const latest=store.profiles[name];const next=latest===undefined?undefined:update(latest);if(next!==undefined){writeProfileStore(environment,{...store,profiles:{...store.profiles,[name]:next}})}return next};var configurationError=(message)=>new BackendManagementConfigurationError({message});var nonEmpty2=(value)=>value===undefined||value.trim()===""?undefined:value;var optionValue=(args,name)=>{const index=args.indexOf(`--${name}`);const value=index===-1?undefined:args[index+1];return value===undefined||value.startsWith("--")?undefined:value};var sameOrigin=(left,right)=>{try{return new URL(left).origin===new URL(right).origin}catch{return false}};var storedProfile=(store,name)=>name!==undefined&&Object.hasOwn(store.profiles,name)?store.profiles[name]:undefined;var tenantProfileName=(apiOrigin)=>{try{return profileName(apiOrigin)}catch{return}};var selectProfile=(store,requestedName,explicitOrigin)=>{if(requestedName!==undefined){const profile=storedProfile(store,requestedName);if(profile===undefined){throw configurationError(`CLI Profile ${requestedName} does not exist; run ci login or select another --profile`)}if(explicitOrigin!==undefined&&!sameOrigin(profile.apiOrigin,explicitOrigin)){throw configurationError(`CLI Profile ${requestedName} belongs to ${profile.apiOrigin}, not ${explicitOrigin}`)}return{name:requestedName,profile}}const name=explicitOrigin===undefined?store.current:tenantProfileName(explicitOrigin);const profile=storedProfile(store,name);if(name===undefined||profile===undefined||explicitOrigin!==undefined&&!sameOrigin(profile.apiOrigin,explicitOrigin)){return}return{name,profile}};var sessionToken=(selected)=>{const session=selected?.profile.session;if(selected===undefined||session===undefined){return}if(session.expiresAt!==undefined&&Date.parse(session.expiresAt)<=Date.now()){throw configurationError(`The CLI Session of Profile ${selected.name} expired; run ci login or set CI_MANAGEMENT_TOKEN`)}return session.token};var isOrganizationApiKey=(token)=>token.startsWith("dpk_");var resolveTarget=(input,organizationRequired)=>{const{args,environment}=input;const explicitOrigin=nonEmpty2(optionValue(args,"backend-url"))??nonEmpty2(environment.CI_BACKEND_URL);const environmentToken=nonEmpty2(environment.CI_MANAGEMENT_TOKEN);const explicitOrganization=nonEmpty2(optionValue(args,"organization"));const apiKey=environmentToken!==undefined&&isOrganizationApiKey(environmentToken);const profileNeeded=explicitOrigin===undefined||environmentToken===undefined||organizationRequired&&explicitOrganization===undefined&&!apiKey;const selected=profileNeeded?selectProfile(readProfileStore(environment),nonEmpty2(optionValue(args,"profile"))??nonEmpty2(environment.CI_PROFILE),explicitOrigin):undefined;const apiOrigin=explicitOrigin??selected?.profile.apiOrigin;if(apiOrigin===undefined){throw configurationError("Missing backend URL: pass --backend-url, set CI_BACKEND_URL, or run ci login")}const token=environmentToken??sessionToken(selected);if(token===undefined){throw configurationError("Missing credential: run ci login or set CI_MANAGEMENT_TOKEN")}return{apiOrigin,credentialSource:environmentToken===undefined?"cli-session":"management-token",organizationId:explicitOrganization??(apiKey?undefined:selected?.profile.currentOrganizationId),profile:selected?.name,token}};var resolveBackendManagementTarget=(input)=>resolveTarget(input,input.organizationLookup===true);var missingOrganizationMessage="Missing Organization: pass --organization or run ci orgs use <organization-id>";var selectedProfile=(input)=>{const store=readProfileStore(input.environment);const selected=selectProfile(store,nonEmpty2(optionValue(input.args,"profile"))??nonEmpty2(input.environment.CI_PROFILE),nonEmpty2(optionValue(input.args,"backend-url"))??nonEmpty2(input.environment.CI_BACKEND_URL));return selected===undefined?undefined:{...selected,store}};var resolveOrganizationTarget=(input)=>{const target=resolveTarget(input,true);if(target.organizationId===undefined){throw configurationError(isOrganizationApiKey(target.token)?"Missing Organization: pass --organization with the Organization of the CI_MANAGEMENT_TOKEN API key":missingOrganizationMessage)}return{...target,organizationId:target.organizationId}};var apiKeyOrganizationMismatch=(input)=>isOrganizationApiKey(input.token)&&input.apiKey!==undefined&&input.apiKey.organizationId!==input.organizationId?configurationError(`Organization API key ${input.apiKey.name} belongs to Organization ${input.apiKey.organizationId} and cannot act for Organization ${input.organizationId}; pass --organization ${input.apiKey.organizationId} or use a credential for ${input.organizationId}`):undefined;var backendManagementClientFromCli=(input)=>{const target=resolveBackendManagementTarget(input);return makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:input.fetch??globalThis.fetch,token:target.token})};var deploymentManagementClients=fn2("BackendManagement.deploymentClients")(function*deploymentManagementClients(input){const publisher=yield*schema(Redacted(String5.check(isMinLength(1))),"CI_PUBLISHER_TOKEN").pipe(provide3(layer6(fromUnknown(input.environment))));return{organization:makeBackendManagementClient({backendUrl:input.target.apiOrigin,fetch:input.fetch,token:input.target.token}),publisher:makeBackendManagementClient({backendUrl:input.target.apiOrigin,fetch:input.fetch,token:value2(publisher)})}});class DevelopmentSessionRejectedError extends TaggedError3()("DevelopmentSessionRejectedError",{reason:Literals(["session_not_found","session_owned"])}){}var hasWireTag=(cause,tag)=>is2(TaggedStruct(tag,{}))(cause);var createDevelopmentSession=async(client,input)=>{try{const result=await developmentSessionsCreate({body:{hostOrigins:[...input.hostOrigins],packageManifest:{fqn:input.packageFqn},protocolVersion:"v1"},client,throwOnError:true});return result.data}catch(error){throw hasWireTag(error,"Conflict")?new DevelopmentSessionRejectedError({reason:"session_owned"}):error}};var updateDevelopmentSessionLocalManifest=flow((client,input)=>tryPromise2(()=>developmentSessionsUpdateLocalManifest({body:{hostedContributions:[...input.hostedContributions]},client,path:{sessionId:input.sessionId},throwOnError:true})).pipe(map5((result)=>result.data),mapError2((cause)=>hasWireTag(cause.cause,"NotFound")?new DevelopmentSessionRejectedError({reason:"session_not_found"}):cause)),runPromise2);var heartbeatDevelopmentSession=flow((client,sessionId)=>tryPromise2(()=>developmentSessionsHeartbeat({client,path:{sessionId},throwOnError:true})).pipe(asVoid2,mapError2((cause)=>hasWireTag(cause.cause,"NotFound")?new DevelopmentSessionRejectedError({reason:"session_not_found"}):cause)),runPromise2);var terminateDevelopmentSession=flow((client,sessionId)=>tryPromise2(()=>developmentSessionsTerminate({client,path:{sessionId},throwOnError:true})).pipe(asVoid2),runPromise2);class ManagementRequestError extends TaggedError3()("ManagementRequestError",{body:optional2(Unknown2),cause:optional2(Unknown2),message:String5,status:Finite}){}var BackendReason=Union2([Struct({message:String5}),Struct({detail:String5}),Struct({error_description:String5}),Struct({error:String5})]);var backendReason=(body)=>{if(!is2(BackendReason)(body)){return}if("message"in body){return body.message}if("detail"in body){return body.detail}return"error_description"in body?body.error_description:body.error};var requestFailure=(label,response,body)=>{if(response.status===401){return new ManagementRequestError({body,message:`${label} failed: the backend rejected the credential; run ci login or check CI_MANAGEMENT_TOKEN`,status:401})}const reason=backendReason(body);return new ManagementRequestError({body,message:`${label} failed (HTTP ${response.status})${reason===undefined?"":`: ${reason}`}`,status:response.status})};var requestTimeout="30 seconds";var withRequestTimeout=(label,subject)=>(effect)=>effect.pipe(timeoutOrElse2({duration:requestTimeout,orElse:()=>fail6(new ManagementRequestError({message:`${label} failed: ${subject} did not respond within ${requestTimeout}`,status:0}))}));var unreachable=(label,cause)=>new ManagementRequestError({cause,message:`${label} failed: could not reach the backend`,status:0});var sendRequest=(label,operation,options)=>tryPromise2({catch:(cause)=>unreachable(label,cause),try:async(signal)=>await operation({...options,signal})}).pipe(withRequestTimeout(label,"the backend"),flatMap4((result)=>{const{response}=result;return response===undefined?fail6(unreachable(label,result.error)):succeed6({response,result})}));var managementData=(label,operation,options)=>flatMap4(sendRequest(label,operation,options),({response,result})=>response.ok&&result.data!==undefined?succeed6(result.data):fail6(requestFailure(label,response,result.error)));var managementOk=(label,operation,options)=>flatMap4(sendRequest(label,operation,options),({response,result})=>response.ok?void_3:fail6(requestFailure(label,response,result.error)));var TenantDiscoverySchema=Struct({api_base_url:String5,dashboard_url:String5,issuer:String5,jwks_uri:String5});var JwksSchema=Struct({keys:ArraySchema(Unknown2)});var SigningKeyUnavailable=Struct({error:Literal2("signing_key_unavailable")});var send=(fetch2,label,url)=>tryPromise2({catch:(cause)=>new ManagementRequestError({cause,message:`${label} failed: could not reach ${url}`,status:0}),try:async(signal)=>{const response=await fetch2(url,{headers:{accept:"application/json"},signal});return{response,text:await response.text()}}}).pipe(withRequestTimeout(label,url));var notJson=(label,url,response,cause)=>new ManagementRequestError({cause,message:`${label} failed: ${url} did not return JSON (HTTP ${response.status})`,status:response.status});var parseJson2=(text,onFailure)=>try_2({catch:onFailure,try:()=>JSON.parse(text)});var readTenantDiscovery=fn2("BackendManagement.readTenantDiscovery")(function*readTenantDiscovery(fetch2,apiUrl){const origin=yield*try_2({catch:()=>new ManagementRequestError({message:`Invalid API URL ${apiUrl}`,status:0}),try:()=>new URL(apiUrl).origin});const label=`Tenant discovery at ${new URL(origin).host}`;const notApiUrl=(status,cause)=>new ManagementRequestError({cause,message:`${label} failed: ${apiUrl} is not a CI API URL; copy the login command from the dashboard: Organization settings \u2192 CLI`,status});const{response,text}=yield*send(fetch2,label,`${origin}/.well-known/ci-configuration`);if(response.status===404){return yield*notApiUrl(404)}const body=yield*parseJson2(text,(cause)=>response.ok?notApiUrl(response.status,cause):notJson(label,apiUrl,response,cause));if(!response.ok){return yield*requestFailure(label,response,body)}const document=yield*decodeUnknownEffect2(TenantDiscoverySchema)(body).pipe(mapError2((cause)=>notApiUrl(response.status,cause)));return{apiBaseUrl:document.api_base_url,dashboardUrl:document.dashboard_url,issuer:document.issuer,jwksUri:document.jwks_uri}});var readSigningKeyCount=fn2("BackendManagement.readSigningKeyCount")(function*readSigningKeyCount(fetch2,jwksUri){const label="JWKS read";const{response,text}=yield*send(fetch2,label,jwksUri);const body=yield*parseJson2(text,(cause)=>notJson(label,jwksUri,response,cause));if(response.status===503&&is2(SigningKeyUnavailable)(body)){return yield*new ManagementRequestError({body,message:"JWKS is unavailable: the backend has no External App signing key (set APP_EXTERNAL_APP_JWT_PRIVATE_JWK)",status:503})}if(!response.ok||!is2(JwksSchema)(body)){return yield*requestFailure(label,response,body)}return body.keys.length});var readIdentity=(client)=>managementData("Identity read",authMe,{client});var resolveManagementContext=fn2("BackendManagement.resolveContext")(function*resolveManagementContext(input){const target=yield*try_2({catch:(cause)=>is2(BackendManagementConfigurationError)(cause)?cause:new BackendManagementConfigurationError({message:"Could not resolve the backend credential"}),try:()=>resolveBackendManagementTarget({args:input.args,environment:input.environment,organizationLookup:true})});const client=makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:input.fetch,token:target.token});const organizationId=target.organizationId===undefined&&isOrganizationApiKey(target.token)?(yield*readIdentity(client)).organizationId:target.organizationId;return{client,organizationId,target}});var resolveOrganizationContext=(input)=>flatMap4(resolveManagementContext(input),(context)=>{const{organizationId}=context;return organizationId===undefined?fail6(new BackendManagementConfigurationError({message:missingOrganizationMessage})):succeed6({...context,organizationId})});var explainOrganizationForbidden=(context,organizationId)=>(error)=>error.status===403&&isOrganizationApiKey(context.target.token)?readIdentity(context.client).pipe(map5((identity)=>apiKeyOrganizationMismatch({apiKey:identity.apiKeyName===undefined||identity.organizationId===undefined?undefined:{name:identity.apiKeyName,organizationId:identity.organizationId},organizationId,token:context.target.token})??error),orElseSucceed2(()=>error),flatMap4(fail6)):fail6(error);class CommandOptionsError extends TaggedError3()("CommandOptionsError",{message:String5}){}var targetOptions=["backend-url","organization","profile"];var parseCommandOptions=(args,spec)=>{const repeatable=new Set(spec.repeatable);const valueNames=new Set([...spec.values??[],...repeatable]);const switchNames=new Set(spec.switches);const values=new Map;const switches=new Set;const positionals=[];for(let index=0;index<args.length;index+=1){const argument=args[index]??"";if(!argument.startsWith("--")){positionals.push(argument);continue}const name=argument.slice(2);if(switchNames.has(name)){switches.add(name);continue}if(!valueNames.has(name)){throw new CommandOptionsError({message:`Unknown option ${argument}`})}const value=args[index+1];if(value===undefined||value.startsWith("--")||value.trim()===""){throw new CommandOptionsError({message:`Missing value for ${argument}`})}index+=1;const existing=values.get(name);if(existing!==undefined&&!repeatable.has(name)){throw new CommandOptionsError({message:`Duplicate option ${argument}`})}values.set(name,[...existing??[],value])}if(positionals.length>(spec.positionals??0)){throw new CommandOptionsError({message:`Unexpected argument ${positionals[spec.positionals??0]??""}`})}return{positionals,switches,values}};var optionValue2=(options,name)=>options.values.get(name)?.[0];var optionValues=(options,name)=>options.values.get(name)??[];var parseCommandOptionsEffect=(args,spec)=>try_2({catch:(cause)=>is2(CommandOptionsError)(cause)?cause:new CommandOptionsError({message:"Invalid options"}),try:()=>parseCommandOptions(args,spec)});class AppsCommandError extends TaggedError3()("AppsCommandError",{cause:optional2(Unknown2),message:String5}){}var usage="Usage: ci apps list | ci apps get <application-id> | ci apps rotate-secret <application-id> | ci apps disable <application-id> | ci apps enroll ... | ci apps env ... | ci apps redirect-uris ... | ci apps origins ...";var encodeJson=encodeSync(fromJsonString2(Unknown2));var applicationSummary=(application)=>({allowedOrigins:application.allowedOrigins,applicationId:application.id,applicationType:application.applicationType,audience:application.audience,clientId:application.clientId,enabled:application.enabled,fqn:application.fqn,name:application.name,postLogoutRedirectUris:application.postLogoutRedirectUris,primaryRedirectUri:application.primaryRedirectUri,redirectUris:application.redirectUris,scopes:application.scopes});var appsCommandEffect=(args,dependencies)=>gen2(function*appsCommand(){const[command,...rest]=args;const options=yield*parseCommandOptionsEffect(rest,{positionals:command==="list"?0:1,values:targetOptions});const[applicationId]=options.positionals;const applicationCommands=new Set(["disable","get","rotate-secret"]);if(command!=="list"&&(applicationId===undefined||!applicationCommands.has(command??""))){return yield*new AppsCommandError({message:usage})}const context=yield*resolveOrganizationContext({args:rest,environment:dependencies.environment,fetch:dependencies.fetch});const request={client:context.client,headers:{"x-organization-id":context.organizationId}};const operation=(id)=>gen2(function*appsOperation(){if(command==="get"){return applicationSummary(yield*managementData("External App read",organizationExternalAppsGet,{...request,path:{id}}))}if(command==="disable"){return applicationSummary(yield*managementData("External App disable",organizationExternalAppsDisable,{...request,path:{id}}))}const rotated=yield*managementData("Client secret rotation",organizationExternalAppsRotateCredential,{...request,path:{id}});return{applicationId:rotated.application.id,clientId:rotated.application.clientId,clientSecret:rotated.clientSecret}});const explainForbidden=(effect)=>effect.pipe(catchTag2("ManagementRequestError",explainOrganizationForbidden(context,context.organizationId)));const result=applicationId===undefined?yield*explainForbidden(managementData("External App list",organizationExternalAppsList,request).pipe(map5((response)=>response.data.map(applicationSummary)))):yield*explainForbidden(operation(applicationId));return yield*sync2(()=>{dependencies.writeOutput(`${encodeJson(result)}
246
246
  `)})}).pipe(mapError2((cause)=>is2(AppsCommandError)(cause)?cause:new AppsCommandError({cause,message:cause.message})));var check=(name,passed,detail)=>({detail,name,passed});var redirectCheck=(applications,fqn,redirectUris)=>{if(fqn===undefined){const missing=redirectUris.filter((uri)=>!applications.some((application)=>application.enabled&&application.redirectUris.includes(uri)));return missing.length===0?check("redirect-uri",true,`registered: ${redirectUris.join(", ")}`):check("redirect-uri",false,`no enabled External App registers ${missing.join(", ")}`)}const application=applications.find((candidate)=>candidate.fqn===fqn);if(application===undefined){return check("redirect-uri",false,`no External App ${fqn} exists`)}if(!application.enabled){return check("redirect-uri",false,`External App ${fqn} is disabled`)}const expected=redirectUris.length===0?application.redirectUris:redirectUris;const missing=expected.filter((uri)=>!application.redirectUris.includes(uri));return missing.length===0&&expected.length>0?check("redirect-uri",true,`${fqn} registers ${expected.join(", ")}`):check("redirect-uri",false,`${fqn} does not register ${missing.length===0?"any redirect URI":missing.join(", ")}`)};var listApplications=(context)=>managementData("External App list",organizationExternalAppsList,{client:context.client,headers:{"x-organization-id":context.organizationId}}).pipe(map5((response)=>response.data),catchTag2("ManagementRequestError",explainOrganizationForbidden(context,context.organizationId)));var runTenantPreflight=fn2("Preflight.tenant")(function*runTenantPreflight(input){const{context}=input;const{apiOrigin}=context.target;const discovery=yield*result2(readTenantDiscovery(input.fetch,apiOrigin));const keys=yield*result2(readSigningKeyCount(input.fetch,isSuccess2(discovery)?discovery.success.jwksUri:`${apiOrigin.replace(/\/$/u,"")}/oauth/jwks`));const applications=yield*result2(listApplications(context));return{applications:isSuccess2(applications)?applications.success:undefined,checks:[isSuccess2(discovery)?check("discovery",true,`issuer ${discovery.success.issuer}`):check("discovery",false,discovery.failure.message),isFailure2(keys)?check("jwks",false,keys.failure.message):check("jwks",keys.success>0,keys.success>0?`${keys.success} signing key(s) published`:"JWKS publishes no signing key"),isSuccess2(applications)?check("organization",true,`Organization ${context.organizationId} is accessible with this credential`):check("organization",false,applications.failure.message)],discovery:isSuccess2(discovery)?discovery.success:undefined}});var runRedirectPreflight=fn2("Preflight.redirect")(function*runRedirectPreflight(input){const applications=yield*result2(listApplications(input.context));return isSuccess2(applications)?redirectCheck(applications.success,input.fqn,input.redirectUris):check("redirect-uri",false,applications.failure.message)});var runPreflight=fn2("Preflight.run")(function*runPreflight(input){const tenant=yield*runTenantPreflight(input);const checks=[...tenant.checks];if(input.fqn!==undefined||input.redirectUris.length>0){checks.push(tenant.applications===undefined?check("redirect-uri",false,"not checked: the Organization check failed"):redirectCheck(tenant.applications,input.fqn,input.redirectUris))}return{checks,discovery:tenant.discovery}});var renderPreflight=(checks)=>`${checks.map((entry)=>`${entry.passed?"PASS":"FAIL"} ${entry.name}: ${entry.detail}`).join(`
247
247
  `)}
@@ -3245,9 +3245,11 @@ window.$RefreshReg$ = () => {};
3245
3245
  window.$RefreshSig$ = () => (type) => type;`;var getPreambleCode=(base)=>preambleCode.replace("__BASE__",base);function virtualPreamblePlugin({name,isEnabled}){return{name:"vite:react-virtual-preamble",resolveId:{order:"pre",filter:{id:exactRegex(name)},handler(source){if(source===name)return"\x00"+source}},load:{filter:{id:exactRegex("\x00"+name)},handler(id){if(id==="\x00"+name){if(isEnabled())return preambleCode.replace("__BASE__","/");return""}}}}}var silenceUseClientWarning=(userConfig)=>({rollupOptions:{onwarn(warning,defaultHandler){if(warning.code==="MODULE_LEVEL_DIRECTIVE"&&(warning.message.includes("use client")||warning.message.includes("use server")))return;if(warning.code==="SOURCEMAP_ERROR"&&warning.message.includes("resolve original location")&&warning.pos===0)return;if(userConfig.build?.rollupOptions?.onwarn)userConfig.build.rollupOptions.onwarn(warning,defaultHandler);else defaultHandler(warning)}}});var defaultCodeFilter=/forwardRef|memo|\b(?:[A-Z]|use[A-Z0-9])/;var reactCompilerPreset=(options={})=>({preset:()=>({plugins:[[fileURLToPath11(import.meta.resolve("babel-plugin-react-compiler")),options]]}),rolldown:{filter:{code:options.compilationMode==="annotation"?/['"]use memo['"]/:defaultCodeFilter},applyToEnvironmentHook:(env)=>env.config.consumer==="client",optimizeDeps:{include:options.target==="17"||options.target==="18"?["react-compiler-runtime"]:["react/compiler-runtime"]}}});var refreshRuntimePath=join7(dirname5(fileURLToPath11(import.meta.url)),"refresh-runtime.js");var defaultIncludeRE=/\.[tj]sx?$/;var defaultExcludeRE=/\/node_modules\//;function viteReact(opts={}){const include=opts.include??defaultIncludeRE;const exclude=opts.exclude??defaultExcludeRE;const jsxImportSource=opts.jsxImportSource??"react";const jsxImportRuntime=`${jsxImportSource}/jsx-runtime`;const jsxImportDevRuntime=`${jsxImportSource}/jsx-dev-runtime`;let runningInVite=false;let skipFastRefresh=true;let base;let isBundledDev=false;function calculateSkipFastRefresh(isProduction,command,hmr){return isProduction||command==="build"||hmr===false}const viteBabel={name:"vite:react-babel",enforce:"pre",config(_userConfig,{command}){if(opts.jsxRuntime==="classic")return{oxc:{jsx:{runtime:"classic",refresh:command==="serve"},jsxRefreshInclude:makeIdFiltersToMatchWithQuery(include),jsxRefreshExclude:makeIdFiltersToMatchWithQuery(exclude)}};else return{oxc:{jsx:{runtime:"automatic",importSource:opts.jsxImportSource,refresh:command==="serve"},jsxRefreshInclude:makeIdFiltersToMatchWithQuery(include),jsxRefreshExclude:makeIdFiltersToMatchWithQuery(exclude)},optimizeDeps:{rolldownOptions:{transform:{jsx:{runtime:"automatic"}}}}}},configResolved(config){runningInVite=true;base=config.base;if(config.experimental.bundledDev)isBundledDev=true;if(skipFastRefresh!==calculateSkipFastRefresh(config.isProduction,config.command,config.server?.hmr))this.warn(`NODE_ENV (${JSON.stringify("development")}) or server.hmr was changed by plugins after the react plugin read the config. This may cause unexpected behavior.`)},options(options){if(!runningInVite){options.transform??={};options.transform.jsx={runtime:opts.jsxRuntime,importSource:opts.jsxImportSource};return options}}};const viteRefreshWrapper={name:"vite:react:refresh-wrapper",apply:"serve",async applyToEnvironment(env){if(env.config.consumer!=="client"||skipFastRefresh)return false;return reactRefreshWrapperPlugin({cwd:process.cwd(),include:makeIdFiltersToMatchWithQuery(include),exclude:makeIdFiltersToMatchWithQuery(exclude),jsxImportSource,reactRefreshHost:opts.reactRefreshHost??""})}};const viteConfigPost={name:"vite:react:config-post",enforce:"post",config(userConfig,{command}){skipFastRefresh=calculateSkipFastRefresh(false,command,userConfig.server?.hmr);if(skipFastRefresh)return{oxc:{jsx:{refresh:false}}}}};const viteReactRefreshBundledDevMode={name:"vite:react-refresh-fbm",enforce:"pre",transformIndexHtml:{handler(){if(!skipFastRefresh&&isBundledDev)return[{tag:"script",attrs:{type:"module"},children:getPreambleCode("/")}]},order:"pre"}};const dependencies=["react","react-dom",jsxImportDevRuntime,jsxImportRuntime];return[viteBabel,viteRefreshWrapper,viteConfigPost,viteReactRefreshBundledDevMode,{name:"vite:react-refresh",enforce:"pre",config:(userConfig)=>({build:silenceUseClientWarning(userConfig),optimizeDeps:{include:dependencies}}),resolveId:{filter:{id:exactRegex(runtimePublicPath)},handler(id){if(id==="/@react-refresh")return id}},load:{filter:{id:exactRegex(runtimePublicPath)},handler(id){if(id==="/@react-refresh")return readFileSync8(refreshRuntimePath,"utf-8").replace(/__README_URL__/g,"https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react")}},transformIndexHtml(){if(!skipFastRefresh&&!isBundledDev)return[{tag:"script",attrs:{type:"module"},children:getPreambleCode(base)}]}},virtualPreamblePlugin({name:"@vitejs/plugin-react/preamble",isEnabled:()=>!skipFastRefresh&&!isBundledDev})]}viteReact.preambleCode=preambleCode;function viteReactForCjs(options){return viteReact.call(this,options)}Object.assign(viteReactForCjs,{default:viteReactForCjs,reactCompilerPreset});import{tmpdir as tmpdir2}from"os";import{fileURLToPath as fileURLToPath12}from"url";import{createServer as createServer3}from"vite";var path12=runSync2(provide3(Path2,layer3));var runNested2=runPromiseWith2(empty());var makeTempDirectory2=flow((prefix)=>gen2(function*makeDirectory(){const fileSystem=yield*FileSystem;return yield*fileSystem.makeTempDirectory({directory:tmpdir2(),prefix})}).pipe(provide3(layer2)),runPromise2);var removeTempDirectory=flow((directory)=>gen2(function*removeTempDirectoryEffect(){const fileSystem=yield*FileSystem;yield*fileSystem.remove(directory,{force:true,recursive:true})}).pipe(provide3(layer2)),runPromise2);var declarationImport=(specifier)=>specifier.startsWith("file:")?fileURLToPath12(specifier):specifier;var moduleExport3=(exportName)=>{if(!/^[$A-Z_a-z][$\w]*$/u.test(exportName)){throw new TypeError(`Hosted Contribution export '${exportName}' is not a JavaScript identifier`)}return exportName};var virtualModuleSource=(input)=>`
3246
3246
  import * as loaded from ${JSON.stringify(input.contributionImport)}
3247
3247
  export const ${moduleExport3(input.exportName)} = loaded[${JSON.stringify(input.exportName)}]
3248
- `;var contributionKey2=(input)=>JSON.stringify([input.packageFqn,input.contributionHost,input.contributionFqn]);var exposedModule=(key)=>`./${key}`;var randomUuid2=()=>{const bytes=new Uint8Array(16);crypto.getRandomValues(bytes);bytes[6]=bytes[6]%16+64;bytes[8]=bytes[8]%64+128;const hex=[...bytes].map((byte)=>byte.toString(16).padStart(2,"0"));return`${hex.slice(0,4).join("")}-${hex.slice(4,6).join("")}-${hex.slice(6,8).join("")}-${hex.slice(8,10).join("")}-${hex.slice(10).join("")}`};var authorizationPlugin=(input)=>({configureServer(server){server.middlewares.use((request,response,next)=>{const{origin}=request.headers;const{pathname}=new URL(request.url??"/","http://127.0.0.1");const authorized=origin===undefined?pathname.startsWith(input.capabilityBase):input.attachedOrigins.has(origin);if(!authorized){response.writeHead(403,{"content-type":"text/plain"});response.end("Host origin is not attached");return}if(origin!==undefined){response.setHeader("access-control-allow-origin",origin)}response.setHeader("cache-control","no-store");next()})},enforce:"pre",name:"ci-hosted-development-authorization"});var startViteDevelopmentAssetServer=flow((input)=>gen2(function*startAssetServer(){const capability=randomUuid2().replaceAll("-","");const capabilityPath=`__ci_capability__/${capability}/`;const capabilityBase=`/${capabilityPath}`;const attachedOrigins=new Set(input.hostOrigins);const frontendCacheDirectory=yield*promise2(()=>makeTempDirectory2("ci-hosted-vite-"));let frontendEntries=new Map;let frontendServer;let frontendServerPort;const warmFrontendServer=flow((server)=>gen2(function*warmServer(){yield*promise2(()=>server.warmupRequest(`${capabilityBase}remoteEntry.js`));yield*promise2(()=>server.waitForRequestsIdle())}),runNested2);const startFrontendServer=flow((entries,port)=>gen2(function*startFrontendServerEffect(){const exposes=Object.fromEntries([...entries.keys()].map((key)=>[exposedModule(key),`virtual:ci-hosted:${encodeURIComponent(key)}`]));const virtualPrefix="\x00virtual:ci-hosted:";const virtualEntries={load(id){return id.startsWith(virtualPrefix)?entries.get(decodeURIComponent(id.slice(virtualPrefix.length)))?.source??null:null},name:"ci-hosted-development-entries",resolveId(id){return id.startsWith("virtual:ci-hosted:")?`\x00${id}`:null}};const shared=Object.fromEntries(frontendHostProvidedModules.map((moduleName)=>[moduleName,{import:false,singleton:true,suppressMissingImportWarning:true}]));const declarationPath=declarationImport(input.declarationSpecifier);const root=path12.isAbsolute(declarationPath)?path12.dirname(declarationPath):process.cwd();const server=yield*promise2(()=>createServer3({base:capabilityBase,cacheDir:frontendCacheDirectory,configFile:false,logLevel:"silent",optimizeDeps:{entries:[...entries.values()].map((entry)=>entry.importPath),exclude:[...frontendHostProvidedModules]},plugins:[authorizationPlugin({attachedOrigins,capabilityBase}),viteReact(),virtualEntries,federation({dev:{remoteHmr:true},dts:false,exposes,filename:"remoteEntry.js",manifest:false,moduleParseIdleTimeout:1,name:`ci_hosted_${capability}`,shared})],resolve:workspaceSourceResolve(process.execArgv),root,server:{cors:false,headers:{"cache-control":"no-store"},host:"127.0.0.1",port,strictPort:port!==0},ssr:workspaceSourceSsrResolve(process.execArgv)}));yield*promise2(()=>server.listen());yield*promise2(()=>warmFrontendServer(server));return server}),runNested2);const synchronizeFrontendServer=flow((entries)=>gen2(function*synchronizeServer(){const previousKeys=[...frontendEntries.keys()].toSorted();const nextKeys=[...entries.keys()].toSorted();if(previousKeys.length===nextKeys.length&&previousKeys.every((key,index)=>key===nextKeys[index]&&frontendEntries.get(key)?.importPath===entries.get(key)?.importPath)){frontendEntries.clear();for(const[key,source]of entries){frontendEntries.set(key,source)}frontendServer?.moduleGraph.invalidateAll();const server=frontendServer;if(server!==undefined){yield*promise2(()=>warmFrontendServer(server))}return yield*void_3}const previousServer=frontendServer;const port=frontendServerPort??0;frontendServer=undefined;if(previousServer!==undefined){yield*promise2(()=>previousServer.close())}frontendEntries=entries;if(entries.size===0){frontendServerPort=undefined;return yield*void_3}const server=yield*promise2(()=>startFrontendServer(entries,port));frontendServer=server;const localUrl=server.resolvedUrls?.local.at(0);if(localUrl===undefined){yield*promise2(()=>server.close());frontendServer=undefined;throw new Error("Vite did not publish a loopback development URL")}frontendServerPort=Number(new URL(localUrl).port);return yield*void_3}),runNested2);const rebuild=flow((declarations)=>gen2(function*rebuildServer(){const nextFrontendEntries=new Map;for(const definition of declarations){for(const contribution of definition.hostedContributions){if(contribution.manifest.host==="backend"){continue}const key=contributionKey2({contributionFqn:contribution.manifest.fqn,contributionHost:contribution.manifest.host,packageFqn:definition.manifest.fqn});const importPath=resolveHostedContributionEntry(input.declarationSpecifier,{fqn:contribution.manifest.fqn,load:contribution.load});const source=virtualModuleSource({contributionImport:importPath,exportName:contribution.manifest.exportName});nextFrontendEntries.set(key,{importPath,source})}}yield*promise2(()=>synchronizeFrontendServer(nextFrontendEntries))}),runNested2);yield*promise2(()=>rebuild(input.declarations)).pipe(tapError2(()=>promise2(()=>frontendServer?.close().then(()=>null).catch(()=>null)??Promise.resolve(null)).pipe(andThen2(()=>promise2(()=>removeTempDirectory(frontendCacheDirectory))))));return{assetsFor:flow((definition)=>sync2(()=>definition.hostedContributions.flatMap(({manifest})=>{if(manifest.host==="backend"){return[]}const key=contributionKey2({contributionFqn:manifest.fqn,contributionHost:manifest.host,packageFqn:definition.manifest.fqn});const localUrl=frontendServer?.resolvedUrls?.local.at(0);if(localUrl===undefined){throw new Error(`Vite federation remote was not started for ${manifest.fqn}`)}const moduleUrl=new URL("remoteEntry.js",localUrl);moduleUrl.hash=encodeURIComponent(exposedModule(key));return{...manifest.compatibility===undefined?undefined:{compatibility:manifest.compatibility},contract:manifest.contract,exportName:manifest.exportName,fqn:manifest.fqn,host:manifest.host,moduleUrl:moduleUrl.href}})),runNested2),close:flow(()=>gen2(function*closeServer(){const server=frontendServer;if(server!==undefined){yield*promise2(()=>server.close())}yield*promise2(()=>removeTempDirectory(frontendCacheDirectory))}),runPromiseWith2(empty())),rebuild}}),runPromise2);class PackageDiagnosticsCommandError extends TaggedError3()("PackageDiagnosticsCommandError",{cause:optional2(Unknown2),message:String5}){}var requireOption3=(options,name)=>{const value=options.get(name);if(value===undefined||value===""){throw new PackageDiagnosticsCommandError({message:`Missing required option --${name}`})}return value};var parseOptions3=(args)=>{const options=new Map;for(let index=1;index<args.length;index+=2){const flag=args[index];const value=args[index+1];if(!flag?.startsWith("--")||!value||value.startsWith("--")){throw new PackageDiagnosticsCommandError({message:"Options must be supplied as --name value pairs"})}options.set(flag.slice(2),value)}return options};var packageDiagnosticsCommandEffect=(args,dependencies)=>{const[command]=args;if(command!=="trace"){return fail6(new PackageDiagnosticsCommandError({message:"Expected package diagnostics command: trace"}))}return try_2({catch:(cause)=>is2(PackageDiagnosticsCommandError)(cause)?cause:new PackageDiagnosticsCommandError({cause,message:"Could not configure package diagnostics command"}),try:()=>parseOptions3(args)}).pipe(flatMap4((options)=>tryPromise2({catch:(cause)=>new PackageDiagnosticsCommandError({cause,message:"Could not read hosted Extension diagnostic trace"}),try:async()=>{const response=await hostedExtensionDiagnosticsReadTrace({client:dependencies.client,headers:{"x-organization-id":requireOption3(options,"organization")},path:{diagnosticId:requireOption3(options,"diagnostic")},throwOnError:true});return response.data}})))};import{createHash as createHash8}from"crypto";var awaitValue7=(value)=>promise2(constant(Promise.resolve(value)));var path13=runSync2(provide3(Path2,layer5));var readBytesEffect=(readBytes,filePath)=>tryPromise2(flow(()=>suspend2(()=>awaitValue7(readBytes(filePath))),runPromise2));class PackageReleaseCommandError extends TaggedError3()("PackageReleaseCommandError",{cause:optional2(Unknown2),message:String5}){}var requireOption4=(options,name)=>{const value=options.get(name);if(value===undefined||value===""){throw new PackageReleaseCommandError({message:`Missing required option --${name}`})}return value};var supportedOptions=new Set(["archive","backend-url","bundle","idempotency-key","inputs","installation","manifest","organization","package","package-manifest","private-maps","release","scope","version"]);var parseOptions4=(args)=>{const options=new Map;for(let index=1;index<args.length;index+=2){const flag=args[index];const value=args[index+1];if(!flag?.startsWith("--")||!value||value.startsWith("--")){throw new PackageReleaseCommandError({message:"Options must be supplied as --name value pairs"})}if(!supportedOptions.has(flag.slice(2))){throw new PackageReleaseCommandError({message:`Unknown option ${flag}`})}options.set(flag.slice(2),value)}return options};var idempotencyHeaders=(options)=>({"idempotency-key":requireOption4(options,"idempotency-key")});var administratorHeaders=(options)=>({...idempotencyHeaders(options),"x-organization-id":requireOption4(options,"organization")});var rejectRetiredPublishOptions=(options)=>{if(options.has("scope")){throw new PackageReleaseCommandError({message:"--scope is no longer supported; publisher credential scope is authoritative"})}if(options.has("organization")){throw new PackageReleaseCommandError({message:"--organization is no longer supported; publisher credential scope is authoritative"})}if(options.has("package")||options.has("version")){throw new PackageReleaseCommandError({message:"--package and --version are no longer supported; the authoritative release manifest supplies both"})}if(options.has("bundle")){throw new PackageReleaseCommandError({message:"--bundle is no longer supported for publication; use the verified --archive release artifact"})}};var digest3=(bytes)=>createHash8("sha256").update(bytes).digest("hex");var rejectInputs=(message)=>{throw new PackageReleaseCommandError({message})};var readInputs2=async(options,readBytes)=>{const filePath=options.get("inputs");return filePath===undefined?{}:inputsFromFile(await readInputsFile(filePath,rejectInputs,readBytes))};var executePublish=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not publish package release"}),try:async()=>{rejectRetiredPublishOptions(options);const archiveBytes=await dependencies.readBytes(requireOption4(options,"archive"));const manifestPath=requireOption4(options,"manifest");const manifestBytes=await dependencies.readBytes(manifestPath);const packageManifestBytes=await dependencies.readBytes(requireOption4(options,"package-manifest"));const privateMapDirectory=options.has("private-maps")?requireOption4(options,"private-maps"):path13.join(path13.dirname(manifestPath),"private-source-maps");const privateMapFiles=await dependencies.listFiles(privateMapDirectory);const privateSourceMaps=await Promise.all(privateMapFiles.toSorted(compareCanonicalText).map(flow((fileName)=>gen2(function*readPrivateSourceMap(){if(!/^[\da-f]{64}\.map$/u.test(fileName)){return yield*new PackageReleaseCommandError({message:`Private source-map file '${fileName}' is not keyed by a runtime asset digest`})}const bytes=yield*readBytesEffect(dependencies.readBytes,path13.join(privateMapDirectory,fileName));return{bytes,digest:digest3(bytes),runtimeAssetDigest:fileName.slice(0,-4),size:bytes.byteLength}}),runPromise2)));const body=await preparePackagePublication({archiveBytes,manifestBytes,packageManifestBytes,privateSourceMaps});const accepted=await publishPackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key")});return accepted.operationId}});var executePromote=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not promote package release"}),try:async()=>{const body={protocolVersion:"v1",releaseId:requireOption4(options,"release")};const accepted=await promotePackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key")});return accepted.operationId}});var executeUpdate=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not update package installation"}),try:async()=>{const body={...await readInputs2(options,dependencies.readBytes),installationId:requireOption4(options,"installation"),protocolVersion:"v1",releaseId:requireOption4(options,"release")};const accepted=await updatePackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key"),organizationId:requireOption4(options,"organization")});return accepted.operationId}});var executeInstall=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not install package"}),try:async()=>{const releaseId=options.get("release");const body={...releaseId===undefined?undefined:{releaseId},...await readInputs2(options,dependencies.readBytes)};const accepted=await installPackage({...Object.keys(body).length===0?undefined:{body},client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key"),organizationId:requireOption4(options,"organization"),packageFqn:requireOption4(options,"package")});return accepted.operationId}});var executeSync=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not sync package"}),try:async()=>{if(options.has("release")){throw new PackageReleaseCommandError({message:"package sync re-applies the current release and does not accept --release; use package update --release for an exact release"})}const accepted=await extensionPackagesSync({client:dependencies.client,headers:administratorHeaders(options),path:{fqn:requireOption4(options,"package")},throwOnError:true});return accepted.data.operationId}});var executeRollback=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not roll back package installation"}),try:async()=>{const accepted=await packageReleasesRollbackInstallation({body:{installationId:requireOption4(options,"installation"),protocolVersion:"v1",releaseId:requireOption4(options,"release")},client:dependencies.client,headers:administratorHeaders(options),throwOnError:true});return accepted.data.operationId}});var packageReleaseCommandEffect=(args,dependencies)=>{const[command]=args;const options=parseOptions4(args);if(options.has("inputs")&&command!=="install"&&command!=="update"){return fail6(new PackageReleaseCommandError({message:"--inputs is supported only for package install/update"}))}switch(command){case"install":{return executeInstall(options,dependencies)}case"publish":{return executePublish(options,dependencies)}case"promote":{return executePromote(options,dependencies)}case"rollback":{return executeRollback(options,dependencies)}case"sync":{return executeSync(options,dependencies)}case"update":{return executeUpdate(options,dependencies)}default:{return fail6(new PackageReleaseCommandError({message:"Expected one of: package publish, package promote, package install, package update, package sync, package rollback"}))}}};class PackageReleasesCommandError extends TaggedError3()("PackageReleasesCommandError",{cause:optional2(Unknown2),message:String5}){}var requireOption5=(options,name)=>{const value=options.get(name);if(value===undefined||value===""){throw new PackageReleasesCommandError({message:`Missing required option --${name}`})}return value};var parseOptions5=(args)=>{const options=new Map;for(let index=0;index<args.length;index+=2){const flag=args[index];const value=args[index+1];if(!flag?.startsWith("--")||!value||value.startsWith("--")){throw new PackageReleasesCommandError({message:"Options must be supplied as --name value pairs"})}options.set(flag.slice(2),value)}return options};var packageReleasesCommandEffect=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleasesCommandError)(cause)?cause:new PackageReleasesCommandError({cause,message:"Could not list package releases"}),try:async()=>{const parsed=parseOptions5(options);const response=await extensionPackagesListReleases({client:dependencies.client,headers:{"x-organization-id":requireOption5(parsed,"organization")},path:{fqn:requireOption5(parsed,"package")},throwOnError:true});return response.data}});import{mkdir as mkdir4,readdir as readdir3,readFile as readFile6,rename as rename3,rm as rm3,stat as stat4}from"fs/promises";import path14 from"path";var portablePath=(value)=>value.split(path14.sep).join("/");var bunTransferFiles={kind:async(target)=>{try{const found=await stat4(target);return found.isDirectory()?"directory":"file"}catch{return null}},list:async(folder)=>{const entries=await readdir3(folder,{recursive:true,withFileTypes:true});return await Promise.all(entries.filter((entry)=>entry.isFile()).map(async(entry)=>{const file=path14.join(entry.parentPath,entry.name);const found=await stat4(file);return{path:portablePath(path14.relative(folder,file)),size:found.size}}))},openRead:(file)=>Bun.file(file).stream(),readText:async(file)=>await readFile6(file,"utf-8"),seekable:(file)=>Bun.file(file),writeStream:async(file,stream)=>{const partial=`${file}.partial`;await mkdir4(path14.dirname(file),{recursive:true});try{await Bun.write(partial,new Response(stream));await rename3(partial,file)}catch(error){await rm3(partial,{force:true});throw error}}};var messageOf2=(failure)=>{switch(failure.code){case"archive_zip_limit":{return`Cannot add ${failure.path} to the zip: a zip holds at most 4 GiB and 65535 files. Export to a folder instead.`}case"size_mismatch":{return`Archive file ${failure.path} has ${failure.actual} bytes, expected ${failure.expected}`}case"zip_manifest_missing":{return"The zip has no manifest.json"}case"manifest_invalid":{return"manifest.json is not a readable archive manifest"}case"zip_incomplete":{return`The zip lacks ${failure.missing.length} files that the manifest lists`}case"zip_malformed":{return`The zip cannot be read: ${failure.reason}`}case"download_failed":{return`Download of archive file ${failure.path} failed with HTTP ${failure.status}`}case"upload_failed":{return`Upload of archive file ${failure.path} failed with HTTP ${failure.status}`}case"run_event_invalid":{return"The transfer stream sent a frame that is not a run event"}case"preview_failed":{return`The export preview did not finish: the run is ${failure.status}`}default:{return failure}}};class TransferClientError extends Error{name="TransferClientError";failure;constructor(failure,options){super(messageOf2(failure),options);this.failure=failure}}var organizationHeaders=(scope)=>({"x-organization-id":scope.organizationId});var DEFAULT_RUN_LIMIT=50;var startTransferExport=async(scope,request)=>{const{data}=await organizationTransferExports({body:request,headers:organizationHeaders(scope),throwOnError:true});return data};var startTransferImport=async(scope,request)=>{const{data}=await organizationTransferImports({body:request,headers:organizationHeaders(scope),throwOnError:true});return data};var startTransferRollback=async(scope,request)=>{const{data}=await organizationTransferRollbacks({body:request,headers:organizationHeaders(scope),throwOnError:true});return data};var listTransferRuns=async(scope,options={})=>{const{data}=await organizationTransferRuns({headers:organizationHeaders(scope),query:{limit:String(options.limit??DEFAULT_RUN_LIMIT)},throwOnError:true});return data};var getTransferRun=async(scope,runId)=>{const{data,error,response}=await organizationTransferRun({headers:organizationHeaders(scope),path:{runId}});if(response.status===404){return}if(error!==undefined){throw error}return data};var cancelTransferRun=async(scope,runId)=>{const{data}=await organizationTransferCancel({headers:organizationHeaders(scope),path:{runId},throwOnError:true});return data};var resumeTransferRun=async(scope,runId)=>{const{data}=await organizationTransferResume({headers:organizationHeaders(scope),path:{runId},throwOnError:true});return data};var purgeTransferRun=async(scope,runId)=>{await organizationTransferPurge({headers:organizationHeaders(scope),path:{runId},throwOnError:true})};var getTransferRunReport=async(scope,runId)=>{const{data}=await organizationTransferReport({headers:organizationHeaders(scope),path:{runId},throwOnError:true});return data};var requestTransferDownloadUrls=async(input)=>{const{data}=await organizationTransferDownloadUrls({headers:organizationHeaders(input),path:{archiveId:input.archiveId},...input.signal===undefined?undefined:{signal:input.signal},throwOnError:true});return data.files};var inPairs=(paths)=>Array.from({length:Math.ceil(paths.length/2)},(_,index)=>{const first=paths[index*2]??"";return[first,paths.at(index*2+1)??first]});var requestTransferUploadUrls=async(input)=>{const answers=await Promise.all(inPairs(input.paths).map(async(paths)=>{const{data}=await organizationTransferUploadUrls({body:{paths},headers:organizationHeaders(input),path:{archiveId:input.archiveId},...input.signal===undefined?undefined:{signal:input.signal},throwOnError:true});return data.urls}));return answers.flat()};var transferRunPlan=(run)=>run.counts.plan;var importApplyRequest=(input)=>{const request={archiveId:input.plan.archiveId,mode:"apply",planRunId:input.planRunId};if(input.confirmReplace!==undefined){request.confirmReplace=input.confirmReplace}if(input.plan.options!==undefined){request.options=input.plan.options}return request};var isTransferRunActive=(run)=>run.status==="queued"||run.status==="running";var PREVIEW_POLL_MS=500;var PREVIEW_MAX_POLL_MS=5000;var wait=async(ms,signal)=>{signal?.throwIfAborted();await new Promise((resolve,reject)=>{const settled=new AbortController;const timer=globalThis.setTimeout(()=>{settled.abort();resolve()},ms);signal?.addEventListener("abort",()=>{globalThis.clearTimeout(timer);reject(signal.reason)},{once:true,signal:settled.signal})})};var previewTransferExport=async(scope,request,options={})=>{const{data:accepted}=await organizationTransferPreview({body:request,headers:organizationHeaders(scope),throwOnError:true});let run=accepted;let delay=options.pollIntervalMs??PREVIEW_POLL_MS;while(run!==undefined&&isTransferRunActive(run)){await wait(delay,options.signal);delay=Math.min(delay*2,PREVIEW_MAX_POLL_MS);run=await getTransferRun(scope,accepted.id)}const preview=run?.counts.preview;if(run?.status!=="completed"||preview===undefined){throw new TransferClientError({code:"preview_failed",status:run?.status??"missing"})}return preview};import{createRequire as createRequire4}from"module";var require2=createRequire4("/");var _a;var Worker;var isMarkedAsUntransferable;try{_a=require2("worker_threads"),Worker=_a.Worker,isMarkedAsUntransferable=_a.isMarkedAsUntransferable}catch(e){}var u8=Uint8Array;var u16=Uint16Array;var i32=Int32Array;var fleb=new u8([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]);var fdeb=new u8([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]);var clim=new u8([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);var freb=function(eb,start){var b=new u16(31);for(var i=0;i<31;++i){b[i]=start+=1<<eb[i-1]}var r=new i32(b[30]);for(var i=1;i<30;++i){for(var j=b[i];j<b[i+1];++j){r[j]=j-b[i]<<5|i}}return{b,r}};var _a=freb(fleb,2);var fl=_a.b;var revfl=_a.r;fl[28]=258,revfl[258]=28;var _b=freb(fdeb,0);var fd=_b.b;var revfd=_b.r;var rev=new u16(32768);for(i2=0;i2<32768;++i2){x=(i2&43690)>>1|(i2&21845)<<1;x=(x&52428)>>2|(x&13107)<<2;x=(x&61680)>>4|(x&3855)<<4;rev[i2]=((x&65280)>>8|(x&255)<<8)>>1}var x;var i2;var hMap=function(cd,mb,r){var s=cd.length;var i=0;var l=new u16(mb);for(;i<s;++i){if(cd[i])++l[cd[i]-1]}var le=new u16(mb);for(i=1;i<mb;++i){le[i]=le[i-1]+l[i-1]<<1}var co;if(r){co=new u16(1<<mb);var rvb=15-mb;for(i=0;i<s;++i){if(cd[i]){var sv=i<<4|cd[i];var r_1=mb-cd[i];var v=le[cd[i]-1]++<<r_1;for(var m=v|(1<<r_1)-1;v<=m;++v){co[rev[v]>>rvb]=sv}}}}else{co=new u16(s);for(i=0;i<s;++i){if(cd[i]){co[i]=rev[le[cd[i]-1]++]>>15-cd[i]}}}return co};var flt=new u8(288);for(i2=0;i2<144;++i2)flt[i2]=8;var i2;for(i2=144;i2<256;++i2)flt[i2]=9;var i2;for(i2=256;i2<280;++i2)flt[i2]=7;var i2;for(i2=280;i2<288;++i2)flt[i2]=8;var i2;var fdt=new u8(32);for(i2=0;i2<32;++i2)fdt[i2]=5;var i2;var flm=hMap(flt,9,0);var flrm=hMap(flt,9,1);var fdm=hMap(fdt,5,0);var fdrm=hMap(fdt,5,1);var max=function(a){var m=a[0];for(var i=1;i<a.length;++i){if(a[i]>m)m=a[i]}return m};var bits=function(d,p,m){var o=p/8|0;return(d[o]|d[o+1]<<8)>>(p&7)&m};var bits16=function(d,p){var o=p/8|0;return(d[o]|d[o+1]<<8|d[o+2]<<16)>>(p&7)};var shft=function(p){return(p+7)/8|0};var slc=function(v,s,e){if(s==null||s<0)s=0;if(e==null||e>v.length)e=v.length;return new u8(v.subarray(s,e))};var ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"];var err=function(ind,msg,nt){var e=new Error(msg||ec[ind]);e.code=ind;if(Error.captureStackTrace)Error.captureStackTrace(e,err);if(!nt)throw e;return e};var inflt=function(dat,st,buf,dict){var sl=dat.length,dl=dict?dict.length:0;if(!sl||st.f&&!st.l)return buf||new u8(0);var noBuf=!buf;var resize=noBuf||st.i!=2;var noSt=st.i;if(noBuf)buf=new u8(sl*3);var cbuf=function(l){var bl=buf.length;if(l>bl){var nbuf=new u8(Math.max(bl*2,l));nbuf.set(buf);buf=nbuf}};var final=st.f||0,pos=st.p||0,bt=st.b||0,{l:lm,d:dm,m:lbt,n:dbt}=st;var tbts=sl*8;do{if(!lm){final=bits(dat,pos,1);var type=bits(dat,pos+1,3);pos+=3;if(!type){var s=shft(pos)+4,l=dat[s-4]|dat[s-3]<<8,t=s+l;if(t>sl){if(noSt)err(0);break}if(resize)cbuf(bt+l);buf.set(dat.subarray(s,t),bt);st.b=bt+=l,st.p=pos=t*8,st.f=final;continue}else if(type==1)lm=flrm,dm=fdrm,lbt=9,dbt=5;else if(type==2){var hLit=bits(dat,pos,31)+257,hcLen=bits(dat,pos+10,15)+4;var tl=hLit+bits(dat,pos+5,31)+1;pos+=14;var ldt=new u8(tl);var clt=new u8(19);for(var i=0;i<hcLen;++i){clt[clim[i]]=bits(dat,pos+i*3,7)}pos+=hcLen*3;var clb=max(clt),clbmsk=(1<<clb)-1;var clm=hMap(clt,clb,1);for(var i=0;i<tl;){var r=clm[bits(dat,pos,clbmsk)];pos+=r&15;var s=r>>4;if(s<16){ldt[i++]=s}else{var c=0,n=0;if(s==16)n=3+bits(dat,pos,3),pos+=2,c=ldt[i-1];else if(s==17)n=3+bits(dat,pos,7),pos+=3;else if(s==18)n=11+bits(dat,pos,127),pos+=7;while(n--)ldt[i++]=c}}var lt=ldt.subarray(0,hLit),dt=ldt.subarray(hLit);lbt=max(lt);dbt=max(dt);lm=hMap(lt,lbt,1);dm=hMap(dt,dbt,1)}else err(1);if(pos>tbts){if(noSt)err(0);break}}if(resize)cbuf(bt+131072);var lms=(1<<lbt)-1,dms=(1<<dbt)-1;var lpos=pos;for(;;lpos=pos){var c=lm[bits16(dat,pos)&lms],sym=c>>4;pos+=c&15;if(pos>tbts){if(noSt)err(0);break}if(!c)err(2);if(sym<256)buf[bt++]=sym;else if(sym==256){lpos=pos,lm=null;break}else{var add=sym-254;if(sym>264){var i=sym-257,b=fleb[i];add=bits(dat,pos,(1<<b)-1)+fl[i];pos+=b}var d=dm[bits16(dat,pos)&dms],dsym=d>>4;if(!d)err(3);pos+=d&15;var dt=fd[dsym];if(dsym>3){var b=fdeb[dsym];dt+=bits16(dat,pos)&(1<<b)-1,pos+=b}if(pos>tbts){if(noSt)err(0);break}if(resize)cbuf(bt+131072);var end=bt+add;if(bt<dt){var shift=dl-dt,dend=Math.min(dt,end);if(shift+bt<0)err(3);for(;bt<dend;++bt)buf[bt]=dict[shift+bt]}for(;bt<end;++bt)buf[bt]=buf[bt-dt]}}st.l=lm,st.p=lpos,st.b=bt,st.f=final;if(lm)final=1,st.m=lbt,st.d=dm,st.n=dbt}while(!final);return bt!=buf.length&&noBuf?slc(buf,0,bt):buf.subarray(0,bt)};var wbits=function(d,p,v){v<<=p&7;var o=p/8|0;d[o]|=v;d[o+1]|=v>>8};var wbits16=function(d,p,v){v<<=p&7;var o=p/8|0;d[o]|=v;d[o+1]|=v>>8;d[o+2]|=v>>16};var hTree=function(d,mb){var t=[];for(var i=0;i<d.length;++i){if(d[i])t.push({s:i,f:d[i]})}var s=t.length;var t2=t.slice();if(!s)return{t:et,l:0};if(s==1){var v=new u8(t[0].s+1);v[t[0].s]=1;return{t:v,l:1}}t.sort(function(a,b){return a.f-b.f});t.push({s:-1,f:25001});var l=t[0],r=t[1],i0=0,i1=1,i2=2;t[0]={s:-1,f:l.f+r.f,l,r};while(i1!=s-1){l=t[t[i0].f<t[i2].f?i0++:i2++];r=t[i0!=i1&&t[i0].f<t[i2].f?i0++:i2++];t[i1++]={s:-1,f:l.f+r.f,l,r}}var maxSym=t2[0].s;for(var i=1;i<s;++i){if(t2[i].s>maxSym)maxSym=t2[i].s}var tr=new u16(maxSym+1);var mbt=ln(t[i1-1],tr,0);if(mbt>mb){var i=0,dt=0;var lft=mbt-mb,cst=1<<lft;t2.sort(function(a,b){return tr[b.s]-tr[a.s]||a.f-b.f});for(;i<s;++i){var i2_1=t2[i].s;if(tr[i2_1]>mb){dt+=cst-(1<<mbt-tr[i2_1]);tr[i2_1]=mb}else break}dt>>=lft;while(dt>0){var i2_2=t2[i].s;if(tr[i2_2]<mb)dt-=1<<mb-tr[i2_2]++-1;else++i}for(;i>=0&&dt;--i){var i2_3=t2[i].s;if(tr[i2_3]==mb){--tr[i2_3];++dt}}mbt=mb}return{t:new u8(tr),l:mbt}};var ln=function(n,l,d){return n.s==-1?Math.max(ln(n.l,l,d+1),ln(n.r,l,d+1)):l[n.s]=d};var lc=function(c){var s=c.length;while(s&&!c[--s]);var cl=new u16(++s);var cli=0,cln=c[0],cls=1;var w=function(v){cl[cli++]=v};for(var i=1;i<=s;++i){if(c[i]==cln&&i!=s)++cls;else{if(!cln&&cls>2){for(;cls>138;cls-=138)w(32754);if(cls>2){w(cls>10?cls-11<<5|28690:cls-3<<5|12305);cls=0}}else if(cls>3){w(cln),--cls;for(;cls>6;cls-=6)w(8304);if(cls>2)w(cls-3<<5|8208),cls=0}while(cls--)w(cln);cls=1;cln=c[i]}}return{c:cl.subarray(0,cli),n:s}};var clen=function(cf,cl){var l=0;for(var i=0;i<cl.length;++i)l+=cf[i]*cl[i];return l};var wfblk=function(out,pos,dat){var s=dat.length;var o=shft(pos+2);out[o]=s&255;out[o+1]=s>>8;out[o+2]=out[o]^255;out[o+3]=out[o+1]^255;for(var i=0;i<s;++i)out[o+i+4]=dat[i];return(o+4+s)*8};var wblk=function(dat,out,final,syms,lf,df,eb,li,bs,bl,p){wbits(out,p++,final);++lf[256];var _a=hTree(lf,15),{t:dlt,l:mlb}=_a;var _b=hTree(df,15),{t:ddt,l:mdb}=_b;var _c=lc(dlt),{c:lclt,n:nlc}=_c;var _d=lc(ddt),{c:lcdt,n:ndc}=_d;var lcfreq=new u16(19);for(var i=0;i<lclt.length;++i)++lcfreq[lclt[i]&31];for(var i=0;i<lcdt.length;++i)++lcfreq[lcdt[i]&31];var _e=hTree(lcfreq,7),{t:lct,l:mlcb}=_e;var nlcc=19;for(;nlcc>4&&!lct[clim[nlcc-1]];--nlcc);var flen=bl+5<<3;var ftlen=clen(lf,flt)+clen(df,fdt)+eb;var dtlen=clen(lf,dlt)+clen(df,ddt)+eb+14+3*nlcc+clen(lcfreq,lct)+2*lcfreq[16]+3*lcfreq[17]+7*lcfreq[18];if(bs>=0&&flen<=ftlen&&flen<=dtlen)return wfblk(out,p,dat.subarray(bs,bs+bl));var lm,ll,dm,dl;wbits(out,p,1+(dtlen<ftlen)),p+=2;if(dtlen<ftlen){lm=hMap(dlt,mlb,0),ll=dlt,dm=hMap(ddt,mdb,0),dl=ddt;var llm=hMap(lct,mlcb,0);wbits(out,p,nlc-257);wbits(out,p+5,ndc-1);wbits(out,p+10,nlcc-4);p+=14;for(var i=0;i<nlcc;++i)wbits(out,p+3*i,lct[clim[i]]);p+=3*nlcc;var lcts=[lclt,lcdt];for(var it=0;it<2;++it){var clct=lcts[it];for(var i=0;i<clct.length;++i){var len=clct[i]&31;wbits(out,p,llm[len]),p+=lct[len];if(len>15)wbits(out,p,clct[i]>>5&127),p+=clct[i]>>12}}}else{lm=flm,ll=flt,dm=fdm,dl=fdt}for(var i=0;i<li;++i){var sym=syms[i];if(sym>255){var len=sym>>18&31;wbits16(out,p,lm[len+257]),p+=ll[len+257];if(len>7)wbits(out,p,sym>>23&31),p+=fleb[len];var dst=sym&31;wbits16(out,p,dm[dst]),p+=dl[dst];if(dst>3)wbits16(out,p,sym>>5&8191),p+=fdeb[dst]}else{wbits16(out,p,lm[sym]),p+=ll[sym]}}wbits16(out,p,lm[256]);return p+ll[256]};var deo=new i32([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]);var et=new u8(0);var dflt=function(dat,lvl,plvl,pre,post,st){var s=st.z||dat.length;var o=new u8(pre+s+5*(1+Math.ceil(s/7000))+post);var w=o.subarray(pre,o.length-post);var lst=st.l;var pos=(st.r||0)&7;if(lvl){if(pos)w[0]=st.r>>3;var opt=deo[lvl-1];var n=opt>>13,c=opt&8191;var msk_1=(1<<plvl)-1;var prev=st.p||new u16(32768),head=st.h||new u16(msk_1+1);var bs1_1=Math.ceil(plvl/3),bs2_1=2*bs1_1;var hsh=function(i){return(dat[i]^dat[i+1]<<bs1_1^dat[i+2]<<bs2_1)&msk_1};var syms=new i32(25000);var lf=new u16(288),df=new u16(32);var lc_1=0,eb=0,i=st.i||0,li=0,wi=st.w||0,bs=0;for(;i+2<s;++i){var hv=hsh(i);var imod=i&32767,pimod=head[hv];prev[imod]=pimod;head[hv]=imod;if(wi<=i){var rem=s-i;if((lc_1>7000||li>24576)&&(rem>423||!lst)){pos=wblk(dat,w,0,syms,lf,df,eb,li,bs,i-bs,pos);li=lc_1=eb=0,bs=i;for(var j=0;j<286;++j)lf[j]=0;for(var j=0;j<30;++j)df[j]=0}var l=2,d=0,ch_1=c,dif=imod-pimod&32767;if(rem>2&&hv==hsh(i-dif)){var maxn=Math.min(n,rem)-1;var maxd=Math.min(32767,i);var ml=Math.min(258,rem);while(dif<=maxd&&--ch_1&&imod!=pimod){if(dat[i+l]==dat[i+l-dif]){var nl=0;for(;nl<ml&&dat[i+nl]==dat[i+nl-dif];++nl);if(nl>l){l=nl,d=dif;if(nl>maxn)break;var mmd=Math.min(dif,nl-2);var md=0;for(var j=0;j<mmd;++j){var ti=i-dif+j&32767;var pti=prev[ti];var cd=ti-pti&32767;if(cd>md)md=cd,pimod=ti}}}imod=pimod,pimod=prev[imod];dif+=imod-pimod&32767}}if(d){syms[li++]=268435456|revfl[l]<<18|revfd[d];var lin=revfl[l]&31,din=revfd[d]&31;eb+=fleb[lin]+fdeb[din];++lf[257+lin];++df[din];wi=i+l;++lc_1}else{syms[li++]=dat[i];++lf[dat[i]]}}}for(i=Math.max(i,wi);i<s;++i){syms[li++]=dat[i];++lf[dat[i]]}pos=wblk(dat,w,lst,syms,lf,df,eb,li,bs,i-bs,pos);if(!lst){st.r=pos&7|w[pos/8|0]<<3;pos-=7;st.h=head,st.p=prev,st.i=i,st.w=wi}}else{for(var i=st.w||0;i<s+lst;i+=65535){var e=i+65535;if(e>=s){w[pos/8|0]=lst;e=s}pos=wfblk(w,pos+1,dat.subarray(i,e))}st.i=s}return slc(o,0,pre+shft(pos)+post)};var crct=function(){var t=new Int32Array(256);for(var i=0;i<256;++i){var c=i,k=9;while(--k)c=(c&1&&-306674912)^c>>>1;t[i]=c}return t}();var crc=function(){var c=-1;return{p:function(d){var cr=c;for(var i=0;i<d.length;++i)cr=crct[cr&255^d[i]]^cr>>>8;c=cr},d:function(){return~c}}};var dopt=function(dat,opt,pre,post,st){if(!st){st={l:1};if(opt.dictionary){var dict=opt.dictionary.subarray(-32768);var newDat=new u8(dict.length+dat.length);newDat.set(dict);newDat.set(dat,dict.length);dat=newDat;st.w=dict.length}}return dflt(dat,opt.level==null?6:opt.level,opt.mem==null?st.l?Math.ceil(Math.max(8,Math.min(13,Math.log(dat.length)))*1.5):20:12+opt.mem,pre,post,st)};var mrg=function(a,b){var o={};for(var k in a)o[k]=a[k];for(var k in b)o[k]=b[k];return o};var wbytes=function(d,b,v){for(;v;++b)d[b]=v,v>>>=8};var Deflate=function(){function Deflate(opts,cb){if(typeof opts=="function")cb=opts,opts={};this.ondata=cb;this.o=opts||{};this.s={l:0,i:32768,w:32768,z:32768};this.b=new u8(98304);if(this.o.dictionary){var dict=this.o.dictionary.subarray(-32768);this.b.set(dict,32768-dict.length);this.s.i=32768-dict.length}}Deflate.prototype.p=function(c,f){this.ondata(dopt(c,this.o,0,0,this.s),f)};Deflate.prototype.push=function(chunk,final){if(!this.ondata)err(5);if(this.s.l)err(4);var endLen=chunk.length+this.s.z;if(endLen>this.b.length){if(endLen>2*this.b.length-32768){var newBuf=new u8(endLen&-32768);newBuf.set(this.b.subarray(0,this.s.z));this.b=newBuf}var split=this.b.length-this.s.z;this.b.set(chunk.subarray(0,split),this.s.z);this.s.z=this.b.length;this.p(this.b,false);this.b.set(this.b.subarray(-32768));this.b.set(chunk.subarray(split),32768);this.s.z=chunk.length-split+32768;this.s.i=32766,this.s.w=32768}else{this.b.set(chunk,this.s.z);this.s.z+=chunk.length}this.s.l=final&1;if(this.s.z>this.s.w+8191||final){this.p(this.b,final||false);this.s.w=this.s.i,this.s.i-=2}if(final){this.s=this.o={};this.b=et}};Deflate.prototype.flush=function(sync){if(!this.ondata)err(5);if(this.s.l)err(4);this.p(this.b,false);this.s.w=this.s.i,this.s.i-=2;if(sync){var c=new u8(6);c[0]=this.s.r>>3;var ep=wfblk(c,this.s.r,et);this.s.r=0;this.ondata(c.subarray(0,ep>>3),false)}};return Deflate}();var Inflate=function(){function Inflate(opts,cb){if(typeof opts=="function")cb=opts,opts={};this.ondata=cb;var dict=opts&&opts.dictionary&&opts.dictionary.subarray(-32768);this.s={i:0,b:dict?dict.length:0};this.o=new u8(32768);this.p=new u8(0);if(dict)this.o.set(dict)}Inflate.prototype.e=function(c){if(!this.ondata)err(5);if(this.d)err(4);if(!this.p.length)this.p=c;else if(c.length){var n=new u8(this.p.length+c.length);n.set(this.p),n.set(c,this.p.length),this.p=n}};Inflate.prototype.c=function(final){this.s.i=+(this.d=final||false);var bts=this.s.b;var dt=inflt(this.p,this.s,this.o);this.ondata(slc(dt,bts,this.s.b),this.d);this.o=slc(dt,this.s.b-32768),this.s.b=this.o.length;this.p=slc(this.p,this.s.p/8|0),this.s.p&=7};Inflate.prototype.push=function(chunk,final){this.e(chunk),this.c(final)};return Inflate}();var te=typeof TextEncoder!="undefined"&&new TextEncoder;var td2=typeof TextDecoder!="undefined"&&new TextDecoder;var tds=0;try{td2.decode(et,{stream:true});tds=1}catch(e){}function strToU8(str,latin1){if(latin1){var ar_1=new u8(str.length);for(var i=0;i<str.length;++i)ar_1[i]=str.charCodeAt(i);return ar_1}if(te)return te.encode(str);var l=str.length;var ar=new u8(str.length+(str.length>>1));var ai=0;var w=function(v){ar[ai++]=v};for(var i=0;i<l;++i){if(ai+5>ar.length){var n=new u8(ai+8+(l-i<<1));n.set(ar);ar=n}var c=str.charCodeAt(i);if(c<128||latin1)w(c);else if(c<2048)w(192|c>>6),w(128|c&63);else if(c>55295&&c<57344)c=65536+(c&1023<<10)|str.charCodeAt(++i)&1023,w(240|c>>18),w(128|c>>12&63),w(128|c>>6&63),w(128|c&63);else w(224|c>>12),w(128|c>>6&63),w(128|c&63)}return slc(ar,0,ai)}var dbf=function(l){return l==1?3:l<6?2:l==9?1:0};var exfl=function(ex){var le=0;if(ex){for(var k in ex){var l=ex[k].length;if(l>65535)err(9);le+=l+4}}return le};var wzh=function(d,b,f,fn,u,c,ce,co){var fl=fn.length,ex=f.extra,col=co&&co.length;var exl=exfl(ex);wbytes(d,b,ce!=null?33639248:67324752),b+=4;if(ce!=null)d[b++]=20,d[b++]=f.os;d[b]=20,b+=2;d[b++]=f.flag<<1|(c<0&&8),d[b++]=u&&8;d[b++]=f.compression&255,d[b++]=f.compression>>8;var dt=new Date(f.mtime==null?Date.now():f.mtime),y=dt.getFullYear()-1980;if(y<0||y>119)err(10);wbytes(d,b,y<<25|dt.getMonth()+1<<21|dt.getDate()<<16|dt.getHours()<<11|dt.getMinutes()<<5|dt.getSeconds()>>1),b+=4;if(c!=-1){wbytes(d,b,f.crc);wbytes(d,b+4,c<0?-c-2:c);wbytes(d,b+8,f.size)}wbytes(d,b+12,fl);wbytes(d,b+14,exl),b+=16;if(ce!=null){wbytes(d,b,col);wbytes(d,b+6,f.attrs);wbytes(d,b+10,ce),b+=14}d.set(fn,b);b+=fl;if(exl){for(var k in ex){var exf=ex[k],l=exf.length;wbytes(d,b,+k);wbytes(d,b+2,l);d.set(exf,b+4),b+=4+l}}if(col)d.set(co,b),b+=col;return b};var wzf=function(o,b,c,d,e){wbytes(o,b,101010256);wbytes(o,b+8,c);wbytes(o,b+10,c);wbytes(o,b+12,d);wbytes(o,b+16,e)};var ZipPassThrough=function(){function ZipPassThrough(filename){this.filename=filename;this.c=crc();this.size=0;this.compression=0}ZipPassThrough.prototype.process=function(chunk,final){this.ondata(null,chunk,final)};ZipPassThrough.prototype.push=function(chunk,final){if(!this.ondata)err(5);this.c.p(chunk);this.size+=chunk.length;if(final)this.crc=this.c.d();this.process(chunk,final||false)};return ZipPassThrough}();var ZipDeflate=function(){function ZipDeflate(filename,opts){var _this=this;if(!opts)opts={};ZipPassThrough.call(this,filename);this.d=new Deflate(opts,function(dat,final){_this.ondata(null,dat,final)});this.compression=8;this.flag=dbf(opts.level)}ZipDeflate.prototype.process=function(chunk,final){try{this.d.push(chunk,final)}catch(e){this.ondata(e,null,final)}};ZipDeflate.prototype.push=function(chunk,final){ZipPassThrough.prototype.push.call(this,chunk,final)};return ZipDeflate}();var Zip=function(){function Zip(cb){this.ondata=cb;this.u=[];this.d=1}Zip.prototype.add=function(file){var _this=this;if(!this.ondata)err(5);if(this.d&2)this.ondata(err(4+(this.d&1)*8,0,1),null,false);else{var f=strToU8(file.filename),fl_1=f.length;var com=file.comment,o=com&&strToU8(com);var u=fl_1!=file.filename.length||o&&com.length!=o.length;var hl_1=fl_1+exfl(file.extra)+30;if(fl_1>65535)this.ondata(err(11,0,1),null,false);var header=new u8(hl_1);wzh(header,0,file,f,u,-1);var chks_1=[header];var pAll_1=function(){for(var _i=0,chks_2=chks_1;_i<chks_2.length;_i++){var chk=chks_2[_i];_this.ondata(null,chk,false)}chks_1=[]};var tr_1=this.d;this.d=0;var ind_1=this.u.length;var uf_1=mrg(file,{f,u,o,t:function(){if(file.terminate)file.terminate()},r:function(){pAll_1();if(tr_1){var nxt=_this.u[ind_1+1];if(nxt)nxt.r();else _this.d=1}tr_1=1}});var cl_1=0;file.ondata=function(err,dat,final){if(err){_this.ondata(err,dat,final);_this.terminate()}else{cl_1+=dat.length;chks_1.push(dat);if(final){var dd=new u8(16);wbytes(dd,0,134695760);wbytes(dd,4,file.crc);wbytes(dd,8,cl_1);wbytes(dd,12,file.size);chks_1.push(dd);uf_1.c=cl_1,uf_1.b=hl_1+cl_1+16,uf_1.crc=file.crc,uf_1.size=file.size;if(tr_1)uf_1.r();tr_1=1}else if(tr_1)pAll_1()}};this.u.push(uf_1)}};Zip.prototype.end=function(){var _this=this;if(this.d&2){this.ondata(err(4+(this.d&1)*8,0,1),null,true);return}if(this.d)this.e();else this.u.push({r:function(){if(!(_this.d&1))return;_this.u.splice(-1,1);_this.e()},t:function(){}});this.d=3};Zip.prototype.e=function(){var bt=0,l=0,tl=0;for(var _i=0,_a=this.u;_i<_a.length;_i++){var f=_a[_i];tl+=46+f.f.length+exfl(f.extra)+(f.o?f.o.length:0)}var out=new u8(tl+22);for(var _b=0,_c=this.u;_b<_c.length;_b++){var f=_c[_b];wzh(out,bt,f,f.f,f.u,-f.c-2,l,f.o);bt+=46+f.f.length+exfl(f.extra)+(f.o?f.o.length:0),l+=f.b}wzf(out,bt,this.u.length,tl,l);this.ondata(null,out,true);this.d=2};Zip.prototype.terminate=function(){for(var _i=0,_a=this.u;_i<_a.length;_i++){var f=_a[_i];f.t()}this.d=2};return Zip}();var ARCHIVE_MANIFEST_PATH="manifest.json";var ARCHIVE_DEFINITIONS_PATH="definitions.json";var ZIP_MAX_BYTES=2**32-1;var ZIP_MAX_ENTRIES=65535;var LOCAL_HEADER_BYTES=30;var DATA_DESCRIPTOR_BYTES=16;var CENTRAL_RECORD_BYTES=46;var END_RECORD_BYTES=22;var STORED_PREFIX="files/";var DEFLATE_LEVEL=6;var manifestSchema=objectType({files:arrayType(objectType({sha256:stringType(),size:numberType().int().nonnegative()})),units:arrayType(objectType({chunks:arrayType(objectType({number:numberType().int().positive(),size:numberType().int().nonnegative()})),domain:stringType(),unit:stringType()}))});var parseManifest=(text)=>{try{return manifestSchema.parse(JSON.parse(text))}catch(error){throw new TransferClientError({code:"manifest_invalid"},error instanceof Error?{cause:error}:undefined)}};var archivePaths=(manifestJson)=>{const manifest=parseManifest(manifestJson);return[{path:ARCHIVE_MANIFEST_PATH},{path:ARCHIVE_DEFINITIONS_PATH},...manifest.units.flatMap(({chunks,domain,unit})=>chunks.map(({number,size})=>({path:`units/${domain}/${unit}/chunks/${String(number).padStart(6,"0")}.ndjson`,size}))),...manifest.files.map(({sha256,size})=>({path:`${STORED_PREFIX}${sha256}`,size}))]};var chunksOf=async function*chunksOf(content,signal){const reader=(content instanceof Blob?content.stream():content).getReader();let finished=false;try{for(;;){signal?.throwIfAborted();const next=await reader.read();if(next.done){finished=true;return}yield next.value}}finally{if(!finished){await reader.cancel()}reader.releaseLock()}};var sizeChecked=async function*sizeChecked(path,expected,chunks){let actual=0;for await(const chunk of chunks){actual+=chunk.byteLength;if(expected!==undefined&&actual>expected){throw new TransferClientError({actual,code:"size_mismatch",expected,path})}yield chunk}if(expected!==undefined&&actual!==expected){throw new TransferClientError({actual,code:"size_mismatch",expected,path})}};var streamOf=(chunks)=>new ReadableStream({cancel:async()=>{await chunks.return()},pull:async(controller)=>{const next=await chunks.next();if(next.done){controller.close()}else{controller.enqueue(next.value)}}});var concat=(parts)=>{const whole=new Uint8Array(parts.reduce((total,part)=>total+part.byteLength,0));let offset=0;for(const part of parts){whole.set(part,offset);offset+=part.byteLength}return whole};var bytesOf=async(chunks)=>{const parts=[];for await(const chunk of chunks){parts.push(chunk)}return concat(parts)};var memoryEntry=(path,bytes)=>({open:()=>new Blob([bytes]),path,size:bytes.byteLength});var zipLimit=(path)=>new TransferClientError({code:"archive_zip_limit",path});var utf8Length=(text)=>new TextEncoder().encode(text).byteLength;var zipChunks=async function*zipChunks(files,signal){const pending=[];let failure;let written=0;let count=0;let reserved=END_RECORD_BYTES;const zip=new Zip((error,chunk)=>{if(error===null){pending.push(chunk);written+=chunk.byteLength}else{failure=error}});const drain=()=>{if(failure!==undefined){throw failure}return pending.splice(0)};try{for await(const file of files){signal?.throwIfAborted();count+=1;const nameBytes=utf8Length(file.path);reserved+=DATA_DESCRIPTOR_BYTES+CENTRAL_RECORD_BYTES+nameBytes;if(count>ZIP_MAX_ENTRIES||written+LOCAL_HEADER_BYTES+nameBytes+(file.size??0)+reserved>ZIP_MAX_BYTES){throw zipLimit(file.path)}const entry=file.path.startsWith(STORED_PREFIX)?new ZipPassThrough(file.path):new ZipDeflate(file.path,{level:DEFLATE_LEVEL});zip.add(entry);const content=await file.open();for await(const chunk of sizeChecked(file.path,file.size,chunksOf(content,signal))){entry.push(chunk,false);yield*drain();if(written+reserved>ZIP_MAX_BYTES){throw zipLimit(file.path)}}entry.push(new Uint8Array,true);yield*drain();if(written+reserved>ZIP_MAX_BYTES){throw zipLimit(file.path)}}zip.end();yield*drain()}catch(error){zip.terminate();throw error}};var zipArchive=(files,options={})=>streamOf(zipChunks(files,options.signal));var randomAccessOf=(source)=>source instanceof Blob?{read:(start,end)=>source.slice(start,end),size:source.size}:source;var END_SIGNATURE=101010256;var END64_SIGNATURE=101075792;var END64_LOCATOR_SIGNATURE=117853008;var CENTRAL_SIGNATURE=33639248;var LOCAL_SIGNATURE=67324752;var END64_LOCATOR_BYTES=20;var END64_RECORD_BYTES=56;var MAX_COMMENT_BYTES=65535;var MAX_16=65535;var MAX_32=4294967295;var ZIP64_EXTRA_ID=1;var METHOD_STORED=0;var METHOD_DEFLATED=8;var ENCRYPTED_BIT=1;var MAX_DIRECTORY_BYTES=256*2**20;var MAX_INLINE_BYTES=128*2**20;var INFLATE_STEP_BYTES=16*1024;var zipMalformed=(reason)=>new TransferClientError({code:"zip_malformed",reason});var viewOf=(bytes)=>new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);var safeNumber=(value)=>{if(value>BigInt(Number.MAX_SAFE_INTEGER)){throw zipMalformed("an offset or size is too large")}return Number(value)};var readRange=async(zip,start,end,signal)=>{const bytes=await bytesOf(chunksOf(await zip.read(start,end),signal));if(bytes.byteLength!==end-start){throw zipMalformed("the zip ends early")}return bytes};var locateDirectory=async(zip,signal)=>{const tailStart=Math.max(0,zip.size-END_RECORD_BYTES-MAX_COMMENT_BYTES);const tail=await readRange(zip,tailStart,zip.size,signal);const view=viewOf(tail);for(let at=tail.byteLength-END_RECORD_BYTES;at>=0;at-=1){if(view.getUint32(at,true)!==END_SIGNATURE||at+END_RECORD_BYTES+view.getUint16(at+20,true)!==tail.byteLength){continue}const count=view.getUint16(at+10,true);const size=view.getUint32(at+12,true);const offset=view.getUint32(at+16,true);if(count!==MAX_16&&size!==MAX_32&&offset!==MAX_32){return{count,offset,size}}const locatorAt=tailStart+at-END64_LOCATOR_BYTES;if(locatorAt<0){throw zipMalformed("the zip64 locator is missing")}const locator=viewOf(await readRange(zip,locatorAt,locatorAt+END64_LOCATOR_BYTES,signal));if(locator.getUint32(0,true)!==END64_LOCATOR_SIGNATURE){throw zipMalformed("the zip64 locator is missing")}const recordAt=safeNumber(locator.getBigUint64(8,true));const record=viewOf(await readRange(zip,recordAt,recordAt+END64_RECORD_BYTES,signal));if(record.getUint32(0,true)!==END64_SIGNATURE){throw zipMalformed("the zip64 end record is missing")}return{count:safeNumber(record.getBigUint64(32,true)),offset:safeNumber(record.getBigUint64(48,true)),size:safeNumber(record.getBigUint64(40,true))}}throw zipMalformed("this is not a zip")};var decoder4=new TextDecoder;var zip64Fields=(view,extraAt,extraEnd,fields)=>{const result={...fields};for(let at=extraAt;at+4<=extraEnd;){const length=view.getUint16(at+2,true);if(view.getUint16(at,true)===ZIP64_EXTRA_ID){let next=at+4;for(const field of["size","compressedSize","offset"]){if(result[field]===MAX_32){if(next+8>at+4+length){throw zipMalformed("a zip64 extra field is too short")}result[field]=safeNumber(view.getBigUint64(next,true));next+=8}}break}at+=4+length}return result};var readDirectory2=async(zip,signal)=>{const{count,offset,size}=await locateDirectory(zip,signal);if(size>MAX_DIRECTORY_BYTES||offset+size>zip.size){throw zipMalformed("the central directory is out of bounds")}const view=viewOf(await readRange(zip,offset,offset+size,signal));const entries=new Map;const duplicates=new Set;let at=0;for(let index=0;index<count;index+=1){if(at+CENTRAL_RECORD_BYTES>size||view.getUint32(at,true)!==CENTRAL_SIGNATURE){throw zipMalformed("the central directory is damaged")}const nameBytes=view.getUint16(at+28,true);const extraBytes=view.getUint16(at+30,true);const next=at+CENTRAL_RECORD_BYTES+nameBytes+extraBytes+view.getUint16(at+32,true);if(next>size){throw zipMalformed("the central directory is damaged")}if(view.getUint16(at+8,true)%2===ENCRYPTED_BIT){throw zipMalformed("an entry is encrypted")}const nameAt=at+CENTRAL_RECORD_BYTES;const name=decoder4.decode(new Uint8Array(view.buffer,view.byteOffset+nameAt,nameBytes));const fields=zip64Fields(view,nameAt+nameBytes,nameAt+nameBytes+extraBytes,{compressedSize:view.getUint32(at+20,true),offset:view.getUint32(at+42,true),size:view.getUint32(at+24,true)});if(entries.has(name)){duplicates.add(name)}entries.set(name,{...fields,method:view.getUint16(at+10,true)});at=next}return{duplicates,entries}};var entryOf=(directory,path)=>{if(directory.duplicates.has(path)){throw zipMalformed(`the zip has more than one entry named ${path}`)}return directory.entries.get(path)};var dataRange=async(zip,entry,signal)=>{const header=viewOf(await readRange(zip,entry.offset,entry.offset+LOCAL_HEADER_BYTES,signal));if(header.getUint32(0,true)!==LOCAL_SIGNATURE){throw zipMalformed("a local header is damaged")}const start=entry.offset+LOCAL_HEADER_BYTES+header.getUint16(26,true)+header.getUint16(28,true);return{end:start+entry.compressedSize,start}};var inflated=async function*inflated(chunks){const out=[];const inflate=new Inflate((chunk)=>{out.push(chunk)});try{for await(const chunk of chunks){for(let at=0;at<chunk.byteLength;at+=INFLATE_STEP_BYTES){inflate.push(chunk.subarray(at,at+INFLATE_STEP_BYTES));yield*out.splice(0)}}inflate.push(new Uint8Array,true);yield*out.splice(0)}catch(error){throw error instanceof TransferClientError?error:zipMalformed("an entry is not valid deflate data")}};var dataOfEntry=async function*dataOfEntry(zip,entry,path,signal){const{end,start}=await dataRange(zip,entry,signal);if(end>zip.size){throw zipMalformed("the zip ends early")}const raw=chunksOf(await zip.read(start,end),signal);yield*sizeChecked(path,entry.size,entry.method===METHOD_DEFLATED?inflated(raw):raw)};var checkedEntry=(directory,path,expected)=>{const entry=entryOf(directory,path);if(entry===undefined){return}if(entry.method!==METHOD_STORED&&entry.method!==METHOD_DEFLATED){throw zipMalformed(`${path} uses compression method ${entry.method}`)}if(entry.method===METHOD_STORED&&entry.compressedSize!==entry.size){throw zipMalformed(`${path} is stored with two sizes`)}if(expected!==undefined&&entry.size!==expected){throw new TransferClientError({actual:entry.size,code:"size_mismatch",expected,path})}return entry};var wholeEntry=async(zip,entry,path,signal)=>{if(entry.size>MAX_INLINE_BYTES){throw zipMalformed(`${path} is too large to read whole`)}return await bytesOf(dataOfEntry(zip,entry,path,signal))};var readArchiveZip=async function*readArchiveZip(source,options={}){const{signal}=options;const zip=randomAccessOf(source);const directory=await readDirectory2(zip,signal);const manifestEntry=checkedEntry(directory,ARCHIVE_MANIFEST_PATH);if(manifestEntry===undefined){throw new TransferClientError({code:"zip_manifest_missing"})}const manifest=await wholeEntry(zip,manifestEntry,ARCHIVE_MANIFEST_PATH,signal);const listed=archivePaths(decoder4.decode(manifest)).filter(({path})=>path!==ARCHIVE_MANIFEST_PATH).map(({path,size})=>({entry:checkedEntry(directory,path,size),path,size}));const missing=listed.filter(({entry,path})=>entry===undefined&&path!==ARCHIVE_DEFINITIONS_PATH).map(({path})=>path);if(missing.length>0){throw new TransferClientError({code:"zip_incomplete",missing})}yield memoryEntry(ARCHIVE_MANIFEST_PATH,manifest);const definitions=listed.find(({path})=>path===ARCHIVE_DEFINITIONS_PATH)?.entry;if(definitions!==undefined){yield memoryEntry(ARCHIVE_DEFINITIONS_PATH,await wholeEntry(zip,definitions,ARCHIVE_DEFINITIONS_PATH,signal))}const files=listed.flatMap(({entry,path,size})=>entry===undefined||size===undefined?[]:[{entry,path,size}]);for(const{entry,path,size}of files){yield{open:()=>streamOf(dataOfEntry(zip,entry,path,signal)),path,size}}};var isFirst=(path)=>path===ARCHIVE_MANIFEST_PATH||path===ARCHIVE_DEFINITIONS_PATH;var archiveEntriesFromDownloadUrls=(files,options={})=>{const ordered=[...files.filter(({path})=>path===ARCHIVE_MANIFEST_PATH),...files.filter(({path})=>path===ARCHIVE_DEFINITIONS_PATH),...files.filter(({path})=>!isFirst(path))];return ordered.map(({path,size,url})=>{const open=async()=>{const init={};if(options.signal!==undefined){init.signal=options.signal}const response=await(options.fetch??globalThis.fetch)(url,init);if(!response.ok){throw new TransferClientError({code:"download_failed",path,status:response.status})}return response.body??new Blob([])};return size===undefined?{open,path}:{open,path,size}})};var runStatuses=["queued","running","completed","failed","stopped","expired"];var runEventSchema=objectType({createdAt:stringType(),failure:stringType().optional(),kind:enumType(["accepted","started","continued","resumed","cancel_requested","stopped","completed","failed"]),previousPrincipalId:stringType().optional(),previousPrincipalKind:enumType(["user","service_principal"]).optional(),principalId:stringType(),principalKind:enumType(["user","service_principal"]),reason:enumType(["cancelled","authority_lost","crashed"]).optional(),sequence:numberType().int().nonnegative(),status:enumType(runStatuses)});var MAX_RECONNECTS_WITHOUT_PROGRESS2=5;var isRunEventError=(error)=>error instanceof TransferClientError&&error.failure.code==="run_event_invalid";var decodedEvents=async function*decodedEvents(frames){for await(const frame of frames){const decoded=runEventSchema.safeParse(frame);if(!decoded.success){throw new TransferClientError({code:"run_event_invalid"},{cause:decoded.error})}yield decoded.data}};var followTransferRun=async(input)=>{const{organizationId,runId}=input;let cursor=input.afterSequence??0;const known=await getTransferRun({organizationId},runId);if(known!==undefined&&!isTransferRunActive(known)&&cursor>=known.lastEventSequence){return{lastEventId:input.afterSequence===undefined?undefined:String(cursor),reason:"terminal"}}return await followEventStream({connect:async(connection)=>{const response=await organizationTransferEvents({...singleConnectionSseOptions,fetch:eventStreamFetch(client.getConfig().fetch),headers:{...connection.lastEventId===undefined?undefined:{"last-event-id":connection.lastEventId},"x-organization-id":organizationId},path:{runId},signal:connection.signal,throwOnError:true});return decodedEvents(response.stream)},eventId:()=>String(cursor),isRetryableError:(error)=>!isRunEventError(error)&&isRetryableEventStreamError(error),isTerminal:(event)=>!isTransferRunActive(event),...input.afterSequence===undefined?undefined:{lastEventId:String(input.afterSequence)},maxRetries:input.maxRetries??MAX_RECONNECTS_WITHOUT_PROGRESS2,onEvent:async(event)=>{if(event.sequence<=cursor){return}cursor=event.sequence;await input.onEvent(event)},...input.retryDelayMs===undefined?undefined:{initialRetryDelayMs:input.retryDelayMs},...input.signal===undefined?undefined:{signal:input.signal}})};var ALREADY_PRESENT=new Set([409,412]);var bodyInit=(entry,body,headers)=>body instanceof Blob?{body,headers}:{body,duplex:"half",headers:{...headers,"content-length":String(entry.size)}};var archiveIds=new WeakMap;var uploadArchiveIdOf=(error)=>archiveIds.get(error);var uploadFile=async(input,entry)=>{const[signed]=await requestTransferUploadUrls({archiveId:input.archiveId,organizationId:input.organizationId,paths:[entry.path],...input.signal===undefined?undefined:{signal:input.signal}});if(signed===undefined){throw new TransferClientError({code:"upload_failed",path:entry.path,status:0})}const body=await entry.open();const init={...bodyInit(entry,body,signed.headers),method:signed.method};if(input.signal!==undefined){init.signal=input.signal}const response=await(input.fetch??globalThis.fetch)(signed.url,init);await response.body?.cancel();if(response.ok){return{outcome:"uploaded",path:entry.path,size:entry.size}}if(ALREADY_PRESENT.has(response.status)){return{outcome:"skipped",path:entry.path,size:entry.size}}throw new TransferClientError({code:"upload_failed",path:entry.path,status:response.status})};var uploadArchive=async(options)=>{const input={...options,archiveId:options.archiveId??crypto.randomUUID()};const{archiveId,signal}=input;const limit=Math.max(1,input.concurrency??1);const uploaded=[];const skipped=[];const inFlight=new Map;let manifest;let failure;let nextId=0;const attempt=async(id,entry)=>{try{const file=await uploadFile(input,entry);(file.outcome==="uploaded"?uploaded:skipped).push(file.path);input.onFile?.(file);return{id}}catch(error){return{failure:{error},id}}};const finishOne=async()=>{const done=await Promise.race(inFlight.values());inFlight.delete(done.id);return done.failure};for await(const entry of input.entries){if(signal?.aborted===true){failure={error:signal.reason};break}if(entry.path===ARCHIVE_MANIFEST_PATH){manifest=entry;continue}nextId+=1;inFlight.set(nextId,attempt(nextId,entry));if(inFlight.size>=limit){failure=await finishOne()}if(failure!==undefined){break}}const rest=await Promise.all(inFlight.values());failure??=rest.find((done)=>done.failure!==undefined)?.failure;if(failure===undefined&&manifest!==undefined){const{failure:manifestFailure}=await attempt(0,manifest);failure=manifestFailure}if(failure!==undefined){if(failure.error instanceof Error){archiveIds.set(failure.error,archiveId)}throw failure.error}return{archiveId,skipped,uploaded}};import path15 from"path";var plainWord=/^[\w@%+=:,./-]+$/u;var shellWord=(word)=>plainWord.test(word)?word:`'${word.replaceAll("'",String.raw`'\''`)}'`;var commandLine=(words)=>["ci","transfer",...words].map((word)=>shellWord(word)).join(" ");var targetArguments=(args)=>targetOptions.flatMap((name)=>{const flag=`--${name}`;const index=args.indexOf(flag);const value=index===-1?undefined:args[index+1];return value===undefined?[]:[flag,value]});class TransferCommandError extends TaggedError3()("TransferCommandError",{archiveId:optional2(String5),cause:optional2(Unknown2),code:optional2(String5),message:String5,nextAction:optional2(String5),runId:optional2(String5),status:optional2(Finite)}){}var interruptedCode="interrupted";var nonEmptyFields=(fields)=>fields;var domains=["knowledge","documents","datasets"];var boundaryModes=["reference","clear","include_referenced"];var policies=["create_only","skip_existing","update","fill_blanks"];var unresolvedReferences=["fail","continue","skip_item"];var datasetModes=["append","upsert","replace"];var userJoinFields=["email","name","id"];var groupJoinFields=["name","slug","fqn"];var archiveFormats=["zip","folder"];var traverse4=forEach2;var refuse=(message)=>new TransferCommandError({message});var choose=(flag,value,allowed)=>{const found=allowed.find((candidate)=>candidate===value);return found===undefined?fail6(refuse(`${flag} must be one of ${allowed.join(", ")}`)):succeed6(found)};var chooseAll=(flag,value,allowed)=>traverse4(value.split(",").filter((part)=>part!==""),(part)=>choose(flag,part,allowed));var positiveInteger=(flag,value,minimum=1)=>{const number=Number(value);return/^\d+$/u.test(value)&&Number.isSafeInteger(number)&&number>=minimum?succeed6(number):fail6(refuse(`${flag} must be a whole number of ${minimum} or more`))};var optionalPositive=fn2("Transfer.optionalPositive")(function*optionalPositive(options,flag){const value=optionValue2(options,flag);return value===undefined?undefined:yield*positiveInteger(`--${flag}`,value)});var pairOf=(flag,value)=>{const separator=value.indexOf("=");const left=value.slice(0,separator);const right=value.slice(separator+1);return separator>0&&right!==""?succeed6([left,right]):fail6(refuse(`${flag} must be written <left>=<right>`))};var requireValue=(options,flag)=>{const value=optionValue2(options,flag);return value===undefined?fail6(refuse(`Missing required option --${flag}`)):succeed6(value)};var optionError=(flags,message)=>fail6(refuse(`${flags} ${message}`));var exportOptionNames={repeatable:["domain","identity-field"],values:["boundary-mode","depth","format","max-dependency-items","out","run","selection"]};var boundaryOf=fn2("Transfer.boundaryOf")(function*boundaryOf(options){const modeValue=optionValue2(options,"boundary-mode");const mode=modeValue===undefined?undefined:yield*choose("--boundary-mode",modeValue,boundaryModes);const depth=yield*optionalPositive(options,"depth");const maxDependencyItems=yield*optionalPositive(options,"max-dependency-items");const identityFields={};for(const value of optionValues(options,"identity-field")){const[unit,fields]=yield*pairOf("--identity-field",value);identityFields[unit]=fields.split(",").filter((field)=>field!=="")}const boundary={...mode===undefined?undefined:{mode},...depth===undefined?undefined:{depth},...maxDependencyItems===undefined?undefined:{maxDependencyItems},...Object.keys(identityFields).length===0?undefined:{identityFields}};return Object.keys(boundary).length===0?undefined:boundary});var selectionOf=fn2("Transfer.selectionOf")(function*selectionOf(options){const file=optionValue2(options,"selection");const named=optionValues(options,"domain");if(file!==undefined&&named.length>0){return yield*optionError("--selection","already names the domains; do not combine it with --domain")}if(file!==undefined){return{kind:"file",path:file}}const chosen=yield*traverse4(named,(domain)=>choose("--domain",domain,domains));return chosen.length===0?undefined:{domains:[...new Set(chosen)],kind:"domains"}});var downloadOf=fn2("Transfer.downloadOf")(function*downloadOf(options){const out=optionValue2(options,"out");const formatValue=optionValue2(options,"format");if(out===undefined){return formatValue===undefined?undefined:yield*optionError("--format","needs --out")}return{format:formatValue===undefined?"zip":yield*choose("--format",formatValue,archiveFormats),out}});var exportCommand=fn2("Transfer.exportCommand")(function*exportCommand(args){const options=yield*parseCommandOptionsEffect(args,{...exportOptionNames,switches:["preview"],values:[...targetOptions,...exportOptionNames.values]});const download=yield*downloadOf(options);const runId=optionValue2(options,"run");if(runId!==undefined){const selecting=["boundary-mode","depth","domain","identity-field","max-dependency-items","selection"].filter((flag)=>options.values.has(flag));if(options.switches.has("preview")||selecting.length>0){return yield*optionError("--run","downloads a finished Export Run; it takes only --out and --format")}return download===undefined?yield*optionError("--run","needs --out"):{action:"export_download",download,runId}}const input={boundary:yield*boundaryOf(options),selection:yield*selectionOf(options)};if(options.switches.has("preview")){return download===undefined?{action:"export_preview",input}:yield*optionError("--preview","starts no run; do not combine with --out")}return{action:"export",download,input}});var importOptionNames={repeatable:["connector-instance","dataset-mode","force","unit"],switches:["events","no-import-origin"],values:["join-group","join-user","max-errors","policy","unresolved-reference"]};var unitChoiceOf=(value)=>{const separator=value.indexOf(":");const prefix=value.slice(0,separator);const domain=domains.find((candidate)=>candidate===prefix);return domain===undefined||separator+1===value.length?{unit:value}:{domain,unit:value.slice(separator+1)}};var unitsOf=fn2("Transfer.unitsOf")(function*unitsOf(options){const names=[...new Set(optionValues(options,"unit"))];const modes=new Map;for(const value of optionValues(options,"dataset-mode")){const[unit,mode]=yield*pairOf("--dataset-mode",value);modes.set(unit,yield*choose("--dataset-mode",mode,datasetModes))}const forced=new Set(optionValues(options,"force"));for(const unit of[...modes.keys(),...forced]){if(!names.includes(unit)){return yield*optionError(`Unit ${unit}`,"has an option but is not named by --unit; naming a unit limits the import to the listed units")}}return names.map((name)=>{const datasetMode=modes.get(name);return{...unitChoiceOf(name),...datasetMode===undefined?undefined:{datasetMode},...forced.has(name)?{force:true}:undefined}})});var importOptionsOf=fn2("Transfer.importOptionsOf")(function*importOptionsOf(options){const policyValue=optionValue2(options,"policy");const unresolvedValue=optionValue2(options,"unresolved-reference");const userValue=optionValue2(options,"join-user");const groupValue=optionValue2(options,"join-group");const maxErrors=yield*optionalPositive(options,"max-errors");const connectorInstances=yield*traverse4(optionValues(options,"connector-instance"),(value)=>map5(pairOf("--connector-instance",value),([sourceInstanceId,targetInstanceId])=>({sourceInstanceId,targetInstanceId})));const units=yield*unitsOf(options);const user=userValue===undefined?undefined:yield*chooseAll("--join-user",userValue,userJoinFields);const group=groupValue===undefined?undefined:yield*chooseAll("--join-group",groupValue,groupJoinFields);const joinFields={...user===undefined?undefined:{user},...group===undefined?undefined:{group}};const result={...connectorInstances.length===0?undefined:{connectorInstances},...options.switches.has("events")?{events:true}:undefined,...options.switches.has("no-import-origin")?{importOrigin:false}:undefined,...maxErrors===undefined?undefined:{maxErrors},...policyValue===undefined?undefined:{policy:yield*choose("--policy",policyValue,policies)},...units.length===0?undefined:{units},...unresolvedValue===undefined?undefined:{unresolvedReference:yield*choose("--unresolved-reference",unresolvedValue,unresolvedReferences)},...Object.keys(joinFields).length===0?undefined:nonEmptyFields({joinFields})};return Object.keys(result).length===0?undefined:result});var importCommand=fn2("Transfer.importCommand")(function*importCommand(args){const options=yield*parseCommandOptionsEffect(args,{repeatable:importOptionNames.repeatable,switches:[...importOptionNames.switches,"apply","confirm-replace","plan"],values:[...targetOptions,...importOptionNames.values,"archive","archive-id","plan-run"]});const plan=options.switches.has("plan");const apply=options.switches.has("apply");if(plan===apply){return yield*optionError("ci transfer import","needs exactly one of --plan or --apply")}const importOptions=yield*importOptionsOf(options);const archivePath=optionValue2(options,"archive");const archiveId=optionValue2(options,"archive-id");if(plan){if(options.switches.has("confirm-replace")){return yield*optionError("--confirm-replace","belongs to --apply")}if(options.values.has("plan-run")){return yield*optionError("--plan-run","belongs to --apply")}if(archivePath!==undefined){return{action:"import_plan",archive:{archiveId,path:archivePath},options:importOptions}}return archiveId===undefined?yield*optionError("--plan","needs --archive <folder|zip> or --archive-id <id>"):{action:"import_plan",archive:{archiveId,path:undefined},options:importOptions}}if(archivePath!==undefined){return yield*optionError("--archive","belongs to --plan; --apply uses the archive of the Plan run")}return{action:"import_apply",archiveId,confirmReplace:options.switches.has("confirm-replace"),options:importOptions,planRunId:yield*requireValue(options,"plan-run")}});var rollbackCommand=fn2("Transfer.rollbackCommand")(function*rollbackCommand(args){const options=yield*parseCommandOptionsEffect(args,{switches:["force"],values:[...targetOptions,"source-run"]});return{action:"rollback",force:options.switches.has("force"),sourceRunId:yield*requireValue(options,"source-run")}});var runsActions=["cancel","purge","report","resume"];var runsCommand=fn2("Transfer.runsCommand")(function*runsCommand(args){const options=yield*parseCommandOptionsEffect(args,{switches:runsActions,values:[...targetOptions,"limit","run"]});const limit=yield*optionalPositive(options,"limit");const runId=optionValue2(options,"run");const chosen=runsActions.filter((action)=>options.switches.has(action));if(chosen.length>1){return yield*optionError(chosen.map((action)=>`--${action}`).join(" and "),"cannot be combined")}if(runId===undefined){return chosen.length===0?{action:"runs_list",limit}:yield*optionError(`--${chosen[0]??""}`,"needs --run <run-id>")}if(limit!==undefined){return yield*optionError("--limit","only applies to the list of runs")}return{action:"runs_run",run:chosen[0]??"show",runId}});var transferUsage="Usage: ci transfer export|import|rollback|runs";var parseTransferCommand=(args)=>{const[name,...rest]=args;const parsed=(()=>{switch(name){case"export":{return exportCommand(rest)}case"import":{return importCommand(rest)}case"rollback":{return rollbackCommand(rest)}case"runs":{return runsCommand(rest)}default:{return fail6(refuse(transferUsage))}}})();return parsed.pipe(mapError2((cause)=>cause instanceof TransferCommandError?cause:refuse(cause.message)))};var blockedNote=(blocked)=>{switch(blocked){case"write_permission_denied":{return"you may not write this unit in the target Organization."}case"unit_incomplete":{return"the export stopped part-way through this unit, so the archive holds only some of its items. Export it again."}case"unit_ambiguous":{return"the target has more than one collection with this name. Rename one and plan again, or leave the unit out."}default:{return blocked}}};var warningNote=(warning)=>{switch(warning){case"no_match_key_or_origin":{return"it has no Match Key and Import Origin is off, so a rerun creates duplicates."}case"forced_duplicates":{return"it is forced, so its rows are appended again and can duplicate earlier rows."}case"earlier_run_committed":{return"a stopped run of this archive already committed batches of this unit, and this run appends them again. Resume that run instead."}case"already_imported":{return"this archive was already imported into this unit, so the unit is skipped unless you force it."}default:{return warning}}};var planNotes=(plan)=>plan.units.flatMap((unit)=>{const name=`${unit.domain}:${unit.unit}`;return[...unit.blocked===undefined?[]:[`${name} is blocked: ${blockedNote(unit.blocked)}`],...unit.warnings.map((warning)=>`${name} warns: ${warningNote(warning)}`)]});var traverse5=forEach2;var manifestUnits=fromJsonString2(Struct({units:ArraySchema(Struct({domain:Literals(domains),unit:String5}))}));var unitsOfManifest=(manifestJson)=>decodeEffect2(manifestUnits)(manifestJson).pipe(map5(({units})=>units),mapError2((cause)=>new TransferCommandError({cause,code:"manifest_invalid",message:"manifest.json is not a readable archive manifest"})));var written=({domain,unit})=>`${domain}:${unit}`;var domainOf=(choice,known,where)=>{const found=known.filter(({unit})=>unit===choice.unit);const[only]=found;if(found.length===1&&only!==undefined){return succeed6(only.domain)}return fail6(new TransferCommandError({code:"unit_domain_unknown",message:found.length===0?`Unit ${choice.unit} is not in ${where}; the units are ${known.map(written).join(", ")}`:`Unit ${choice.unit} is in several domains of ${where}; write ${found.map(written).join(" or ")}`}))};var withUnitDomains=fn2("Transfer.withUnitDomains")(function*withUnitDomains(options,source){if(options===undefined){return options}const{units:choices,...rest}=options;if(choices===undefined){return rest}const known=choices.some(({domain})=>domain===undefined)?yield*source.units:[];const units=yield*traverse5(choices,(choice)=>choice.domain===undefined?map5(domainOf(choice,known,source.where),(domain)=>({...choice,domain})):succeed6({...choice,domain:choice.domain}));return{...rest,units}});var traverse6=forEach2;var encodeJson4=encodeSync(fromJsonString2(Unknown2));var isClientFailure=is2(Struct({failure:Struct({code:String5}),message:String5,name:Literal2("TransferClientError")}));var describeFailure2=(cause)=>{if(is2(ManagementRequestError)(cause)){return cause}if(is2(TransferCommandError)(cause)){return cause}if(cause instanceof EventStreamHttpError){return new TransferCommandError({cause,message:`The transfer event stream was rejected with HTTP ${cause.status}`,status:cause.status})}if(cause instanceof EventStreamRetriesExhaustedError){return new TransferCommandError({cause,code:"event_stream_lost",message:"The transfer event stream disconnected; the run continues"})}if(isClientFailure(cause)){return new TransferCommandError({cause,code:cause.failure.code,message:cause.message})}return new TransferCommandError({cause,message:cause instanceof Error?cause.message:"Transfer request failed"})};var call2=(operation)=>tryPromise2({catch:describeFailure2,try:operation});var withTransferClient=(context,fetch2)=>(effect)=>acquireUseRelease2(sync2(()=>{const{baseUrl,headers}=context.client.getConfig();const previous=client.getConfig();client.setConfig({...baseUrl===undefined?undefined:{baseUrl},fetch:fetch2,...headers===undefined?undefined:{headers}});const interceptor=client.interceptors.error.use((body,response,request)=>{const reply=response;return reply===undefined?new ManagementRequestError({cause:body,message:"Organization transfer request failed: could not reach the backend",status:0}):requestFailure(`Organization transfer ${request.method} ${new URL(request.url).pathname}`,reply,body)});return{interceptor,previous}}),()=>effect,({interceptor,previous})=>sync2(()=>{client.interceptors.error.eject(interceptor);client.setConfig({...previous.baseUrl===undefined?undefined:{baseUrl:previous.baseUrl},...previous.fetch===undefined?undefined:{fetch:previous.fetch},headers:{authorization:null}})}));var refuse2=(message,extra={})=>new TransferCommandError({...extra,message});var withDetails=(failure,details)=>new TransferCommandError({archiveId:failure.archiveId,cause:failure.cause,code:failure.code,message:failure.message,nextAction:failure.nextAction,runId:failure.runId,status:failure.status,...details});var commandError=(cause)=>{if(is2(TransferCommandError)(cause)){return cause}return new TransferCommandError({cause,message:cause.message,...is2(ManagementRequestError)(cause)?{status:cause.status}:undefined})};var selectionFromFile=fn2("Transfer.selectionFromFile")(function*selectionFromFile(files,file){const text=yield*tryPromise2({catch:(cause)=>new TransferCommandError({cause,message:`Cannot read the selection file ${file}`}),try:()=>files.readText(file)});return yield*decodeEffect2(fromJsonString2(JsonObject))(text).pipe(mapError2((cause)=>new TransferCommandError({cause,message:`${file} is not a JSON object that names a Selection`})))});var exportRequest=fn2("Transfer.exportRequest")(function*exportRequest(input,files){const{selection}=input;const fromFile=selection?.kind==="file"?yield*selectionFromFile(files,selection.path):undefined;const selected=selection?.kind==="domains"?{domains:selection.domains}:fromFile;const request={...input.boundary===undefined?undefined:{boundary:input.boundary},...selected===undefined?undefined:nonEmptyFields({selection:selected})};return request});var findRun=fn2("Transfer.findRun")(function*findRun(scope,runId){const run=yield*call2(()=>getTransferRun(scope,runId));return run===undefined?yield*refuse2(`Run ${runId} not found; check the run id`,{code:"run_not_found"}):run});var requireCompleted=(run,runCommand,newRunCommand)=>{if(run.status==="completed"){return succeed6(run)}const reason=run.stopReason===null?"":` (${run.stopReason})`;const cannotResume=run.status==="stopped"&&run.journalExpiredAt!==null;return fail6(new TransferCommandError({code:`run_${run.status}`,message:`${run.type} run ${run.id} ${run.status}${reason}${cannotResume?"; its journal expired, so it can no longer resume":""}`,nextAction:cannotResume?newRunCommand(run):runCommand(run.id,run.status==="stopped"?"--resume":"--report"),runId:run.id}))};var manifestText=async(archiveFiles)=>{for await(const file of archiveFiles){if(file.path===ARCHIVE_MANIFEST_PATH){return await new Response(await file.open()).text()}}throw new TransferCommandError({code:"archive_incomplete",message:"The archive has no manifest.json"})};var folderOutOfBounds=(file)=>path15.isAbsolute(file)||file.split("/").includes("..");var folderEntries=fn2("Transfer.folderEntries")(function*folderEntries(files,folder){const[listed,manifest]=yield*tryPromise2({catch:describeFailure2,try:()=>Promise.all([files.list(folder),files.readText(path15.join(folder,ARCHIVE_MANIFEST_PATH))])});const wanted=yield*try_2({catch:describeFailure2,try:()=>archivePaths(manifest)});const sizes=new Map(listed.map((file)=>[file.path,file.size]));const missing=wanted.filter((file)=>file.path!==ARCHIVE_DEFINITIONS_PATH&&!sizes.has(file.path));if(missing.length>0){return yield*refuse2(`${folder} lacks ${missing.length} files that manifest.json lists, for example ${missing[0]?.path??""}`,{code:"archive_incomplete"})}return wanted.flatMap(({path:file})=>{const size=sizes.get(file);return size===undefined?[]:[{open:()=>files.openRead(path15.join(folder,file)),path:file,size}]})});var transferCommandEffect=(args,dependencies)=>gen2(function*transferCommand(){const{files,writeOutput}=dependencies;const writeLine=(line)=>{writeOutput(`${encodeJson4(line)}
3249
- `)};const parsed=yield*parseTransferCommand(args);const context=yield*resolveOrganizationContext({args,environment:dependencies.environment,fetch:dependencies.fetch}).pipe(mapError2(commandError));const scope={organizationId:context.organizationId};const{signal}=dependencies;const backendArgs=targetArguments(args);const runCommand=(runId,flag)=>commandLine(["runs","--run",runId,...flag===undefined?[]:[flag],...backendArgs]);const newRunCommand=(stopped)=>{switch(stopped.type){case"export":{return commandLine(["export",...backendArgs])}case"rollback":{return commandLine(["rollback",...stopped.sourceRunId===null?[]:["--source-run",stopped.sourceRunId],...backendArgs])}case"import":{return commandLine(["import","--plan",...stopped.archiveId===null?[]:["--archive-id",stopped.archiveId],...backendArgs])}default:{return stopped.type}}};const interruptible=(operation)=>tryPromise2({catch:(cause)=>signal.aborted?new TransferCommandError({cause,code:interruptedCode,message:"The command was interrupted"}):describeFailure2(cause),try:operation});const finish=fn2("Transfer.finish")(function*finish(started){const followed=yield*interruptible(()=>followTransferRun({onEvent:(event)=>{writeLine({event,kind:"progress",runId:started.id,step:"run"})},organizationId:scope.organizationId,runId:started.id,signal})).pipe(mapError2((cause)=>is2(TransferCommandError)(cause)?withDetails(cause,{nextAction:runCommand(started.id),runId:started.id}):cause));if(followed.reason==="aborted"){return yield*new TransferCommandError({code:interruptedCode,message:`Interrupted; run ${started.id} continues on the backend`,nextAction:runCommand(started.id),runId:started.id})}return yield*requireCompleted(yield*findRun(scope,started.id),runCommand,newRunCommand)});const kindOf=fn2("Transfer.kindOf")(function*kindOf(source){const kind=yield*tryPromise2({catch:describeFailure2,try:()=>files.kind(source)});return kind===null?yield*refuse2(`${source} does not exist`):kind});const retryUpload=(archiveId)=>commandLine([...args,...args.includes("--archive-id")?[]:["--archive-id",archiveId]]);const resumable=(failure)=>{if(!is2(TransferCommandError)(failure)){return failure}const archiveId=failure.cause instanceof Error?uploadArchiveIdOf(failure.cause):undefined;return archiveId===undefined?failure:withDetails(failure,{archiveId,nextAction:retryUpload(archiveId)})};const upload=fn2("Transfer.upload")(function*upload(source,archiveId){const entries=(yield*kindOf(source))==="file"?readArchiveZip(files.seekable(source),{signal}):yield*folderEntries(files,source);yield*interruptible(()=>uploadArchive({archiveId,concurrency:4,entries,fetch:dependencies.fetch,onFile:(file)=>{writeLine({archiveId,kind:"progress",outcome:file.outcome,path:file.path,size:file.size,step:"upload"})},organizationId:scope.organizationId,signal})).pipe(mapError2(resumable))});const download=fn2("Transfer.download")(function*download(runId,archiveId,target){const listed=yield*interruptible(()=>requestTransferDownloadUrls({archiveId,organizationId:scope.organizationId,signal}));writeLine({archiveId,files:listed.length,format:target.format,kind:"progress",out:target.out,step:"download"});const archiveFiles=archiveEntriesFromDownloadUrls(listed,{fetch:dependencies.fetch,signal});const written=target.format==="zip"?interruptible(()=>files.writeStream(target.out,zipArchive(archiveFiles,{signal}))):traverse6(archiveFiles,(file)=>folderOutOfBounds(file.path)?fail6(refuse2(`Archive file ${file.path} points outside the folder`)):interruptible(async()=>{const content=await file.open();await files.writeStream(path15.join(target.out,file.path),content instanceof Blob?content.stream():content)}));yield*written.pipe(mapError2((cause)=>is2(TransferCommandError)(cause)&&cause.code==="archive_zip_limit"?withDetails(cause,{archiveId,nextAction:commandLine(["export","--run",runId,"--out",target.out,"--format","folder",...backendArgs]),runId}):cause))});const exportDownloaded=fn2("Transfer.exportDownloaded")(function*exportDownloaded(run,target){if(target!==undefined&&run.archiveId!==null){yield*download(run.id,run.archiveId,target)}writeLine({archiveId:run.archiveId,kind:"result",...target,run})});const archiveManifest=fn2("Transfer.archiveManifest")(function*archiveManifest(archive){if(archive.path===undefined){return yield*interruptible(async()=>manifestText(archiveEntriesFromDownloadUrls(await requestTransferDownloadUrls({archiveId:archive.archiveId,organizationId:scope.organizationId,signal}),{fetch:dependencies.fetch,signal})))}const source=archive.path;return(yield*kindOf(source))==="directory"?yield*tryPromise2({catch:describeFailure2,try:()=>files.readText(path15.join(source,ARCHIVE_MANIFEST_PATH))}):yield*interruptible(()=>manifestText(readArchiveZip(files.seekable(source),{signal})))});const importPlanned=fn2("Transfer.importPlanned")(function*importPlanned(archive,input){const options=yield*withUnitDomains(input,{units:archiveManifest(archive).pipe(mapError2(commandError),flatMap4(unitsOfManifest)),where:"the archive"});const archiveId=archive.archiveId??dependencies.newArchiveId();if(archive.path!==undefined){yield*upload(archive.path,archiveId)}const run=yield*finish(yield*call2(()=>startTransferImport(scope,{archiveId,mode:"plan",...options===undefined?undefined:{options}})));const planned=transferRunPlan(run);writeLine({archiveId,kind:"result",plan:planned,run});for(const note of planned===undefined?[]:planNotes(planned)){dependencies.writeDiagnostic(`${note}
3250
- `)}});const planUnits=fn2("Transfer.planUnits")(function*planUnits(planRunId){const planned=transferRunPlan(yield*findRun(scope,planRunId));return planned===undefined?yield*refuse2(`Run ${planRunId} has no Plan to take the unit domains from; write each unit as <domain>:<unit>`):planned.units});const importApplied=fn2("Transfer.importApplied")(function*importApplied(apply){const archiveId=apply.archiveId??(yield*findRun(scope,apply.planRunId)).archiveId;if(archiveId===null){return yield*refuse2(`Run ${apply.planRunId} has no archive; pass --archive-id`)}const options=yield*withUnitDomains(apply.options,{units:planUnits(apply.planRunId).pipe(mapError2(commandError)),where:"the Plan"});const request=importApplyRequest({...apply.confirmReplace?{confirmReplace:true}:undefined,plan:{archiveId,mode:"plan",...options===undefined?undefined:{options}},planRunId:apply.planRunId});const run=yield*finish(yield*call2(()=>startTransferImport(scope,request)));writeLine({archiveId,kind:"result",run})});const runsRun=fn2("Transfer.runsRun")(function*runsRun(selected){const{run,runId}=selected;if(run==="report"){writeLine({kind:"result",report:yield*call2(()=>getTransferRunReport(scope,runId))})}else if(run==="purge"){yield*call2(()=>purgeTransferRun(scope,runId));writeLine({kind:"result",purged:runId})}else if(run==="cancel"){writeLine({kind:"result",run:yield*call2(()=>cancelTransferRun(scope,runId))})}else if(run==="resume"){writeLine({kind:"result",run:yield*finish(yield*call2(()=>resumeTransferRun(scope,runId)))})}else{writeLine({kind:"result",run:yield*findRun(scope,runId)})}});yield*gen2(function*selectedCommand(){switch(parsed.action){case"export_preview":{const request=yield*exportRequest(parsed.input,files);writeLine({kind:"result",preview:yield*call2(()=>previewTransferExport(scope,request))});break}case"export":{const request=yield*exportRequest(parsed.input,files);const run=yield*finish(yield*call2(()=>startTransferExport(scope,request)));yield*exportDownloaded(run,parsed.download);break}case"export_download":{const run=yield*findRun(scope,parsed.runId);if(run.type!=="export"||run.archiveId===null){return yield*refuse2(`Run ${run.id} is not a finished Export Run`)}yield*exportDownloaded(yield*requireCompleted(run,runCommand,newRunCommand),parsed.download);break}case"import_plan":{yield*importPlanned(parsed.archive,parsed.options);break}case"import_apply":{yield*importApplied(parsed);break}case"rollback":{const run=yield*finish(yield*call2(()=>startTransferRollback(scope,{...parsed.force?{force:true}:undefined,sourceRunId:parsed.sourceRunId})));writeLine({kind:"result",run});break}case"runs_list":{const list=yield*call2(()=>listTransferRuns(scope,parsed.limit===undefined?{}:{limit:parsed.limit}));writeLine({kind:"result",runs:list.data});break}case"runs_run":{yield*runsRun(parsed);break}default:{return parsed}}}).pipe(withTransferClient(context,dependencies.fetch),catchTag2("ManagementRequestError",explainOrganizationForbidden(context,context.organizationId)))}).pipe(mapError2(commandError));import path16 from"path";class UpgradeCommandError extends TaggedError3()("UpgradeCommandError",{cause:optional2(Unknown2),message:String5}){}var registryUrl="https://registry.npmjs.org";var registryTimeout="30 seconds";var RegistryVersion=Struct({version:String5});var packageManagers=[{globalRoot:["npm","root","-g"],install:["npm","install","-g","--prefer-online"]},{globalRoot:["pnpm","root","-g"],install:["pnpm","add","-g"]}];var bunInstall=["bun","add","-g"];var bunGlobalRoot="/install/global/node_modules/";var latestVersion=(fetch2,name)=>tryPromise2({catch:(cause)=>new UpgradeCommandError({cause,message:`Could not reach ${registryUrl} to read the latest ci version`}),try:async(signal)=>{const response=await fetch2(`${registryUrl}/${name}/latest`,{headers:{accept:"application/json"},signal});return response.ok?await response.json():undefined}}).pipe(timeoutOrElse2({duration:registryTimeout,orElse:()=>fail6(new UpgradeCommandError({message:`${registryUrl} did not respond within ${registryTimeout}`}))}),flatMap4((body)=>is2(RegistryVersion)(body)?succeed6(body.version):fail6(new UpgradeCommandError({message:`${registryUrl} did not return the latest ci version`}))));var runPackageManager=(dependencies,command)=>tryPromise2({catch:(cause)=>new UpgradeCommandError({cause,message:`Could not run ${command.join(" ")}`}),try:async()=>await dependencies.runPackageManager(command)});var globalInstallCommand=fn2("Upgrade.globalInstallCommand")(function*globalInstallCommand(dependencies){const{directory,name}=dependencies.installation;if(directory.replaceAll("\\","/").includes(bunGlobalRoot)){return some2(bunInstall)}for(const manager of packageManagers){const root=yield*option2(runPackageManager(dependencies,manager.globalRoot));if(isSome2(root)&&root.value.exitCode===0&&dependencies.realPath(path16.join(root.value.stdout.trim(),name))===directory){return some2(manager.install)}}return none2()});var upgradeCommandEffect=(args,dependencies)=>gen2(function*upgradeCommand(){yield*parseCommandOptionsEffect(args,{});const{directory,name,version}=dependencies.installation;const latest=yield*latestVersion(dependencies.fetch,name);if(Bun.semver.order(version,latest)>=0){return yield*sync2(()=>{dependencies.writeOutput(`ci ${version} is the latest version
3248
+ `;var contributionKey2=(input)=>JSON.stringify([input.packageFqn,input.contributionHost,input.contributionFqn]);var exposedModule=(key)=>`./${key}`;var randomUuid2=()=>{const bytes=new Uint8Array(16);crypto.getRandomValues(bytes);bytes[6]=bytes[6]%16+64;bytes[8]=bytes[8]%64+128;const hex=[...bytes].map((byte)=>byte.toString(16).padStart(2,"0"));return`${hex.slice(0,4).join("")}-${hex.slice(4,6).join("")}-${hex.slice(6,8).join("")}-${hex.slice(8,10).join("")}-${hex.slice(10).join("")}`};var authorizationPlugin=(input)=>({configureServer(server){server.middlewares.use((request,response,next)=>{const{origin}=request.headers;const{pathname}=new URL(request.url??"/","http://127.0.0.1");const authorized=origin===undefined?pathname.startsWith(input.capabilityBase):input.attachedOrigins.has(origin);if(!authorized){response.writeHead(403,{"content-type":"text/plain"});response.end("Host origin is not attached");return}if(origin!==undefined){response.setHeader("access-control-allow-origin",origin)}response.setHeader("cache-control","no-store");next()})},enforce:"pre",name:"ci-hosted-development-authorization"});var startViteDevelopmentAssetServer=flow((input)=>gen2(function*startAssetServer(){const capability=randomUuid2().replaceAll("-","");const capabilityPath=`__ci_capability__/${capability}/`;const capabilityBase=`/${capabilityPath}`;const attachedOrigins=new Set(input.hostOrigins);const frontendCacheDirectory=yield*promise2(()=>makeTempDirectory2("ci-hosted-vite-"));let frontendEntries=new Map;let frontendServer;let frontendServerPort;const warmFrontendServer=flow((server)=>gen2(function*warmServer(){yield*promise2(()=>server.warmupRequest(`${capabilityBase}remoteEntry.js`));yield*promise2(()=>server.waitForRequestsIdle())}),runNested2);const startFrontendServer=flow((entries,port)=>gen2(function*startFrontendServerEffect(){const exposes=Object.fromEntries([...entries.keys()].map((key)=>[exposedModule(key),`virtual:ci-hosted:${encodeURIComponent(key)}`]));const virtualPrefix="\x00virtual:ci-hosted:";const virtualEntries={load(id){return id.startsWith(virtualPrefix)?entries.get(decodeURIComponent(id.slice(virtualPrefix.length)))?.source??null:null},name:"ci-hosted-development-entries",resolveId(id){return id.startsWith("virtual:ci-hosted:")?`\x00${id}`:null}};const shared=Object.fromEntries(frontendHostProvidedModules.map((moduleName)=>[moduleName,{import:false,singleton:true,suppressMissingImportWarning:true}]));const declarationPath=declarationImport(input.declarationSpecifier);const root=path12.isAbsolute(declarationPath)?path12.dirname(declarationPath):process.cwd();const server=yield*promise2(()=>createServer3({base:capabilityBase,cacheDir:frontendCacheDirectory,configFile:false,logLevel:"silent",optimizeDeps:{entries:[...entries.values()].map((entry)=>entry.importPath),exclude:[...frontendHostProvidedModules]},plugins:[authorizationPlugin({attachedOrigins,capabilityBase}),viteReact(),virtualEntries,federation({dev:{remoteHmr:true},dts:false,exposes,filename:"remoteEntry.js",manifest:false,moduleParseIdleTimeout:1,name:`ci_hosted_${capability}`,shared})],resolve:workspaceSourceResolve(process.execArgv),root,server:{cors:false,headers:{"cache-control":"no-store"},host:"127.0.0.1",port,strictPort:port!==0},ssr:workspaceSourceSsrResolve(process.execArgv)}));yield*promise2(()=>server.listen());yield*promise2(()=>warmFrontendServer(server));return server}),runNested2);const synchronizeFrontendServer=flow((entries)=>gen2(function*synchronizeServer(){const previousKeys=[...frontendEntries.keys()].toSorted();const nextKeys=[...entries.keys()].toSorted();if(previousKeys.length===nextKeys.length&&previousKeys.every((key,index)=>key===nextKeys[index]&&frontendEntries.get(key)?.importPath===entries.get(key)?.importPath)){frontendEntries.clear();for(const[key,source]of entries){frontendEntries.set(key,source)}frontendServer?.moduleGraph.invalidateAll();const server=frontendServer;if(server!==undefined){yield*promise2(()=>warmFrontendServer(server))}return yield*void_3}const previousServer=frontendServer;const port=frontendServerPort??0;frontendServer=undefined;if(previousServer!==undefined){yield*promise2(()=>previousServer.close())}frontendEntries=entries;if(entries.size===0){frontendServerPort=undefined;return yield*void_3}const server=yield*promise2(()=>startFrontendServer(entries,port));frontendServer=server;const localUrl=server.resolvedUrls?.local.at(0);if(localUrl===undefined){yield*promise2(()=>server.close());frontendServer=undefined;throw new Error("Vite did not publish a loopback development URL")}frontendServerPort=Number(new URL(localUrl).port);return yield*void_3}),runNested2);const rebuild=flow((declarations)=>gen2(function*rebuildServer(){const nextFrontendEntries=new Map;for(const definition of declarations){for(const contribution of definition.hostedContributions){if(contribution.manifest.host==="backend"){continue}const key=contributionKey2({contributionFqn:contribution.manifest.fqn,contributionHost:contribution.manifest.host,packageFqn:definition.manifest.fqn});const importPath=resolveHostedContributionEntry(input.declarationSpecifier,{fqn:contribution.manifest.fqn,load:contribution.load});const source=virtualModuleSource({contributionImport:importPath,exportName:contribution.manifest.exportName});nextFrontendEntries.set(key,{importPath,source})}}yield*promise2(()=>synchronizeFrontendServer(nextFrontendEntries))}),runNested2);yield*promise2(()=>rebuild(input.declarations)).pipe(tapError2(()=>promise2(()=>frontendServer?.close().then(()=>null).catch(()=>null)??Promise.resolve(null)).pipe(andThen2(()=>promise2(()=>removeTempDirectory(frontendCacheDirectory))))));return{assetsFor:flow((definition)=>sync2(()=>definition.hostedContributions.flatMap(({manifest})=>{if(manifest.host==="backend"){return[]}const key=contributionKey2({contributionFqn:manifest.fqn,contributionHost:manifest.host,packageFqn:definition.manifest.fqn});const localUrl=frontendServer?.resolvedUrls?.local.at(0);if(localUrl===undefined){throw new Error(`Vite federation remote was not started for ${manifest.fqn}`)}const moduleUrl=new URL("remoteEntry.js",localUrl);moduleUrl.hash=encodeURIComponent(exposedModule(key));return{...manifest.compatibility===undefined?undefined:{compatibility:manifest.compatibility},contract:manifest.contract,exportName:manifest.exportName,fqn:manifest.fqn,host:manifest.host,moduleUrl:moduleUrl.href}})),runNested2),close:flow(()=>gen2(function*closeServer(){const server=frontendServer;if(server!==undefined){yield*promise2(()=>server.close())}yield*promise2(()=>removeTempDirectory(frontendCacheDirectory))}),runPromiseWith2(empty())),rebuild}}),runPromise2);class PackageDiagnosticsCommandError extends TaggedError3()("PackageDiagnosticsCommandError",{cause:optional2(Unknown2),message:String5}){}var requireOption3=(options,name)=>{const value=options.get(name);if(value===undefined||value===""){throw new PackageDiagnosticsCommandError({message:`Missing required option --${name}`})}return value};var parseOptions3=(args)=>{const options=new Map;for(let index=1;index<args.length;index+=2){const flag=args[index];const value=args[index+1];if(!flag?.startsWith("--")||!value||value.startsWith("--")){throw new PackageDiagnosticsCommandError({message:"Options must be supplied as --name value pairs"})}options.set(flag.slice(2),value)}return options};var packageDiagnosticsCommandEffect=(args,dependencies)=>{const[command]=args;if(command!=="trace"){return fail6(new PackageDiagnosticsCommandError({message:"Expected package diagnostics command: trace"}))}return try_2({catch:(cause)=>is2(PackageDiagnosticsCommandError)(cause)?cause:new PackageDiagnosticsCommandError({cause,message:"Could not configure package diagnostics command"}),try:()=>parseOptions3(args)}).pipe(flatMap4((options)=>tryPromise2({catch:(cause)=>new PackageDiagnosticsCommandError({cause,message:"Could not read hosted Extension diagnostic trace"}),try:async()=>{const response=await hostedExtensionDiagnosticsReadTrace({client:dependencies.client,headers:{"x-organization-id":requireOption3(options,"organization")},path:{diagnosticId:requireOption3(options,"diagnostic")},throwOnError:true});return response.data}})))};import{createHash as createHash8}from"crypto";var awaitValue7=(value)=>promise2(constant(Promise.resolve(value)));var path13=runSync2(provide3(Path2,layer5));var readBytesEffect=(readBytes,filePath)=>tryPromise2(flow(()=>suspend2(()=>awaitValue7(readBytes(filePath))),runPromise2));class PackageReleaseCommandError extends TaggedError3()("PackageReleaseCommandError",{cause:optional2(Unknown2),message:String5}){}var requireOption4=(options,name)=>{const value=options.get(name);if(value===undefined||value===""){throw new PackageReleaseCommandError({message:`Missing required option --${name}`})}return value};var supportedOptions=new Set(["archive","backend-url","bundle","idempotency-key","inputs","installation","manifest","organization","package","package-manifest","private-maps","release","scope","version"]);var parseOptions4=(args)=>{const options=new Map;for(let index=1;index<args.length;index+=2){const flag=args[index];const value=args[index+1];if(!flag?.startsWith("--")||!value||value.startsWith("--")){throw new PackageReleaseCommandError({message:"Options must be supplied as --name value pairs"})}if(!supportedOptions.has(flag.slice(2))){throw new PackageReleaseCommandError({message:`Unknown option ${flag}`})}options.set(flag.slice(2),value)}return options};var idempotencyHeaders=(options)=>({"idempotency-key":requireOption4(options,"idempotency-key")});var administratorHeaders=(options)=>({...idempotencyHeaders(options),"x-organization-id":requireOption4(options,"organization")});var rejectRetiredPublishOptions=(options)=>{if(options.has("scope")){throw new PackageReleaseCommandError({message:"--scope is no longer supported; publisher credential scope is authoritative"})}if(options.has("organization")){throw new PackageReleaseCommandError({message:"--organization is no longer supported; publisher credential scope is authoritative"})}if(options.has("package")||options.has("version")){throw new PackageReleaseCommandError({message:"--package and --version are no longer supported; the authoritative release manifest supplies both"})}if(options.has("bundle")){throw new PackageReleaseCommandError({message:"--bundle is no longer supported for publication; use the verified --archive release artifact"})}};var digest3=(bytes)=>createHash8("sha256").update(bytes).digest("hex");var rejectInputs=(message)=>{throw new PackageReleaseCommandError({message})};var readInputs2=async(options,readBytes)=>{const filePath=options.get("inputs");return filePath===undefined?{}:inputsFromFile(await readInputsFile(filePath,rejectInputs,readBytes))};var executePublish=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not publish package release"}),try:async()=>{rejectRetiredPublishOptions(options);const archiveBytes=await dependencies.readBytes(requireOption4(options,"archive"));const manifestPath=requireOption4(options,"manifest");const manifestBytes=await dependencies.readBytes(manifestPath);const packageManifestBytes=await dependencies.readBytes(requireOption4(options,"package-manifest"));const privateMapDirectory=options.has("private-maps")?requireOption4(options,"private-maps"):path13.join(path13.dirname(manifestPath),"private-source-maps");const privateMapFiles=await dependencies.listFiles(privateMapDirectory);const privateSourceMaps=await Promise.all(privateMapFiles.toSorted(compareCanonicalText).map(flow((fileName)=>gen2(function*readPrivateSourceMap(){if(!/^[\da-f]{64}\.map$/u.test(fileName)){return yield*new PackageReleaseCommandError({message:`Private source-map file '${fileName}' is not keyed by a runtime asset digest`})}const bytes=yield*readBytesEffect(dependencies.readBytes,path13.join(privateMapDirectory,fileName));return{bytes,digest:digest3(bytes),runtimeAssetDigest:fileName.slice(0,-4),size:bytes.byteLength}}),runPromise2)));const body=await preparePackagePublication({archiveBytes,manifestBytes,packageManifestBytes,privateSourceMaps});const accepted=await publishPackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key")});return accepted.operationId}});var executePromote=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not promote package release"}),try:async()=>{const body={protocolVersion:"v1",releaseId:requireOption4(options,"release")};const accepted=await promotePackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key")});return accepted.operationId}});var executeUpdate=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not update package installation"}),try:async()=>{const body={...await readInputs2(options,dependencies.readBytes),installationId:requireOption4(options,"installation"),protocolVersion:"v1",releaseId:requireOption4(options,"release")};const accepted=await updatePackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key"),organizationId:requireOption4(options,"organization")});return accepted.operationId}});var executeInstall=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not install package"}),try:async()=>{const releaseId=options.get("release");const body={...releaseId===undefined?undefined:{releaseId},...await readInputs2(options,dependencies.readBytes)};const accepted=await installPackage({...Object.keys(body).length===0?undefined:{body},client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key"),organizationId:requireOption4(options,"organization"),packageFqn:requireOption4(options,"package")});return accepted.operationId}});var executeSync=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not sync package"}),try:async()=>{if(options.has("release")){throw new PackageReleaseCommandError({message:"package sync re-applies the current release and does not accept --release; use package update --release for an exact release"})}const accepted=await extensionPackagesSync({client:dependencies.client,headers:administratorHeaders(options),path:{fqn:requireOption4(options,"package")},throwOnError:true});return accepted.data.operationId}});var executeRollback=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not roll back package installation"}),try:async()=>{const accepted=await packageReleasesRollbackInstallation({body:{installationId:requireOption4(options,"installation"),protocolVersion:"v1",releaseId:requireOption4(options,"release")},client:dependencies.client,headers:administratorHeaders(options),throwOnError:true});return accepted.data.operationId}});var packageReleaseCommandEffect=(args,dependencies)=>{const[command]=args;const options=parseOptions4(args);if(options.has("inputs")&&command!=="install"&&command!=="update"){return fail6(new PackageReleaseCommandError({message:"--inputs is supported only for package install/update"}))}switch(command){case"install":{return executeInstall(options,dependencies)}case"publish":{return executePublish(options,dependencies)}case"promote":{return executePromote(options,dependencies)}case"rollback":{return executeRollback(options,dependencies)}case"sync":{return executeSync(options,dependencies)}case"update":{return executeUpdate(options,dependencies)}default:{return fail6(new PackageReleaseCommandError({message:"Expected one of: package publish, package promote, package install, package update, package sync, package rollback"}))}}};class PackageReleasesCommandError extends TaggedError3()("PackageReleasesCommandError",{cause:optional2(Unknown2),message:String5}){}var requireOption5=(options,name)=>{const value=options.get(name);if(value===undefined||value===""){throw new PackageReleasesCommandError({message:`Missing required option --${name}`})}return value};var parseOptions5=(args)=>{const options=new Map;for(let index=0;index<args.length;index+=2){const flag=args[index];const value=args[index+1];if(!flag?.startsWith("--")||!value||value.startsWith("--")){throw new PackageReleasesCommandError({message:"Options must be supplied as --name value pairs"})}options.set(flag.slice(2),value)}return options};var packageReleasesCommandEffect=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleasesCommandError)(cause)?cause:new PackageReleasesCommandError({cause,message:"Could not list package releases"}),try:async()=>{const parsed=parseOptions5(options);const response=await extensionPackagesListReleases({client:dependencies.client,headers:{"x-organization-id":requireOption5(parsed,"organization")},path:{fqn:requireOption5(parsed,"package")},throwOnError:true});return response.data}});import{mkdir as mkdir4,readdir as readdir3,readFile as readFile6,rename as rename3,rm as rm3,stat as stat4}from"fs/promises";import path14 from"path";var portablePath=(value)=>value.split(path14.sep).join("/");var bunTransferFiles={kind:async(target)=>{try{const found=await stat4(target);return found.isDirectory()?"directory":"file"}catch{return null}},list:async(folder)=>{const entries=await readdir3(folder,{recursive:true,withFileTypes:true});return await Promise.all(entries.filter((entry)=>entry.isFile()).map(async(entry)=>{const file=path14.join(entry.parentPath,entry.name);const found=await stat4(file);return{path:portablePath(path14.relative(folder,file)),size:found.size}}))},openRead:(file)=>Bun.file(file).stream(),readText:async(file)=>await readFile6(file,"utf-8"),seekable:(file)=>Bun.file(file),writeStream:async(file,stream)=>{const partial=`${file}.partial`;await mkdir4(path14.dirname(file),{recursive:true});try{await Bun.write(partial,new Response(stream));await rename3(partial,file)}catch(error){await rm3(partial,{force:true});throw error}}};var messageOf2=(failure)=>{switch(failure.code){case"configuration_json_invalid":{return"The portability configuration is not valid JSON"}case"mapping_pages_changed":{return"The mapping pages changed or repeated; download the result again"}case"archive_zip_limit":{return`Cannot add ${failure.path} to the zip: a zip holds at most 4 GiB and 65535 files. Export to a folder instead.`}case"size_mismatch":{return`Archive file ${failure.path} has ${failure.actual} bytes, expected ${failure.expected}`}case"zip_manifest_missing":{return"The zip has no manifest.json"}case"manifest_invalid":{return"manifest.json is not a readable archive manifest"}case"zip_incomplete":{return`The zip lacks ${failure.missing.length} files that the manifest lists`}case"zip_malformed":{return`The zip cannot be read: ${failure.reason}`}case"download_failed":{return`Download of archive file ${failure.path} failed with HTTP ${failure.status}`}case"upload_failed":{return`Upload of archive file ${failure.path} failed with HTTP ${failure.status}`}case"run_event_invalid":{return"The transfer stream sent a frame that is not a run event"}case"preview_failed":{return`The export preview did not finish: the run is ${failure.status}`}default:{return failure}}};class TransferClientError extends Error{name="TransferClientError";failure;constructor(failure,options){super(messageOf2(failure),options);this.failure=failure}}var organizationHeaders=(scope)=>({"x-organization-id":scope.organizationId});var DEFAULT_RUN_LIMIT=50;var validateTransferConfiguration=async(scope,text,options={})=>{let body;try{body=JSON.parse(text)}catch(error){throw new TransferClientError({code:"configuration_json_invalid"},error instanceof Error?{cause:error}:undefined)}const{data}=await organizationTransferValidateConfiguration({body,headers:organizationHeaders(scope),...options.signal===undefined?undefined:{signal:options.signal},throwOnError:true});return data};var startTransferExport=async(scope,request)=>{const{data}=await organizationTransferExports({body:request,headers:organizationHeaders(scope),throwOnError:true});return data};var startTransferImport=async(scope,request)=>{const{data}=await organizationTransferImports({body:request,headers:organizationHeaders(scope),throwOnError:true});return data};var startTransferRollback=async(scope,request)=>{const{data}=await organizationTransferRollbacks({body:request,headers:organizationHeaders(scope),throwOnError:true});return data};var listTransferRuns=async(scope,options={})=>{const{data}=await organizationTransferRuns({headers:organizationHeaders(scope),query:{limit:String(options.limit??DEFAULT_RUN_LIMIT)},throwOnError:true});return data};var getTransferRun=async(scope,runId)=>{const{data,error,response}=await organizationTransferRun({headers:organizationHeaders(scope),path:{runId}});if(response.status===404){return}if(error!==undefined){throw error}return data};var cancelTransferRun=async(scope,runId)=>{const{data}=await organizationTransferCancel({headers:organizationHeaders(scope),path:{runId},throwOnError:true});return data};var resumeTransferRun=async(scope,runId)=>{const{data}=await organizationTransferResume({headers:organizationHeaders(scope),path:{runId},throwOnError:true});return data};var purgeTransferRun=async(scope,runId)=>{await organizationTransferPurge({headers:organizationHeaders(scope),path:{runId},throwOnError:true})};var getTransferRunReport=async(scope,runId)=>{const{data}=await organizationTransferReport({headers:organizationHeaders(scope),path:{runId},throwOnError:true});return data};var getTransferMappings=async(scope,runId,options={})=>{const{data}=await organizationTransferMappings({headers:organizationHeaders(scope),path:{runId},query:{...options.cursor===undefined?undefined:{cursor:options.cursor},...options.limit===undefined?undefined:{limit:String(options.limit)}},...options.signal===undefined?undefined:{signal:options.signal},throwOnError:true});return data};var downloadTransferMappings=async(scope,runId,options={})=>{const first=await getTransferMappings(scope,runId,options);const mappings=[...first.mappings];const visited=new Set;let cursor=first.nextCursor;while(cursor!==null){options.signal?.throwIfAborted();visited.add(cursor);const page=await getTransferMappings(scope,runId,{...options,cursor});if(page.configurationHash!==first.configurationHash||page.nextCursor!==null&&visited.has(page.nextCursor)){throw new TransferClientError({code:"mapping_pages_changed"})}mappings.push(...page.mappings);cursor=page.nextCursor}return{...first,mappings,nextCursor:null}};var requestTransferDownloadUrls=async(input)=>{const{data}=await organizationTransferDownloadUrls({headers:organizationHeaders(input),path:{archiveId:input.archiveId},...input.signal===undefined?undefined:{signal:input.signal},throwOnError:true});return data.files};var requestTransferUploadUrls=async(input)=>{const{data}=await organizationTransferUploadUrls({body:{paths:[...input.paths]},headers:organizationHeaders(input),path:{archiveId:input.archiveId},...input.signal===undefined?undefined:{signal:input.signal},throwOnError:true});return data.urls};var transferRunPlan=(run)=>run.counts.plan;var importApplyRequest=(input)=>{const request={archiveId:input.plan.archiveId,mode:"apply",planRunId:input.planRunId};if(input.confirmReplace!==undefined){request.confirmReplace=input.confirmReplace}if(input.plan.options!==undefined){request.options=input.plan.options}return request};var isTransferRunActive=(run)=>run.status==="queued"||run.status==="running";var PREVIEW_POLL_MS=500;var PREVIEW_MAX_POLL_MS=5000;var wait=async(ms,signal)=>{signal?.throwIfAborted();await new Promise((resolve,reject)=>{const settled=new AbortController;const timer=globalThis.setTimeout(()=>{settled.abort();resolve()},ms);signal?.addEventListener("abort",()=>{globalThis.clearTimeout(timer);reject(signal.reason)},{once:true,signal:settled.signal})})};var previewTransferExport=async(scope,request,options={})=>{const{data:accepted}=await organizationTransferPreview({body:request,headers:organizationHeaders(scope),throwOnError:true});let run=accepted;let delay=options.pollIntervalMs??PREVIEW_POLL_MS;while(run!==undefined&&isTransferRunActive(run)){await wait(delay,options.signal);delay=Math.min(delay*2,PREVIEW_MAX_POLL_MS);run=await getTransferRun(scope,accepted.id)}const preview=run?.counts.preview;if(run?.status!=="completed"||preview===undefined){throw new TransferClientError({code:"preview_failed",status:run?.status??"missing"})}return preview};import{createRequire as createRequire4}from"module";var require2=createRequire4("/");var _a;var Worker;var isMarkedAsUntransferable;try{_a=require2("worker_threads"),Worker=_a.Worker,isMarkedAsUntransferable=_a.isMarkedAsUntransferable}catch(e){}var u8=Uint8Array;var u16=Uint16Array;var i32=Int32Array;var fleb=new u8([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]);var fdeb=new u8([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]);var clim=new u8([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);var freb=function(eb,start){var b=new u16(31);for(var i=0;i<31;++i){b[i]=start+=1<<eb[i-1]}var r=new i32(b[30]);for(var i=1;i<30;++i){for(var j=b[i];j<b[i+1];++j){r[j]=j-b[i]<<5|i}}return{b,r}};var _a=freb(fleb,2);var fl=_a.b;var revfl=_a.r;fl[28]=258,revfl[258]=28;var _b=freb(fdeb,0);var fd=_b.b;var revfd=_b.r;var rev=new u16(32768);for(i2=0;i2<32768;++i2){x=(i2&43690)>>1|(i2&21845)<<1;x=(x&52428)>>2|(x&13107)<<2;x=(x&61680)>>4|(x&3855)<<4;rev[i2]=((x&65280)>>8|(x&255)<<8)>>1}var x;var i2;var hMap=function(cd,mb,r){var s=cd.length;var i=0;var l=new u16(mb);for(;i<s;++i){if(cd[i])++l[cd[i]-1]}var le=new u16(mb);for(i=1;i<mb;++i){le[i]=le[i-1]+l[i-1]<<1}var co;if(r){co=new u16(1<<mb);var rvb=15-mb;for(i=0;i<s;++i){if(cd[i]){var sv=i<<4|cd[i];var r_1=mb-cd[i];var v=le[cd[i]-1]++<<r_1;for(var m=v|(1<<r_1)-1;v<=m;++v){co[rev[v]>>rvb]=sv}}}}else{co=new u16(s);for(i=0;i<s;++i){if(cd[i]){co[i]=rev[le[cd[i]-1]++]>>15-cd[i]}}}return co};var flt=new u8(288);for(i2=0;i2<144;++i2)flt[i2]=8;var i2;for(i2=144;i2<256;++i2)flt[i2]=9;var i2;for(i2=256;i2<280;++i2)flt[i2]=7;var i2;for(i2=280;i2<288;++i2)flt[i2]=8;var i2;var fdt=new u8(32);for(i2=0;i2<32;++i2)fdt[i2]=5;var i2;var flm=hMap(flt,9,0);var flrm=hMap(flt,9,1);var fdm=hMap(fdt,5,0);var fdrm=hMap(fdt,5,1);var max=function(a){var m=a[0];for(var i=1;i<a.length;++i){if(a[i]>m)m=a[i]}return m};var bits=function(d,p,m){var o=p/8|0;return(d[o]|d[o+1]<<8)>>(p&7)&m};var bits16=function(d,p){var o=p/8|0;return(d[o]|d[o+1]<<8|d[o+2]<<16)>>(p&7)};var shft=function(p){return(p+7)/8|0};var slc=function(v,s,e){if(s==null||s<0)s=0;if(e==null||e>v.length)e=v.length;return new u8(v.subarray(s,e))};var ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"];var err=function(ind,msg,nt){var e=new Error(msg||ec[ind]);e.code=ind;if(Error.captureStackTrace)Error.captureStackTrace(e,err);if(!nt)throw e;return e};var inflt=function(dat,st,buf,dict){var sl=dat.length,dl=dict?dict.length:0;if(!sl||st.f&&!st.l)return buf||new u8(0);var noBuf=!buf;var resize=noBuf||st.i!=2;var noSt=st.i;if(noBuf)buf=new u8(sl*3);var cbuf=function(l){var bl=buf.length;if(l>bl){var nbuf=new u8(Math.max(bl*2,l));nbuf.set(buf);buf=nbuf}};var final=st.f||0,pos=st.p||0,bt=st.b||0,{l:lm,d:dm,m:lbt,n:dbt}=st;var tbts=sl*8;do{if(!lm){final=bits(dat,pos,1);var type=bits(dat,pos+1,3);pos+=3;if(!type){var s=shft(pos)+4,l=dat[s-4]|dat[s-3]<<8,t=s+l;if(t>sl){if(noSt)err(0);break}if(resize)cbuf(bt+l);buf.set(dat.subarray(s,t),bt);st.b=bt+=l,st.p=pos=t*8,st.f=final;continue}else if(type==1)lm=flrm,dm=fdrm,lbt=9,dbt=5;else if(type==2){var hLit=bits(dat,pos,31)+257,hcLen=bits(dat,pos+10,15)+4;var tl=hLit+bits(dat,pos+5,31)+1;pos+=14;var ldt=new u8(tl);var clt=new u8(19);for(var i=0;i<hcLen;++i){clt[clim[i]]=bits(dat,pos+i*3,7)}pos+=hcLen*3;var clb=max(clt),clbmsk=(1<<clb)-1;var clm=hMap(clt,clb,1);for(var i=0;i<tl;){var r=clm[bits(dat,pos,clbmsk)];pos+=r&15;var s=r>>4;if(s<16){ldt[i++]=s}else{var c=0,n=0;if(s==16)n=3+bits(dat,pos,3),pos+=2,c=ldt[i-1];else if(s==17)n=3+bits(dat,pos,7),pos+=3;else if(s==18)n=11+bits(dat,pos,127),pos+=7;while(n--)ldt[i++]=c}}var lt=ldt.subarray(0,hLit),dt=ldt.subarray(hLit);lbt=max(lt);dbt=max(dt);lm=hMap(lt,lbt,1);dm=hMap(dt,dbt,1)}else err(1);if(pos>tbts){if(noSt)err(0);break}}if(resize)cbuf(bt+131072);var lms=(1<<lbt)-1,dms=(1<<dbt)-1;var lpos=pos;for(;;lpos=pos){var c=lm[bits16(dat,pos)&lms],sym=c>>4;pos+=c&15;if(pos>tbts){if(noSt)err(0);break}if(!c)err(2);if(sym<256)buf[bt++]=sym;else if(sym==256){lpos=pos,lm=null;break}else{var add=sym-254;if(sym>264){var i=sym-257,b=fleb[i];add=bits(dat,pos,(1<<b)-1)+fl[i];pos+=b}var d=dm[bits16(dat,pos)&dms],dsym=d>>4;if(!d)err(3);pos+=d&15;var dt=fd[dsym];if(dsym>3){var b=fdeb[dsym];dt+=bits16(dat,pos)&(1<<b)-1,pos+=b}if(pos>tbts){if(noSt)err(0);break}if(resize)cbuf(bt+131072);var end=bt+add;if(bt<dt){var shift=dl-dt,dend=Math.min(dt,end);if(shift+bt<0)err(3);for(;bt<dend;++bt)buf[bt]=dict[shift+bt]}for(;bt<end;++bt)buf[bt]=buf[bt-dt]}}st.l=lm,st.p=lpos,st.b=bt,st.f=final;if(lm)final=1,st.m=lbt,st.d=dm,st.n=dbt}while(!final);return bt!=buf.length&&noBuf?slc(buf,0,bt):buf.subarray(0,bt)};var wbits=function(d,p,v){v<<=p&7;var o=p/8|0;d[o]|=v;d[o+1]|=v>>8};var wbits16=function(d,p,v){v<<=p&7;var o=p/8|0;d[o]|=v;d[o+1]|=v>>8;d[o+2]|=v>>16};var hTree=function(d,mb){var t=[];for(var i=0;i<d.length;++i){if(d[i])t.push({s:i,f:d[i]})}var s=t.length;var t2=t.slice();if(!s)return{t:et,l:0};if(s==1){var v=new u8(t[0].s+1);v[t[0].s]=1;return{t:v,l:1}}t.sort(function(a,b){return a.f-b.f});t.push({s:-1,f:25001});var l=t[0],r=t[1],i0=0,i1=1,i2=2;t[0]={s:-1,f:l.f+r.f,l,r};while(i1!=s-1){l=t[t[i0].f<t[i2].f?i0++:i2++];r=t[i0!=i1&&t[i0].f<t[i2].f?i0++:i2++];t[i1++]={s:-1,f:l.f+r.f,l,r}}var maxSym=t2[0].s;for(var i=1;i<s;++i){if(t2[i].s>maxSym)maxSym=t2[i].s}var tr=new u16(maxSym+1);var mbt=ln(t[i1-1],tr,0);if(mbt>mb){var i=0,dt=0;var lft=mbt-mb,cst=1<<lft;t2.sort(function(a,b){return tr[b.s]-tr[a.s]||a.f-b.f});for(;i<s;++i){var i2_1=t2[i].s;if(tr[i2_1]>mb){dt+=cst-(1<<mbt-tr[i2_1]);tr[i2_1]=mb}else break}dt>>=lft;while(dt>0){var i2_2=t2[i].s;if(tr[i2_2]<mb)dt-=1<<mb-tr[i2_2]++-1;else++i}for(;i>=0&&dt;--i){var i2_3=t2[i].s;if(tr[i2_3]==mb){--tr[i2_3];++dt}}mbt=mb}return{t:new u8(tr),l:mbt}};var ln=function(n,l,d){return n.s==-1?Math.max(ln(n.l,l,d+1),ln(n.r,l,d+1)):l[n.s]=d};var lc=function(c){var s=c.length;while(s&&!c[--s]);var cl=new u16(++s);var cli=0,cln=c[0],cls=1;var w=function(v){cl[cli++]=v};for(var i=1;i<=s;++i){if(c[i]==cln&&i!=s)++cls;else{if(!cln&&cls>2){for(;cls>138;cls-=138)w(32754);if(cls>2){w(cls>10?cls-11<<5|28690:cls-3<<5|12305);cls=0}}else if(cls>3){w(cln),--cls;for(;cls>6;cls-=6)w(8304);if(cls>2)w(cls-3<<5|8208),cls=0}while(cls--)w(cln);cls=1;cln=c[i]}}return{c:cl.subarray(0,cli),n:s}};var clen=function(cf,cl){var l=0;for(var i=0;i<cl.length;++i)l+=cf[i]*cl[i];return l};var wfblk=function(out,pos,dat){var s=dat.length;var o=shft(pos+2);out[o]=s&255;out[o+1]=s>>8;out[o+2]=out[o]^255;out[o+3]=out[o+1]^255;for(var i=0;i<s;++i)out[o+i+4]=dat[i];return(o+4+s)*8};var wblk=function(dat,out,final,syms,lf,df,eb,li,bs,bl,p){wbits(out,p++,final);++lf[256];var _a=hTree(lf,15),{t:dlt,l:mlb}=_a;var _b=hTree(df,15),{t:ddt,l:mdb}=_b;var _c=lc(dlt),{c:lclt,n:nlc}=_c;var _d=lc(ddt),{c:lcdt,n:ndc}=_d;var lcfreq=new u16(19);for(var i=0;i<lclt.length;++i)++lcfreq[lclt[i]&31];for(var i=0;i<lcdt.length;++i)++lcfreq[lcdt[i]&31];var _e=hTree(lcfreq,7),{t:lct,l:mlcb}=_e;var nlcc=19;for(;nlcc>4&&!lct[clim[nlcc-1]];--nlcc);var flen=bl+5<<3;var ftlen=clen(lf,flt)+clen(df,fdt)+eb;var dtlen=clen(lf,dlt)+clen(df,ddt)+eb+14+3*nlcc+clen(lcfreq,lct)+2*lcfreq[16]+3*lcfreq[17]+7*lcfreq[18];if(bs>=0&&flen<=ftlen&&flen<=dtlen)return wfblk(out,p,dat.subarray(bs,bs+bl));var lm,ll,dm,dl;wbits(out,p,1+(dtlen<ftlen)),p+=2;if(dtlen<ftlen){lm=hMap(dlt,mlb,0),ll=dlt,dm=hMap(ddt,mdb,0),dl=ddt;var llm=hMap(lct,mlcb,0);wbits(out,p,nlc-257);wbits(out,p+5,ndc-1);wbits(out,p+10,nlcc-4);p+=14;for(var i=0;i<nlcc;++i)wbits(out,p+3*i,lct[clim[i]]);p+=3*nlcc;var lcts=[lclt,lcdt];for(var it=0;it<2;++it){var clct=lcts[it];for(var i=0;i<clct.length;++i){var len=clct[i]&31;wbits(out,p,llm[len]),p+=lct[len];if(len>15)wbits(out,p,clct[i]>>5&127),p+=clct[i]>>12}}}else{lm=flm,ll=flt,dm=fdm,dl=fdt}for(var i=0;i<li;++i){var sym=syms[i];if(sym>255){var len=sym>>18&31;wbits16(out,p,lm[len+257]),p+=ll[len+257];if(len>7)wbits(out,p,sym>>23&31),p+=fleb[len];var dst=sym&31;wbits16(out,p,dm[dst]),p+=dl[dst];if(dst>3)wbits16(out,p,sym>>5&8191),p+=fdeb[dst]}else{wbits16(out,p,lm[sym]),p+=ll[sym]}}wbits16(out,p,lm[256]);return p+ll[256]};var deo=new i32([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]);var et=new u8(0);var dflt=function(dat,lvl,plvl,pre,post,st){var s=st.z||dat.length;var o=new u8(pre+s+5*(1+Math.ceil(s/7000))+post);var w=o.subarray(pre,o.length-post);var lst=st.l;var pos=(st.r||0)&7;if(lvl){if(pos)w[0]=st.r>>3;var opt=deo[lvl-1];var n=opt>>13,c=opt&8191;var msk_1=(1<<plvl)-1;var prev=st.p||new u16(32768),head=st.h||new u16(msk_1+1);var bs1_1=Math.ceil(plvl/3),bs2_1=2*bs1_1;var hsh=function(i){return(dat[i]^dat[i+1]<<bs1_1^dat[i+2]<<bs2_1)&msk_1};var syms=new i32(25000);var lf=new u16(288),df=new u16(32);var lc_1=0,eb=0,i=st.i||0,li=0,wi=st.w||0,bs=0;for(;i+2<s;++i){var hv=hsh(i);var imod=i&32767,pimod=head[hv];prev[imod]=pimod;head[hv]=imod;if(wi<=i){var rem=s-i;if((lc_1>7000||li>24576)&&(rem>423||!lst)){pos=wblk(dat,w,0,syms,lf,df,eb,li,bs,i-bs,pos);li=lc_1=eb=0,bs=i;for(var j=0;j<286;++j)lf[j]=0;for(var j=0;j<30;++j)df[j]=0}var l=2,d=0,ch_1=c,dif=imod-pimod&32767;if(rem>2&&hv==hsh(i-dif)){var maxn=Math.min(n,rem)-1;var maxd=Math.min(32767,i);var ml=Math.min(258,rem);while(dif<=maxd&&--ch_1&&imod!=pimod){if(dat[i+l]==dat[i+l-dif]){var nl=0;for(;nl<ml&&dat[i+nl]==dat[i+nl-dif];++nl);if(nl>l){l=nl,d=dif;if(nl>maxn)break;var mmd=Math.min(dif,nl-2);var md=0;for(var j=0;j<mmd;++j){var ti=i-dif+j&32767;var pti=prev[ti];var cd=ti-pti&32767;if(cd>md)md=cd,pimod=ti}}}imod=pimod,pimod=prev[imod];dif+=imod-pimod&32767}}if(d){syms[li++]=268435456|revfl[l]<<18|revfd[d];var lin=revfl[l]&31,din=revfd[d]&31;eb+=fleb[lin]+fdeb[din];++lf[257+lin];++df[din];wi=i+l;++lc_1}else{syms[li++]=dat[i];++lf[dat[i]]}}}for(i=Math.max(i,wi);i<s;++i){syms[li++]=dat[i];++lf[dat[i]]}pos=wblk(dat,w,lst,syms,lf,df,eb,li,bs,i-bs,pos);if(!lst){st.r=pos&7|w[pos/8|0]<<3;pos-=7;st.h=head,st.p=prev,st.i=i,st.w=wi}}else{for(var i=st.w||0;i<s+lst;i+=65535){var e=i+65535;if(e>=s){w[pos/8|0]=lst;e=s}pos=wfblk(w,pos+1,dat.subarray(i,e))}st.i=s}return slc(o,0,pre+shft(pos)+post)};var crct=function(){var t=new Int32Array(256);for(var i=0;i<256;++i){var c=i,k=9;while(--k)c=(c&1&&-306674912)^c>>>1;t[i]=c}return t}();var crc=function(){var c=-1;return{p:function(d){var cr=c;for(var i=0;i<d.length;++i)cr=crct[cr&255^d[i]]^cr>>>8;c=cr},d:function(){return~c}}};var dopt=function(dat,opt,pre,post,st){if(!st){st={l:1};if(opt.dictionary){var dict=opt.dictionary.subarray(-32768);var newDat=new u8(dict.length+dat.length);newDat.set(dict);newDat.set(dat,dict.length);dat=newDat;st.w=dict.length}}return dflt(dat,opt.level==null?6:opt.level,opt.mem==null?st.l?Math.ceil(Math.max(8,Math.min(13,Math.log(dat.length)))*1.5):20:12+opt.mem,pre,post,st)};var mrg=function(a,b){var o={};for(var k in a)o[k]=a[k];for(var k in b)o[k]=b[k];return o};var wbytes=function(d,b,v){for(;v;++b)d[b]=v,v>>>=8};var Deflate=function(){function Deflate(opts,cb){if(typeof opts=="function")cb=opts,opts={};this.ondata=cb;this.o=opts||{};this.s={l:0,i:32768,w:32768,z:32768};this.b=new u8(98304);if(this.o.dictionary){var dict=this.o.dictionary.subarray(-32768);this.b.set(dict,32768-dict.length);this.s.i=32768-dict.length}}Deflate.prototype.p=function(c,f){this.ondata(dopt(c,this.o,0,0,this.s),f)};Deflate.prototype.push=function(chunk,final){if(!this.ondata)err(5);if(this.s.l)err(4);var endLen=chunk.length+this.s.z;if(endLen>this.b.length){if(endLen>2*this.b.length-32768){var newBuf=new u8(endLen&-32768);newBuf.set(this.b.subarray(0,this.s.z));this.b=newBuf}var split=this.b.length-this.s.z;this.b.set(chunk.subarray(0,split),this.s.z);this.s.z=this.b.length;this.p(this.b,false);this.b.set(this.b.subarray(-32768));this.b.set(chunk.subarray(split),32768);this.s.z=chunk.length-split+32768;this.s.i=32766,this.s.w=32768}else{this.b.set(chunk,this.s.z);this.s.z+=chunk.length}this.s.l=final&1;if(this.s.z>this.s.w+8191||final){this.p(this.b,final||false);this.s.w=this.s.i,this.s.i-=2}if(final){this.s=this.o={};this.b=et}};Deflate.prototype.flush=function(sync){if(!this.ondata)err(5);if(this.s.l)err(4);this.p(this.b,false);this.s.w=this.s.i,this.s.i-=2;if(sync){var c=new u8(6);c[0]=this.s.r>>3;var ep=wfblk(c,this.s.r,et);this.s.r=0;this.ondata(c.subarray(0,ep>>3),false)}};return Deflate}();var Inflate=function(){function Inflate(opts,cb){if(typeof opts=="function")cb=opts,opts={};this.ondata=cb;var dict=opts&&opts.dictionary&&opts.dictionary.subarray(-32768);this.s={i:0,b:dict?dict.length:0};this.o=new u8(32768);this.p=new u8(0);if(dict)this.o.set(dict)}Inflate.prototype.e=function(c){if(!this.ondata)err(5);if(this.d)err(4);if(!this.p.length)this.p=c;else if(c.length){var n=new u8(this.p.length+c.length);n.set(this.p),n.set(c,this.p.length),this.p=n}};Inflate.prototype.c=function(final){this.s.i=+(this.d=final||false);var bts=this.s.b;var dt=inflt(this.p,this.s,this.o);this.ondata(slc(dt,bts,this.s.b),this.d);this.o=slc(dt,this.s.b-32768),this.s.b=this.o.length;this.p=slc(this.p,this.s.p/8|0),this.s.p&=7};Inflate.prototype.push=function(chunk,final){this.e(chunk),this.c(final)};return Inflate}();var te=typeof TextEncoder!="undefined"&&new TextEncoder;var td2=typeof TextDecoder!="undefined"&&new TextDecoder;var tds=0;try{td2.decode(et,{stream:true});tds=1}catch(e){}function strToU8(str,latin1){if(latin1){var ar_1=new u8(str.length);for(var i=0;i<str.length;++i)ar_1[i]=str.charCodeAt(i);return ar_1}if(te)return te.encode(str);var l=str.length;var ar=new u8(str.length+(str.length>>1));var ai=0;var w=function(v){ar[ai++]=v};for(var i=0;i<l;++i){if(ai+5>ar.length){var n=new u8(ai+8+(l-i<<1));n.set(ar);ar=n}var c=str.charCodeAt(i);if(c<128||latin1)w(c);else if(c<2048)w(192|c>>6),w(128|c&63);else if(c>55295&&c<57344)c=65536+(c&1023<<10)|str.charCodeAt(++i)&1023,w(240|c>>18),w(128|c>>12&63),w(128|c>>6&63),w(128|c&63);else w(224|c>>12),w(128|c>>6&63),w(128|c&63)}return slc(ar,0,ai)}var dbf=function(l){return l==1?3:l<6?2:l==9?1:0};var exfl=function(ex){var le=0;if(ex){for(var k in ex){var l=ex[k].length;if(l>65535)err(9);le+=l+4}}return le};var wzh=function(d,b,f,fn,u,c,ce,co){var fl=fn.length,ex=f.extra,col=co&&co.length;var exl=exfl(ex);wbytes(d,b,ce!=null?33639248:67324752),b+=4;if(ce!=null)d[b++]=20,d[b++]=f.os;d[b]=20,b+=2;d[b++]=f.flag<<1|(c<0&&8),d[b++]=u&&8;d[b++]=f.compression&255,d[b++]=f.compression>>8;var dt=new Date(f.mtime==null?Date.now():f.mtime),y=dt.getFullYear()-1980;if(y<0||y>119)err(10);wbytes(d,b,y<<25|dt.getMonth()+1<<21|dt.getDate()<<16|dt.getHours()<<11|dt.getMinutes()<<5|dt.getSeconds()>>1),b+=4;if(c!=-1){wbytes(d,b,f.crc);wbytes(d,b+4,c<0?-c-2:c);wbytes(d,b+8,f.size)}wbytes(d,b+12,fl);wbytes(d,b+14,exl),b+=16;if(ce!=null){wbytes(d,b,col);wbytes(d,b+6,f.attrs);wbytes(d,b+10,ce),b+=14}d.set(fn,b);b+=fl;if(exl){for(var k in ex){var exf=ex[k],l=exf.length;wbytes(d,b,+k);wbytes(d,b+2,l);d.set(exf,b+4),b+=4+l}}if(col)d.set(co,b),b+=col;return b};var wzf=function(o,b,c,d,e){wbytes(o,b,101010256);wbytes(o,b+8,c);wbytes(o,b+10,c);wbytes(o,b+12,d);wbytes(o,b+16,e)};var ZipPassThrough=function(){function ZipPassThrough(filename){this.filename=filename;this.c=crc();this.size=0;this.compression=0}ZipPassThrough.prototype.process=function(chunk,final){this.ondata(null,chunk,final)};ZipPassThrough.prototype.push=function(chunk,final){if(!this.ondata)err(5);this.c.p(chunk);this.size+=chunk.length;if(final)this.crc=this.c.d();this.process(chunk,final||false)};return ZipPassThrough}();var ZipDeflate=function(){function ZipDeflate(filename,opts){var _this=this;if(!opts)opts={};ZipPassThrough.call(this,filename);this.d=new Deflate(opts,function(dat,final){_this.ondata(null,dat,final)});this.compression=8;this.flag=dbf(opts.level)}ZipDeflate.prototype.process=function(chunk,final){try{this.d.push(chunk,final)}catch(e){this.ondata(e,null,final)}};ZipDeflate.prototype.push=function(chunk,final){ZipPassThrough.prototype.push.call(this,chunk,final)};return ZipDeflate}();var Zip=function(){function Zip(cb){this.ondata=cb;this.u=[];this.d=1}Zip.prototype.add=function(file){var _this=this;if(!this.ondata)err(5);if(this.d&2)this.ondata(err(4+(this.d&1)*8,0,1),null,false);else{var f=strToU8(file.filename),fl_1=f.length;var com=file.comment,o=com&&strToU8(com);var u=fl_1!=file.filename.length||o&&com.length!=o.length;var hl_1=fl_1+exfl(file.extra)+30;if(fl_1>65535)this.ondata(err(11,0,1),null,false);var header=new u8(hl_1);wzh(header,0,file,f,u,-1);var chks_1=[header];var pAll_1=function(){for(var _i=0,chks_2=chks_1;_i<chks_2.length;_i++){var chk=chks_2[_i];_this.ondata(null,chk,false)}chks_1=[]};var tr_1=this.d;this.d=0;var ind_1=this.u.length;var uf_1=mrg(file,{f,u,o,t:function(){if(file.terminate)file.terminate()},r:function(){pAll_1();if(tr_1){var nxt=_this.u[ind_1+1];if(nxt)nxt.r();else _this.d=1}tr_1=1}});var cl_1=0;file.ondata=function(err,dat,final){if(err){_this.ondata(err,dat,final);_this.terminate()}else{cl_1+=dat.length;chks_1.push(dat);if(final){var dd=new u8(16);wbytes(dd,0,134695760);wbytes(dd,4,file.crc);wbytes(dd,8,cl_1);wbytes(dd,12,file.size);chks_1.push(dd);uf_1.c=cl_1,uf_1.b=hl_1+cl_1+16,uf_1.crc=file.crc,uf_1.size=file.size;if(tr_1)uf_1.r();tr_1=1}else if(tr_1)pAll_1()}};this.u.push(uf_1)}};Zip.prototype.end=function(){var _this=this;if(this.d&2){this.ondata(err(4+(this.d&1)*8,0,1),null,true);return}if(this.d)this.e();else this.u.push({r:function(){if(!(_this.d&1))return;_this.u.splice(-1,1);_this.e()},t:function(){}});this.d=3};Zip.prototype.e=function(){var bt=0,l=0,tl=0;for(var _i=0,_a=this.u;_i<_a.length;_i++){var f=_a[_i];tl+=46+f.f.length+exfl(f.extra)+(f.o?f.o.length:0)}var out=new u8(tl+22);for(var _b=0,_c=this.u;_b<_c.length;_b++){var f=_c[_b];wzh(out,bt,f,f.f,f.u,-f.c-2,l,f.o);bt+=46+f.f.length+exfl(f.extra)+(f.o?f.o.length:0),l+=f.b}wzf(out,bt,this.u.length,tl,l);this.ondata(null,out,true);this.d=2};Zip.prototype.terminate=function(){for(var _i=0,_a=this.u;_i<_a.length;_i++){var f=_a[_i];f.t()}this.d=2};return Zip}();var ARCHIVE_MANIFEST_PATH="manifest.json";var ARCHIVE_DEFINITIONS_PATH="definitions.json";var ZIP_MAX_BYTES=2**32-1;var ZIP_MAX_ENTRIES=65535;var LOCAL_HEADER_BYTES=30;var DATA_DESCRIPTOR_BYTES=16;var CENTRAL_RECORD_BYTES=46;var END_RECORD_BYTES=22;var STORED_PREFIX="files/";var DEFLATE_LEVEL=6;var manifestSchema=objectType({files:arrayType(objectType({sha256:stringType(),size:numberType().int().nonnegative()})),units:arrayType(objectType({chunks:arrayType(objectType({number:numberType().int().positive(),size:numberType().int().nonnegative()})),domain:stringType(),unit:stringType()}))});var parseManifest=(text)=>{try{return manifestSchema.parse(JSON.parse(text))}catch(error){throw new TransferClientError({code:"manifest_invalid"},error instanceof Error?{cause:error}:undefined)}};var archivePaths=(manifestJson)=>{const manifest=parseManifest(manifestJson);return[{path:ARCHIVE_MANIFEST_PATH},{path:ARCHIVE_DEFINITIONS_PATH},...manifest.units.flatMap(({chunks,domain,unit})=>chunks.map(({number,size})=>({path:`units/${domain}/${unit}/chunks/${String(number).padStart(6,"0")}.ndjson`,size}))),...manifest.files.map(({sha256,size})=>({path:`${STORED_PREFIX}${sha256}`,size}))]};var chunksOf=async function*chunksOf(content,signal){const reader=(content instanceof Blob?content.stream():content).getReader();let finished=false;try{for(;;){signal?.throwIfAborted();const next=await reader.read();if(next.done){finished=true;return}yield next.value}}finally{if(!finished){await reader.cancel()}reader.releaseLock()}};var sizeChecked=async function*sizeChecked(path,expected,chunks){let actual=0;for await(const chunk of chunks){actual+=chunk.byteLength;if(expected!==undefined&&actual>expected){throw new TransferClientError({actual,code:"size_mismatch",expected,path})}yield chunk}if(expected!==undefined&&actual!==expected){throw new TransferClientError({actual,code:"size_mismatch",expected,path})}};var streamOf=(chunks)=>new ReadableStream({cancel:async()=>{await chunks.return()},pull:async(controller)=>{const next=await chunks.next();if(next.done){controller.close()}else{controller.enqueue(next.value)}}});var concat=(parts)=>{const whole=new Uint8Array(parts.reduce((total,part)=>total+part.byteLength,0));let offset=0;for(const part of parts){whole.set(part,offset);offset+=part.byteLength}return whole};var bytesOf=async(chunks)=>{const parts=[];for await(const chunk of chunks){parts.push(chunk)}return concat(parts)};var memoryEntry=(path,bytes)=>({open:()=>new Blob([bytes]),path,size:bytes.byteLength});var zipLimit=(path)=>new TransferClientError({code:"archive_zip_limit",path});var utf8Length=(text)=>new TextEncoder().encode(text).byteLength;var zipChunks=async function*zipChunks(files,signal){const pending=[];let failure;let written=0;let count=0;let reserved=END_RECORD_BYTES;const zip=new Zip((error,chunk)=>{if(error===null){pending.push(chunk);written+=chunk.byteLength}else{failure=error}});const drain=()=>{if(failure!==undefined){throw failure}return pending.splice(0)};try{for await(const file of files){signal?.throwIfAborted();count+=1;const nameBytes=utf8Length(file.path);reserved+=DATA_DESCRIPTOR_BYTES+CENTRAL_RECORD_BYTES+nameBytes;if(count>ZIP_MAX_ENTRIES||written+LOCAL_HEADER_BYTES+nameBytes+(file.size??0)+reserved>ZIP_MAX_BYTES){throw zipLimit(file.path)}const entry=file.path.startsWith(STORED_PREFIX)?new ZipPassThrough(file.path):new ZipDeflate(file.path,{level:DEFLATE_LEVEL});zip.add(entry);const content=await file.open();for await(const chunk of sizeChecked(file.path,file.size,chunksOf(content,signal))){entry.push(chunk,false);yield*drain();if(written+reserved>ZIP_MAX_BYTES){throw zipLimit(file.path)}}entry.push(new Uint8Array,true);yield*drain();if(written+reserved>ZIP_MAX_BYTES){throw zipLimit(file.path)}}zip.end();yield*drain()}catch(error){zip.terminate();throw error}};var zipArchive=(files,options={})=>streamOf(zipChunks(files,options.signal));var randomAccessOf=(source)=>source instanceof Blob?{read:(start,end)=>source.slice(start,end),size:source.size}:source;var END_SIGNATURE=101010256;var END64_SIGNATURE=101075792;var END64_LOCATOR_SIGNATURE=117853008;var CENTRAL_SIGNATURE=33639248;var LOCAL_SIGNATURE=67324752;var END64_LOCATOR_BYTES=20;var END64_RECORD_BYTES=56;var MAX_COMMENT_BYTES=65535;var MAX_16=65535;var MAX_32=4294967295;var ZIP64_EXTRA_ID=1;var METHOD_STORED=0;var METHOD_DEFLATED=8;var ENCRYPTED_BIT=1;var MAX_DIRECTORY_BYTES=256*2**20;var MAX_INLINE_BYTES=128*2**20;var INFLATE_STEP_BYTES=16*1024;var zipMalformed=(reason)=>new TransferClientError({code:"zip_malformed",reason});var viewOf=(bytes)=>new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);var safeNumber=(value)=>{if(value>BigInt(Number.MAX_SAFE_INTEGER)){throw zipMalformed("an offset or size is too large")}return Number(value)};var readRange=async(zip,start,end,signal)=>{const bytes=await bytesOf(chunksOf(await zip.read(start,end),signal));if(bytes.byteLength!==end-start){throw zipMalformed("the zip ends early")}return bytes};var locateDirectory=async(zip,signal)=>{const tailStart=Math.max(0,zip.size-END_RECORD_BYTES-MAX_COMMENT_BYTES);const tail=await readRange(zip,tailStart,zip.size,signal);const view=viewOf(tail);for(let at=tail.byteLength-END_RECORD_BYTES;at>=0;at-=1){if(view.getUint32(at,true)!==END_SIGNATURE||at+END_RECORD_BYTES+view.getUint16(at+20,true)!==tail.byteLength){continue}const count=view.getUint16(at+10,true);const size=view.getUint32(at+12,true);const offset=view.getUint32(at+16,true);if(count!==MAX_16&&size!==MAX_32&&offset!==MAX_32){return{count,offset,size}}const locatorAt=tailStart+at-END64_LOCATOR_BYTES;if(locatorAt<0){throw zipMalformed("the zip64 locator is missing")}const locator=viewOf(await readRange(zip,locatorAt,locatorAt+END64_LOCATOR_BYTES,signal));if(locator.getUint32(0,true)!==END64_LOCATOR_SIGNATURE){throw zipMalformed("the zip64 locator is missing")}const recordAt=safeNumber(locator.getBigUint64(8,true));const record=viewOf(await readRange(zip,recordAt,recordAt+END64_RECORD_BYTES,signal));if(record.getUint32(0,true)!==END64_SIGNATURE){throw zipMalformed("the zip64 end record is missing")}return{count:safeNumber(record.getBigUint64(32,true)),offset:safeNumber(record.getBigUint64(48,true)),size:safeNumber(record.getBigUint64(40,true))}}throw zipMalformed("this is not a zip")};var decoder4=new TextDecoder;var zip64Fields=(view,extraAt,extraEnd,fields)=>{const result={...fields};for(let at=extraAt;at+4<=extraEnd;){const length=view.getUint16(at+2,true);if(view.getUint16(at,true)===ZIP64_EXTRA_ID){let next=at+4;for(const field of["size","compressedSize","offset"]){if(result[field]===MAX_32){if(next+8>at+4+length){throw zipMalformed("a zip64 extra field is too short")}result[field]=safeNumber(view.getBigUint64(next,true));next+=8}}break}at+=4+length}return result};var readDirectory2=async(zip,signal)=>{const{count,offset,size}=await locateDirectory(zip,signal);if(size>MAX_DIRECTORY_BYTES||offset+size>zip.size){throw zipMalformed("the central directory is out of bounds")}const view=viewOf(await readRange(zip,offset,offset+size,signal));const entries=new Map;const duplicates=new Set;let at=0;for(let index=0;index<count;index+=1){if(at+CENTRAL_RECORD_BYTES>size||view.getUint32(at,true)!==CENTRAL_SIGNATURE){throw zipMalformed("the central directory is damaged")}const nameBytes=view.getUint16(at+28,true);const extraBytes=view.getUint16(at+30,true);const next=at+CENTRAL_RECORD_BYTES+nameBytes+extraBytes+view.getUint16(at+32,true);if(next>size){throw zipMalformed("the central directory is damaged")}if(view.getUint16(at+8,true)%2===ENCRYPTED_BIT){throw zipMalformed("an entry is encrypted")}const nameAt=at+CENTRAL_RECORD_BYTES;const name=decoder4.decode(new Uint8Array(view.buffer,view.byteOffset+nameAt,nameBytes));const fields=zip64Fields(view,nameAt+nameBytes,nameAt+nameBytes+extraBytes,{compressedSize:view.getUint32(at+20,true),offset:view.getUint32(at+42,true),size:view.getUint32(at+24,true)});if(entries.has(name)){duplicates.add(name)}entries.set(name,{...fields,method:view.getUint16(at+10,true)});at=next}return{duplicates,entries}};var entryOf=(directory,path)=>{if(directory.duplicates.has(path)){throw zipMalformed(`the zip has more than one entry named ${path}`)}return directory.entries.get(path)};var dataRange=async(zip,entry,signal)=>{const header=viewOf(await readRange(zip,entry.offset,entry.offset+LOCAL_HEADER_BYTES,signal));if(header.getUint32(0,true)!==LOCAL_SIGNATURE){throw zipMalformed("a local header is damaged")}const start=entry.offset+LOCAL_HEADER_BYTES+header.getUint16(26,true)+header.getUint16(28,true);return{end:start+entry.compressedSize,start}};var inflated=async function*inflated(chunks){const out=[];const inflate=new Inflate((chunk)=>{out.push(chunk)});try{for await(const chunk of chunks){for(let at=0;at<chunk.byteLength;at+=INFLATE_STEP_BYTES){inflate.push(chunk.subarray(at,at+INFLATE_STEP_BYTES));yield*out.splice(0)}}inflate.push(new Uint8Array,true);yield*out.splice(0)}catch(error){throw error instanceof TransferClientError?error:zipMalformed("an entry is not valid deflate data")}};var dataOfEntry=async function*dataOfEntry(zip,entry,path,signal){const{end,start}=await dataRange(zip,entry,signal);if(end>zip.size){throw zipMalformed("the zip ends early")}const raw=chunksOf(await zip.read(start,end),signal);yield*sizeChecked(path,entry.size,entry.method===METHOD_DEFLATED?inflated(raw):raw)};var checkedEntry=(directory,path,expected)=>{const entry=entryOf(directory,path);if(entry===undefined){return}if(entry.method!==METHOD_STORED&&entry.method!==METHOD_DEFLATED){throw zipMalformed(`${path} uses compression method ${entry.method}`)}if(entry.method===METHOD_STORED&&entry.compressedSize!==entry.size){throw zipMalformed(`${path} is stored with two sizes`)}if(expected!==undefined&&entry.size!==expected){throw new TransferClientError({actual:entry.size,code:"size_mismatch",expected,path})}return entry};var wholeEntry=async(zip,entry,path,signal)=>{if(entry.size>MAX_INLINE_BYTES){throw zipMalformed(`${path} is too large to read whole`)}return await bytesOf(dataOfEntry(zip,entry,path,signal))};var readArchiveZip=async function*readArchiveZip(source,options={}){const{signal}=options;const zip=randomAccessOf(source);const directory=await readDirectory2(zip,signal);const manifestEntry=checkedEntry(directory,ARCHIVE_MANIFEST_PATH);if(manifestEntry===undefined){throw new TransferClientError({code:"zip_manifest_missing"})}const manifest=await wholeEntry(zip,manifestEntry,ARCHIVE_MANIFEST_PATH,signal);const listed=archivePaths(decoder4.decode(manifest)).filter(({path})=>path!==ARCHIVE_MANIFEST_PATH).map(({path,size})=>({entry:checkedEntry(directory,path,size),path,size}));const missing=listed.filter(({entry,path})=>entry===undefined&&path!==ARCHIVE_DEFINITIONS_PATH).map(({path})=>path);if(missing.length>0){throw new TransferClientError({code:"zip_incomplete",missing})}yield memoryEntry(ARCHIVE_MANIFEST_PATH,manifest);const definitions=listed.find(({path})=>path===ARCHIVE_DEFINITIONS_PATH)?.entry;if(definitions!==undefined){yield memoryEntry(ARCHIVE_DEFINITIONS_PATH,await wholeEntry(zip,definitions,ARCHIVE_DEFINITIONS_PATH,signal))}const files=listed.flatMap(({entry,path,size})=>entry===undefined||size===undefined?[]:[{entry,path,size}]);for(const{entry,path,size}of files){yield{open:()=>streamOf(dataOfEntry(zip,entry,path,signal)),path,size}}};var isFirst=(path)=>path===ARCHIVE_MANIFEST_PATH||path===ARCHIVE_DEFINITIONS_PATH;var archiveEntriesFromDownloadUrls=(files,options={})=>{const ordered=[...files.filter(({path})=>path===ARCHIVE_MANIFEST_PATH),...files.filter(({path})=>path===ARCHIVE_DEFINITIONS_PATH),...files.filter(({path})=>!isFirst(path))];return ordered.map(({path,size,url})=>{const open=async()=>{const init={};if(options.signal!==undefined){init.signal=options.signal}const response=await(options.fetch??globalThis.fetch)(url,init);if(!response.ok){throw new TransferClientError({code:"download_failed",path,status:response.status})}return response.body??new Blob([])};return size===undefined?{open,path}:{open,path,size}})};var runStatuses=["queued","running","completed","failed","stopped","expired"];var runEventSchema=objectType({createdAt:stringType(),failure:stringType().optional(),kind:enumType(["accepted","started","continued","resumed","cancel_requested","stopped","completed","failed"]),previousPrincipalId:stringType().optional(),previousPrincipalKind:enumType(["user","service_principal"]).optional(),principalId:stringType(),principalKind:enumType(["user","service_principal"]),reason:enumType(["cancelled","authority_lost","crashed"]).optional(),sequence:numberType().int().nonnegative(),status:enumType(runStatuses)});var MAX_RECONNECTS_WITHOUT_PROGRESS2=5;var isRunEventError=(error)=>error instanceof TransferClientError&&error.failure.code==="run_event_invalid";var decodedEvents=async function*decodedEvents(frames){for await(const frame of frames){const decoded=runEventSchema.safeParse(frame);if(!decoded.success){throw new TransferClientError({code:"run_event_invalid"},{cause:decoded.error})}yield decoded.data}};var followTransferRun=async(input)=>{const{organizationId,runId}=input;let cursor=input.afterSequence??0;const known=await getTransferRun({organizationId},runId);if(known!==undefined&&!isTransferRunActive(known)&&cursor>=known.lastEventSequence){return{lastEventId:input.afterSequence===undefined?undefined:String(cursor),reason:"terminal"}}return await followEventStream({connect:async(connection)=>{const response=await organizationTransferEvents({...singleConnectionSseOptions,fetch:eventStreamFetch(client.getConfig().fetch),headers:{...connection.lastEventId===undefined?undefined:{"last-event-id":connection.lastEventId},"x-organization-id":organizationId},path:{runId},signal:connection.signal,throwOnError:true});return decodedEvents(response.stream)},eventId:()=>String(cursor),isRetryableError:(error)=>!isRunEventError(error)&&isRetryableEventStreamError(error),isTerminal:(event)=>!isTransferRunActive(event),...input.afterSequence===undefined?undefined:{lastEventId:String(input.afterSequence)},maxRetries:input.maxRetries??MAX_RECONNECTS_WITHOUT_PROGRESS2,onEvent:async(event)=>{if(event.sequence<=cursor){return}cursor=event.sequence;await input.onEvent(event)},...input.retryDelayMs===undefined?undefined:{initialRetryDelayMs:input.retryDelayMs},...input.signal===undefined?undefined:{signal:input.signal}})};var ALREADY_PRESENT=new Set([409,412]);var bodyInit=(entry,body,headers)=>body instanceof Blob?{body,headers}:{body,duplex:"half",headers:{...headers,"content-length":String(entry.size)}};var archiveIds=new WeakMap;var uploadArchiveIdOf=(error)=>archiveIds.get(error);var uploadFile=async(input,entry)=>{const[signed]=await requestTransferUploadUrls({archiveId:input.archiveId,organizationId:input.organizationId,paths:[entry.path],...input.signal===undefined?undefined:{signal:input.signal}});if(signed===undefined){throw new TransferClientError({code:"upload_failed",path:entry.path,status:0})}const body=await entry.open();const init={...bodyInit(entry,body,signed.headers),method:signed.method};if(input.signal!==undefined){init.signal=input.signal}const response=await(input.fetch??globalThis.fetch)(signed.url,init);await response.body?.cancel();if(response.ok){return{outcome:"uploaded",path:entry.path,size:entry.size}}if(ALREADY_PRESENT.has(response.status)){return{outcome:"skipped",path:entry.path,size:entry.size}}throw new TransferClientError({code:"upload_failed",path:entry.path,status:response.status})};var uploadArchive=async(options)=>{const input={...options,archiveId:options.archiveId??crypto.randomUUID()};const{archiveId,signal}=input;const limit=Math.max(1,input.concurrency??1);const uploaded=[];const skipped=[];const inFlight=new Map;let manifest;let failure;let nextId=0;const attempt=async(id,entry)=>{try{const file=await uploadFile(input,entry);(file.outcome==="uploaded"?uploaded:skipped).push(file.path);input.onFile?.(file);return{id}}catch(error){return{failure:{error},id}}};const finishOne=async()=>{const done=await Promise.race(inFlight.values());inFlight.delete(done.id);return done.failure};for await(const entry of input.entries){if(signal?.aborted===true){failure={error:signal.reason};break}if(entry.path===ARCHIVE_MANIFEST_PATH){manifest=entry;continue}nextId+=1;inFlight.set(nextId,attempt(nextId,entry));if(inFlight.size>=limit){failure=await finishOne()}if(failure!==undefined){break}}const rest=await Promise.all(inFlight.values());failure??=rest.find((done)=>done.failure!==undefined)?.failure;if(failure===undefined&&manifest!==undefined){const{failure:manifestFailure}=await attempt(0,manifest);failure=manifestFailure}if(failure!==undefined){if(failure.error instanceof Error){archiveIds.set(failure.error,archiveId)}throw failure.error}return{archiveId,skipped,uploaded}};import path15 from"path";var plainWord=/^[\w@%+=:,./-]+$/u;var shellWord=(word)=>plainWord.test(word)?word:`'${word.replaceAll("'",String.raw`'\''`)}'`;var commandLine=(words)=>["ci","transfer",...words].map((word)=>shellWord(word)).join(" ");var targetArguments=(args)=>targetOptions.flatMap((name)=>{const flag=`--${name}`;const index=args.indexOf(flag);const value=index===-1?undefined:args[index+1];return value===undefined?[]:[flag,value]});class TransferCommandError extends TaggedError3()("TransferCommandError",{archiveId:optional2(String5),cause:optional2(Unknown2),code:optional2(String5),message:String5,nextAction:optional2(String5),runId:optional2(String5),status:optional2(Finite)}){}var interruptedCode="interrupted";var domains=["knowledge","documents","datasets"];var boundaryModes=["reference","clear","include_referenced"];var policies=["create_only","skip_existing","update","fill_blanks"];var unresolvedReferences=["fail","continue","skip_item"];var datasetModes=["append","upsert","replace"];var userJoinFields=["email","name","id"];var groupJoinFields=["name","slug","fqn"];var archiveFormats=["zip","folder"];var traverse4=forEach2;var refuse=(message)=>new TransferCommandError({message});var choose=(flag,value,allowed)=>{const found=allowed.find((candidate)=>candidate===value);return found===undefined?fail6(refuse(`${flag} must be one of ${allowed.join(", ")}`)):succeed6(found)};var chooseAll=(flag,value,allowed)=>traverse4(value.split(",").filter((part)=>part!==""),(part)=>choose(flag,part,allowed));var positiveInteger=(flag,value,minimum=1)=>{const number=Number(value);return/^\d+$/u.test(value)&&Number.isSafeInteger(number)&&number>=minimum?succeed6(number):fail6(refuse(`${flag} must be a whole number of ${minimum} or more`))};var optionalPositive=fn2("Transfer.optionalPositive")(function*optionalPositive(options,flag){const value=optionValue2(options,flag);return value===undefined?undefined:yield*positiveInteger(`--${flag}`,value)});var pairOf=(flag,value)=>{const separator=value.indexOf("=");const left=value.slice(0,separator);const right=value.slice(separator+1);return separator>0&&right!==""?succeed6([left,right]):fail6(refuse(`${flag} must be written <left>=<right>`))};var requireValue=(options,flag)=>{const value=optionValue2(options,flag);return value===undefined?fail6(refuse(`Missing required option --${flag}`)):succeed6(value)};var optionError=(flags,message)=>fail6(refuse(`${flags} ${message}`));var exportOptionNames={repeatable:["domain","identity-field"],values:["boundary-mode","depth","format","max-dependency-items","out","portability","run","selection"]};var boundaryOf=fn2("Transfer.boundaryOf")(function*boundaryOf(options){const modeValue=optionValue2(options,"boundary-mode");const mode=modeValue===undefined?undefined:yield*choose("--boundary-mode",modeValue,boundaryModes);const depth=yield*optionalPositive(options,"depth");const maxDependencyItems=yield*optionalPositive(options,"max-dependency-items");const identityFields={};for(const value of optionValues(options,"identity-field")){const[unit,fields]=yield*pairOf("--identity-field",value);identityFields[unit]=fields.split(",").filter((field)=>field!=="")}const boundary={...mode===undefined?undefined:{mode},...depth===undefined?undefined:{depth},...maxDependencyItems===undefined?undefined:{maxDependencyItems},...Object.keys(identityFields).length===0?undefined:{identityFields}};return Object.keys(boundary).length===0?undefined:boundary});var selectionOf=fn2("Transfer.selectionOf")(function*selectionOf(options){const file=optionValue2(options,"selection");const named=optionValues(options,"domain");if(file!==undefined&&named.length>0){return yield*optionError("--selection","already names the domains; do not combine it with --domain")}if(file!==undefined){return{kind:"file",path:file}}const chosen=yield*traverse4(named,(domain)=>choose("--domain",domain,domains));return chosen.length===0?undefined:{domains:[...new Set(chosen)],kind:"domains"}});var downloadOf=fn2("Transfer.downloadOf")(function*downloadOf(options){const out=optionValue2(options,"out");const formatValue=optionValue2(options,"format");if(out===undefined){return formatValue===undefined?undefined:yield*optionError("--format","needs --out")}return{format:formatValue===undefined?"zip":yield*choose("--format",formatValue,archiveFormats),out}});var exportCommand=fn2("Transfer.exportCommand")(function*exportCommand(args){const options=yield*parseCommandOptionsEffect(args,{...exportOptionNames,switches:["preview"],values:[...targetOptions,...exportOptionNames.values]});const download=yield*downloadOf(options);const runId=optionValue2(options,"run");if(runId!==undefined){const selecting=["boundary-mode","depth","domain","identity-field","max-dependency-items","portability","selection"].filter((flag)=>options.values.has(flag));if(options.switches.has("preview")||selecting.length>0){return yield*optionError("--run","downloads a finished Export Run; it takes only --out and --format")}return download===undefined?yield*optionError("--run","needs --out"):{action:"export_download",download,runId}}const input={boundary:yield*boundaryOf(options),portability:optionValue2(options,"portability"),selection:yield*selectionOf(options)};if(options.switches.has("preview")){return download===undefined?{action:"export_preview",input}:yield*optionError("--preview","starts no run; do not combine with --out")}return{action:"export",download,input}});var importOptionNames={repeatable:["connector-instance","dataset-mode","force","unit"],switches:["events","no-import-origin"],values:["join-group","join-user","max-errors","policy","unresolved-reference"]};var unitChoiceOf=(value)=>{const separator=value.indexOf(":");const prefix=value.slice(0,separator);const domain=domains.find((candidate)=>candidate===prefix);return domain===undefined||separator+1===value.length?{unit:value}:{domain,unit:value.slice(separator+1)}};var unitsOf=fn2("Transfer.unitsOf")(function*unitsOf(options){const names=[...new Set(optionValues(options,"unit"))];const modes=new Map;for(const value of optionValues(options,"dataset-mode")){const[unit,mode]=yield*pairOf("--dataset-mode",value);modes.set(unit,yield*choose("--dataset-mode",mode,datasetModes))}const forced=new Set(optionValues(options,"force"));for(const unit of[...modes.keys(),...forced]){if(!names.includes(unit)){return yield*optionError(`Unit ${unit}`,"has an option but is not named by --unit; naming a unit limits the import to the listed units")}}return names.map((name)=>{const datasetMode=modes.get(name);return{...unitChoiceOf(name),...datasetMode===undefined?undefined:{datasetMode},...forced.has(name)?{force:true}:undefined}})});var importOptionsOf=fn2("Transfer.importOptionsOf")(function*importOptionsOf(options){const policyValue=optionValue2(options,"policy");const unresolvedValue=optionValue2(options,"unresolved-reference");const userValue=optionValue2(options,"join-user");const groupValue=optionValue2(options,"join-group");const maxErrors=yield*optionalPositive(options,"max-errors");const connectorInstances=yield*traverse4(optionValues(options,"connector-instance"),(value)=>map5(pairOf("--connector-instance",value),([sourceInstanceId,targetInstanceId])=>({sourceInstanceId,targetInstanceId})));const units=yield*unitsOf(options);const user=userValue===undefined?undefined:yield*chooseAll("--join-user",userValue,userJoinFields);const group=groupValue===undefined?undefined:yield*chooseAll("--join-group",groupValue,groupJoinFields);const joinFields={...user===undefined?undefined:{user},...group===undefined?undefined:{group}};const result={...connectorInstances.length===0?undefined:{connectorInstances},...options.switches.has("events")?{events:true}:undefined,...options.switches.has("no-import-origin")?{importOrigin:false}:undefined,...maxErrors===undefined?undefined:{maxErrors},...policyValue===undefined?undefined:{policy:yield*choose("--policy",policyValue,policies)},...units.length===0?undefined:{units},...unresolvedValue===undefined?undefined:{unresolvedReference:yield*choose("--unresolved-reference",unresolvedValue,unresolvedReferences)},...Object.keys(joinFields).length===0?undefined:{joinFields}};return Object.keys(result).length===0?undefined:result});var importCommand=fn2("Transfer.importCommand")(function*importCommand(args){const options=yield*parseCommandOptionsEffect(args,{repeatable:importOptionNames.repeatable,switches:[...importOptionNames.switches,"apply","confirm-replace","plan"],values:[...targetOptions,...importOptionNames.values,"archive","archive-id","plan-run","plan-file","save-plan","portability"]});const plan=options.switches.has("plan");const apply=options.switches.has("apply");if(plan===apply){return yield*optionError("ci transfer import","needs exactly one of --plan or --apply")}const importOptions=yield*importOptionsOf(options);const archivePath=optionValue2(options,"archive");const archiveId=optionValue2(options,"archive-id");if(plan){if(options.values.has("plan-file")){return yield*optionError("--plan-file","belongs to --apply")}if(options.switches.has("confirm-replace")){return yield*optionError("--confirm-replace","belongs to --apply")}if(options.values.has("plan-run")){return yield*optionError("--plan-run","belongs to --apply")}if(archivePath!==undefined){return{action:"import_plan",archive:{archiveId,path:archivePath},options:importOptions,portability:optionValue2(options,"portability"),savePlan:optionValue2(options,"save-plan")}}return archiveId===undefined?yield*optionError("--plan","needs --archive <folder|zip> or --archive-id <id>"):{action:"import_plan",archive:{archiveId,path:undefined},options:importOptions,portability:optionValue2(options,"portability"),savePlan:optionValue2(options,"save-plan")}}if(options.values.has("portability")||options.values.has("save-plan")){return yield*optionError("--portability and --save-plan","belong to --plan; apply the saved --plan-file")}const planFile=optionValue2(options,"plan-file");if(planFile!==undefined){if(archivePath!==undefined||archiveId!==undefined||importOptions!==undefined||options.values.has("plan-run")){return yield*optionError("--plan-file","cannot be combined with archive, plan-run or import option overrides; make a new Plan")}return{action:"import_saved_apply",confirmReplace:options.switches.has("confirm-replace"),planFile}}if(archivePath!==undefined){return yield*optionError("--archive","belongs to --plan; --apply uses the archive of the Plan run")}return{action:"import_apply",archiveId,confirmReplace:options.switches.has("confirm-replace"),options:importOptions,planRunId:yield*requireValue(options,"plan-run")}});var rollbackCommand=fn2("Transfer.rollbackCommand")(function*rollbackCommand(args){const options=yield*parseCommandOptionsEffect(args,{switches:["force"],values:[...targetOptions,"source-run"]});return{action:"rollback",force:options.switches.has("force"),sourceRunId:yield*requireValue(options,"source-run")}});var runsActions=["mappings","cancel","purge","report","resume"];var runsCommand=fn2("Transfer.runsCommand")(function*runsCommand(args){const options=yield*parseCommandOptionsEffect(args,{switches:runsActions,values:[...targetOptions,"limit","run","out"]});const limit=yield*optionalPositive(options,"limit");const runId=optionValue2(options,"run");const chosen=runsActions.filter((action)=>options.switches.has(action));const out=optionValue2(options,"out");if(out!==undefined&&!options.switches.has("mappings")){return yield*optionError("--out","requires --mappings and --run")}if(chosen.length>1){return yield*optionError(chosen.map((action)=>`--${action}`).join(" and "),"cannot be combined")}if(runId===undefined){return chosen.length===0?{action:"runs_list",limit}:yield*optionError(`--${chosen[0]??""}`,"needs --run <run-id>")}if(limit!==undefined){return yield*optionError("--limit","only applies to the list of runs")}return{action:"runs_run",out,run:chosen[0]??"show",runId}});var transferUsage="Usage: ci transfer export|import|rollback|runs";var parseTransferCommand=(args)=>{const[name,...rest]=args;const parsed=(()=>{switch(name){case"export":{return exportCommand(rest)}case"import":{return importCommand(rest)}case"rollback":{return rollbackCommand(rest)}case"runs":{return runsCommand(rest)}default:{return fail6(refuse(transferUsage))}}})();return parsed.pipe(mapError2((cause)=>cause instanceof TransferCommandError?cause:refuse(cause.message)))};var blockedNote=(blocked)=>{switch(blocked){case"write_permission_denied":{return"you may not write this unit in the target Organization."}case"unit_incomplete":{return"the export stopped part-way through this unit, so the archive holds only some of its items. Export it again."}case"unit_ambiguous":{return"the target has more than one collection with this name. Rename one and plan again, or leave the unit out."}default:{return blocked}}};var warningNote=(warning)=>{switch(warning){case"no_match_key_or_origin":{return"it has no Match Key and Import Origin is off, so a rerun creates duplicates."}case"forced_duplicates":{return"it is forced, so its rows are appended again and can duplicate earlier rows."}case"earlier_run_committed":{return"a stopped run of this archive already committed batches of this unit, and this run appends them again. Resume that run instead."}case"already_imported":{return"this archive was already imported into this unit, so the unit is skipped unless you force it."}default:{return warning}}};var portabilityNotes=(plan)=>{const{portability}=plan;if(portability===undefined||portability.status==="legacy_unverified"){return["Legacy portability is unverified; this Plan does not prove cross-instance reference or file coverage."]}const{coverage,references,users,files}=portability;return[`Portability: ${portability.status}. Coverage: ${coverage.assessed} assessed, ${coverage.unassessed} unassessed.`,`Entity references: ${references.resolved}/${references.total} resolved, ${references.missing} missing, ${references.ambiguous} ambiguous.`,`Users: ${users.resolved}/${users.total} resolved, ${users.missing} missing, ${users.ambiguous} ambiguous.`,`Files: ${files.copies} copies, ${files.rewrites} rewrites, ${files.external} external.`,...portability.transformations.map((change)=>`Transform ${change.domain}:${change.unit} ${change.sourceId} ${JSON.stringify(change.path)}: ${change.kind}, ${JSON.stringify(change.before)} -> ${JSON.stringify(change.after)}.`),...portability.issues.map((issue)=>{const location=[issue.domain,issue.unit,issue.sourceId,issue.path===undefined?undefined:JSON.stringify(issue.path)].filter((part)=>part!==undefined).join(" ");return`${issue.code}: ${issue.message}${location===""?"":` (${location})`}`})]};var planNotes=(plan)=>[...plan.units.flatMap((unit)=>{const name=`${unit.domain}:${unit.unit}`;return[`${name}: ${unit.counts.creates} creates, ${unit.counts.updates} updates, ${unit.counts.skips} skips, ${unit.counts.conflicts} conflicts.`,...unit.blocked===undefined?[]:[`${name} is blocked: ${blockedNote(unit.blocked)}`],...unit.warnings.map((warning)=>`${name} warns: ${warningNote(warning)}`)]}),...portabilityNotes(plan)];var SavedPlan=Struct({archiveId:String5,backend:String5,options:optionalKey2(JsonObject),organizationId:String5,planRunId:String5,version:Literal2(1)});var decodeSavedPlan=decodeUnknownSync(fromJsonString2(SavedPlan));var savedPlanBackend=(value)=>{const url=new URL(value);url.username="";url.password="";url.hash="";url.search="";return url.toString().replace(/\/$/u,"")};var traverse5=forEach2;var manifestUnits=fromJsonString2(Struct({units:ArraySchema(Struct({domain:Literals(domains),unit:String5}))}));var unitsOfManifest=(manifestJson)=>decodeEffect2(manifestUnits)(manifestJson).pipe(map5(({units})=>units),mapError2((cause)=>new TransferCommandError({cause,code:"manifest_invalid",message:"manifest.json is not a readable archive manifest"})));var written=({domain,unit})=>`${domain}:${unit}`;var domainOf=(choice,known,where)=>{const found=known.filter(({unit})=>unit===choice.unit);const[only]=found;if(found.length===1&&only!==undefined){return succeed6(only.domain)}return fail6(new TransferCommandError({code:"unit_domain_unknown",message:found.length===0?`Unit ${choice.unit} is not in ${where}; the units are ${known.map(written).join(", ")}`:`Unit ${choice.unit} is in several domains of ${where}; write ${found.map(written).join(" or ")}`}))};var withUnitDomains=fn2("Transfer.withUnitDomains")(function*withUnitDomains(options,source){if(options===undefined){return options}const{units:choices,...rest}=options;if(choices===undefined){return rest}const known=choices.some(({domain})=>domain===undefined)?yield*source.units:[];const units=yield*traverse5(choices,(choice)=>choice.domain===undefined?map5(domainOf(choice,known,source.where),(domain)=>({...choice,domain})):succeed6({...choice,domain:choice.domain}));return{...rest,units}});var traverse6=forEach2;var encodeJson4=encodeSync(fromJsonString2(Unknown2));var isClientFailure=is2(Struct({failure:Struct({code:String5}),message:String5,name:Literal2("TransferClientError")}));var describeFailure2=(cause)=>{if(is2(ManagementRequestError)(cause)){return cause}if(is2(TransferCommandError)(cause)){return cause}if(cause instanceof EventStreamHttpError){return new TransferCommandError({cause,message:`The transfer event stream was rejected with HTTP ${cause.status}`,status:cause.status})}if(cause instanceof EventStreamRetriesExhaustedError){return new TransferCommandError({cause,code:"event_stream_lost",message:"The transfer event stream disconnected; the run continues"})}if(isClientFailure(cause)){return new TransferCommandError({cause,code:cause.failure.code,message:cause.message})}return new TransferCommandError({cause,message:cause instanceof Error?cause.message:"Transfer request failed"})};var call2=(operation)=>tryPromise2({catch:describeFailure2,try:operation});var withTransferClient=(context,fetch2)=>(effect)=>acquireUseRelease2(sync2(()=>{const{baseUrl,headers}=context.client.getConfig();const previous=client.getConfig();client.setConfig({...baseUrl===undefined?undefined:{baseUrl},fetch:fetch2,...headers===undefined?undefined:{headers}});const interceptor=client.interceptors.error.use((body,response,request)=>{const reply=response;return reply===undefined?new ManagementRequestError({cause:body,message:"Organization transfer request failed: could not reach the backend",status:0}):requestFailure(`Organization transfer ${request.method} ${new URL(request.url).pathname}`,reply,body)});return{interceptor,previous}}),()=>effect,({interceptor,previous})=>sync2(()=>{client.interceptors.error.eject(interceptor);client.setConfig({...previous.baseUrl===undefined?undefined:{baseUrl:previous.baseUrl},...previous.fetch===undefined?undefined:{fetch:previous.fetch},headers:{authorization:null}})}));var refuse2=(message,extra={})=>new TransferCommandError({...extra,message});var withDetails=(failure,details)=>new TransferCommandError({archiveId:failure.archiveId,cause:failure.cause,code:failure.code,message:failure.message,nextAction:failure.nextAction,runId:failure.runId,status:failure.status,...details});var commandError=(cause)=>{if(is2(TransferCommandError)(cause)){return cause}return new TransferCommandError({cause,message:cause.message,...is2(ManagementRequestError)(cause)?{status:cause.status}:undefined})};var selectionFromFile=fn2("Transfer.selectionFromFile")(function*selectionFromFile(files,file){const text=yield*tryPromise2({catch:(cause)=>new TransferCommandError({cause,message:`Cannot read the selection file ${file}`}),try:()=>files.readText(file)});return yield*decodeEffect2(fromJsonString2(JsonObject))(text).pipe(mapError2((cause)=>new TransferCommandError({cause,message:`${file} is not a JSON object that names a Selection`})))});var exportRequest=fn2("Transfer.exportRequest")(function*exportRequest(input,files){const{selection}=input;const fromFile=selection?.kind==="file"?yield*selectionFromFile(files,selection.path):undefined;const selected=selection?.kind==="domains"?{domains:selection.domains}:fromFile;const request={...input.boundary===undefined?undefined:{boundary:input.boundary},...selected===undefined?undefined:{selection:selected}};return request});var findRun=fn2("Transfer.findRun")(function*findRun(scope,runId){const run=yield*call2(()=>getTransferRun(scope,runId));return run===undefined?yield*refuse2(`Run ${runId} not found; check the run id`,{code:"run_not_found"}):run});var requireCompleted=(run,runCommand,newRunCommand)=>{if(run.status==="completed"){return succeed6(run)}const reason=run.stopReason===null?"":` (${run.stopReason})`;const cannotResume=run.status==="stopped"&&run.journalExpiredAt!==null;return fail6(new TransferCommandError({code:`run_${run.status}`,message:`${run.type} run ${run.id} ${run.status}${reason}${cannotResume?"; its journal expired, so it can no longer resume":""}`,nextAction:cannotResume?newRunCommand(run):runCommand(run.id,run.status==="stopped"?"--resume":"--report"),runId:run.id}))};var manifestText=async(archiveFiles)=>{for await(const file of archiveFiles){if(file.path===ARCHIVE_MANIFEST_PATH){return await new Response(await file.open()).text()}}throw new TransferCommandError({code:"archive_incomplete",message:"The archive has no manifest.json"})};var folderOutOfBounds=(file)=>path15.isAbsolute(file)||file.split("/").includes("..");var folderEntries=fn2("Transfer.folderEntries")(function*folderEntries(files,folder){const[listed,manifest]=yield*tryPromise2({catch:describeFailure2,try:()=>Promise.all([files.list(folder),files.readText(path15.join(folder,ARCHIVE_MANIFEST_PATH))])});const wanted=yield*try_2({catch:describeFailure2,try:()=>archivePaths(manifest)});const sizes=new Map(listed.map((file)=>[file.path,file.size]));const missing=wanted.filter((file)=>file.path!==ARCHIVE_DEFINITIONS_PATH&&!sizes.has(file.path));if(missing.length>0){return yield*refuse2(`${folder} lacks ${missing.length} files that manifest.json lists, for example ${missing[0]?.path??""}`,{code:"archive_incomplete"})}return wanted.flatMap(({path:file})=>{const size=sizes.get(file);return size===undefined?[]:[{open:()=>files.openRead(path15.join(folder,file)),path:file,size}]})});var transferCommandEffect=(args,dependencies)=>gen2(function*transferCommand(){const{files,writeOutput}=dependencies;const writeLine=(line)=>{writeOutput(`${encodeJson4(line)}
3249
+ `)};const parsed=yield*parseTransferCommand(args);const context=yield*resolveOrganizationContext({args,environment:dependencies.environment,fetch:dependencies.fetch}).pipe(mapError2(commandError));const scope={organizationId:context.organizationId};const{signal}=dependencies;const backendArgs=targetArguments(args);const runCommand=(runId,flag)=>commandLine(["runs","--run",runId,...flag===undefined?[]:[flag],...backendArgs]);const newRunCommand=(stopped)=>{switch(stopped.type){case"export":{return commandLine(["export",...backendArgs])}case"rollback":{return commandLine(["rollback",...stopped.sourceRunId===null?[]:["--source-run",stopped.sourceRunId],...backendArgs])}case"import":{return commandLine(["import","--plan",...stopped.archiveId===null?[]:["--archive-id",stopped.archiveId],...backendArgs])}default:{return stopped.type}}};const interruptible=(operation)=>tryPromise2({catch:(cause)=>signal.aborted?new TransferCommandError({cause,code:interruptedCode,message:"The command was interrupted"}):describeFailure2(cause),try:operation});const configuration=fn2("Transfer.configuration")(function*configuration(file){if(file===undefined){return}const text=yield*interruptible(()=>files.readText(file));return yield*interruptible(()=>validateTransferConfiguration(scope,text,{signal}))});const configuredExport=fn2("Transfer.configuredExport")(function*configuredExport(input){const portability=yield*configuration(input.portability);const request=yield*exportRequest(input,files);return{...request,...portability===undefined?undefined:{portability}}});const finish=fn2("Transfer.finish")(function*finish(started){const followed=yield*interruptible(()=>followTransferRun({onEvent:(event)=>{writeLine({event,kind:"progress",runId:started.id,step:"run"})},organizationId:scope.organizationId,runId:started.id,signal})).pipe(mapError2((cause)=>is2(TransferCommandError)(cause)?withDetails(cause,{nextAction:runCommand(started.id),runId:started.id}):cause));if(followed.reason==="aborted"){return yield*new TransferCommandError({code:interruptedCode,message:`Interrupted; run ${started.id} continues on the backend`,nextAction:runCommand(started.id),runId:started.id})}return yield*requireCompleted(yield*findRun(scope,started.id),runCommand,newRunCommand)});const kindOf=fn2("Transfer.kindOf")(function*kindOf(source){const kind=yield*tryPromise2({catch:describeFailure2,try:()=>files.kind(source)});return kind===null?yield*refuse2(`${source} does not exist`):kind});const retryUpload=(archiveId)=>commandLine([...args,...args.includes("--archive-id")?[]:["--archive-id",archiveId]]);const resumable=(failure)=>{if(!is2(TransferCommandError)(failure)){return failure}const archiveId=failure.cause instanceof Error?uploadArchiveIdOf(failure.cause):undefined;return archiveId===undefined?failure:withDetails(failure,{archiveId,nextAction:retryUpload(archiveId)})};const upload=fn2("Transfer.upload")(function*upload(source,archiveId){const entries=(yield*kindOf(source))==="file"?readArchiveZip(files.seekable(source),{signal}):yield*folderEntries(files,source);yield*interruptible(()=>uploadArchive({archiveId,concurrency:4,entries,fetch:dependencies.fetch,onFile:(file)=>{writeLine({archiveId,kind:"progress",outcome:file.outcome,path:file.path,size:file.size,step:"upload"})},organizationId:scope.organizationId,signal})).pipe(mapError2(resumable))});const download=fn2("Transfer.download")(function*download(runId,archiveId,target){const listed=yield*interruptible(()=>requestTransferDownloadUrls({archiveId,organizationId:scope.organizationId,signal}));writeLine({archiveId,files:listed.length,format:target.format,kind:"progress",out:target.out,step:"download"});const archiveFiles=archiveEntriesFromDownloadUrls(listed,{fetch:dependencies.fetch,signal});const written=target.format==="zip"?interruptible(()=>files.writeStream(target.out,zipArchive(archiveFiles,{signal}))):traverse6(archiveFiles,(file)=>folderOutOfBounds(file.path)?fail6(refuse2(`Archive file ${file.path} points outside the folder`)):interruptible(async()=>{const content=await file.open();await files.writeStream(path15.join(target.out,file.path),content instanceof Blob?content.stream():content)}));yield*written.pipe(mapError2((cause)=>is2(TransferCommandError)(cause)&&cause.code==="archive_zip_limit"?withDetails(cause,{archiveId,nextAction:commandLine(["export","--run",runId,"--out",target.out,"--format","folder",...backendArgs]),runId}):cause))});const exportDownloaded=fn2("Transfer.exportDownloaded")(function*exportDownloaded(run,target){if(target!==undefined&&run.archiveId!==null){yield*download(run.id,run.archiveId,target)}writeLine({archiveId:run.archiveId,kind:"result",...target,run})});const archiveManifest=fn2("Transfer.archiveManifest")(function*archiveManifest(archive){if(archive.path===undefined){return yield*interruptible(async()=>manifestText(archiveEntriesFromDownloadUrls(await requestTransferDownloadUrls({archiveId:archive.archiveId,organizationId:scope.organizationId,signal}),{fetch:dependencies.fetch,signal})))}const source=archive.path;return(yield*kindOf(source))==="directory"?yield*tryPromise2({catch:describeFailure2,try:()=>files.readText(path15.join(source,ARCHIVE_MANIFEST_PATH))}):yield*interruptible(()=>manifestText(readArchiveZip(files.seekable(source),{signal})))});const importPlanned=fn2("Transfer.importPlanned")(function*importPlanned(archive,selected){const portability=yield*configuration(selected.portability);const options=yield*withUnitDomains(portability===undefined?selected.options:{...selected.options,portability},{units:archiveManifest(archive).pipe(mapError2(commandError),flatMap4(unitsOfManifest)),where:"the archive"});const archiveId=archive.archiveId??dependencies.newArchiveId();if(archive.path!==undefined){yield*upload(archive.path,archiveId)}const run=yield*finish(yield*call2(()=>startTransferImport(scope,{archiveId,mode:"plan",...options===undefined?undefined:{options}})));const planned=transferRunPlan(run);if(selected.savePlan!==undefined){const target=selected.savePlan;yield*interruptible(()=>files.writeStream(target,new Blob([encodeJson4({archiveId,backend:savedPlanBackend(context.target.apiOrigin),organizationId:scope.organizationId,planRunId:run.id,version:1,...options===undefined?undefined:{options}})]).stream()));dependencies.writeDiagnostic(`Saved Plan to ${target}. Apply with --plan-file ${target}.
3250
+ `)}writeLine({archiveId,kind:"result",plan:planned,run});for(const note of planned===undefined?[]:planNotes(planned)){dependencies.writeDiagnostic(`${note}
3251
+ `)}});const planUnits=fn2("Transfer.planUnits")(function*planUnits(planRunId){const planned=transferRunPlan(yield*findRun(scope,planRunId));return planned===undefined?yield*refuse2(`Run ${planRunId} has no Plan to take the unit domains from; write each unit as <domain>:<unit>`):planned.units});const applicablePlan=fn2("Transfer.applicablePlan")(function*applicablePlan(planRunId,archiveId){const run=yield*findRun(scope,planRunId);const planned=transferRunPlan(run);if(run.id!==planRunId||run.organizationId!==scope.organizationId||run.type!=="import"||run.mode!=="plan"||run.status!=="completed"||planned===undefined||archiveId!==undefined&&run.archiveId!==archiveId){return yield*refuse2("Apply needs the completed import Plan for this archive; create a new Plan",{code:"plan_mismatch"})}for(const note of planNotes(planned)){dependencies.writeDiagnostic(`${note}
3252
+ `)}if(planned.mismatches.length>0||planned.portability?.status==="blocked"||planned.portability!==undefined&&(planned.portability.issues.length>0||planned.portability.coverage.unassessed>0)||planned.units.some(({blocked,counts,linkCollisions})=>blocked!==undefined||counts.conflicts>0||counts.unresolved>0||linkCollisions.length>0)){return yield*refuse2("Plan is blocked; fix the issues or reselect units and Plan again",{code:"plan_blocked"})}return run});const importApplied=fn2("Transfer.importApplied")(function*importApplied(apply){const plannedRun=yield*applicablePlan(apply.planRunId,apply.archiveId);const archiveId=apply.archiveId??plannedRun.archiveId;if(archiveId===null){return yield*refuse2(`Run ${apply.planRunId} has no archive; pass --archive-id`)}const options=yield*withUnitDomains(apply.options,{units:planUnits(apply.planRunId).pipe(mapError2(commandError)),where:"the Plan"});const request=importApplyRequest({...apply.confirmReplace?{confirmReplace:true}:undefined,plan:{archiveId,mode:"plan",...options===undefined?undefined:{options}},planRunId:apply.planRunId});const run=yield*finish(yield*call2(()=>startTransferImport(scope,request)));writeLine({archiveId,kind:"result",run})});const importSaved=fn2("Transfer.importSaved")(function*importSaved(selected){const saved=yield*interruptible(async()=>decodeSavedPlan(await files.readText(selected.planFile)));if(saved.backend!==savedPlanBackend(context.target.apiOrigin)||saved.organizationId!==scope.organizationId){return yield*refuse2("Saved Plan belongs to another Backend or Organization",{code:"plan_target_mismatch"})}yield*applicablePlan(saved.planRunId,saved.archiveId);const request=importApplyRequest({plan:{archiveId:saved.archiveId,mode:"plan",...saved.options===undefined?undefined:{options:saved.options}},planRunId:saved.planRunId,...selected.confirmReplace?{confirmReplace:true}:undefined});const run=yield*finish(yield*call2(()=>startTransferImport(scope,request)));writeLine({archiveId:saved.archiveId,kind:"result",run})});const runsRun=fn2("Transfer.runsRun")(function*runsRun(selected){const{run,runId}=selected;if(run==="mappings"){const mappings=yield*interruptible(()=>downloadTransferMappings(scope,runId,{signal}));const{out}=selected;if(out!==undefined){yield*interruptible(()=>files.writeStream(out,new Blob([encodeJson4(mappings)]).stream()))}writeLine({kind:"result",mappings,...out===undefined?undefined:{out}})}else if(run==="report"){writeLine({kind:"result",report:yield*call2(()=>getTransferRunReport(scope,runId))})}else if(run==="purge"){yield*call2(()=>purgeTransferRun(scope,runId));writeLine({kind:"result",purged:runId})}else if(run==="cancel"){writeLine({kind:"result",run:yield*call2(()=>cancelTransferRun(scope,runId))})}else if(run==="resume"){writeLine({kind:"result",run:yield*finish(yield*call2(()=>resumeTransferRun(scope,runId)))})}else{writeLine({kind:"result",run:yield*findRun(scope,runId)})}});yield*gen2(function*selectedCommand(){switch(parsed.action){case"export_preview":{const request=yield*configuredExport(parsed.input);writeLine({kind:"result",preview:yield*call2(()=>previewTransferExport(scope,request))});break}case"export":{const request=yield*configuredExport(parsed.input);const run=yield*finish(yield*call2(()=>startTransferExport(scope,request)));yield*exportDownloaded(run,parsed.download);break}case"export_download":{const run=yield*findRun(scope,parsed.runId);if(run.type!=="export"||run.archiveId===null){return yield*refuse2(`Run ${run.id} is not a finished Export Run`)}yield*exportDownloaded(yield*requireCompleted(run,runCommand,newRunCommand),parsed.download);break}case"import_plan":{yield*importPlanned(parsed.archive,parsed);break}case"import_saved_apply":{yield*importSaved(parsed);break}case"import_apply":{yield*importApplied(parsed);break}case"rollback":{const run=yield*finish(yield*call2(()=>startTransferRollback(scope,{...parsed.force?{force:true}:undefined,sourceRunId:parsed.sourceRunId})));writeLine({kind:"result",run});break}case"runs_list":{const list=yield*call2(()=>listTransferRuns(scope,parsed.limit===undefined?{}:{limit:parsed.limit}));writeLine({kind:"result",runs:list.data});break}case"runs_run":{yield*runsRun(parsed);break}default:{return parsed}}}).pipe(withTransferClient(context,dependencies.fetch),catchTag2("ManagementRequestError",explainOrganizationForbidden(context,context.organizationId)))}).pipe(mapError2(commandError));import path16 from"path";class UpgradeCommandError extends TaggedError3()("UpgradeCommandError",{cause:optional2(Unknown2),message:String5}){}var registryUrl="https://registry.npmjs.org";var registryTimeout="30 seconds";var RegistryVersion=Struct({version:String5});var packageManagers=[{globalRoot:["npm","root","-g"],install:["npm","install","-g","--prefer-online"]},{globalRoot:["pnpm","root","-g"],install:["pnpm","add","-g"]}];var bunInstall=["bun","add","-g"];var bunGlobalRoot="/install/global/node_modules/";var latestVersion=(fetch2,name)=>tryPromise2({catch:(cause)=>new UpgradeCommandError({cause,message:`Could not reach ${registryUrl} to read the latest ci version`}),try:async(signal)=>{const response=await fetch2(`${registryUrl}/${name}/latest`,{headers:{accept:"application/json"},signal});return response.ok?await response.json():undefined}}).pipe(timeoutOrElse2({duration:registryTimeout,orElse:()=>fail6(new UpgradeCommandError({message:`${registryUrl} did not respond within ${registryTimeout}`}))}),flatMap4((body)=>is2(RegistryVersion)(body)?succeed6(body.version):fail6(new UpgradeCommandError({message:`${registryUrl} did not return the latest ci version`}))));var runPackageManager=(dependencies,command)=>tryPromise2({catch:(cause)=>new UpgradeCommandError({cause,message:`Could not run ${command.join(" ")}`}),try:async()=>await dependencies.runPackageManager(command)});var globalInstallCommand=fn2("Upgrade.globalInstallCommand")(function*globalInstallCommand(dependencies){const{directory,name}=dependencies.installation;if(directory.replaceAll("\\","/").includes(bunGlobalRoot)){return some2(bunInstall)}for(const manager of packageManagers){const root=yield*option2(runPackageManager(dependencies,manager.globalRoot));if(isSome2(root)&&root.value.exitCode===0&&dependencies.realPath(path16.join(root.value.stdout.trim(),name))===directory){return some2(manager.install)}}return none2()});var upgradeCommandEffect=(args,dependencies)=>gen2(function*upgradeCommand(){yield*parseCommandOptionsEffect(args,{});const{directory,name,version}=dependencies.installation;const latest=yield*latestVersion(dependencies.fetch,name);if(Bun.semver.order(version,latest)>=0){return yield*sync2(()=>{dependencies.writeOutput(`ci ${version} is the latest version
3251
3253
  `)})}const install=yield*globalInstallCommand(dependencies);if(isNone2(install)){return yield*new UpgradeCommandError({message:`ci at ${directory} is not a global npm, pnpm or Bun install; install ${name}@${latest} with the package manager that installed it`})}const command=[...install.value,`${name}@${latest}`];dependencies.writeDiagnostic(`Upgrading ci from ${version} to ${latest}: ${command.join(" ")}
3252
3254
  `);const{exitCode,stdout}=yield*runPackageManager(dependencies,command);if(exitCode!==0){return yield*new UpgradeCommandError({message:`${stdout}${command.join(" ")} failed (exit code ${exitCode}); ci ${version} is still installed`})}return yield*sync2(()=>{dependencies.writeOutput(`Upgraded ci from ${version} to ${latest}
3253
3255
  `)})}).pipe(mapError2((cause)=>is2(UpgradeCommandError)(cause)?cause:new UpgradeCommandError({cause,message:cause.message})));class WhoamiCommandError extends TaggedError3()("WhoamiCommandError",{cause:optional2(Unknown2),message:String5}){}var whoamiCommandEffect=(args,dependencies)=>gen2(function*whoamiCommand(){yield*parseCommandOptionsEffect(args,{values:targetOptions});const target=yield*tryConfiguration(()=>resolveBackendManagementTarget({args,environment:dependencies.environment,organizationLookup:true}));const identity=yield*managementData("Identity read",authMe,{client:makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:dependencies.fetch,token:target.token})});const source=target.credentialSource==="management-token"?"CI_MANAGEMENT_TOKEN":`CLI Session (Profile ${target.profile??"unknown"})`;const keyOrganization=identity.organizationId===undefined?undefined:`${identity.organizationName??identity.organizationId} (${identity.organizationId})`;const lines=identity.credentialKind==="api_key"?[`Credential: ${source}`,`API key: ${identity.apiKeyName??identity.id}`,`API key Organization: ${keyOrganization??"unknown"}`,`Tenant: ${target.apiOrigin}`,`Current Organization: ${target.organizationId??identity.organizationId??"none"}`]:[`Credential: ${source}`,`User: ${identity.name??identity.email??identity.id}${identity.email===null?"":` <${identity.email}>`}`,`Tenant: ${target.apiOrigin}`,`Current Organization: ${target.organizationId??"none (run ci orgs use <organization-id>)"}`,`Session expires: ${identity.sessionExpiresAt??"unknown"}`];dependencies.writeOutput(`${lines.join(`
@@ -3279,12 +3281,13 @@ export const ${moduleExport3(input.exportName)} = loaded[${JSON.stringify(input.
3279
3281
  ci doctor [--fqn <fqn>] [--redirect-uri <uri>]...
3280
3282
  (whoami, logout, orgs, apps, api-keys and doctor also accept [--backend-url <url>] [--organization <organization-id>] [--profile <name>])
3281
3283
  ci upgrade (installs the latest version over a global npm, pnpm or Bun install)
3282
- ci transfer export [--preview | --run <run-id>] [--domain <knowledge|documents|datasets>]... [--selection <file>] [--boundary-mode <reference|clear|include_referenced>] [--depth <n>] [--max-dependency-items <n>] [--identity-field <unit>=<field,...>]... [--out <path>] [--format <zip|folder>]
3283
- ci transfer import --plan (--archive <folder|zip> [--archive-id <id>] | --archive-id <id>) [import options]
3284
+ ci transfer export [--preview | --run <run-id>] [--domain <knowledge|documents|datasets>]... [--selection <file>] [--portability <file>] [--boundary-mode <reference|clear|include_referenced>] [--depth <n>] [--max-dependency-items <n>] [--identity-field <unit>=<field,...>]... [--out <path>] [--format <zip|folder>]
3285
+ ci transfer import --plan (--archive <folder|zip> [--archive-id <id>] | --archive-id <id>) [--portability <file>] [--save-plan <file>] [import options]
3286
+ ci transfer import --apply --plan-file <file> [--confirm-replace]
3284
3287
  ci transfer import --apply --plan-run <run-id> [--archive-id <id>] [--confirm-replace] [import options]
3285
3288
  import options: [--policy <create_only|skip_existing|update|fill_blanks>] [--unresolved-reference <fail|continue|skip_item>] [--join-user <email,name,id>] [--join-group <name,slug,fqn>] [--connector-instance <source-id>=<target-id>]... [--max-errors <n>] [--no-import-origin] [--events] [--unit <domain>:<unit>|<unit>]... [--dataset-mode <unit>=<append|upsert|replace>]... [--force <unit>]...
3286
3289
  ci transfer rollback --source-run <run-id> [--force]
3287
- ci transfer runs [--limit <n>] [--run <run-id> [--report | --cancel | --resume | --purge]]
3290
+ ci transfer runs [--limit <n>] [--run <run-id> [--report | --cancel | --resume | --purge | --mappings [--out <file>]]]
3288
3291
  (transfer prints JSON lines: progress, then one result or error; it also accepts [--backend-url <url>] [--organization <organization-id>] [--profile <name>])
3289
3292
  ci deploy --backend-url <url> --organization <organization-id> --declaration <module> [--inputs <file>] [--var <name>=<value>|<name>=@<ORG_VARIABLE_KEY>]... [--gateway-url <GatewayFQN>=<HTTPS-origin>]... [--accept-breaking-changes] [--allow-admin-principals] [--timeout-ms <milliseconds>] [--non-interactive] [--json]
3290
3293
  ci deploy --backend-url <url> --organization <organization-id> --resume <receipt-file> [--timeout-ms <milliseconds>] [--json]