@zuplo/runtime 6.59.50 → 6.59.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/out/esm/index.js CHANGED
@@ -52,7 +52,7 @@ import{a as qt,d as Se,e as px,f as la,g as da,h as mx,i as fx}from"./chunk-L2AZ
52
52
 
53
53
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);n.cycles==="ref"&&a(d);continue}if(p.count>1&&n.reused==="ref"){a(d);continue}}let u=i((d,p)=>{let m=this.seen.get(d),g=m.def??m.schema,h={...g};if(m.ref===null)return;let v=m.ref;if(m.ref=null,v){u(v,p);let b=this.seen.get(v).schema;b.$ref&&p.target==="draft-7"?(g.allOf=g.allOf??[],g.allOf.push(b)):(Object.assign(g,b),Object.assign(g,h))}m.isParent||this.override({zodSchema:d,jsonSchema:g})},"flattenRef");for(let d of[...this.seen.entries()].reverse())u(d[0],{target:this.target});let c={...o.def},l=n.external?.defs??{};for(let d of this.seen.entries()){let p=d[1];p.def&&p.defId&&(l[p.defId]=p.def)}!n.external&&Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l),this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};i(Bd,"toJSONSchema")});var lb={};var db=ee(()=>{});var Dt={};Ot(Dt,{$ZodAny:()=>Jc,$ZodArray:()=>Xc,$ZodAsyncError:()=>It,$ZodBase64:()=>Dc,$ZodBase64URL:()=>Zc,$ZodBigInt:()=>Gi,$ZodBigIntFormat:()=>Hc,$ZodBoolean:()=>Wn,$ZodCIDRv4:()=>Mc,$ZodCIDRv6:()=>zc,$ZodCUID:()=>Sc,$ZodCUID2:()=>kc,$ZodCatch:()=>gl,$ZodCheck:()=>Ce,$ZodCheckBigIntFormat:()=>Yu,$ZodCheckEndsWith:()=>dc,$ZodCheckGreaterThan:()=>ji,$ZodCheckIncludes:()=>cc,$ZodCheckLengthEquals:()=>ic,$ZodCheckLessThan:()=>Zi,$ZodCheckLowerCase:()=>ac,$ZodCheckMaxLength:()=>nc,$ZodCheckMaxSize:()=>ec,$ZodCheckMimeType:()=>mc,$ZodCheckMinLength:()=>oc,$ZodCheckMinSize:()=>tc,$ZodCheckMultipleOf:()=>Qu,$ZodCheckNumberFormat:()=>Xu,$ZodCheckOverwrite:()=>fc,$ZodCheckProperty:()=>pc,$ZodCheckRegex:()=>sc,$ZodCheckSizeEquals:()=>rc,$ZodCheckStartsWith:()=>lc,$ZodCheckStringFormat:()=>Dr,$ZodCheckUpperCase:()=>uc,$ZodCustom:()=>xl,$ZodDate:()=>Qc,$ZodDefault:()=>dl,$ZodDiscriminatedUnion:()=>el,$ZodE164:()=>jc,$ZodEmail:()=>xc,$ZodEmoji:()=>Rc,$ZodEnum:()=>il,$ZodError:()=>Fn,$ZodFile:()=>al,$ZodFunction:()=>hs,$ZodGUID:()=>vc,$ZodIPv4:()=>Nc,$ZodIPv6:()=>Lc,$ZodISODate:()=>$c,$ZodISODateTime:()=>Cc,$ZodISODuration:()=>Ac,$ZodISOTime:()=>Oc,$ZodIntersection:()=>tl,$ZodJWT:()=>qc,$ZodKSUID:()=>Ec,$ZodLazy:()=>wl,$ZodLiteral:()=>sl,$ZodMap:()=>nl,$ZodNaN:()=>hl,$ZodNanoID:()=>Ic,$ZodNever:()=>Wc,$ZodNonOptional:()=>ml,$ZodNull:()=>Vc,$ZodNullable:()=>ll,$ZodNumber:()=>Bi,$ZodNumberFormat:()=>Fc,$ZodObject:()=>Yc,$ZodOptional:()=>cl,$ZodPipe:()=>Qn,$ZodPrefault:()=>pl,$ZodPromise:()=>vl,$ZodReadonly:()=>yl,$ZodRealError:()=>Ur,$ZodRecord:()=>rl,$ZodRegistry:()=>Zr,$ZodSet:()=>ol,$ZodString:()=>Jn,$ZodStringFormat:()=>Ie,$ZodSuccess:()=>fl,$ZodSymbol:()=>Bc,$ZodTemplateLiteral:()=>bl,$ZodTransform:()=>ul,$ZodTuple:()=>fr,$ZodType:()=>le,$ZodULID:()=>_c,$ZodURL:()=>Pc,$ZodUUID:()=>wc,$ZodUndefined:()=>Gc,$ZodUnion:()=>Vi,$ZodUnknown:()=>Kn,$ZodVoid:()=>Kc,$ZodXID:()=>Tc,$brand:()=>ki,$constructor:()=>S,$input:()=>nd,$output:()=>rd,Doc:()=>Vn,JSONSchema:()=>lb,JSONSchemaGenerator:()=>ho,_any:()=>_d,_array:()=>Dd,_base64:()=>ps,_base64url:()=>ms,_bigint:()=>wd,_boolean:()=>bd,_catch:()=>dk,_cidrv4:()=>ls,_cidrv6:()=>ds,_coercedBigint:()=>xd,_coercedBoolean:()=>vd,_coercedDate:()=>Od,_coercedNumber:()=>pd,_coercedString:()=>sd,_cuid:()=>ns,_cuid2:()=>os,_custom:()=>go,_date:()=>$d,_default:()=>uk,_discriminatedUnion:()=>QS,_e164:()=>fs,_email:()=>Wi,_emoji:()=>ts,_endsWith:()=>uo,_enum:()=>rk,_file:()=>jd,_float32:()=>fd,_float64:()=>gd,_gt:()=>zt,_gte:()=>Ve,_guid:()=>to,_includes:()=>so,_int:()=>md,_int32:()=>hd,_int64:()=>Pd,_intersection:()=>XS,_ipv4:()=>us,_ipv6:()=>cs,_isoDate:()=>ud,_isoDateTime:()=>ad,_isoDuration:()=>ld,_isoTime:()=>cd,_jwt:()=>gs,_ksuid:()=>as,_lazy:()=>gk,_length:()=>Fr,_literal:()=>ok,_lowercase:()=>oo,_lt:()=>Mt,_lte:()=>ct,_map:()=>ek,_max:()=>ct,_maxLength:()=>qr,_maxSize:()=>jr,_mime:()=>co,_min:()=>Ve,_minLength:()=>Kt,_minSize:()=>hr,_multipleOf:()=>gr,_nan:()=>Ad,_nanoid:()=>rs,_nativeEnum:()=>nk,_negative:()=>Ld,_never:()=>Ed,_nonnegative:()=>zd,_nonoptional:()=>ck,_nonpositive:()=>Md,_normalize:()=>lo,_null:()=>kd,_nullable:()=>ak,_number:()=>dd,_optional:()=>sk,_overwrite:()=>Ut,_parse:()=>Ei,_parseAsync:()=>$i,_pipe:()=>pk,_positive:()=>Nd,_promise:()=>hk,_property:()=>Ud,_readonly:()=>mk,_record:()=>YS,_refine:()=>yk,_regex:()=>no,_safeParse:()=>Ai,_safeParseAsync:()=>Ni,_set:()=>tk,_size:()=>ro,_startsWith:()=>ao,_string:()=>id,_stringbool:()=>qd,_success:()=>lk,_symbol:()=>Id,_templateLiteral:()=>fk,_toLowerCase:()=>mo,_toUpperCase:()=>fo,_transform:()=>ik,_trim:()=>po,_tuple:()=>Zd,_uint32:()=>yd,_uint64:()=>Rd,_ulid:()=>is,_undefined:()=>Sd,_union:()=>KS,_unknown:()=>Td,_uppercase:()=>io,_url:()=>es,_uuid:()=>Ki,_uuidv4:()=>Qi,_uuidv6:()=>Xi,_uuidv7:()=>Yi,_void:()=>Cd,_xid:()=>ss,clone:()=>tt,config:()=>ze,flattenError:()=>Hn,formatError:()=>Bn,function:()=>Hd,globalConfig:()=>Ln,globalRegistry:()=>kt,isValidBase64:()=>Uc,isValidBase64URL:()=>qh,isValidJWT:()=>Fh,locales:()=>eo,parse:()=>Ci,parseAsync:()=>Oi,prettifyError:()=>xu,regexes:()=>mr,registry:()=>Ji,safeParse:()=>Ru,safeParseAsync:()=>Iu,toDotPath:()=>Ih,toJSONSchema:()=>Bd,treeifyError:()=>wu,util:()=>Y,version:()=>hc});var Je=ee(()=>{zr();Li();Pu();Xn();qi();yc();me();Di();ab();od();gc();ub();Fd();cb();db()});var Gd=ee(()=>{Je()});var ys={};Ot(ys,{ZodISODate:()=>mb,ZodISODateTime:()=>pb,ZodISODuration:()=>gb,ZodISOTime:()=>fb,date:()=>Jd,datetime:()=>Vd,duration:()=>Kd,time:()=>Wd});function Vd(t){return ad(pb,t)}function Jd(t){return ud(mb,t)}function Wd(t){return cd(fb,t)}function Kd(t){return ld(gb,t)}var pb,mb,fb,gb,Qd=ee(()=>{Je();bs();pb=S("ZodISODateTime",(t,e)=>{Cc.init(t,e),ke.init(t,e)});i(Vd,"datetime");mb=S("ZodISODate",(t,e)=>{$c.init(t,e),ke.init(t,e)});i(Jd,"date");fb=S("ZodISOTime",(t,e)=>{Oc.init(t,e),ke.init(t,e)});i(Wd,"time");gb=S("ZodISODuration",(t,e)=>{Ac.init(t,e),ke.init(t,e)});i(Kd,"duration")});var yb,wk,Hr,Xd=ee(()=>{Je();Je();yb=i((t,e)=>{Fn.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:i(r=>Bn(t,r),"value")},flatten:{value:i(r=>Hn(t,r),"value")},addIssue:{value:i(r=>t.issues.push(r),"value")},addIssues:{value:i(r=>t.issues.push(...r),"value")},isEmpty:{get(){return t.issues.length===0}}})},"initializer"),wk=S("ZodError",yb),Hr=S("ZodError",yb,{Parent:Error})});var Yd,ep,tp,rp,np=ee(()=>{Je();Xd();Yd=Ei(Hr),ep=$i(Hr),tp=Ai(Hr),rp=Ni(Hr)});var op={};Ot(op,{bigint:()=>Sk,boolean:()=>Ik,date:()=>kk,number:()=>Rk,string:()=>Pk});function Pk(t){return sd(vs,t)}function Rk(t){return pd(yo,t)}function Ik(t){return vd(bo,t)}function Sk(t){return xd(vo,t)}function kk(t){return Od(ws,t)}var bb=ee(()=>{Je();bs();i(Pk,"string");i(Rk,"number");i(Ik,"boolean");i(Sk,"bigint");i(kk,"date")});function ip(t){return id(vs,t)}function _k(t){return Wi(up,t)}function Tk(t){return to(xs,t)}function Ek(t){return Ki(Zt,t)}function Ck(t){return Qi(Zt,t)}function $k(t){return Xi(Zt,t)}function Ok(t){return Yi(Zt,t)}function Ak(t){return es(cp,t)}function Nk(t){return ts(lp,t)}function Lk(t){return rs(dp,t)}function Mk(t){return ns(pp,t)}function zk(t){return os(mp,t)}function Uk(t){return is(fp,t)}function Dk(t){return ss(gp,t)}function Zk(t){return as(hp,t)}function jk(t){return us(yp,t)}function qk(t){return cs(bp,t)}function Fk(t){return ls(vp,t)}function Hk(t){return ds(wp,t)}function Bk(t){return ps(xp,t)}function Gk(t){return ms(Pp,t)}function Vk(t){return fs(Rp,t)}function Jk(t){return gs(Ip,t)}function vb(t){return dd(yo,t)}function sp(t){return md(Br,t)}function Wk(t){return fd(Br,t)}function Kk(t){return gd(Br,t)}function Qk(t){return hd(Br,t)}function Xk(t){return yd(Br,t)}function wb(t){return bd(bo,t)}function Yk(t){return wd(vo,t)}function e_(t){return Pd(Sp,t)}function t_(t){return Rd(Sp,t)}function r_(t){return Id(xb,t)}function n_(t){return Sd(Pb,t)}function Ib(t){return kd(Rb,t)}function o_(){return _d(Sb)}function Ps(){return Td(kp)}function ks(t){return Ed(kb,t)}function i_(t){return Cd(_b,t)}function s_(t){return $d(ws,t)}function _p(t,e){return Dd(Tb,t,e)}function a_(t){let e=t._zod.def.shape;return Ub(Object.keys(e))}function u_(t,e){let r={type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},...Y.normalizeParams(e)};return new _s(r)}function c_(t,e){return new _s({type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},catchall:ks(),...Y.normalizeParams(e)})}function l_(t,e){return new _s({type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},catchall:Ps(),...Y.normalizeParams(e)})}function Ts(t,e){return new Tp({type:"union",options:t,...Y.normalizeParams(e)})}function d_(t,e,r){return new Eb({type:"union",options:e,discriminator:t,...Y.normalizeParams(r)})}function $b(t,e){return new Cb({type:"intersection",left:t,right:e})}function p_(t,e,r){let n=e instanceof le,o=n?r:e,s=n?e:null;return new Ob({type:"tuple",items:t,rest:s,...Y.normalizeParams(o)})}function Ab(t,e,r){return new Ep({type:"record",keyType:t,valueType:e,...Y.normalizeParams(r)})}function m_(t,e,r){return new Ep({type:"record",keyType:Ts([t,ks()]),valueType:e,...Y.normalizeParams(r)})}function f_(t,e,r){return new Nb({type:"map",keyType:t,valueType:e,...Y.normalizeParams(r)})}function g_(t,e){return new Lb({type:"set",valueType:t,...Y.normalizeParams(e)})}function Mb(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new wo({type:"enum",entries:r,...Y.normalizeParams(e)})}function h_(t,e){return new wo({type:"enum",entries:t,...Y.normalizeParams(e)})}function Ub(t,e){return new zb({type:"literal",values:Array.isArray(t)?t:[t],...Y.normalizeParams(e)})}function y_(t){return jd(Db,t)}function Cp(t){return new Zb({type:"transform",transform:t})}function Rs(t){return new $p({type:"optional",innerType:t})}function Is(t){return new jb({type:"nullable",innerType:t})}function b_(t){return Rs(Is(t))}function Fb(t,e){return new qb({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Bb(t,e){return new Hb({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function Gb(t,e){return new Op({type:"nonoptional",innerType:t,...Y.normalizeParams(e)})}function v_(t){return new Vb({type:"success",innerType:t})}function Wb(t,e){return new Jb({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function w_(t){return Ad(Kb,t)}function Ss(t,e){return new Ap({type:"pipe",in:t,out:e})}function Xb(t){return new Qb({type:"readonly",innerType:t})}function x_(t,e){return new Yb({type:"template_literal",parts:t,...Y.normalizeParams(e)})}function tv(t){return new ev({type:"lazy",getter:t})}function P_(t){return new rv({type:"promise",innerType:t})}function nv(t,e){let r=new Ce({check:"custom",...Y.normalizeParams(e)});return r._zod.check=t,r}function R_(t,e){return go(Es,t??(()=>!0),e)}function ov(t,e={}){return go(Es,t,e)}function iv(t,e){let r=nv(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(Y.issue(o,n.value,r._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(Y.issue(s))}},t(n.value,n)),e);return r}function I_(t,e={error:`Input not instance of ${t.name}`}){let r=new Es({type:"custom",check:"custom",fn:i(n=>n instanceof t,"fn"),abort:!0,...Y.normalizeParams(e)});return r._zod.bag.Class=t,r}function k_(t){let e=tv(()=>Ts([ip(t),vb(),wb(),Ib(),_p(e),Ab(ip(),e)]));return e}function __(t,e){return Ss(Cp(t),e)}var ge,ap,vs,ke,up,xs,Zt,cp,lp,dp,pp,mp,fp,gp,hp,yp,bp,vp,wp,xp,Pp,Rp,Ip,yo,Br,bo,vo,Sp,xb,Pb,Rb,Sb,kp,kb,_b,ws,Tb,_s,Tp,Eb,Cb,Ob,Ep,Nb,Lb,wo,zb,Db,Zb,$p,jb,qb,Hb,Op,Vb,Jb,Kb,Ap,Qb,Yb,ev,rv,Es,S_,bs=ee(()=>{Je();Je();Gd();Qd();np();Qd();bb();ge=S("ZodType",(t,e)=>(le.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>tt(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>Yd(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>tp(t,r,n),t.parseAsync=async(r,n)=>ep(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>rp(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(ov(r,n)),t.superRefine=r=>t.check(iv(r)),t.overwrite=r=>t.check(Ut(r)),t.optional=()=>Rs(t),t.nullable=()=>Is(t),t.nullish=()=>Rs(Is(t)),t.nonoptional=r=>Gb(t,r),t.array=()=>_p(t),t.or=r=>Ts([t,r]),t.and=r=>$b(t,r),t.transform=r=>Ss(t,Cp(r)),t.default=r=>Fb(t,r),t.prefault=r=>Bb(t,r),t.catch=r=>Wb(t,r),t.pipe=r=>Ss(t,r),t.readonly=()=>Xb(t),t.describe=r=>{let n=t.clone();return kt.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return kt.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return kt.get(t);let n=t.clone();return kt.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),ap=S("_ZodString",(t,e)=>{Jn.init(t,e),ge.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(no(...n)),t.includes=(...n)=>t.check(so(...n)),t.startsWith=n=>t.check(ao(n)),t.endsWith=n=>t.check(uo(n)),t.min=(...n)=>t.check(Kt(...n)),t.max=(...n)=>t.check(qr(...n)),t.length=(...n)=>t.check(Fr(...n)),t.nonempty=(...n)=>t.check(Kt(1,...n)),t.lowercase=n=>t.check(oo(n)),t.uppercase=n=>t.check(io(n)),t.trim=()=>t.check(po()),t.normalize=(...n)=>t.check(lo(...n)),t.toLowerCase=()=>t.check(mo()),t.toUpperCase=()=>t.check(fo())}),vs=S("ZodString",(t,e)=>{Jn.init(t,e),ap.init(t,e),t.email=r=>t.check(Wi(up,r)),t.url=r=>t.check(es(cp,r)),t.jwt=r=>t.check(gs(Ip,r)),t.emoji=r=>t.check(ts(lp,r)),t.guid=r=>t.check(to(xs,r)),t.uuid=r=>t.check(Ki(Zt,r)),t.uuidv4=r=>t.check(Qi(Zt,r)),t.uuidv6=r=>t.check(Xi(Zt,r)),t.uuidv7=r=>t.check(Yi(Zt,r)),t.nanoid=r=>t.check(rs(dp,r)),t.guid=r=>t.check(to(xs,r)),t.cuid=r=>t.check(ns(pp,r)),t.cuid2=r=>t.check(os(mp,r)),t.ulid=r=>t.check(is(fp,r)),t.base64=r=>t.check(ps(xp,r)),t.base64url=r=>t.check(ms(Pp,r)),t.xid=r=>t.check(ss(gp,r)),t.ksuid=r=>t.check(as(hp,r)),t.ipv4=r=>t.check(us(yp,r)),t.ipv6=r=>t.check(cs(bp,r)),t.cidrv4=r=>t.check(ls(vp,r)),t.cidrv6=r=>t.check(ds(wp,r)),t.e164=r=>t.check(fs(Rp,r)),t.datetime=r=>t.check(Vd(r)),t.date=r=>t.check(Jd(r)),t.time=r=>t.check(Wd(r)),t.duration=r=>t.check(Kd(r))});i(ip,"string");ke=S("ZodStringFormat",(t,e)=>{Ie.init(t,e),ap.init(t,e)}),up=S("ZodEmail",(t,e)=>{xc.init(t,e),ke.init(t,e)});i(_k,"email");xs=S("ZodGUID",(t,e)=>{vc.init(t,e),ke.init(t,e)});i(Tk,"guid");Zt=S("ZodUUID",(t,e)=>{wc.init(t,e),ke.init(t,e)});i(Ek,"uuid");i(Ck,"uuidv4");i($k,"uuidv6");i(Ok,"uuidv7");cp=S("ZodURL",(t,e)=>{Pc.init(t,e),ke.init(t,e)});i(Ak,"url");lp=S("ZodEmoji",(t,e)=>{Rc.init(t,e),ke.init(t,e)});i(Nk,"emoji");dp=S("ZodNanoID",(t,e)=>{Ic.init(t,e),ke.init(t,e)});i(Lk,"nanoid");pp=S("ZodCUID",(t,e)=>{Sc.init(t,e),ke.init(t,e)});i(Mk,"cuid");mp=S("ZodCUID2",(t,e)=>{kc.init(t,e),ke.init(t,e)});i(zk,"cuid2");fp=S("ZodULID",(t,e)=>{_c.init(t,e),ke.init(t,e)});i(Uk,"ulid");gp=S("ZodXID",(t,e)=>{Tc.init(t,e),ke.init(t,e)});i(Dk,"xid");hp=S("ZodKSUID",(t,e)=>{Ec.init(t,e),ke.init(t,e)});i(Zk,"ksuid");yp=S("ZodIPv4",(t,e)=>{Nc.init(t,e),ke.init(t,e)});i(jk,"ipv4");bp=S("ZodIPv6",(t,e)=>{Lc.init(t,e),ke.init(t,e)});i(qk,"ipv6");vp=S("ZodCIDRv4",(t,e)=>{Mc.init(t,e),ke.init(t,e)});i(Fk,"cidrv4");wp=S("ZodCIDRv6",(t,e)=>{zc.init(t,e),ke.init(t,e)});i(Hk,"cidrv6");xp=S("ZodBase64",(t,e)=>{Dc.init(t,e),ke.init(t,e)});i(Bk,"base64");Pp=S("ZodBase64URL",(t,e)=>{Zc.init(t,e),ke.init(t,e)});i(Gk,"base64url");Rp=S("ZodE164",(t,e)=>{jc.init(t,e),ke.init(t,e)});i(Vk,"e164");Ip=S("ZodJWT",(t,e)=>{qc.init(t,e),ke.init(t,e)});i(Jk,"jwt");yo=S("ZodNumber",(t,e)=>{Bi.init(t,e),ge.init(t,e),t.gt=(n,o)=>t.check(zt(n,o)),t.gte=(n,o)=>t.check(Ve(n,o)),t.min=(n,o)=>t.check(Ve(n,o)),t.lt=(n,o)=>t.check(Mt(n,o)),t.lte=(n,o)=>t.check(ct(n,o)),t.max=(n,o)=>t.check(ct(n,o)),t.int=n=>t.check(sp(n)),t.safe=n=>t.check(sp(n)),t.positive=n=>t.check(zt(0,n)),t.nonnegative=n=>t.check(Ve(0,n)),t.negative=n=>t.check(Mt(0,n)),t.nonpositive=n=>t.check(ct(0,n)),t.multipleOf=(n,o)=>t.check(gr(n,o)),t.step=(n,o)=>t.check(gr(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});i(vb,"number");Br=S("ZodNumberFormat",(t,e)=>{Fc.init(t,e),yo.init(t,e)});i(sp,"int");i(Wk,"float32");i(Kk,"float64");i(Qk,"int32");i(Xk,"uint32");bo=S("ZodBoolean",(t,e)=>{Wn.init(t,e),ge.init(t,e)});i(wb,"boolean");vo=S("ZodBigInt",(t,e)=>{Gi.init(t,e),ge.init(t,e),t.gte=(n,o)=>t.check(Ve(n,o)),t.min=(n,o)=>t.check(Ve(n,o)),t.gt=(n,o)=>t.check(zt(n,o)),t.gte=(n,o)=>t.check(Ve(n,o)),t.min=(n,o)=>t.check(Ve(n,o)),t.lt=(n,o)=>t.check(Mt(n,o)),t.lte=(n,o)=>t.check(ct(n,o)),t.max=(n,o)=>t.check(ct(n,o)),t.positive=n=>t.check(zt(BigInt(0),n)),t.negative=n=>t.check(Mt(BigInt(0),n)),t.nonpositive=n=>t.check(ct(BigInt(0),n)),t.nonnegative=n=>t.check(Ve(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(gr(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});i(Yk,"bigint");Sp=S("ZodBigIntFormat",(t,e)=>{Hc.init(t,e),vo.init(t,e)});i(e_,"int64");i(t_,"uint64");xb=S("ZodSymbol",(t,e)=>{Bc.init(t,e),ge.init(t,e)});i(r_,"symbol");Pb=S("ZodUndefined",(t,e)=>{Gc.init(t,e),ge.init(t,e)});i(n_,"_undefined");Rb=S("ZodNull",(t,e)=>{Vc.init(t,e),ge.init(t,e)});i(Ib,"_null");Sb=S("ZodAny",(t,e)=>{Jc.init(t,e),ge.init(t,e)});i(o_,"any");kp=S("ZodUnknown",(t,e)=>{Kn.init(t,e),ge.init(t,e)});i(Ps,"unknown");kb=S("ZodNever",(t,e)=>{Wc.init(t,e),ge.init(t,e)});i(ks,"never");_b=S("ZodVoid",(t,e)=>{Kc.init(t,e),ge.init(t,e)});i(i_,"_void");ws=S("ZodDate",(t,e)=>{Qc.init(t,e),ge.init(t,e),t.min=(n,o)=>t.check(Ve(n,o)),t.max=(n,o)=>t.check(ct(n,o));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});i(s_,"date");Tb=S("ZodArray",(t,e)=>{Xc.init(t,e),ge.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Kt(r,n)),t.nonempty=r=>t.check(Kt(1,r)),t.max=(r,n)=>t.check(qr(r,n)),t.length=(r,n)=>t.check(Fr(r,n))});i(_p,"array");i(a_,"keyof");_s=S("ZodObject",(t,e)=>{Yc.init(t,e),ge.init(t,e),Y.defineLazy(t,"shape",()=>Object.fromEntries(Object.entries(t._zod.def.shape))),t.keyof=()=>Mb(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ps()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ps()}),t.strict=()=>t.clone({...t._zod.def,catchall:ks()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>Y.extend(t,r),t.merge=r=>Y.merge(t,r),t.pick=r=>Y.pick(t,r),t.omit=r=>Y.omit(t,r),t.partial=(...r)=>Y.partial($p,t,r[0]),t.required=(...r)=>Y.required(Op,t,r[0])});i(u_,"object");i(c_,"strictObject");i(l_,"looseObject");Tp=S("ZodUnion",(t,e)=>{Vi.init(t,e),ge.init(t,e),t.options=e.options});i(Ts,"union");Eb=S("ZodDiscriminatedUnion",(t,e)=>{Tp.init(t,e),el.init(t,e)});i(d_,"discriminatedUnion");Cb=S("ZodIntersection",(t,e)=>{tl.init(t,e),ge.init(t,e)});i($b,"intersection");Ob=S("ZodTuple",(t,e)=>{fr.init(t,e),ge.init(t,e),t.rest=r=>t.clone({...t._zod.def,rest:r})});i(p_,"tuple");Ep=S("ZodRecord",(t,e)=>{rl.init(t,e),ge.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});i(Ab,"record");i(m_,"partialRecord");Nb=S("ZodMap",(t,e)=>{nl.init(t,e),ge.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});i(f_,"map");Lb=S("ZodSet",(t,e)=>{ol.init(t,e),ge.init(t,e),t.min=(...r)=>t.check(hr(...r)),t.nonempty=r=>t.check(hr(1,r)),t.max=(...r)=>t.check(jr(...r)),t.size=(...r)=>t.check(ro(...r))});i(g_,"set");wo=S("ZodEnum",(t,e)=>{il.init(t,e),ge.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let a of n)if(r.has(a))s[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new wo({...e,checks:[],...Y.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let a of n)if(r.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new wo({...e,checks:[],...Y.normalizeParams(o),entries:s})}});i(Mb,"_enum");i(h_,"nativeEnum");zb=S("ZodLiteral",(t,e)=>{sl.init(t,e),ge.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});i(Ub,"literal");Db=S("ZodFile",(t,e)=>{al.init(t,e),ge.init(t,e),t.min=(r,n)=>t.check(hr(r,n)),t.max=(r,n)=>t.check(jr(r,n)),t.mime=(r,n)=>t.check(co(r,n))});i(y_,"file");Zb=S("ZodTransform",(t,e)=>{ul.init(t,e),ge.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Y.issue(s,r.value,e));else{let a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),a.continue??(a.continue=!0),r.issues.push(Y.issue(a))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});i(Cp,"transform");$p=S("ZodOptional",(t,e)=>{cl.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType});i(Rs,"optional");jb=S("ZodNullable",(t,e)=>{ll.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType});i(Is,"nullable");i(b_,"nullish");qb=S("ZodDefault",(t,e)=>{dl.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});i(Fb,"_default");Hb=S("ZodPrefault",(t,e)=>{pl.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType});i(Bb,"prefault");Op=S("ZodNonOptional",(t,e)=>{ml.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType});i(Gb,"nonoptional");Vb=S("ZodSuccess",(t,e)=>{fl.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType});i(v_,"success");Jb=S("ZodCatch",(t,e)=>{gl.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});i(Wb,"_catch");Kb=S("ZodNaN",(t,e)=>{hl.init(t,e),ge.init(t,e)});i(w_,"nan");Ap=S("ZodPipe",(t,e)=>{Qn.init(t,e),ge.init(t,e),t.in=e.in,t.out=e.out});i(Ss,"pipe");Qb=S("ZodReadonly",(t,e)=>{yl.init(t,e),ge.init(t,e)});i(Xb,"readonly");Yb=S("ZodTemplateLiteral",(t,e)=>{bl.init(t,e),ge.init(t,e)});i(x_,"templateLiteral");ev=S("ZodLazy",(t,e)=>{wl.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.getter()});i(tv,"lazy");rv=S("ZodPromise",(t,e)=>{vl.init(t,e),ge.init(t,e),t.unwrap=()=>t._zod.def.innerType});i(P_,"promise");Es=S("ZodCustom",(t,e)=>{xl.init(t,e),ge.init(t,e)});i(nv,"check");i(R_,"custom");i(ov,"refine");i(iv,"superRefine");i(I_,"_instanceof");S_=qd.bind(null,{Pipe:Ap,Boolean:bo,Unknown:kp});i(k_,"json");i(__,"preprocess")});function $_(t){ze({customError:t})}function O_(){return ze().customError}var T_,E_,C_,sv=ee(()=>{Je();Je();T_={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"},E_=Object.freeze({status:"aborted"}),C_=E_;i($_,"setErrorMap");i(O_,"getErrorMap")});var f={};Ot(f,{$brand:()=>ki,$input:()=>nd,$output:()=>rd,NEVER:()=>C_,ZodAny:()=>Sb,ZodArray:()=>Tb,ZodBase64:()=>xp,ZodBase64URL:()=>Pp,ZodBigInt:()=>vo,ZodBigIntFormat:()=>Sp,ZodBoolean:()=>bo,ZodCIDRv4:()=>vp,ZodCIDRv6:()=>wp,ZodCUID:()=>pp,ZodCUID2:()=>mp,ZodCatch:()=>Jb,ZodCustom:()=>Es,ZodDate:()=>ws,ZodDefault:()=>qb,ZodDiscriminatedUnion:()=>Eb,ZodE164:()=>Rp,ZodEmail:()=>up,ZodEmoji:()=>lp,ZodEnum:()=>wo,ZodError:()=>wk,ZodFile:()=>Db,ZodGUID:()=>xs,ZodIPv4:()=>yp,ZodIPv6:()=>bp,ZodIntersection:()=>Cb,ZodIssueCode:()=>T_,ZodJWT:()=>Ip,ZodKSUID:()=>hp,ZodLazy:()=>ev,ZodLiteral:()=>zb,ZodMap:()=>Nb,ZodNaN:()=>Kb,ZodNanoID:()=>dp,ZodNever:()=>kb,ZodNonOptional:()=>Op,ZodNull:()=>Rb,ZodNullable:()=>jb,ZodNumber:()=>yo,ZodNumberFormat:()=>Br,ZodObject:()=>_s,ZodOptional:()=>$p,ZodPipe:()=>Ap,ZodPrefault:()=>Hb,ZodPromise:()=>rv,ZodReadonly:()=>Qb,ZodRealError:()=>Hr,ZodRecord:()=>Ep,ZodSet:()=>Lb,ZodString:()=>vs,ZodStringFormat:()=>ke,ZodSuccess:()=>Vb,ZodSymbol:()=>xb,ZodTemplateLiteral:()=>Yb,ZodTransform:()=>Zb,ZodTuple:()=>Ob,ZodType:()=>ge,ZodULID:()=>fp,ZodURL:()=>cp,ZodUUID:()=>Zt,ZodUndefined:()=>Pb,ZodUnion:()=>Tp,ZodUnknown:()=>kp,ZodVoid:()=>_b,ZodXID:()=>gp,_ZodString:()=>ap,_default:()=>Fb,any:()=>o_,array:()=>_p,base64:()=>Bk,base64url:()=>Gk,bigint:()=>Yk,boolean:()=>wb,catch:()=>Wb,check:()=>nv,cidrv4:()=>Fk,cidrv6:()=>Hk,clone:()=>tt,coerce:()=>op,config:()=>ze,core:()=>Dt,cuid:()=>Mk,cuid2:()=>zk,custom:()=>R_,date:()=>s_,discriminatedUnion:()=>d_,e164:()=>Vk,email:()=>_k,emoji:()=>Nk,endsWith:()=>uo,enum:()=>Mb,file:()=>y_,flattenError:()=>Hn,float32:()=>Wk,float64:()=>Kk,formatError:()=>Bn,function:()=>Hd,getErrorMap:()=>O_,globalRegistry:()=>kt,gt:()=>zt,gte:()=>Ve,guid:()=>Tk,includes:()=>so,instanceof:()=>I_,int:()=>sp,int32:()=>Qk,int64:()=>e_,intersection:()=>$b,ipv4:()=>jk,ipv6:()=>qk,iso:()=>ys,json:()=>k_,jwt:()=>Jk,keyof:()=>a_,ksuid:()=>Zk,lazy:()=>tv,length:()=>Fr,literal:()=>Ub,locales:()=>eo,looseObject:()=>l_,lowercase:()=>oo,lt:()=>Mt,lte:()=>ct,map:()=>f_,maxLength:()=>qr,maxSize:()=>jr,mime:()=>co,minLength:()=>Kt,minSize:()=>hr,multipleOf:()=>gr,nan:()=>w_,nanoid:()=>Lk,nativeEnum:()=>h_,negative:()=>Ld,never:()=>ks,nonnegative:()=>zd,nonoptional:()=>Gb,nonpositive:()=>Md,normalize:()=>lo,null:()=>Ib,nullable:()=>Is,nullish:()=>b_,number:()=>vb,object:()=>u_,optional:()=>Rs,overwrite:()=>Ut,parse:()=>Yd,parseAsync:()=>ep,partialRecord:()=>m_,pipe:()=>Ss,positive:()=>Nd,prefault:()=>Bb,preprocess:()=>__,prettifyError:()=>xu,promise:()=>P_,property:()=>Ud,readonly:()=>Xb,record:()=>Ab,refine:()=>ov,regex:()=>no,regexes:()=>mr,registry:()=>Ji,safeParse:()=>tp,safeParseAsync:()=>rp,set:()=>g_,setErrorMap:()=>$_,size:()=>ro,startsWith:()=>ao,strictObject:()=>c_,string:()=>ip,stringbool:()=>S_,success:()=>v_,superRefine:()=>iv,symbol:()=>r_,templateLiteral:()=>x_,toJSONSchema:()=>Bd,toLowerCase:()=>mo,toUpperCase:()=>fo,transform:()=>Cp,treeifyError:()=>wu,trim:()=>po,tuple:()=>p_,uint32:()=>Xk,uint64:()=>t_,ulid:()=>Uk,undefined:()=>n_,union:()=>Ts,unknown:()=>Ps,uppercase:()=>io,url:()=>Ak,uuid:()=>Ek,uuidv4:()=>Ck,uuidv6:()=>$k,uuidv7:()=>Ok,void:()=>i_,xid:()=>Dk});var Np=ee(()=>{Je();bs();Gd();Xd();np();sv();Je();Tl();Je();ze(Yn())});var Lp=ee(()=>{Np();Np()});var Ue=ee(()=>{Lp();Lp()});var ht,$e,Qt=ee(()=>{ht="2.0";(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})($e||($e={}))});var xo,av,Cs=ee(()=>{Ue();xo=f.union([f.string(),f.number().int()]),av=f.union([xo,f.null()])});var N_,Xt,uv,Po=ee(()=>{Ue();Qt();N_=f.object({_meta:f.optional(f.object({}).loose())}).loose(),Xt=f.object({method:f.string(),params:f.optional(N_)}),uv=f.object({jsonrpc:f.literal(ht),...Xt.shape}).strict()});var L_,M_,nt,ot,cv,br=ee(()=>{Ue();Qt();Cs();L_=f.union([f.string(),f.number().int()]),M_=f.object({progressToken:f.optional(L_)}).loose(),nt=f.object({_meta:f.optional(M_)}).loose(),ot=f.object({method:f.string(),params:f.optional(nt)}),cv=f.object({jsonrpc:f.literal(ht),id:xo,...ot.shape}).strict()});var lt,sq,lv,vr=ee(()=>{Ue();Qt();Cs();lt=f.object({_meta:f.optional(f.object({}).loose())}).loose(),sq=lt.strict(),lv=f.object({jsonrpc:f.literal(ht),id:xo,result:lt}).strict()});var _t,Yt,Gr=ee(()=>{Ue();_t=f.object({name:f.string(),title:f.optional(f.string())}).loose(),Yt=f.object({audience:f.optional(f.array(f.enum(["user","assistant"]))),priority:f.optional(f.number().min(0).max(1)),lastModified:f.optional(f.string())}).loose()});var zp,gv=ee(()=>{Ue();zp=f.string()});var er,tr,hv=ee(()=>{Ue();gv();br();vr();er=ot.extend({params:nt.extend({cursor:f.optional(zp)}).optional()}),tr=lt.extend({nextCursor:f.optional(zp)})});var As=ee(()=>{hv()});var Up={};Ot(Up,{AudioContentSchema:()=>D_,EmbeddedResourceSchema:()=>Z_,ImageContentSchema:()=>U_,TextContentSchema:()=>z_});var z_,U_,D_,Z_,Dp=ee(()=>{Ue();Gr();z_=f.object({type:f.literal("text"),text:f.string(),annotations:f.optional(Yt),_meta:f.optional(f.object({}).loose())}).loose(),U_=f.object({type:f.literal("image"),data:f.base64(),mimeType:f.string(),annotations:f.optional(Yt),_meta:f.optional(f.object({}).loose())}).loose(),D_=f.object({type:f.literal("audio"),data:f.base64(),mimeType:f.string(),annotations:f.optional(Yt),_meta:f.optional(f.object({}).loose())}).loose(),Z_=f.lazy(()=>f.object({type:f.literal("resource"),resource:f.union([f.object({uri:f.url(),mimeType:f.optional(f.string()),_meta:f.optional(f.object({}).loose()),text:f.string()}).loose(),f.object({uri:f.url(),mimeType:f.optional(f.string()),_meta:f.optional(f.object({}).loose()),blob:f.base64()}).loose()]),annotations:f.optional(Yt),_meta:f.optional(f.object({}).loose())}).loose())});var qp={};Ot(qp,{BlobResourceContentsSchema:()=>bv,ListResourceTemplatesRequestSchema:()=>H_,ListResourceTemplatesResultSchema:()=>B_,ListResourcesRequestSchema:()=>q_,ListResourcesResultSchema:()=>F_,ReadResourceRequestSchema:()=>G_,ReadResourceResultSchema:()=>V_,ResourceContentsSchema:()=>Zp,ResourceLinkSchema:()=>j_,ResourceListChangedNotificationSchema:()=>K_,ResourceSchema:()=>jp,ResourceTemplateSchema:()=>vv,ResourceUpdatedNotificationSchema:()=>Q_,SubscribeRequestSchema:()=>J_,TextResourceContentsSchema:()=>yv,UnsubscribeRequestSchema:()=>W_});var Zp,yv,bv,jp,j_,vv,q_,F_,H_,B_,G_,V_,J_,W_,K_,Q_,Fp=ee(()=>{Ue();Po();br();vr();Gr();As();Zp=f.object({uri:f.url(),mimeType:f.optional(f.string()),_meta:f.optional(f.object({}).loose())}).loose(),yv=Zp.extend({text:f.string()}),bv=Zp.extend({blob:f.base64()}),jp=_t.extend({uri:f.url(),description:f.optional(f.string()),mimeType:f.optional(f.string()),annotations:f.optional(Yt),size:f.optional(f.number()),_meta:f.optional(f.object({}).loose())}),j_=jp.extend({type:f.literal("resource_link")}),vv=_t.extend({uriTemplate:f.string(),description:f.optional(f.string()),mimeType:f.optional(f.string()),annotations:f.optional(Yt),_meta:f.optional(f.object({}).loose())}),q_=er.extend({method:f.literal("resources/list")}),F_=tr.extend({resources:f.array(jp)}),H_=er.extend({method:f.literal("resources/templates/list")}),B_=tr.extend({resourceTemplates:f.array(vv)}),G_=ot.extend({method:f.literal("resources/read"),params:nt.extend({uri:f.url()})}),V_=lt.extend({contents:f.array(f.union([yv,bv]))}),J_=ot.extend({method:f.literal("resources/subscribe"),params:nt.extend({uri:f.url()})}),W_=ot.extend({method:f.literal("resources/unsubscribe"),params:nt.extend({uri:f.url()})}),K_=Xt.extend({method:f.literal("notifications/resources/list_changed")}),Q_=Xt.extend({method:f.literal("notifications/resources/updated"),params:f.object({uri:f.url()}).loose()})});Function.prototype.toString=function(){return"[native code]"};var Xo=globalThis,mg=Xo.caches;if(mg){let t=mg.open;Xo.caches.open=function(e){let r=R.instance.deploymentName??R.instance.build.BUILD_ID;return t.call(this,`${r}-${e}`)},delete Xo.caches.default,Object.freeze(Xo.caches)}var Yo=new Set,fg=new Set;function w(t){fg.has(t)||(fg.add(t),Yo.add(t))}i(w,"trackFeature");function gg(){let t=[...Yo];return Yo.clear(),t}i(gg,"getUnsentFeatures");function hg(t){for(let e of t)Yo.add(e)}i(hg,"restoreFeatures");function De(t,e){t.has("Authorization")||t.set("Authorization",`Bearer ${R.instance.authApiJWT}`),t.set("zp-rid",e??`global-${crypto.randomUUID()}`),t.set("zp-dn",R.instance.deploymentName??"unknown"),t.set("User-Agent",R.instance.systemUserAgent),t.set("zp-compat-date",R.instance.build.COMPATIBILITY_DATE??"none")}i(De,"setZuploHeaders");var Sr=class extends Error{static{i(this,"ApiError")}type;title;status;detail;instance;constructor(e,r){super(e.title,r);let{type:n,title:o,status:s,detail:a,instance:u}=e;this.name="ApiProblemError",this.type=n,this.title=o,this.status=s,this.detail=a,this.instance=u}};function gx(t){return t!=null&&typeof t=="object"&&"type"in t&&"title"in t&&"status"in t&&typeof t.type=="string"&&typeof t.title=="string"&&typeof t.status=="number"}i(gx,"isProblemDetails");async function hx(t,e={}){w("utility.zuplo-api-services");let{method:r="GET",data:n}=e,o=new URL(t,R.instance.zuploEdgeApiUrl),s=new Headers(e.headers);De(s),s.set("Content-Type","application/json");let a={method:r,headers:s};n&&(a.body=JSON.stringify(n));let u=await W.fetch(o,a),c;try{if(!u.ok){if(c=await u.clone().json(),gx(c))throw new Sr(c);let l={type:`https://zup.fail/http-status/${u.status}`,title:`HTTP ${u.status}`,status:u.status,detail:JSON.stringify(c)||"Request failed"};throw new Sr(l)}if(u.status===204)return;c=await u.clone().json()}catch(l){if(l instanceof Sr)throw l;let d={type:"https://zup.fail/unknown-error",title:"Internal Server Error",status:500,detail:l instanceof Error?l.message:String(l)};throw new Sr(d,{cause:l})}return c}i(hx,"apiServices");var yg=new Map,pa=class{static{i(this,"LruTtlCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let r=this.#n.get(e);if(!r)return;let n=Date.now();if(n>r.expiresAt){this.delete(e);return}r.lastUsed=n;let o=this.#r.indexOf(e);return o>=0&&(this.#r.splice(o,1),this.#r.push(e)),this.#o(),r?.data}put(e,r,n){if(n<=0)return;let o=this.#r.indexOf(e),s=o>=0;if(s)this.#r.splice(o,1);else if(this.#n.size>=this.#e){let c=this.#r.shift();c&&this.#n.delete(c)}let a=Date.now(),u={created:s?this.#n.get(e).created:a,lastUsed:a,expiresAt:a+n*1e3,data:r};this.#r.push(e),this.#n.set(e,u)}delete(e){let r=this.#r.indexOf(e);r>=0&&this.#r.splice(r,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();e>this.#t+1e4&&(this.purge(),this.#t=e)}purge(){let e=Date.now(),r=[];this.#n.forEach((n,o)=>{e>n.expiresAt&&r.push(o)}),r.forEach(n=>this.delete(n))}},ft=class{static{i(this,"MemoryCache")}constructor(e,r={maxSize:1e3}){this.name=e;let n=yg.get(e);n||(n=new pa(r),yg.set(e,n)),this.#e=n}name;#e;get(e){return this.#e.get(e)}put(e,r,n){return this.#e.put(e,r,n)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var ma="__zuplo-expiry-header",hn=class{static{i(this,"ZoneCache")}constructor(e,r){this.#t=e,this.#e=r}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let r=await this.#r(),n=this.#o(e),o=await r.match(n);if(!o)return;let s=o.headers.get(ma);if(!s){try{await r.delete(n)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await r.delete(n)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await o.json()}catch(r){this.logDebug(r)}}async put(e,r,n){let o=new Headers({"cache-control":`s-maxage=${n}, must-revalidate`,"content-type":"application/json"});o.set(ma,`${Date.now()+n*1e3}`);let s=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(r),{headers:o});await s.put(a,u)}async delete(e){let r=await this.#r(),n=this.#o(e);try{await r.delete(n)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let r=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});r.set(ma,`${Date.now()}`);let n=await this.#r(),o=this.#o(e),s=new Response("",{headers:r});await n.put(o,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var be=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,r,n){let o=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=n?new ft(o,n):new ft(o),this.#n=new hn(o,r),this.#r=r}#e;#t;#n;#r;async get(e){let r=this.#t.get(e);if(r)return r;let n=await this.#n.get(e);if(n){let o=Math.floor((n.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,n.data,o),n.data}}put(e,r,n){this.#t.put(e,r,n);let o={data:r,expires:Date.now()+n*1e3},s=this.#n.put(e,o,n).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(s)}async delete(e){this.#t.delete(e),await this.#n.delete(e)}};var fa="__zuplo-expiry-header",ga=class{static{i(this,"StreamingZoneCache")}constructor(e,r){this.#t=e,this.#e=r}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://streaming-zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let r=await this.#r(),n=this.#o(e),o=await r.match(n);if(!o)return;let s=o.headers.get(fa);if(!s){await r.delete(n).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting missing expiry entry ${e}`,u)});return}let a=parseInt(s,10);if(Date.now()>=a){await r.delete(n).catch(u=>{this.logDebug(`StreamingZoneCache: error deleting expired entry ${e}`,u)});return}return o.body??void 0}catch(r){this.logDebug(`get(${e}) failed`,r);return}}async put(e,r,n){let o=new Headers({"cache-control":`s-maxage=${n}, must-revalidate`});o.set(fa,`${Date.now()+n*1e3}`);let s=new Response(r,{headers:o}),a=await this.#r(),u=this.#o(e);await a.put(u,s)}async delete(e){try{await(await this.#r()).delete(this.#o(e))}catch(r){this.logDebug(`delete(${e}) fallback needed`,r),await this.deleteFallback(e)}}async deleteFallback(e){let r=new Headers({"Cache-Control":"s-maxage=0, must-revalidate",[fa]:`${Date.now()}`}),n=new Response("",{headers:r}),o=await this.#r(),s=this.#o(e);await o.put(s,n)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`StreamingZoneCache(${this.#t}):`,...e):"log"in this.#e&&this.#e.log.debug(`StreamingZoneCache(${this.#t}):`,...e)}};var de=class t{static{i(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,r){t.set(e,this.#t,r)}get(e){return t.get(e,this.#t)}static set(e,r,n){t.#e||(t.#e=new WeakMap);let o=t.#e.get(e);o||(o=new Map),o.set(r,n),t.#e.set(e,o)}static get(e,r){return t.#e||(t.#e=new WeakMap),t.#e.get(e)?.get(r)}};import{trace as dP}from"@opentelemetry/api";import{SpanStatusCode as Cx,trace as $x}from"@opentelemetry/api";import{SpanStatusCode as ni,trace as oi}from"@opentelemetry/api";var bg=i(t=>(e,r)=>t(e,r),"globalRequestHandlerProxy");function vg(t){bg=t}i(vg,"setTelemetryInitFunction");var wg=i(t=>bg(t),"proxyHandler");var Ft=class{static{i(this,"RuntimePlugin")}},Ee=class extends Ft{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e){}},ei=class extends Ee{static{i(this,"MeteringPlugin")}},yn=class extends Ft{static{i(this,"TelemetryPlugin")}};var bn=class t{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let r=e.problem,n=JSON.stringify(r,null,2);return new Response(n,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(w("runtime.problem-response-formatter"),t.problemResponseFormat=(r,n,o)=>{try{return e(r,n,o)}catch(s){throw new q("Error in custom 'problemResponseFormat'",{cause:s})}})}},sr=class{static{i(this,"ProblemResponseFormatter")}static async format(e,r,n){return await bn.problemResponseFormat(e,r,n)}};function ti(t){for(let e in t){let r=t[e];r&&typeof r=="object"&&ti(r)}return Object.freeze(t)}i(ti,"deepFreeze");var pe=class t extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,r){super(e,r);let n=r?.params;n?this.#t=n:e instanceof t?this.#t=e.#t:this.#t={};let o=r?.user;o?this.user=o:e instanceof t&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},r=new URL(this.url).searchParams;for(let[n,o]of r.entries())e[n]=o;this.#e=e}return ti(this.#e)}get params(){return ti(this.#t)}user};var wa={},gt=[],ha=[],ya=[],ba=[],va=[];var ri={addPlugin(t){gt.push(t)},addRequestHook(t){ha.push(t)},addResponseSendingHook(t){ya.push(t)},addResponseSendingFinalHook(t){ba.push(t)},addPreRoutingHook(t){va.push(t)}},Pg=i(async(t,e)=>{if(ha.length===0)return t;let r=oi.getTracer("extension");return r.startActiveSpan("hook:onRequest",async n=>{try{let o=t;for(let s of ha){let a=await r.startActiveSpan(s.name,async u=>{let c=await s(o,e);if(c instanceof pe||c instanceof Response)return u.end(),c;{let l=new y(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:ni.ERROR}),l}});if(a instanceof pe)o=a;else return a}return o}finally{n.end()}})},"invokeOnRequestExtensions"),Rg=i(async(t,e,r)=>{if(ya.length===0)return t;let n=oi.getTracer("extension");return n.startActiveSpan("hook:onResponseSending",async o=>{try{let s=t;for(let a of ya)await n.startActiveSpan(a.name,async u=>{let c=await a(t,e,r);if(c instanceof Response)s=c,u.end();else{let l=new y(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:ni.ERROR}),u.end(),l}});return s}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Ig=i(async(t,e,r)=>{if(ba.length===0)return;let n=oi.getTracer("extension");return n.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let s of ba)await n.startActiveSpan(s.name,async a=>{try{await s(t,e,r)}catch(u){throw a.recordException(u),a.setStatus({code:ni.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Sg=i(async t=>{if(va.length===0)return t;let e=oi.getTracer("extension");return e.startActiveSpan("hook:preRouting",async r=>{try{let n=t;for(let o of va)n=await e.startActiveSpan(o.name,async a=>{try{let u=await o(n);if(u instanceof Request)return u;{let c=new q(`Invalid state - the PreRouting hook must return a Request. Received ${typeof u}.`);throw a.recordException(c),a.setStatus({code:ni.ERROR}),c}}finally{a.end()}});return n}finally{r.end()}})},"invokePreRoutingHooks"),xg=!1;async function kg(t){if(!xg){t&&(w("runtime.extensions"),await t(ri)),wa.value=ri;for(let e of gt)if(e instanceof yn){let{requestHandlerProxy:r}=e.instrument({accountName:R.instance.build.ACCOUNT_NAME,projectName:R.instance.build.PROJECT_NAME,buildId:R.instance.build.BUILD_ID,zuploVersion:R.instance.build.ZUPLO_VERSION,compatibilityDate:R.instance.build.COMPATIBILITY_DATE,instanceId:R.instance.instanceId,environmentType:R.instance.loggingEnvironmentType,environmentStage:R.instance.loggingEnvironmentStage,deploymentName:R.instance.deploymentName});vg(r)}await Promise.all(gt.map(async e=>{e instanceof Ee&&await e.initialize(ri)})),bn.setProblemResponseFormat(ri.problemResponseFormat),xg=!0}}i(kg,"initializeRuntime");var xa={Json:"application/json",Form:"application/x-www-form-urlencoded"};function Pa(t,e){if(t!==null)return e&&typeof t=="string"?t:typeof t=="object"&&e?.startsWith(xa.Form)?new URLSearchParams(t).toString():typeof t=="object"&&e?.startsWith(xa.Json)||!e?JSON.stringify(t):t}i(Pa,"serialize");function kr(t){let{developerPortal:e}=ve.instance.runtimeSettings;return e.enabled&&e.basePath&&t.pathname.startsWith(e.basePath)||t.pathname.startsWith("/__zuplo/")||t.pathname.startsWith("/__/zuplo/")}i(kr,"isSystemRoute");var ii=(L=>(L[L.CONTINUE=100]="CONTINUE",L[L.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",L[L.PROCESSING=102]="PROCESSING",L[L.EARLY_HINTS=103]="EARLY_HINTS",L[L.OK=200]="OK",L[L.CREATED=201]="CREATED",L[L.ACCEPTED=202]="ACCEPTED",L[L.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",L[L.NO_CONTENT=204]="NO_CONTENT",L[L.RESET_CONTENT=205]="RESET_CONTENT",L[L.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",L[L.MULTI_STATUS=207]="MULTI_STATUS",L[L.ALREADY_REPORTED=208]="ALREADY_REPORTED",L[L.IM_USED=226]="IM_USED",L[L.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",L[L.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",L[L.FOUND=302]="FOUND",L[L.SEE_OTHER=303]="SEE_OTHER",L[L.NOT_MODIFIED=304]="NOT_MODIFIED",L[L.USE_PROXY=305]="USE_PROXY",L[L.SWITCH_PROXY=306]="SWITCH_PROXY",L[L.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",L[L.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",L[L.BAD_REQUEST=400]="BAD_REQUEST",L[L.UNAUTHORIZED=401]="UNAUTHORIZED",L[L.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",L[L.FORBIDDEN=403]="FORBIDDEN",L[L.NOT_FOUND=404]="NOT_FOUND",L[L.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",L[L.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",L[L.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",L[L.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",L[L.CONFLICT=409]="CONFLICT",L[L.GONE=410]="GONE",L[L.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",L[L.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",L[L.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",L[L.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",L[L.URI_TOO_LONG=414]="URI_TOO_LONG",L[L.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",L[L.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",L[L.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",L[L.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",L[L.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",L[L.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",L[L.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",L[L.LOCKED=423]="LOCKED",L[L.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",L[L.TOO_EARLY=425]="TOO_EARLY",L[L.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",L[L.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",L[L.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",L[L.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",L[L.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",L[L.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",L[L.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",L[L.BAD_GATEWAY=502]="BAD_GATEWAY",L[L.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",L[L.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",L[L.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",L[L.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",L[L.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",L[L.LOOP_DETECTED=508]="LOOP_DETECTED",L[L.NOT_EXTENDED=510]="NOT_EXTENDED",L[L.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",L))(ii||{}),_g={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var yx={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},Ra=yx;function bx(t){return`${new URL(t.url).pathname}`}i(bx,"instance");function vx(t,e){let r={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:R.instance.build.BUILD_ID},n=t.headers.get(Ir);return n&&(r.rayId=n),r}i(vx,"trace");var wx=i((t,e,r,n,o)=>({problem:{type:t.type,title:t.title,status:t.status,detail:t.detail,instance:bx(e),trace:vx(e,r),...n},additionalHeaders:o,statusText:Ra[t.status]}),"merge"),Ia=class{static{i(this,"HttpProblemsBase")}static format=i((e,r,n)=>"problem"in e?sr.format(e,r,n):sr.format({problem:e},r,n),"format");static getProblemFromStatus(e,r){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:_g[e],...r}}},M=class extends Ia{static{i(this,"HttpProblems")}static#e(e,r,n,o,s){let a=wx(this.getProblemFromStatus(e),r,n,o,s);return sr.format(a,r,n)}static continue=i((e,r,n,o)=>this.#e(200,e,r,n,o),"continue");static switchingProtocols=i((e,r,n,o)=>this.#e(101,e,r,n,o),"switchingProtocols");static processing=i((e,r,n,o)=>this.#e(102,e,r,n,o),"processing");static earlyHints=i((e,r,n,o)=>this.#e(103,e,r,n,o),"earlyHints");static ok=i((e,r,n,o)=>this.#e(200,e,r,n,o),"ok");static created=i((e,r,n,o)=>this.#e(201,e,r,n,o),"created");static accepted=i((e,r,n,o)=>this.#e(202,e,r,n,o),"accepted");static nonAuthoritativeInformation=i((e,r,n,o)=>this.#e(203,e,r,n,o),"nonAuthoritativeInformation");static noContent=i((e,r,n,o)=>this.#e(204,e,r,n,o),"noContent");static resetContent=i((e,r,n,o)=>this.#e(205,e,r,n,o),"resetContent");static partialContent=i((e,r,n,o)=>this.#e(206,e,r,n,o),"partialContent");static multiStatus=i((e,r,n,o)=>this.#e(207,e,r,n,o),"multiStatus");static alreadyReported=i((e,r,n,o)=>this.#e(208,e,r,n,o),"alreadyReported");static imUsed=i((e,r,n,o)=>this.#e(226,e,r,n,o),"imUsed");static multipleChoices=i((e,r,n,o)=>this.#e(300,e,r,n,o),"multipleChoices");static movedPermanently=i((e,r,n,o)=>this.#e(301,e,r,n,o),"movedPermanently");static found=i((e,r,n,o)=>this.#e(302,e,r,n,o),"found");static seeOther=i((e,r,n,o)=>this.#e(303,e,r,n,o),"seeOther");static notModified=i((e,r,n,o)=>this.#e(304,e,r,n,o),"notModified");static useProxy=i((e,r,n,o)=>this.#e(305,e,r,n,o),"useProxy");static switchProxy=i((e,r,n,o)=>this.#e(306,e,r,n,o),"switchProxy");static temporaryRedirect=i((e,r,n,o)=>this.#e(307,e,r,n,o),"temporaryRedirect");static permanentRedirect=i((e,r,n,o)=>this.#e(308,e,r,n,o),"permanentRedirect");static badRequest=i((e,r,n,o)=>this.#e(400,e,r,n,o),"badRequest");static unauthorized=i((e,r,n,o)=>this.#e(401,e,r,n,o),"unauthorized");static paymentRequired=i((e,r,n,o)=>this.#e(402,e,r,n,o),"paymentRequired");static forbidden=i((e,r,n,o)=>this.#e(403,e,r,n,o),"forbidden");static notFound=i((e,r,n,o)=>this.#e(404,e,r,n,o),"notFound");static methodNotAllowed=i((e,r,n,o)=>this.#e(405,e,r,n,o),"methodNotAllowed");static notAcceptable=i((e,r,n,o)=>this.#e(406,e,r,n,o),"notAcceptable");static proxyAuthenticationRequired=i((e,r,n,o)=>this.#e(407,e,r,n,o),"proxyAuthenticationRequired");static requestTimeout=i((e,r,n,o)=>this.#e(408,e,r,n,o),"requestTimeout");static conflict=i((e,r,n,o)=>this.#e(409,e,r,n,o),"conflict");static gone=i((e,r,n,o)=>this.#e(410,e,r,n,o),"gone");static lengthRequired=i((e,r,n,o)=>this.#e(411,e,r,n,o),"lengthRequired");static preconditionFailed=i((e,r,n,o)=>this.#e(412,e,r,n,o),"preconditionFailed");static contentTooLarge=i((e,r,n,o)=>this.#e(413,e,r,n,o),"contentTooLarge");static uriTooLong=i((e,r,n,o)=>this.#e(414,e,r,n,o),"uriTooLong");static unsupportedMediaType=i((e,r,n,o)=>this.#e(415,e,r,n,o),"unsupportedMediaType");static rangeNotSatisfiable=i((e,r,n,o)=>this.#e(416,e,r,n,o),"rangeNotSatisfiable");static expectationFailed=i((e,r,n,o)=>this.#e(417,e,r,n,o),"expectationFailed");static imATeapot=i((e,r,n,o)=>this.#e(418,e,r,n,o),"imATeapot");static misdirectedRequest=i((e,r,n,o)=>this.#e(421,e,r,n,o),"misdirectedRequest");static unprocessableContent=i((e,r,n,o)=>this.#e(422,e,r,n,o),"unprocessableContent");static locked=i((e,r,n,o)=>this.#e(423,e,r,n,o),"locked");static failedDependency=i((e,r,n,o)=>this.#e(424,e,r,n,o),"failedDependency");static tooEarly=i((e,r,n,o)=>this.#e(425,e,r,n,o),"tooEarly");static upgradeRequired=i((e,r,n,o)=>this.#e(426,e,r,n,o),"upgradeRequired");static preconditionRequired=i((e,r,n,o)=>this.#e(428,e,r,n,o),"preconditionRequired");static tooManyRequests=i((e,r,n,o)=>this.#e(429,e,r,n,o),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,r,n,o)=>this.#e(431,e,r,n,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,r,n,o)=>this.#e(451,e,r,n,o),"unavailableForLegalReasons");static internalServerError=i((e,r,n,o)=>this.#e(500,e,r,n,o),"internalServerError");static notImplemented=i((e,r,n,o)=>this.#e(501,e,r,n,o),"notImplemented");static badGateway=i((e,r,n,o)=>this.#e(502,e,r,n,o),"badGateway");static serviceUnavailable=i((e,r,n,o)=>this.#e(503,e,r,n,o),"serviceUnavailable");static gatewayTimeout=i((e,r,n,o)=>this.#e(504,e,r,n,o),"gatewayTimeout");static httpVersionNotSupported=i((e,r,n,o)=>this.#e(505,e,r,n,o),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,r,n,o)=>this.#e(506,e,r,n,o),"variantAlsoNegotiates");static insufficientStorage=i((e,r,n,o)=>this.#e(507,e,r,n,o),"insufficientStorage");static loopDetected=i((e,r,n,o)=>this.#e(508,e,r,n,o),"loopDetected");static notExtended=i((e,r,n,o)=>this.#e(510,e,r,n,o),"notExtended");static networkAuthenticationRequired=i((e,r,n,o)=>this.#e(511,e,r,n,o),"networkAuthenticationRequired")};var{toString:xx}=Object.prototype,{propertyIsEnumerable:Px}=Object.prototype;function Sa(t){return xx.call(t)}i(Sa,"toString");function Xe(t){return typeof t=="string"}i(Xe,"isString");function _r(t){return Xe(t)&&t!==""}i(_r,"isNonEmptyString");function Tg(t){return Sa(t)==="[object RegExp]"}i(Tg,"isRegexp");function Eg(t){return[...Object.keys(t),...Object.getOwnPropertySymbols(t).filter(e=>Px.call(t,e))]}i(Eg,"getOwnEnumerableKeys");function ar(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&!(t instanceof RegExp)&&!(t instanceof Date)}i(ar,"isObject");function ka(t){return typeof t=="number"&&!isNaN(t)}i(ka,"isNumber");function _a(t){return t===!0||t===!1}i(_a,"isBoolean");function Cg(t){return typeof t>"u"}i(Cg,"isUndefined");function $g(t){return Cg(t)||t===null}i($g,"isUndefinedOrNull");function vn(t){return!!t&&typeof t=="object"&&"name"in t&&"message"in t&&"stack"in t}i(vn,"isErrorLike");var Rx=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(t=>[t.name,t]),Ix=new Map(Rx);var Sx=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Ta=Symbol(".toJSON was called"),kx=i(t=>{t[Ta]=!0;let e=t.toJSON();return delete t[Ta],e},"toJSON"),_x=i(t=>Ix.get(t)??Error,"getErrorConstructor"),Og=i(({from:t,seen:e,to:r,forceEnumerable:n,maxDepth:o,depth:s,useToJSON:a,serialize:u})=>{if(!r)if(Array.isArray(t))r=[];else if(!u&&vn(t)){let l=_x(t.name);r=new l}else r={};if(e.push(t),s>=o)return r;if(a&&typeof t.toJSON=="function"&&t[Ta]!==!0)return kx(t);let c=i(l=>Og({from:l,seen:[...e],forceEnumerable:n,maxDepth:o,depth:s,useToJSON:a,serialize:u}),"continueDestroyCircular");for(let[l,d]of Object.entries(t)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){r[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){r[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){r[l]=d;continue}if(!e.includes(t[l])){s++,r[l]=c(t[l]);continue}r[l]="[Circular]"}}for(let{property:l,enumerable:d}of Sx)typeof t[l]<"u"&&t[l]!==null&&Object.defineProperty(r,l,{value:vn(t[l])?c(t[l]):t[l],enumerable:n?!0:d,configurable:!0,writable:!0});return r},"destroyCircular");function ur(t,e){let r=e?.maxDepth??Number.POSITIVE_INFINITY,n=e?.useToJSON??!0;return typeof t=="object"&&t!==null?Og({from:t,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:n,serialize:!0}):typeof t=="function"?`[Function: ${t.name??"anonymous"}]`:t}i(ur,"serializeError");var Tx=/file:\/\/\/(.*?)\/dist\//g,Ex="at async Event.respondWith";function Ea(t){return typeof t!="string"?t:t.split(`
54
54
  `).filter(e=>!e.trim().startsWith("at async file")).map((e,r)=>{let n=e.replaceAll(Tx,"").replaceAll(Ex,"").trim();return r===0||n.length===0?n:` ${n}`}).filter(e=>e.length>0).join(`
55
- `)}i(Ea,"cleanStack");function wt(t,e,r,n){e.log.error(r,n);let o={};if(R.instance.isLocalDevelopment||R.instance.isWorkingCopy)if(n instanceof q&&n.extensionMembers)o=n.extensionMembers;else if(n.cause){let s=ur(n.cause);"stack"in s&&(s.stack=Ea(s.stack)),o={cause:s}}else{let s=ur(n);"stack"in s&&(s.stack=Ea(s.stack)),o={cause:s}}return M.internalServerError(t,e,{detail:n.message,...o})}i(wt,"errorHandler");var Le=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i(e=>async(r,n)=>$x.getTracer("pipeline").startActiveSpan(`handler:${n.route.handler.export}`,async s=>{try{return await e(r,n)}catch(a){let u=wt(r,n,"Error executing request handler.",a);return s.setStatus({code:Cx.ERROR}),u}finally{s.end()}}),"#errorWrappedHandler");#t=i(({processors:e,handler:r})=>async(n,o)=>{let s=je.getContextExtensions(o),a=[...e],u=i(async h=>{let v=a.pop();if(!v){let k=await this.#e(async x=>{let $=await r(x,o);return Ox($)})(h,o);try{await s.onHandlerResponse(k,h,o)}catch(x){return wt(n,o,"Error invoking 'context.onHandlerResponse' hook",x)}return k}return v(n,o,u)},"nextPipe"),l=await u(n),d=new URL(n.url);if(kr(d)&&R.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new wn(n,l);o.dispatchEvent(p);let m=s.latestRequest,g;try{g=await p.mutableResponse}catch(h){return wt(n,o,"Error retrieving mutableResponse",h)}try{g=await s.onResponseSending(g,m,o)}catch(h){return wt(n,o,"Error invoking 'context.onResponseSending' hook",h)}try{g=await Rg(g,m,o)}catch(h){return wt(n,o,"Error invoking 'context.onResponseSending' hook",h)}o.dispatchEvent(new xn(n,g));try{await s.onResponseSendingFinal(l,m,o)}catch(h){throw o.log.error("Error invoking 'runtime.onResponseSending' hook",h),h}try{await Ig(l,m,o)}catch(h){throw o.log.error("Error invoking 'runtime.onResponseSending' hook",h),h}return g},"#toZuploPipeline")};function Ox(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Pa(t),{headers:{"content-type":"application/json"}})}i(Ox,"resultToResponse");var xt=class extends Ft{static{i(this,"MetricsPlugin")}};var re=class t{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let r=t.#e.get(e);if(!r){let n=`No system logger found for context with requestId '${e.requestId}'`;throw W.console.error(n),new ue(n)}return r}static addLogger(e,r){t.#e.set(e,r)}};var ce=class{static{i(this,"BatchDispatch")}constructor(e,r,n,o){this.#t=e,this.#i=r,this.#r=n,this.#n=o??W.console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=i(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(r=>{setTimeout(()=>{if(this.#o.length>0){let n=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(n).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{r()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed");get queueSize(){return this.#o.length}};async function Te(t,e,r){for(let n=0;n<=t.retries;n++){try{let o=W.fetch(e,r);if(n===t.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;t.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status})}catch(o){if(n===t.retries)throw o;t.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,error:o})}await new Promise(o=>setTimeout(o,t.retryDelayMs*Math.pow(2,n)))}throw new y("An unknown error occurred, ensure retries is not negative")}i(Te,"fetchRetry");var si=class{static{i(this,"ZuploMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new ce("zuplo-metrics-transport",10,this.dispatchFunction,re.getLogger(e))}pushMetrics(e,r){this.#t.enqueue(e),r.waitUntil(this.#t.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let{remoteLogURL:r,deploymentName:n}=R.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=R.instance.build,a=e.map(p=>{let m=Object.assign({},p);return delete m.requestContentLength,delete m.responseContentLength,m}),u=gg(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:n},metrics:a,features:u},l=new Headers({"content-type":"application/json"});De(l);let d=await Te({retries:3,retryDelayMs:1e3,logger:W.console},`${r}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:l});if(!d.ok){let p=await d.text();re.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),hg(u)}}catch(r){re.getLogger(this.#e).error("Failed to send Zuplo metrics.",r)}},"dispatchFunction")};var Tr="SYSTEM_IGNORED";var Me=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:r,methods:n,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=r,this.methods=n,this.corsPolicy=s,this.handler={export:Tr,module:Tr},this.systemRouteName=o}label;path;methods;handler;corsPolicy;policies;systemRouteName;metadata;raw(){return{}}};var Ca="x-real-ip",Ax="true-client-ip",Nx="cf-connecting-ip",Lx="x-forwarded-for";function at(t){let e=t.headers,r=e.get(Ca)??e.get(Ax)??e.get(Nx);if(r)return r;let n=e.get(Lx);if(n){let o=n.split(/,\s*/).map(s=>s.trim()).find(s=>s.length>0);if(o)return o}}i(at,"getClientIp");var qe=i(async(t,e,r)=>{let n=new Date,o=Date.now(),s=await r(t),a=t.headers.get(Ir)??void 0,u=at(t),c=e.incomingRequestProperties,l;e.route instanceof Me&&(l=e.route.systemRouteName);let d=je.getContextExtensions(e).latestRequest,p={timestamp:n,statusCode:s.status,durationMs:Date.now()-o,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:s.headers.get("content-length")?Number(s.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:l,contextId:e.contextId,parentContextId:e.parentContext?.contextId,requestId:e.requestId,parentRequestId:e.parentContext?.requestId,method:t.method,asn:c.asn,asOrganization:c.asOrganization,colo:c.colo,continent:c.continent,country:c.country,city:c.city,latitude:c.latitude,longitude:c.longitude,rayId:a,instanceId:R.instance.instanceId,userSub:d.user?.sub,clientIp:u},m=[];return!R.instance.isLocalDevelopment&&R.instance.remoteLogURL&&R.instance.remoteLogToken&&R.instance.loggingId&&m.push(new si(e)),gt.forEach(g=>{if(g instanceof xt){let h=g.getTransport();m.push(h)}}),m.forEach(g=>{g.pushMetrics(p,e)}),s},"metricsProcessor");var $a=i(t=>{let e=i(async(o,s)=>{let a=new URL(o.url),u=R.instance.build,c={buildId:u.BUILD_ID,zuploVersion:u.ZUPLO_VERSION,compatibilityDate:u.COMPATIBILITY_DATE,apiVersion:u.API_VERSION,gitSha:u.GIT_SHA,timestamp:u.TIMESTAMP,isProduction:u.ENVIRONMENT_TYPE==="PRODUCTION"};if(a.searchParams.get("system_log")==="true"&&re.getLogger(s).error("Test System Log",c),a.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(c,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new Le({processors:[qe],handler:e}),n=new Me({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(n,r.execute)},"registerBuildRoute");var ai=class{static{i(this,"BoundedSet")}limit;items;constructor(e){this.limit=e,this.items=new Map}add(e){if(this.items.has(e))this.items.delete(e);else if(this.items.size>=this.limit){let r=this.items.keys().next().value;r&&this.items.delete(r)}this.items.set(e,!0)}has(e){return this.items.has(e)}values(){return Array.from(this.items.keys())}size(){return this.items.size}};var Ag=new Map;function Pt(t){if(Array.isArray(t)&&!t.some(o=>typeof o!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new y("Malformed input string");let e=Ag.get(t);if(e)return e;let r=t.split(","),n=[];for(let o of r){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)n.push(c)}else n.push(parseInt(o,10))}return Ag.set(t,n),n}i(Pt,"statusCodesStringToNumberArray");function At(t,e,r){if(!e.startsWith("."))throw new y(`Invalid ${r} - must start with '.' - '${e}' does not`);let n=e.split(".").splice(1),o=t;return n.forEach(s=>{if(o===void 0)throw new q(`Error applying ${r} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(At,"getValueFromRequestUser");function Ng(t,e){if(!e.startsWith("."))throw new y(`Invalid selector. must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),n=t;return r.forEach(o=>{if(n===void 0)throw new q(`Error applying'${e}', reading '${o}'`);if(n&&typeof n=="object")n=Reflect.get(n,o);else throw new q(`Error applying'${e}', reading '${o}'`)}),`${n}`}i(Ng,"selectPropertyUsingJsonPath");function Nt(t){if(Array.isArray(t)){if(t.includes(r=>typeof r!="string"))throw new y("Received an array that contains non-string values.");return t}if(Xe(t))return t.includes(",")?t.split(",").map(r=>r.trim()).filter(r=>r!==","&&r!==""):[t];throw new y(`Expected type of string, received type '${typeof t}'`)}i(Nt,"parseValueToStringArray");function Lg(t){if(t==null)return[];if(!Array.isArray(t))throw new y(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(r=>{if(!ar(r))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof r}'`);if(!_r(r.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(r.maxAge!==void 0&&!ka(r.maxAge))throw new y(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof r.maxAge}'`);if(r.allowCredentials!==void 0&&!_a(r.allowCredentials))throw new y("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let n=Oa(r,"allowedHeaders"),o=Oa(r,"allowedMethods"),s=Oa(r,"exposeHeaders"),a;try{a=Nt(r.allowedOrigins)}catch(c){throw new y(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:r.name,allowCredentials:typeof r.allowCredentials=="boolean"?String(r.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:n?n.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof r.maxAge=="number"?r.maxAge.toString():void 0}})}i(Lg,"parseCorsPolicies");function Oa(t,e){let r;if(t[e]!==void 0)try{r=Nt(t[e])}catch(n){throw new y(`Value of '${e}' on custom cors policies is invalid. ${n.message} If using an environment variable, check that it is set correctly.`)}return r}i(Oa,"parseOptionalProperty");var Aa=new Map,Mx=i((t,e,r)=>{for(let n of t){let o=n.trim().toLowerCase();if(o==="*")return e;if(o.includes("*.")){let a=o.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*\\\./g,"[^.]+\\.");if(new RegExp(`^${a}$`).test(r))return e}else{let s=o.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${s}$`).test(r))return e}}},"testMatchinOrigin"),ui=i((t,e,r)=>{if(r===null)return;let n=r.trim().toLowerCase(),o=Aa.get(t);if(o?.has(n))return r;let s=Mx(e,r,n);return s&&(o||Aa.set(t,new ai(20)),Aa.get(t)?.add(n)),s},"findMatchingOrigin"),ci=i((t,e)=>{let r={"access-control-allow-origin":e};t.allowedHeaders&&(r["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(r["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(r["access-control-expose-headers"]=t.exposeHeaders);let n=t.allowCredentials;n&&(r["access-control-allow-credentials"]=n);let o=t.maxAge?.toString()??void 0;return o&&(r["access-control-max-age"]=o),r},"generateCorsHeaders"),li=i((t,e)=>{if(!t)return!1;let{developerPortal:r}=e;return r.enabled&&r.type==="zudoku"&&r.urls?r.urls.urls.includes(t):!1},"isDevPortalOrigin");var Na=i((t,e,r)=>{let n=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return M.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});if(li(p,e)){let v={"access-control-allow-origin":p,"access-control-allow-methods":l,"access-control-allow-headers":d??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"};return new Response(void 0,{status:200,statusText:"OK",headers:v})}let m=t.lookup(c,l);if(!m)return M.notFound(a,u);let g=m.routeConfiguration,h=zx({requestedMethod:l,requestedHeaders:d,requestedOrigin:p,routeConfig:g,customPolicies:r});return h.isValid?new Response(void 0,{status:200,statusText:"OK",headers:h.headers}):(h.error&&u.log.warn(h.error),M.notFound(a,u))},"optionsHandler"),o=new Le({processors:[qe],handler:n}),s=new Me({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(s,o.execute)},"registerCorsRoute"),zx=i(({requestedMethod:t,requestedHeaders:e,requestedOrigin:r,routeConfig:n,customPolicies:o})=>{let s={isValid:!1,headers:{}};if(n.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":r,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(n.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${n.pathPattern}'`};let a=o?.find(l=>l.name===n.corsPolicy);if(!a)throw new y(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=ui(a.name,a.allowedOrigins,r);return u?{isValid:!0,headers:ci(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${r}'`}},"validateAndBuildResponseHeaders");var Mg=i(t=>{let e=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new Le({processors:[qe],handler:e}),n=new Me({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(n,r.execute)},"registerNoRoutes");var Ht=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.mcp=e.mcp,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.metadata=e.metadata,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;metadata;custom;mcp;methods;handler;corsPolicy;policies};var Ux=new Me({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),zg=i(t=>{let e=i(async(n,o)=>{let s=wa.value?.notFoundHandler;if(s){let a=new URL(n.url);return s(n,o,{get routesMatchedByPathOnly(){return t.lookupByPathOnly(a.pathname).map(c=>c.routeConfiguration).filter(c=>c instanceof Ht)}})}return M.notFound(n,o)},"notFoundHandler"),r=new Le({processors:[qe],handler:e});t.addRoute(Ux,r.execute)},"registerNotMatchedHandler");var Dx=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ug=i(t=>{Dx.forEach(e=>t.delete(e))},"stripCorsHeaders"),Er=i(async(t,e,r)=>{let n=e.route,o=t.headers.get("origin"),s=li(o,ve.instance.runtimeSettings);if((!n.corsPolicy||n.corsPolicy==="none")&&!s){let p=await r(t),m=new Headers(p.headers);return Ug(m),new Response(p.body,{status:p.status,statusText:p.statusText,headers:m,webSocket:p.webSocket})}let a=await r(t);if(!(a instanceof Response))throw new ue(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof a}'`);let u=Zx(n,ve.instance.routeData.corsPolicies,s),c=jx(o,u),l=new Headers(a.headers);return Ug(l),Object.entries(c).forEach(([p,m])=>{l.set(p,m)}),new Response(a.body,{status:a.status,statusText:a.statusText,headers:l,webSocket:a.webSocket})},"corsProcessor"),Zx=i((t,e,r)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};if(r)return{name:"dev-portal-anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(o=>o.name===t.corsPolicy);if(n===void 0)throw new y(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),jx=i((t,e)=>{let r=ui(e.name,e.allowedOrigins,t);return r?ci(e,r):{}},"getCorsHeaders");var La=i(t=>{let e=i(async()=>new Response(JSON.stringify({buildId:R.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new Le({processors:[Er],handler:e}),n=new Me({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(n,r.execute)},"registerPingRoute");import{SpanStatusCode as Dg,trace as Zg}from"@opentelemetry/api";var Lt={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var di=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,r){if(!Xe(r))throw new q(`The name of a policy must be a string. Received '${r}' of type '${typeof r}'`);this.options=e,this.policyName=r,this.policyType=Object.getPrototypeOf(this).constructor.name}},xe=class extends di{static{i(this,"InboundPolicy")}},Bt=class extends di{static{i(this,"OutboundPolicy")}};var Ua=class extends xe{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.policyType=e.name,this.#e=e}handler(e,r){return this.#e(e,r,this.options,this.policyName)}},Da=class extends Bt{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.policyType=e.name,this.#e=e}handler(e,r,n){return this.#e(e,r,n,this.options,this.policyName)}},Ma=new Map;function Pn(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.inbound??[],n=t.path),r.filter(s=>!Ma.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new y(`Invalid state - no Policy with the name '${s}' ${n&&`on route '${n}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new y(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof u}')`);if(u.prototype instanceof xe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Ua(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${s}' on route '${n}' (typeof handler '${typeof c.handler}')`);Ma.set(a.name,c)}),r.map(s=>{let a=Ma.get(s);if(a===void 0)throw new q("Internal error. Policy not found in cache.");return a})}i(Pn,"getInboundPolicyInstances");var za=new Map;function Rn(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.outbound??[],n=t.path),r.filter(s=>!za.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new y(`Invalid state - no Policy with the name '${s}' on route '${n}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export],c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof u}')`);if(u.prototype instanceof Bt)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new Da(u,a.handler.options??{},a.name);else throw new y(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${s}' on route '${n}'`);za.set(a.name,c)}),r.map(s=>{let a=za.get(s);if(a===void 0)throw new q("Internal error. Policy not found in cache.");return a})}i(Rn,"getOutboundPolicyInstances");var Za=i(t=>async(e,r)=>{let n=je.getContextExtensions(r),o=Zg.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...t],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,r);if(p instanceof Request||p instanceof pe||p instanceof Response)return d.end(),p instanceof Response||p instanceof pe?p:new pe(p);{let m=new y(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Dg.ERROR}),d.recordException(m),m}});if(l instanceof pe)u=l;else if(l instanceof Request)u=new pe(l);else if(l instanceof Response)return l;n.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),ja=i(t=>async(e,r,n)=>{let o=Zg.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...t],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Lt.PolicyName,c.policyName),d.setAttribute(Lt.PolicyType,c.policyType);let p=await c.handler(u,r,n);if(p instanceof Response)return p;{let m=new y(`Invalid state - invalid handler on policy '${c.policyName}' on route '${n.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Dg.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),pi=i(async(t,e,r)=>{let n=Pn(e.route,ve.instance.routeData.policies),o=Rn(e.route,ve.instance.routeData.policies);return qg({request:t,context:e,inboundPolicies:n,outboundPolicies:o,next:r})},"policyProcessor");function jg({inboundPolicies:t=[],outboundPolicies:e=[]}){return i(async(n,o,s)=>qg({request:n,context:o,inboundPolicies:t,outboundPolicies:e,next:s}),"policyProcessor")}i(jg,"createInternalPolicyProcessor");async function qg({request:t,context:e,inboundPolicies:r,outboundPolicies:n,next:o}){let s=Za(r);try{let a=await s(t,e);if(a instanceof Response)return a;let u=await o(a),c=ja(n),l;return R.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?l=c(u,t,e):l=u.ok?c(u,t,e):u,l}catch(a){return wt(t,e,"Error executing policies",a)}}i(qg,"executePolicyProcessor");var Gg=dx(Bg(),1);function Vg(t,e){try{let r=/v\d+(-\d+)?/g,o=(0,Gg.parse)(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&r.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}i(Vg,"devPortalBaseURL");var Jg="/__zuplo/dev-portal",Xx="dev-portal-id",Yx="dev-portal-host",eP="zp-account",tP="zp-project",rP="dev-portal-build",nP=`
55
+ `)}i(Ea,"cleanStack");function wt(t,e,r,n){e.log.error(r,n);let o={};if(R.instance.isLocalDevelopment||R.instance.isWorkingCopy)if(n instanceof q&&n.extensionMembers)o=n.extensionMembers;else if(n.cause){let s=ur(n.cause);"stack"in s&&(s.stack=Ea(s.stack)),o={cause:s}}else{let s=ur(n);"stack"in s&&(s.stack=Ea(s.stack)),o={cause:s}}return M.internalServerError(t,e,{detail:n.message,...o})}i(wt,"errorHandler");var Le=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i(e=>async(r,n)=>$x.getTracer("pipeline").startActiveSpan(`handler:${n.route.handler.export}`,async s=>{try{return await e(r,n)}catch(a){let u=wt(r,n,"Error executing request handler.",a);return s.setStatus({code:Cx.ERROR}),u}finally{s.end()}}),"#errorWrappedHandler");#t=i(({processors:e,handler:r})=>async(n,o)=>{let s=je.getContextExtensions(o),a=[...e],u=i(async h=>{let v=a.pop();if(!v){let k=await this.#e(async x=>{let $=await r(x,o);return Ox($)})(h,o);try{await s.onHandlerResponse(k,h,o)}catch(x){return wt(n,o,"Error invoking 'context.onHandlerResponse' hook",x)}return k}return v(n,o,u)},"nextPipe"),l=await u(n),d=new URL(n.url);if(kr(d)&&R.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new wn(n,l);o.dispatchEvent(p);let m=s.latestRequest,g;try{g=await p.mutableResponse}catch(h){return wt(n,o,"Error retrieving mutableResponse",h)}try{g=await s.onResponseSending(g,m,o)}catch(h){return wt(n,o,"Error invoking 'context.onResponseSending' hook",h)}try{g=await Rg(g,m,o)}catch(h){return wt(n,o,"Error invoking 'context.onResponseSending' hook",h)}o.dispatchEvent(new xn(n,g));try{await s.onResponseSendingFinal(l,m,o)}catch(h){throw o.log.error("Error invoking 'runtime.onResponseSending' hook",h),h}try{await Ig(l,m,o)}catch(h){throw o.log.error("Error invoking 'runtime.onResponseSending' hook",h),h}return g},"#toZuploPipeline")};function Ox(t){return t instanceof Response?t:typeof t>"u"?new Response:new Response(Pa(t),{headers:{"content-type":"application/json"}})}i(Ox,"resultToResponse");var xt=class extends Ft{static{i(this,"MetricsPlugin")}};var re=class t{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let r=t.#e.get(e);if(!r){let n=`No system logger found for context with requestId '${e.requestId}'`;throw W.console.error(n),new ue(n)}return r}static addLogger(e,r){t.#e.set(e,r)}};var ce=class{static{i(this,"BatchDispatch")}constructor(e,r,n,o){this.#t=e,this.#i=r,this.#r=n,this.#n=o??W.console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=i(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(r=>{setTimeout(()=>{if(this.#o.length>0){let n=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(n).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{r()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed");get queueSize(){return this.#o.length}};async function Te(t,e,r){for(let n=0;n<=t.retries;n++){try{let o=W.fetch(e,r);if(n===t.retries)return o;let s=await o;if(s.status<500&&s.status!==429)return s;t.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:s.status})}catch(o){if(n===t.retries)throw o;t.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,error:o})}await new Promise(o=>setTimeout(o,t.retryDelayMs*Math.pow(2,n)))}throw new y("An unknown error occurred, ensure retries is not negative")}i(Te,"fetchRetry");var si=class{static{i(this,"ZuploMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new ce("zuplo-metrics-transport",10,this.dispatchFunction,re.getLogger(e))}pushMetrics(e,r){this.#t.enqueue(e),r.waitUntil(this.#t.waitUntilFlushed())}dispatchFunction=i(async e=>{if(e.length!==0)try{let{remoteLogURL:r,deploymentName:n}=R.instance,{ACCOUNT_NAME:o,PROJECT_NAME:s}=R.instance.build,a=e.map(p=>{let m=Object.assign({},p);return delete m.requestContentLength,delete m.responseContentLength,m}),u=gg(),c={metadata:{timestamp:new Date,accountName:o,projectName:s,deploymentName:n},metrics:a,features:u},l=new Headers({"content-type":"application/json"});De(l);let d=await Te({retries:3,retryDelayMs:1e3,logger:W.console},`${r}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:l});if(!d.ok){let p=await d.text();re.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),hg(u)}}catch(r){re.getLogger(this.#e).error("Failed to send Zuplo metrics.",r)}},"dispatchFunction")};var Tr="SYSTEM_IGNORED";var Me=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:r,methods:n,systemRouteName:o,corsPolicy:s="none"}){this.label=e,this.path=r,this.methods=n,this.corsPolicy=s,this.handler={export:Tr,module:Tr},this.systemRouteName=o}label;path;methods;handler;corsPolicy;policies;systemRouteName;metadata;raw(){return{}}};var Ca="x-real-ip",Ax="true-client-ip",Nx="cf-connecting-ip",Lx="x-forwarded-for";function at(t){let e=t.headers,r=e.get(Ca)??e.get(Ax)??e.get(Nx);if(r)return r;let n=e.get(Lx);if(n){let o=n.split(/,\s*/).map(s=>s.trim()).find(s=>s.length>0);if(o)return o}}i(at,"getClientIp");var qe=i(async(t,e,r)=>{let n=new Date,o=Date.now(),s=await r(t),a=t.headers.get(Ir)??void 0,u=at(t),c=e.incomingRequestProperties,l;e.route instanceof Me&&(l=e.route.systemRouteName);let d=je.getContextExtensions(e).latestRequest,p={timestamp:n,statusCode:s.status,durationMs:Date.now()-o,requestContentLength:t.headers.get("content-length")?Number(t.headers.get("content-length")):void 0,responseContentLength:s.headers.get("content-length")?Number(s.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:l,contextId:e.contextId,parentContextId:e.parentContext?.contextId,requestId:e.requestId,parentRequestId:e.parentContext?.requestId,method:t.method,asn:c.asn,asOrganization:c.asOrganization,colo:c.colo,continent:c.continent,country:c.country,city:c.city,latitude:c.latitude,longitude:c.longitude,rayId:a,instanceId:R.instance.instanceId,userSub:d.user?.sub,clientIp:u},m=[];return!R.instance.isLocalDevelopment&&R.instance.remoteLogURL&&R.instance.remoteLogToken&&R.instance.loggingId&&m.push(new si(e)),gt.forEach(g=>{if(g instanceof xt){let h=g.getTransport();m.push(h)}}),m.forEach(g=>{g.pushMetrics(p,e)}),s},"metricsProcessor");var $a=i(t=>{let e=i(async(o,s)=>{let a=new URL(o.url),u=R.instance.build,c={buildId:u.BUILD_ID,zuploVersion:u.ZUPLO_VERSION,compatibilityDate:u.COMPATIBILITY_DATE,apiVersion:u.API_VERSION,gitSha:u.GIT_SHA,timestamp:u.TIMESTAMP,isProduction:u.ENVIRONMENT_TYPE==="PRODUCTION"};if(a.searchParams.get("system_log")==="true"&&re.getLogger(s).error("Test System Log",c),a.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(c,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new Le({processors:[qe],handler:e}),n=new Me({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});t.addRoute(n,r.execute)},"registerBuildRoute");var ai=class{static{i(this,"BoundedSet")}limit;items;constructor(e){this.limit=e,this.items=new Map}add(e){if(this.items.has(e))this.items.delete(e);else if(this.items.size>=this.limit){let r=this.items.keys().next().value;r&&this.items.delete(r)}this.items.set(e,!0)}has(e){return this.items.has(e)}values(){return Array.from(this.items.keys())}size(){return this.items.size}};var Ag=new Map;function Pt(t){if(Array.isArray(t)&&!t.some(o=>typeof o!="number"))return t;if(typeof t!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(t))throw new y("Malformed input string");let e=Ag.get(t);if(e)return e;let r=t.split(","),n=[];for(let o of r){let s=o.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)n.push(c)}else n.push(parseInt(o,10))}return Ag.set(t,n),n}i(Pt,"statusCodesStringToNumberArray");function At(t,e,r){if(!e.startsWith("."))throw new y(`Invalid ${r} - must start with '.' - '${e}' does not`);let n=e.split(".").splice(1),o=t;return n.forEach(s=>{if(o===void 0)throw new q(`Error applying ${r} '${e}', reading '${s}'`);o=o[s]}),`${o}`}i(At,"getValueFromRequestUser");function Ng(t,e){if(!e.startsWith("."))throw new y(`Invalid selector. must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),n=t;return r.forEach(o=>{if(n===void 0)throw new q(`Error applying'${e}', reading '${o}'`);if(n&&typeof n=="object")n=Reflect.get(n,o);else throw new q(`Error applying'${e}', reading '${o}'`)}),`${n}`}i(Ng,"selectPropertyUsingJsonPath");function Nt(t){if(Array.isArray(t)){if(t.includes(r=>typeof r!="string"))throw new y("Received an array that contains non-string values.");return t}if(Xe(t))return t.includes(",")?t.split(",").map(r=>r.trim()).filter(r=>r!==","&&r!==""):[t];throw new y(`Expected type of string, received type '${typeof t}'`)}i(Nt,"parseValueToStringArray");function Lg(t){if(t==null)return[];if(!Array.isArray(t))throw new y(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof t}'`);return t.map(r=>{if(!ar(r))throw new y(`Invalid custom cors policy is set. Expected an object, received '${typeof r}'`);if(!_r(r.name))throw new y("Value of 'name' on custom cors policies must be a non-empty string.");if(r.maxAge!==void 0&&!ka(r.maxAge))throw new y(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof r.maxAge}'`);if(r.allowCredentials!==void 0&&!_a(r.allowCredentials))throw new y("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let n=Oa(r,"allowedHeaders"),o=Oa(r,"allowedMethods"),s=Oa(r,"exposeHeaders"),a;try{a=Nt(r.allowedOrigins)}catch(c){throw new y(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:r.name,allowCredentials:typeof r.allowCredentials=="boolean"?String(r.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:n?n.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof r.maxAge=="number"?r.maxAge.toString():void 0}})}i(Lg,"parseCorsPolicies");function Oa(t,e){let r;if(t[e]!==void 0)try{r=Nt(t[e])}catch(n){throw new y(`Value of '${e}' on custom cors policies is invalid. ${n.message} If using an environment variable, check that it is set correctly.`)}return r}i(Oa,"parseOptionalProperty");var Aa=new Map,Mx=i((t,e,r)=>{for(let n of t){let o=n.trim().toLowerCase();if(o==="*")return e;if(o.includes("*.")){let a=o.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*\\\./g,"[^.]+\\.");if(new RegExp(`^${a}$`).test(r))return e}else{let s=o.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,".*");if(new RegExp(`^${s}$`).test(r))return e}}},"testMatchinOrigin"),ui=i((t,e,r)=>{if(r===null)return;let n=r.trim().toLowerCase(),o=Aa.get(t);if(o?.has(n))return r;let s=Mx(e,r,n);return s&&(o||Aa.set(t,new ai(20)),Aa.get(t)?.add(n)),s},"findMatchingOrigin"),ci=i((t,e)=>{let r={"access-control-allow-origin":e};t.allowedHeaders&&(r["access-control-allow-headers"]=t.allowedHeaders),t.allowedMethods&&(r["access-control-allow-methods"]=t.allowedMethods),t.exposeHeaders&&(r["access-control-expose-headers"]=t.exposeHeaders);let n=t.allowCredentials;n&&(r["access-control-allow-credentials"]=n);let o=t.maxAge?.toString()??void 0;return o&&(r["access-control-max-age"]=o),r},"generateCorsHeaders"),li=i((t,e)=>{if(!t)return!1;let{developerPortal:r}=e;return r.enabled&&r.type==="zudoku"&&r.urls?r.urls.urls.includes(t):!1},"isDevPortalOrigin");var Na=i((t,e,r)=>{let n=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return M.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});if(li(p,e)){let v={"access-control-allow-origin":p,"access-control-allow-methods":l,"access-control-allow-headers":d??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"};return new Response(void 0,{status:200,statusText:"OK",headers:v})}let m=t.lookup(c,l);if(!m)return M.notFound(a,u);let g=m.routeConfiguration,h=zx({requestedMethod:l,requestedHeaders:d,requestedOrigin:p,routeConfig:g,customPolicies:r});return h.isValid?new Response(void 0,{status:200,statusText:"OK",headers:h.headers}):(h.error&&u.log.warn(h.error),M.notFound(a,u))},"optionsHandler"),o=new Le({processors:[qe],handler:n}),s=new Me({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});t.addRoute(s,o.execute)},"registerCorsRoute"),zx=i(({requestedMethod:t,requestedHeaders:e,requestedOrigin:r,routeConfig:n,customPolicies:o})=>{let s={isValid:!1,headers:{}};if(n.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":r,"access-control-allow-methods":t,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(n.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${n.pathPattern}'`};let a=o?.find(l=>l.name===n.corsPolicy);if(!a)throw new y(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=ui(a.name,a.allowedOrigins,r);return u?{isValid:!0,headers:ci(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${r}'`}},"validateAndBuildResponseHeaders");var Mg=i(t=>{let e=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new Le({processors:[qe],handler:e}),n=new Me({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});t.addRoute(n,r.execute)},"registerNoRoutes");var Ht=class{static{i(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.mcp=e.mcp,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.metadata=e.metadata,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;metadata;custom;mcp;methods;handler;corsPolicy;policies};var Ux=new Me({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),zg=i(t=>{let e=i(async(n,o)=>{let s=wa.value?.notFoundHandler;if(s){let l=new URL(n.url);return s(n,o,{get routesMatchedByPathOnly(){return t.lookupByPathOnly(l.pathname).map(p=>p.routeConfiguration).filter(p=>p instanceof Ht)}})}let a=new URL(n.url);return t.lookupByPathOnly(a.pathname).filter(l=>l.routeConfiguration.handler?.export==="mcpServerHandler").length>0&&n.method!=="POST"?M.methodNotAllowed(n,o):M.notFound(n,o)},"notFoundHandler"),r=new Le({processors:[qe],handler:e});t.addRoute(Ux,r.execute)},"registerNotMatchedHandler");var Dx=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ug=i(t=>{Dx.forEach(e=>t.delete(e))},"stripCorsHeaders"),Er=i(async(t,e,r)=>{let n=e.route,o=t.headers.get("origin"),s=li(o,ve.instance.runtimeSettings);if((!n.corsPolicy||n.corsPolicy==="none")&&!s){let p=await r(t),m=new Headers(p.headers);return Ug(m),new Response(p.body,{status:p.status,statusText:p.statusText,headers:m,webSocket:p.webSocket})}let a=await r(t);if(!(a instanceof Response))throw new ue(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof a}'`);let u=Zx(n,ve.instance.routeData.corsPolicies,s),c=jx(o,u),l=new Headers(a.headers);return Ug(l),Object.entries(c).forEach(([p,m])=>{l.set(p,m)}),new Response(a.body,{status:a.status,statusText:a.statusText,headers:l,webSocket:a.webSocket})},"corsProcessor"),Zx=i((t,e,r)=>{if(t.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};if(r)return{name:"dev-portal-anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:t.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let n=e?.find(o=>o.name===t.corsPolicy);if(n===void 0)throw new y(`Invalid Configuration - no corsPolicy '${t.corsPolicy}' found in *.oas.json`);return n},"getCorsPolicy"),jx=i((t,e)=>{let r=ui(e.name,e.allowedOrigins,t);return r?ci(e,r):{}},"getCorsHeaders");var La=i(t=>{let e=i(async()=>new Response(JSON.stringify({buildId:R.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new Le({processors:[Er],handler:e}),n=new Me({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});t.addRoute(n,r.execute)},"registerPingRoute");import{SpanStatusCode as Dg,trace as Zg}from"@opentelemetry/api";var Lt={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var di=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,r){if(!Xe(r))throw new q(`The name of a policy must be a string. Received '${r}' of type '${typeof r}'`);this.options=e,this.policyName=r,this.policyType=Object.getPrototypeOf(this).constructor.name}},xe=class extends di{static{i(this,"InboundPolicy")}},Bt=class extends di{static{i(this,"OutboundPolicy")}};var Ua=class extends xe{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.policyType=e.name,this.#e=e}handler(e,r){return this.#e(e,r,this.options,this.policyName)}},Da=class extends Bt{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,r,n){super(r,n),this.policyType=e.name,this.#e=e}handler(e,r,n){return this.#e(e,r,n,this.options,this.policyName)}},Ma=new Map;function Pn(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.inbound??[],n=t.path),r.filter(s=>!Ma.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new y(`Invalid state - no Policy with the name '${s}' ${n&&`on route '${n}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new y(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof u}')`);if(u.prototype instanceof xe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Ua(u,a.handler.options,a.name);else throw new y(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${s}' on route '${n}' (typeof handler '${typeof c.handler}')`);Ma.set(a.name,c)}),r.map(s=>{let a=Ma.get(s);if(a===void 0)throw new q("Internal error. Policy not found in cache.");return a})}i(Pn,"getInboundPolicyInstances");var za=new Map;function Rn(t,e){let r,n;return Array.isArray(t)?r=t:(r=t.policies?.outbound??[],n=t.path),r.filter(s=>!za.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new y(`Invalid state - no Policy with the name '${s}' on route '${n}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new y(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export],c;if(typeof u!="function")throw new y(`Invalid state - invalid policy '${s}' on route '${n}' (typeof module '${typeof u}')`);if(u.prototype instanceof Bt)c=new u(a.handler.options??{},a.name);else if(typeof u=="function")c=new Da(u,a.handler.options??{},a.name);else throw new y(`Invalid state - invalid policy '${s}' on route '${n}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new y(`Invalid state - invalid handler on policy '${s}' on route '${n}'`);za.set(a.name,c)}),r.map(s=>{let a=za.get(s);if(a===void 0)throw new q("Internal error. Policy not found in cache.");return a})}i(Rn,"getOutboundPolicyInstances");var Za=i(t=>async(e,r)=>{let n=je.getContextExtensions(r),o=Zg.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async s=>{try{let a=[...t],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,r);if(p instanceof Request||p instanceof pe||p instanceof Response)return d.end(),p instanceof Response||p instanceof pe?p:new pe(p);{let m=new y(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Dg.ERROR}),d.recordException(m),m}});if(l instanceof pe)u=l;else if(l instanceof Request)u=new pe(l);else if(l instanceof Response)return l;n.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),ja=i(t=>async(e,r,n)=>{let o=Zg.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async s=>{try{let a=[...t],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Lt.PolicyName,c.policyName),d.setAttribute(Lt.PolicyType,c.policyType);let p=await c.handler(u,r,n);if(p instanceof Response)return p;{let m=new y(`Invalid state - invalid handler on policy '${c.policyName}' on route '${n.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Dg.ERROR}),d.recordException(m),m}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),pi=i(async(t,e,r)=>{let n=Pn(e.route,ve.instance.routeData.policies),o=Rn(e.route,ve.instance.routeData.policies);return qg({request:t,context:e,inboundPolicies:n,outboundPolicies:o,next:r})},"policyProcessor");function jg({inboundPolicies:t=[],outboundPolicies:e=[]}){return i(async(n,o,s)=>qg({request:n,context:o,inboundPolicies:t,outboundPolicies:e,next:s}),"policyProcessor")}i(jg,"createInternalPolicyProcessor");async function qg({request:t,context:e,inboundPolicies:r,outboundPolicies:n,next:o}){let s=Za(r);try{let a=await s(t,e);if(a instanceof Response)return a;let u=await o(a),c=ja(n),l;return R.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?l=c(u,t,e):l=u.ok?c(u,t,e):u,l}catch(a){return wt(t,e,"Error executing policies",a)}}i(qg,"executePolicyProcessor");var Gg=dx(Bg(),1);function Vg(t,e){try{let r=/v\d+(-\d+)?/g,o=(0,Gg.parse)(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&r.test(o)?`https://dev-portal-${o}.zuplo.com`:t}catch{}return t}i(Vg,"devPortalBaseURL");var Jg="/__zuplo/dev-portal",Xx="dev-portal-id",Yx="dev-portal-host",eP="zp-account",tP="zp-project",rP="dev-portal-build",nP=`
56
56
  <!DOCTYPE html>
57
57
  <html lang="en">
58
58
  <head>