@zuplo/runtime 6.63.3 → 6.63.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/esm/{chunk-CRSNWVTX.js → chunk-5YGMAZTS.js} +2 -2
- package/out/esm/{chunk-BHPOLR2W.js → chunk-AURJS7GN.js} +5 -5
- package/out/esm/{chunk-BHPOLR2W.js.map → chunk-AURJS7GN.js.map} +1 -1
- package/out/esm/{chunk-2TEG5A7U.js → chunk-KLJAHVJG.js} +2 -2
- package/out/esm/index.js +2 -2
- package/out/esm/index.js.map +1 -1
- package/out/esm/internal/index.js +1 -1
- package/out/esm/mocks/index.js +1 -1
- package/out/types/index.d.ts +2 -2
- package/package.json +1 -1
- /package/out/esm/{chunk-CRSNWVTX.js.map → chunk-5YGMAZTS.js.map} +0 -0
- /package/out/esm/{chunk-BHPOLR2W.js.LEGAL.txt → chunk-AURJS7GN.js.LEGAL.txt} +0 -0
- /package/out/esm/{chunk-2TEG5A7U.js.map → chunk-KLJAHVJG.js.map} +0 -0
package/out/esm/index.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a as Ht,d as ke,e as Yx,f as $a,g as Aa,h as eR,i as tR}from"./chunk-2TEG5A7U.js";import{a as Oe,b as zg}from"./chunk-CRSNWVTX.js";import{A as Tg,B as Cg,C as ti,D as ri,E as ni,F as oi,G as ii,H as si,I as Eg,J as _g,K as ai,L as ci,M as Og,N as ui,O as li,P as $g,Q as Ag,R as Ng,S as Lg,T as Mg,U as Dg,V as Ug,W as Cn,X as En,Y as di,Z as j,a as s,b as te,c as Qx,d as Nt,e as Xx,f as ei,g as Ne,h as le,i as F,j as w,k as P,l as fg,m as Tn,n as gg,o as Nr,p as hg,q as yg,r as bg,s as wg,t as vg,u as xg,v as Rg,w as Pg,x as Ig,y as Sg,z as kg}from"./chunk-BHPOLR2W.js";var bh=Qx(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.parse=LR;Ti.serialize=MR;var ER=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,_R=/^[\u0021-\u003A\u003C-\u007E]*$/,OR=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,$R=/^[\u0020-\u003A\u003D-\u007E]*$/,AR=Object.prototype.toString,NR=(()=>{let t=s(function(){},"C");return t.prototype=Object.create(null),t})();function LR(t,e){let r=new NR,n=t.length;if(n<2)return r;let o=e?.decode||DR,i=0;do{let a=t.indexOf("=",i);if(a===-1)break;let c=t.indexOf(";",i),u=c===-1?n:c;if(a>u){i=t.lastIndexOf(";",a-1)+1;continue}let l=hh(t,i,a),d=yh(t,a,l),p=t.slice(l,d);if(r[p]===void 0){let m=hh(t,a+1,u),f=yh(t,u,m),g=o(t.slice(m,f));r[p]=g}i=u+1}while(i<n);return r}s(LR,"parse");function hh(t,e,r){do{let n=t.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<r);return r}s(hh,"startIndex");function yh(t,e,r){for(;e>r;){let n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}s(yh,"endIndex");function MR(t,e,r){let n=r?.encode||encodeURIComponent;if(!ER.test(t))throw new TypeError(`argument name is invalid: ${t}`);let o=n(e);if(!_R.test(o))throw new TypeError(`argument val is invalid: ${e}`);let i=t+"="+o;if(!r)return i;if(r.maxAge!==void 0){if(!Number.isInteger(r.maxAge))throw new TypeError(`option maxAge is invalid: ${r.maxAge}`);i+="; Max-Age="+r.maxAge}if(r.domain){if(!OR.test(r.domain))throw new TypeError(`option domain is invalid: ${r.domain}`);i+="; Domain="+r.domain}if(r.path){if(!$R.test(r.path))throw new TypeError(`option path is invalid: ${r.path}`);i+="; Path="+r.path}if(r.expires){if(!UR(r.expires)||!Number.isFinite(r.expires.valueOf()))throw new TypeError(`option expires is invalid: ${r.expires}`);i+="; Expires="+r.expires.toUTCString()}if(r.httpOnly&&(i+="; HttpOnly"),r.secure&&(i+="; Secure"),r.partitioned&&(i+="; Partitioned"),r.priority)switch(typeof r.priority=="string"?r.priority.toLowerCase():void 0){case"low":i+="; Priority=Low";break;case"medium":i+="; Priority=Medium";break;case"high":i+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${r.priority}`)}if(r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:case"strict":i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"none":i+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${r.sameSite}`)}return i}s(MR,"serialize");function DR(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}s(DR,"decode");function UR(t){return AR.call(t)==="[object Date]"}s(UR,"isDate")});function T(t,e,r){function n(c,u){var l;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(l=c._zod).traits??(l.traits=new Set),c._zod.traits.add(t),e(c,u);for(let d in a.prototype)Object.defineProperty(c,d,{value:a.prototype[d].bind(c)});c._zod.constr=a,c._zod.def=u}s(n,"init");let o=r?.Parent??Object;class i extends o{static{s(this,"Definition")}}Object.defineProperty(i,"name",{value:t});function a(c){var u;let l=r?.Parent?new i:this;n(l,c),(u=l._zod).deferred??(u.deferred=[]);for(let d of l._zod.deferred)d();return l}return s(a,"_"),Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:s(c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(t),"value")}),Object.defineProperty(a,"name",{value:t}),a}function ze(t){return t&&Object.assign(Wn,t),Wn}var zi,St,Wn,Jr=te(()=>{s(T,"$constructor");zi=Symbol("zod_brand"),St=class extends Error{static{s(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Wn={};s(ze,"config")});var ee={};Nt(ee,{BIGINT_FORMAT_RANGES:()=>jc,Class:()=>$c,NUMBER_FORMAT_RANGES:()=>zc,aborted:()=>br,allowsEval:()=>Mc,assert:()=>ZP,assertEqual:()=>DP,assertIs:()=>zP,assertNever:()=>jP,assertNotEqual:()=>UP,assignProp:()=>Lc,cached:()=>Qn,cleanEnum:()=>eI,cleanRegex:()=>Xn,clone:()=>rt,createTransparentProxy:()=>VP,defineLazy:()=>Pe,esc:()=>yr,escapeRegex:()=>kt,extend:()=>KP,finalizeIssue:()=>nt,floatSafeRemainder:()=>Nc,getElementAtPath:()=>FP,getLengthableOrigin:()=>ro,getParsedType:()=>BP,getSizableOrigin:()=>to,getValidEnumValues:()=>qP,isObject:()=>Zi,isPlainObject:()=>Yn,issue:()=>Zc,joinValues:()=>q,jsonStringifyReplacer:()=>Ac,merge:()=>QP,normalizeParams:()=>K,nullish:()=>Qt,numKeys:()=>GP,omit:()=>WP,optionalKeys:()=>Uc,partial:()=>XP,pick:()=>JP,prefixIssues:()=>Je,primitiveTypes:()=>Dc,promiseAllObject:()=>HP,propertyKeyTypes:()=>eo,randomString:()=>ji,required:()=>YP,stringifyPrimitive:()=>re,unwrapMessage:()=>Kn});function DP(t){return t}function UP(t){return t}function zP(t){}function jP(t){throw new Error}function ZP(t){}function qP(t){let e=Object.keys(t).filter(n=>typeof t[t[n]]!="number"),r={};for(let n of e)r[n]=t[n];return Object.values(r)}function q(t,e="|"){return t.map(r=>re(r)).join(e)}function Ac(t,e){return typeof e=="bigint"?e.toString():e}function Qn(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Qt(t){return t==null}function Xn(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Nc(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return i%a/10**o}function Pe(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Lc(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function FP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function HP(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<e.length;i++)o[e[i]]=n[i];return o})}function ji(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function yr(t){return JSON.stringify(t)}function Zi(t){return typeof t=="object"&&t!==null}function Yn(t){return typeof t=="object"&&t!==null&&Object.getPrototypeOf(t)===Object.prototype}function GP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function kt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function K(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:s(()=>e,"error")};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:s(()=>e.error,"error")}:e}function VP(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,i){return e??(e=t()),Reflect.set(e,n,o,i)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function re(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Uc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional")}function JP(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return rt(t,{...t._zod.def,shape:r,checks:[]})}function WP(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return rt(t,{...t._zod.def,shape:r,checks:[]})}function KP(t,e){let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Lc(this,"shape",n),n},checks:[]};return rt(t,r)}function QP(t,e){return rt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Lc(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function XP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=t?new t({type:"optional",innerType:n[i]}):n[i])}else for(let i in n)o[i]=t?new t({type:"optional",innerType:n[i]}):n[i];return rt(e,{...e._zod.def,shape:o,checks:[]})}function YP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=new t({type:"nonoptional",innerType:n[i]}))}else for(let i in n)o[i]=new t({type:"nonoptional",innerType:n[i]});return rt(e,{...e._zod.def,shape:o,checks:[]})}function br(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r].continue!==!0)return!0;return!1}function Je(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Kn(t){return typeof t=="string"?t:t?.message}function nt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Kn(t.inst?._zod.def?.error?.(t))??Kn(e?.error?.(t))??Kn(r.customError?.(t))??Kn(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function to(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ro(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Zc(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function eI(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Mc,BP,eo,Dc,zc,jc,$c,me=te(()=>{s(DP,"assertEqual");s(UP,"assertNotEqual");s(zP,"assertIs");s(jP,"assertNever");s(ZP,"assert");s(qP,"getValidEnumValues");s(q,"joinValues");s(Ac,"jsonStringifyReplacer");s(Qn,"cached");s(Qt,"nullish");s(Xn,"cleanRegex");s(Nc,"floatSafeRemainder");s(Pe,"defineLazy");s(Lc,"assignProp");s(FP,"getElementAtPath");s(HP,"promiseAllObject");s(ji,"randomString");s(yr,"esc");s(Zi,"isObject");Mc=Qn(()=>{try{let t=Function;return new t(""),!0}catch{return!1}});s(Yn,"isPlainObject");s(GP,"numKeys");BP=s(t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},"getParsedType"),eo=new Set(["string","number","symbol"]),Dc=new Set(["string","number","bigint","boolean","symbol","undefined"]);s(kt,"escapeRegex");s(rt,"clone");s(K,"normalizeParams");s(VP,"createTransparentProxy");s(re,"stringifyPrimitive");s(Uc,"optionalKeys");zc={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},jc={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};s(JP,"pick");s(WP,"omit");s(KP,"extend");s(QP,"merge");s(XP,"partial");s(YP,"required");s(br,"aborted");s(Je,"prefixIssues");s(Kn,"unwrapMessage");s(nt,"finalizeIssue");s(to,"getSizableOrigin");s(ro,"getLengthableOrigin");s(Zc,"issue");s(eI,"cleanEnum");$c=class{static{s(this,"Class")}constructor(...e){}}});function oo(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function io(t,e){let r=e||function(i){return i.message},n={_errors:[]},o=s(i=>{for(let a of i.issues)if(a.code==="invalid_union")a.errors.map(c=>o({issues:c}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let c=n,u=0;for(;u<a.path.length;){let l=a.path[u];u===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(r(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}},"processError");return o(t),n}function qc(t,e){let r=e||function(i){return i.message},n={errors:[]},o=s((i,a=[])=>{var c,u;for(let l of i.issues)if(l.code==="invalid_union")l.errors.map(d=>o({issues:d},l.path));else if(l.code==="invalid_key")o({issues:l.issues},l.path);else if(l.code==="invalid_element")o({issues:l.issues},l.path);else{let d=[...a,...l.path];if(d.length===0){n.errors.push(r(l));continue}let p=n,m=0;for(;m<d.length;){let f=d[m],g=m===d.length-1;typeof f=="string"?(p.properties??(p.properties={}),(c=p.properties)[f]??(c[f]={errors:[]}),p=p.properties[f]):(p.items??(p.items=[]),(u=p.items)[f]??(u[f]={errors:[]}),p=p.items[f]),g&&p.errors.push(r(l)),m++}}},"processError");return o(t),n}function Qh(t){let e=[];for(let r of t)typeof r=="number"?e.push(`[${r}]`):typeof r=="symbol"?e.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?e.push(`[${JSON.stringify(r)}]`):(e.length&&e.push("."),e.push(r));return e.join("")}function Fc(t){let e=[],r=[...t.issues].sort((n,o)=>n.path.length-o.path.length);for(let n of r)e.push(`\u2716 ${n.message}`),n.path?.length&&e.push(` \u2192 at ${Qh(n.path)}`);return e.join(`
|
|
25
|
+
import{a as Ht,d as ke,e as Yx,f as $a,g as Aa,h as eR,i as tR}from"./chunk-KLJAHVJG.js";import{a as Oe,b as zg}from"./chunk-5YGMAZTS.js";import{A as Tg,B as Cg,C as ti,D as ri,E as ni,F as oi,G as ii,H as si,I as Eg,J as _g,K as ai,L as ci,M as Og,N as ui,O as li,P as $g,Q as Ag,R as Ng,S as Lg,T as Mg,U as Dg,V as Ug,W as Cn,X as En,Y as di,Z as j,a as s,b as te,c as Qx,d as Nt,e as Xx,f as ei,g as Ne,h as le,i as F,j as w,k as P,l as fg,m as Tn,n as gg,o as Nr,p as hg,q as yg,r as bg,s as wg,t as vg,u as xg,v as Rg,w as Pg,x as Ig,y as Sg,z as kg}from"./chunk-AURJS7GN.js";var bh=Qx(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.parse=LR;Ti.serialize=MR;var ER=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,_R=/^[\u0021-\u003A\u003C-\u007E]*$/,OR=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,$R=/^[\u0020-\u003A\u003D-\u007E]*$/,AR=Object.prototype.toString,NR=(()=>{let t=s(function(){},"C");return t.prototype=Object.create(null),t})();function LR(t,e){let r=new NR,n=t.length;if(n<2)return r;let o=e?.decode||DR,i=0;do{let a=t.indexOf("=",i);if(a===-1)break;let c=t.indexOf(";",i),u=c===-1?n:c;if(a>u){i=t.lastIndexOf(";",a-1)+1;continue}let l=hh(t,i,a),d=yh(t,a,l),p=t.slice(l,d);if(r[p]===void 0){let m=hh(t,a+1,u),f=yh(t,u,m),g=o(t.slice(m,f));r[p]=g}i=u+1}while(i<n);return r}s(LR,"parse");function hh(t,e,r){do{let n=t.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<r);return r}s(hh,"startIndex");function yh(t,e,r){for(;e>r;){let n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}s(yh,"endIndex");function MR(t,e,r){let n=r?.encode||encodeURIComponent;if(!ER.test(t))throw new TypeError(`argument name is invalid: ${t}`);let o=n(e);if(!_R.test(o))throw new TypeError(`argument val is invalid: ${e}`);let i=t+"="+o;if(!r)return i;if(r.maxAge!==void 0){if(!Number.isInteger(r.maxAge))throw new TypeError(`option maxAge is invalid: ${r.maxAge}`);i+="; Max-Age="+r.maxAge}if(r.domain){if(!OR.test(r.domain))throw new TypeError(`option domain is invalid: ${r.domain}`);i+="; Domain="+r.domain}if(r.path){if(!$R.test(r.path))throw new TypeError(`option path is invalid: ${r.path}`);i+="; Path="+r.path}if(r.expires){if(!UR(r.expires)||!Number.isFinite(r.expires.valueOf()))throw new TypeError(`option expires is invalid: ${r.expires}`);i+="; Expires="+r.expires.toUTCString()}if(r.httpOnly&&(i+="; HttpOnly"),r.secure&&(i+="; Secure"),r.partitioned&&(i+="; Partitioned"),r.priority)switch(typeof r.priority=="string"?r.priority.toLowerCase():void 0){case"low":i+="; Priority=Low";break;case"medium":i+="; Priority=Medium";break;case"high":i+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${r.priority}`)}if(r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:case"strict":i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"none":i+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${r.sameSite}`)}return i}s(MR,"serialize");function DR(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}s(DR,"decode");function UR(t){return AR.call(t)==="[object Date]"}s(UR,"isDate")});function T(t,e,r){function n(c,u){var l;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(l=c._zod).traits??(l.traits=new Set),c._zod.traits.add(t),e(c,u);for(let d in a.prototype)Object.defineProperty(c,d,{value:a.prototype[d].bind(c)});c._zod.constr=a,c._zod.def=u}s(n,"init");let o=r?.Parent??Object;class i extends o{static{s(this,"Definition")}}Object.defineProperty(i,"name",{value:t});function a(c){var u;let l=r?.Parent?new i:this;n(l,c),(u=l._zod).deferred??(u.deferred=[]);for(let d of l._zod.deferred)d();return l}return s(a,"_"),Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:s(c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(t),"value")}),Object.defineProperty(a,"name",{value:t}),a}function ze(t){return t&&Object.assign(Wn,t),Wn}var zi,St,Wn,Jr=te(()=>{s(T,"$constructor");zi=Symbol("zod_brand"),St=class extends Error{static{s(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Wn={};s(ze,"config")});var ee={};Nt(ee,{BIGINT_FORMAT_RANGES:()=>jc,Class:()=>$c,NUMBER_FORMAT_RANGES:()=>zc,aborted:()=>br,allowsEval:()=>Mc,assert:()=>ZP,assertEqual:()=>DP,assertIs:()=>zP,assertNever:()=>jP,assertNotEqual:()=>UP,assignProp:()=>Lc,cached:()=>Qn,cleanEnum:()=>eI,cleanRegex:()=>Xn,clone:()=>rt,createTransparentProxy:()=>VP,defineLazy:()=>Pe,esc:()=>yr,escapeRegex:()=>kt,extend:()=>KP,finalizeIssue:()=>nt,floatSafeRemainder:()=>Nc,getElementAtPath:()=>FP,getLengthableOrigin:()=>ro,getParsedType:()=>BP,getSizableOrigin:()=>to,getValidEnumValues:()=>qP,isObject:()=>Zi,isPlainObject:()=>Yn,issue:()=>Zc,joinValues:()=>q,jsonStringifyReplacer:()=>Ac,merge:()=>QP,normalizeParams:()=>K,nullish:()=>Qt,numKeys:()=>GP,omit:()=>WP,optionalKeys:()=>Uc,partial:()=>XP,pick:()=>JP,prefixIssues:()=>Je,primitiveTypes:()=>Dc,promiseAllObject:()=>HP,propertyKeyTypes:()=>eo,randomString:()=>ji,required:()=>YP,stringifyPrimitive:()=>re,unwrapMessage:()=>Kn});function DP(t){return t}function UP(t){return t}function zP(t){}function jP(t){throw new Error}function ZP(t){}function qP(t){let e=Object.keys(t).filter(n=>typeof t[t[n]]!="number"),r={};for(let n of e)r[n]=t[n];return Object.values(r)}function q(t,e="|"){return t.map(r=>re(r)).join(e)}function Ac(t,e){return typeof e=="bigint"?e.toString():e}function Qn(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Qt(t){return t==null}function Xn(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Nc(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return i%a/10**o}function Pe(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Lc(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function FP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function HP(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<e.length;i++)o[e[i]]=n[i];return o})}function ji(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function yr(t){return JSON.stringify(t)}function Zi(t){return typeof t=="object"&&t!==null}function Yn(t){return typeof t=="object"&&t!==null&&Object.getPrototypeOf(t)===Object.prototype}function GP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function kt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function K(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:s(()=>e,"error")};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:s(()=>e.error,"error")}:e}function VP(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,i){return e??(e=t()),Reflect.set(e,n,o,i)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function re(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Uc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional")}function JP(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return rt(t,{...t._zod.def,shape:r,checks:[]})}function WP(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return rt(t,{...t._zod.def,shape:r,checks:[]})}function KP(t,e){let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Lc(this,"shape",n),n},checks:[]};return rt(t,r)}function QP(t,e){return rt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Lc(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function XP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=t?new t({type:"optional",innerType:n[i]}):n[i])}else for(let i in n)o[i]=t?new t({type:"optional",innerType:n[i]}):n[i];return rt(e,{...e._zod.def,shape:o,checks:[]})}function YP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(o[i]=new t({type:"nonoptional",innerType:n[i]}))}else for(let i in n)o[i]=new t({type:"nonoptional",innerType:n[i]});return rt(e,{...e._zod.def,shape:o,checks:[]})}function br(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r].continue!==!0)return!0;return!1}function Je(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Kn(t){return typeof t=="string"?t:t?.message}function nt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Kn(t.inst?._zod.def?.error?.(t))??Kn(e?.error?.(t))??Kn(r.customError?.(t))??Kn(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function to(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ro(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Zc(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function eI(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Mc,BP,eo,Dc,zc,jc,$c,me=te(()=>{s(DP,"assertEqual");s(UP,"assertNotEqual");s(zP,"assertIs");s(jP,"assertNever");s(ZP,"assert");s(qP,"getValidEnumValues");s(q,"joinValues");s(Ac,"jsonStringifyReplacer");s(Qn,"cached");s(Qt,"nullish");s(Xn,"cleanRegex");s(Nc,"floatSafeRemainder");s(Pe,"defineLazy");s(Lc,"assignProp");s(FP,"getElementAtPath");s(HP,"promiseAllObject");s(ji,"randomString");s(yr,"esc");s(Zi,"isObject");Mc=Qn(()=>{try{let t=Function;return new t(""),!0}catch{return!1}});s(Yn,"isPlainObject");s(GP,"numKeys");BP=s(t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},"getParsedType"),eo=new Set(["string","number","symbol"]),Dc=new Set(["string","number","bigint","boolean","symbol","undefined"]);s(kt,"escapeRegex");s(rt,"clone");s(K,"normalizeParams");s(VP,"createTransparentProxy");s(re,"stringifyPrimitive");s(Uc,"optionalKeys");zc={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},jc={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};s(JP,"pick");s(WP,"omit");s(KP,"extend");s(QP,"merge");s(XP,"partial");s(YP,"required");s(br,"aborted");s(Je,"prefixIssues");s(Kn,"unwrapMessage");s(nt,"finalizeIssue");s(to,"getSizableOrigin");s(ro,"getLengthableOrigin");s(Zc,"issue");s(eI,"cleanEnum");$c=class{static{s(this,"Class")}constructor(...e){}}});function oo(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function io(t,e){let r=e||function(i){return i.message},n={_errors:[]},o=s(i=>{for(let a of i.issues)if(a.code==="invalid_union")a.errors.map(c=>o({issues:c}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let c=n,u=0;for(;u<a.path.length;){let l=a.path[u];u===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(r(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}},"processError");return o(t),n}function qc(t,e){let r=e||function(i){return i.message},n={errors:[]},o=s((i,a=[])=>{var c,u;for(let l of i.issues)if(l.code==="invalid_union")l.errors.map(d=>o({issues:d},l.path));else if(l.code==="invalid_key")o({issues:l.issues},l.path);else if(l.code==="invalid_element")o({issues:l.issues},l.path);else{let d=[...a,...l.path];if(d.length===0){n.errors.push(r(l));continue}let p=n,m=0;for(;m<d.length;){let f=d[m],g=m===d.length-1;typeof f=="string"?(p.properties??(p.properties={}),(c=p.properties)[f]??(c[f]={errors:[]}),p=p.properties[f]):(p.items??(p.items=[]),(u=p.items)[f]??(u[f]={errors:[]}),p=p.items[f]),g&&p.errors.push(r(l)),m++}}},"processError");return o(t),n}function Qh(t){let e=[];for(let r of t)typeof r=="number"?e.push(`[${r}]`):typeof r=="symbol"?e.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?e.push(`[${JSON.stringify(r)}]`):(e.length&&e.push("."),e.push(r));return e.join("")}function Fc(t){let e=[],r=[...t.issues].sort((n,o)=>n.path.length-o.path.length);for(let n of r)e.push(`\u2716 ${n.message}`),n.path?.length&&e.push(` \u2192 at ${Qh(n.path)}`);return e.join(`
|
|
26
26
|
`)}var Kh,no,Wr,Hc=te(()=>{Jr();me();Kh=s((t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Ac,2)},enumerable:!0})},"initializer"),no=T("$ZodError",Kh),Wr=T("$ZodError",Kh,{Parent:Error});s(oo,"flattenError");s(io,"formatError");s(qc,"treeifyError");s(Qh,"toDotPath");s(Fc,"prettifyError")});var qi,Fi,Hi,Gi,Bi,Gc,Vi,Bc,Ji=te(()=>{Jr();Hc();me();qi=s(t=>(e,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new St;if(a.issues.length){let c=new(o?.Err??t)(a.issues.map(u=>nt(u,i,ze())));throw Error.captureStackTrace(c,o?.callee),c}return a.value},"_parse"),Fi=qi(Wr),Hi=s(t=>async(e,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let c=new(o?.Err??t)(a.issues.map(u=>nt(u,i,ze())));throw Error.captureStackTrace(c,o?.callee),c}return a.value},"_parseAsync"),Gi=Hi(Wr),Bi=s(t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new St;return i.issues.length?{success:!1,error:new(t??no)(i.issues.map(a=>nt(a,o,ze())))}:{success:!0,data:i.value}},"_safeParse"),Gc=Bi(Wr),Vi=s(t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(a=>nt(a,o,ze())))}:{success:!0,data:i.value}},"_safeParseAsync"),Bc=Vi(Wr)});var vr={};Nt(vr,{_emoji:()=>Xh,base64:()=>iu,base64url:()=>Qi,bigint:()=>du,boolean:()=>fu,browserEmail:()=>uI,cidrv4:()=>nu,cidrv6:()=>ou,cuid:()=>Vc,cuid2:()=>Jc,date:()=>au,datetime:()=>uu,duration:()=>Yc,e164:()=>su,email:()=>tu,emoji:()=>ru,extendedDuration:()=>rI,guid:()=>eu,hostname:()=>so,html5Email:()=>sI,integer:()=>pu,ip:()=>lI,ipv4:()=>Wi,ipv6:()=>Ki,ksuid:()=>Qc,lowercase:()=>yu,nanoid:()=>Xc,null:()=>gu,number:()=>mu,rfc5322Email:()=>aI,string:()=>lu,time:()=>cu,ulid:()=>Wc,undefined:()=>hu,unicodeEmail:()=>cI,uppercase:()=>bu,uuid:()=>wr,uuid4:()=>nI,uuid6:()=>oI,uuid7:()=>iI,xid:()=>Kc});function ru(){return new RegExp(Xh,"u")}function ey(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function cu(t){return new RegExp(`^${ey(t)}$`)}function uu(t){let e=`${Yh}T${ey(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}var Vc,Jc,Wc,Kc,Qc,Xc,Yc,rI,eu,wr,nI,oI,iI,tu,sI,aI,cI,uI,Xh,Wi,Ki,nu,ou,lI,iu,Qi,so,su,Yh,au,lu,du,pu,mu,fu,gu,hu,yu,bu,Xi=te(()=>{Vc=/^[cC][^\s-]{8,}$/,Jc=/^[0-9a-z]+$/,Wc=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Kc=/^[0-9a-vA-V]{20}$/,Qc=/^[A-Za-z0-9]{27}$/,Xc=/^[a-zA-Z0-9_-]{21}$/,Yc=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,rI=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,eu=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,wr=s(t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,"uuid"),nI=wr(4),oI=wr(6),iI=wr(7),tu=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,sI=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,aI=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,cI=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,uI=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Xh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";s(ru,"emoji");Wi=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ki=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,nu=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ou=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,lI=new RegExp(`(${Wi.source})|(${Ki.source})`),iu=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Qi=/^[A-Za-z0-9_-]*$/,so=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,su=/^\+(?:[0-9]){6,14}[0-9]$/,Yh="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",au=new RegExp(`^${Yh}$`);s(ey,"timeSource");s(cu,"time");s(uu,"datetime");lu=s(t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},"string"),du=/^\d+n?$/,pu=/^\d+$/,mu=/^-?\d+(?:\.\d+)?/i,fu=/true|false/i,gu=/null/i,hu=/undefined/i,yu=/^[^A-Z]*$/,bu=/^[^a-z]*$/});function ty(t,e,r){t.issues.length&&e.issues.push(...Je(r,t.issues))}var Ae,ry,Yi,es,wu,vu,xu,Ru,Pu,Iu,Su,ku,Tu,Kr,Cu,Eu,_u,Ou,$u,Au,Nu,Lu,Mu,ts=te(()=>{Jr();Xi();me();Ae=T("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),ry={number:"number",bigint:"bigint",object:"date"},Yi=T("$ZodCheckLessThan",(t,e)=>{Ae.init(t,e);let r=ry[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,i=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),es=T("$ZodCheckGreaterThan",(t,e)=>{Ae.init(t,e);let r=ry[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,i=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),wu=T("$ZodCheckMultipleOf",(t,e)=>{Ae.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Nc(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),vu=T("$ZodCheckNumberFormat",(t,e)=>{Ae.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,i]=zc[e.format];t._zod.onattach.push(a=>{let c=a._zod.bag;c.format=e.format,c.minimum=o,c.maximum=i,r&&(c.pattern=pu)}),t._zod.check=a=>{let c=a.value;if(r){if(!Number.isInteger(c)){a.issues.push({expected:n,format:e.format,code:"invalid_type",input:c,inst:t});return}if(!Number.isSafeInteger(c)){c>0?a.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):a.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}c<o&&a.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),c>i&&a.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inst:t})}}),xu=T("$ZodCheckBigIntFormat",(t,e)=>{Ae.init(t,e);let[r,n]=jc[e.format];t._zod.onattach.push(o=>{let i=o._zod.bag;i.format=e.format,i.minimum=r,i.maximum=n}),t._zod.check=o=>{let i=o.value;i<r&&o.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:t,continue:!e.abort}),i>n&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:n,inst:t})}}),Ru=T("$ZodCheckMaxSize",(t,e)=>{Ae.init(t,e),t._zod.when=r=>{let n=r.value;return!Qt(n)&&n.size!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let n=r.value;n.size<=e.maximum||r.issues.push({origin:to(n),code:"too_big",maximum:e.maximum,input:n,inst:t,continue:!e.abort})}}),Pu=T("$ZodCheckMinSize",(t,e)=>{Ae.init(t,e),t._zod.when=r=>{let n=r.value;return!Qt(n)&&n.size!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let n=r.value;n.size>=e.minimum||r.issues.push({origin:to(n),code:"too_small",minimum:e.minimum,input:n,inst:t,continue:!e.abort})}}),Iu=T("$ZodCheckSizeEquals",(t,e)=>{Ae.init(t,e),t._zod.when=r=>{let n=r.value;return!Qt(n)&&n.size!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag;n.minimum=e.size,n.maximum=e.size,n.size=e.size}),t._zod.check=r=>{let n=r.value,o=n.size;if(o===e.size)return;let i=o>e.size;r.issues.push({origin:to(n),...i?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},input:r.value,inst:t,continue:!e.abort})}}),Su=T("$ZodCheckMaxLength",(t,e)=>{Ae.init(t,e),t._zod.when=r=>{let n=r.value;return!Qt(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let n=r.value;if(n.length<=e.maximum)return;let i=ro(n);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,input:n,inst:t,continue:!e.abort})}}),ku=T("$ZodCheckMinLength",(t,e)=>{Ae.init(t,e),t._zod.when=r=>{let n=r.value;return!Qt(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let n=r.value;if(n.length>=e.minimum)return;let i=ro(n);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,input:n,inst:t,continue:!e.abort})}}),Tu=T("$ZodCheckLengthEquals",(t,e)=>{Ae.init(t,e),t._zod.when=r=>{let n=r.value;return!Qt(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=r=>{let n=r.value,o=n.length;if(o===e.length)return;let i=ro(n),a=o>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},input:r.value,inst:t,continue:!e.abort})}}),Kr=T("$ZodCheckStringFormat",(t,e)=>{var r;Ae.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.format=e.format,e.pattern&&(n._zod.bag.pattern=e.pattern)}),(r=t._zod).check??(r.check=n=>{if(!e.pattern)throw new Error("Not implemented.");e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:e.format,input:n.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})})}),Cu=T("$ZodCheckRegex",(t,e)=>{Kr.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Eu=T("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=yu),Kr.init(t,e)}),_u=T("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=bu),Kr.init(t,e)}),Ou=T("$ZodCheckIncludes",(t,e)=>{Ae.init(t,e);let r=new RegExp(kt(e.includes));e.pattern=r,t._zod.onattach.push(n=>{n._zod.bag.pattern=r}),t._zod.check=n=>{n.value.includes(e.includes,e.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:n.value,inst:t,continue:!e.abort})}}),$u=T("$ZodCheckStartsWith",(t,e)=>{Ae.init(t,e);let r=new RegExp(`^${kt(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{n._zod.bag.pattern=r}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Au=T("$ZodCheckEndsWith",(t,e)=>{Ae.init(t,e);let r=new RegExp(`.*${kt(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{n._zod.bag.pattern=new RegExp(`.*${kt(e.suffix)}$`)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});s(ty,"handleCheckPropertyResult");Nu=T("$ZodCheckProperty",(t,e)=>{Ae.init(t,e),t._zod.check=r=>{let n=e.schema._zod.run({value:r.value[e.property],issues:[]},{});if(n instanceof Promise)return n.then(o=>ty(o,r,e.property));ty(n,r,e.property)}}),Lu=T("$ZodCheckMimeType",(t,e)=>{Ae.init(t,e);let r=new Set(e.mime);t._zod.onattach.push(n=>{n._zod.bag.mime=e.mime}),t._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:e.mime,input:n.value.type,path:["type"],inst:t})}}),Mu=T("$ZodCheckOverwrite",(t,e)=>{Ae.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var ao,Du=te(()=>{ao=class{static{s(this,"Doc")}constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
27
27
|
`).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),i=n.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(let a of i)this.content.push(a)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...r,o.join(`
|
|
28
28
|
`))}}});var Uu,zu=te(()=>{Uu={major:4,minor:0,patch:0}});function sl(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function gy(t){if(!Qi.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return sl(r)}function hy(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r,o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function oy(t,e,r){t.issues.length&&e.issues.push(...Je(r,t.issues)),e.value[r]=t.value}function rs(t,e,r){t.issues.length&&e.issues.push(...Je(r,t.issues)),e.value[r]=t.value}function iy(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Je(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function sy(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(i=>nt(i,n,ze())))}),e}function yy(t,e,r){let n=!0,o=t?.[e];if(r.values.size&&!r.values.has(o)&&(n=!1),r.maps.length>0)for(let i of r.maps)dI(o,i)||(n=!1);return n}function dI(t,e){let r=!0;for(let[n,o]of e)yy(t,n,o)||(r=!1);return r}function ju(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Yn(t)&&Yn(e)){let r=Object.keys(e),n=Object.keys(t).filter(i=>r.indexOf(i)!==-1),o={...t,...e};for(let i of n){let a=ju(t[i],e[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],i=e[n],a=ju(o,i);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function ay(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),br(t))return t;let n=ju(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function ns(t,e,r){t.issues.length&&e.issues.push(...Je(r,t.issues)),e.value[r]=t.value}function cy(t,e,r,n,o,i,a){t.issues.length&&(eo.has(typeof n)?r.issues.push(...Je(n,t.issues)):r.issues.push({origin:"map",code:"invalid_key",input:o,inst:i,issues:t.issues.map(c=>nt(c,a,ze()))})),e.issues.length&&(eo.has(typeof n)?r.issues.push(...Je(n,e.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:n,issues:e.issues.map(c=>nt(c,a,ze()))})),r.value.set(t.value,e.value)}function uy(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function ly(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function dy(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function py(t,e,r){return br(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function my(t){return t.value=Object.freeze(t.value),t}function fy(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Zc(o))}}var ue,co,Ce,Zu,qu,Fu,Hu,Gu,Bu,Vu,Ju,Wu,Ku,Qu,Xu,Yu,el,tl,rl,nl,ol,il,al,cl,ul,ll,os,dl,uo,is,pl,ml,fl,gl,hl,lo,yl,bl,wl,vl,xl,ss,Rl,Pl,xr,Il,Sl,kl,Tl,Cl,El,_l,Ol,$l,Al,Nl,Ll,Ml,Dl,Ul,po,zl,jl,Zl,ql,Fl,mo=te(()=>{ts();Jr();Du();Ji();Xi();me();zu();me();ue=T("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.id=e.type+"_"+ji(10),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Uu;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let i of o._zod.onattach)i(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=s((i,a,c)=>{let u=br(i),l;for(let d of a){if(d._zod.when){if(!d._zod.when(i))continue}else if(u)continue;let p=i.issues.length,m=d._zod.check(i);if(m instanceof Promise&&c?.async===!1)throw new St;if(l||m instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await m,i.issues.length!==p&&(u||(u=br(i,p)))});else{if(i.issues.length===p)continue;u||(u=br(i,p))}}return l?l.then(()=>i):i},"runChecks");t._zod.run=(i,a)=>{let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new St;return c.then(u=>o(u,n,a))}return o(c,n,a)}}t["~standard"]={validate:s(o=>{try{let i=Gc(t,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Bc(t,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},"validate"),vendor:"zod",version:1}}),co=T("$ZodString",(t,e)=>{ue.init(t,e),t._zod.pattern=t?._zod.bag?.pattern??lu(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Ce=T("$ZodStringFormat",(t,e)=>{Kr.init(t,e),co.init(t,e)}),Zu=T("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=eu),Ce.init(t,e)}),qu=T("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=wr(n))}else e.pattern??(e.pattern=wr());Ce.init(t,e)}),Fu=T("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=tu),Ce.init(t,e)}),Hu=T("$ZodURL",(t,e)=>{Ce.init(t,e),t._zod.check=r=>{try{let n=new URL(r.value);so.lastIndex=0,so.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:so.source,input:r.value,inst:t}),e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t}));return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t})}}}),Gu=T("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=ru()),Ce.init(t,e)}),Bu=T("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Xc),Ce.init(t,e)}),Vu=T("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Vc),Ce.init(t,e)}),Ju=T("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Jc),Ce.init(t,e)}),Wu=T("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Wc),Ce.init(t,e)}),Ku=T("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Kc),Ce.init(t,e)}),Qu=T("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Qc),Ce.init(t,e)}),Xu=T("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=uu(e)),Ce.init(t,e)}),Yu=T("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=au),Ce.init(t,e)}),el=T("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=cu(e)),Ce.init(t,e)}),tl=T("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Yc),Ce.init(t,e)}),rl=T("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Wi),Ce.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.format="ipv4"})}),nl=T("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Ki),Ce.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t})}}}),ol=T("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=nu),Ce.init(t,e)}),il=T("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=ou),Ce.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t})}}});s(sl,"isValidBase64");al=T("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=iu),Ce.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{sl(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t})}});s(gy,"isValidBase64URL");cl=T("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Qi),Ce.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{gy(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t})}}),ul=T("$ZodE164",(t,e)=>{e.pattern??(e.pattern=su),Ce.init(t,e)});s(hy,"isValidJWT");ll=T("$ZodJWT",(t,e)=>{Ce.init(t,e),t._zod.check=r=>{hy(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t})}}),os=T("$ZodNumber",(t,e)=>{ue.init(t,e),t._zod.pattern=t._zod.bag.pattern??mu,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...i?{received:i}:{}}),r}}),dl=T("$ZodNumber",(t,e)=>{vu.init(t,e),os.init(t,e)}),uo=T("$ZodBoolean",(t,e)=>{ue.init(t,e),t._zod.pattern=fu,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),is=T("$ZodBigInt",(t,e)=>{ue.init(t,e),t._zod.pattern=du,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}let{value:o}=r;return typeof o=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:o,inst:t}),r}}),pl=T("$ZodBigInt",(t,e)=>{xu.init(t,e),is.init(t,e)}),ml=T("$ZodSymbol",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let{value:o}=r;return typeof o=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:t}),r}}),fl=T("$ZodUndefined",(t,e)=>{ue.init(t,e),t._zod.pattern=hu,t._zod.values=new Set([void 0]),t._zod.parse=(r,n)=>{let{value:o}=r;return typeof o>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:t}),r}}),gl=T("$ZodNull",(t,e)=>{ue.init(t,e),t._zod.pattern=gu,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let{value:o}=r;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),hl=T("$ZodAny",(t,e)=>{ue.init(t,e),t._zod.parse=r=>r}),lo=T("$ZodUnknown",(t,e)=>{ue.init(t,e),t._zod.parse=r=>r}),yl=T("$ZodNever",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)}),bl=T("$ZodVoid",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let{value:o}=r;return typeof o>"u"||r.issues.push({expected:"void",code:"invalid_type",input:o,inst:t}),r}}),wl=T("$ZodDate",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:t}),r}});s(oy,"handleArrayResult");vl=T("$ZodArray",(t,e)=>{ue.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let i=[];for(let a=0;a<o.length;a++){let c=o[a],u=e.element._zod.run({value:c,issues:[]},n);u instanceof Promise?i.push(u.then(l=>oy(l,r,a))):oy(u,r,a)}return i.length?Promise.all(i).then(()=>r):r}});s(rs,"handleObjectResult");s(iy,"handleOptionalObjectResult");xl=T("$ZodObject",(t,e)=>{ue.init(t,e);let r=Qn(()=>{let p=Object.keys(e.shape),m=Uc(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(m)}});Pe(t._zod,"disc",()=>{let p=e.shape,m=new Map,f=!1;for(let g in p){let b=p[g]._zod;if(b.values||b.disc){f=!0;let h={values:new Set(b.values??[]),maps:b.disc?[b.disc]:[]};m.set(g,h)}}if(f)return m});let n=s(p=>{let m=new ao(["shape","payload","ctx"]),{keys:f,optionalKeys:g}=r.value,b=s(v=>{let C=yr(v);return`shape[${C}]._zod.run({ value: input[${C}], issues: [] }, ctx)`},"parseStr");m.write("const input = payload.value;");let h=Object.create(null);for(let v of f)h[v]=ji(15);m.write("const newResult = {}");for(let v of f)if(g.has(v)){let C=h[v];m.write(`const ${C} = ${b(v)};`);let A=yr(v);m.write(`
|
|
@@ -84,7 +84,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
84
84
|
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!v.has("X-Amz-Expires")&&v.set("X-Amz-Expires","86400"),v.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),v.set("X-Amz-Credential",`${this.accessKeyId}/${this.credentialString}`),v.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Fh(this.encodedPath);let C=new Set;this.encodedSearch=[...this.url.searchParams].filter(([A])=>{if(!A)return!1;if(this.service==="s3"){if(C.has(A))return!1;C.add(A)}return!0}).map(A=>A.map(O=>Fh(encodeURIComponent(O)))).sort(([A,O],[S,M])=>A<S?-1:A>S?1:O<M?-1:O>M?1:0).map(A=>A.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,`SignedHeaders=${this.signedHeaders}`,`Signature=${await this.signature()}`].join(", ")}async signature(){let e=this.datetime.slice(0,8),r=[this.secretAccessKey,e,this.region,this.service].join(),n=this.cache.get(r);if(!n){let o=await Jn(`AWS4${this.secretAccessKey}`,e),i=await Jn(o,this.region),a=await Jn(i,this.service);n=await Jn(a,"aws4_request"),this.cache.set(r,n)}return Sc(await Jn(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Sc(await qh(await this.canonicalString()))].join(`
|
|
85
85
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,`${this.canonicalHeaders}
|
|
86
86
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
87
|
-
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new F("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Sc(await qh(this.body||""))}return e}};async function Jn(t,e){let r=await crypto.subtle.importKey("raw",typeof t=="string"?kc.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,kc.encode(e))}s(Jn,"hmac");async function qh(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?kc.encode(t):t)}s(qh,"hash");function Sc(t){return Array.prototype.map.call(new Uint8Array(t),e=>`0${e.toString(16)}`.slice(-2)).join("")}s(Sc,"buf2hex");function Fh(t){return t.replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}s(Fh,"encodeRfc3986");function cP(t,e){let{hostname:r,pathname:n}=t,o=r.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")r.startsWith("iot.")?i="execute-api":r.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let c=(e.get("X-Amz-Target")||"").split(".")[0];c==="AnyScaleFrontendService"?i="application-autoscaling":c==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in Zh?[Zh[i],a]:[i,a]}s(cP,"guessServiceRegion");function uP(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}s(uP,"b64ToUint6");function Hh(t,e){let r=t.replace(/[^A-Za-z0-9+/]/g,""),n=r.length,o=e?Math.ceil((n*3+1>>2)/e)*e:n*3+1>>2,i=new Uint8Array(o),a,c,u=0,l=0;for(let d=0;d<n;d++)if(c=d&3,u|=uP(r.charCodeAt(d))<<6*(3-c),c===3||n-d===1){for(a=0;a<3&&l<o;)i[l]=u>>>(16>>>a&24)&255,a++,l++;u=0}return i}s(Hh,"base64Decode");function Ui(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Ui,"uint6ToB64");function Gh(t){let e=2,r="",n=t.length,o=0;for(let i=0;i<n;i++)e=i%3,o|=t[i]<<(16>>>e&24),(e===2||t.length-i===1)&&(r+=String.fromCodePoint(Ui(o>>>18&63),Ui(o>>>12&63),Ui(o>>>6&63),Ui(o&63)),o=0);return r.substring(0,r.length-2+e)+(e===2?"":e===1?"=":"==")}s(Gh,"base64Encode");function Gr(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(Gr,"numberToString");function lP(t){let e=t.getTimezoneOffset(),r=Math.abs(e),n=e>0?"-":"+",o=Gr(Math.floor(r/60)),i=Gr(r%60);return`${n}${o}${i}`}s(lP,"getCLFOffset");function Cc(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],r=Gr(t.getDate()),n=e[t.getMonth()],o=t.getFullYear(),i=Gr(t.getHours()),a=Gr(t.getMinutes()),c=Gr(t.getSeconds()),u=lP(t);return`${r}/${n}/${o}:${i}:${a}:${c} ${u}`}s(Cc,"toCLFDate");var Bh=Ne("zuplo:runtime"),Br="X-Amzn-Trace-Id",dP="x-amzn-errortype",Vh=[],pP=s(async(t,e,r)=>{let n=r;for await(let o of Vh)n=await o(t,e,r);return n},"onSendingAwsLambdaEvent"),tt=class extends F{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,r){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=r.get(Br)??void 0,this.errorType=r.get(dP)??void 0}},mP={addSendingAwsLambdaEventHook:s(t=>{Vh.push(t)},"addSendingAwsLambdaEventHook")};async function fP(t,e){R("handler.aws-lambda");let{accessKeyId:r,secretAccessKey:n,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:c=!1,binaryMediaTypes:u}=e.route.handler.options;if(!r)throw new w("awsAccessKeyId is not set in the handler options");if(!n)throw new w("secretAccessKey is not set in the handler options");if(!o)throw new w("region is not set in the handler options");if(!i)throw new w("functionName is not set in the handler options");let l=new Hr({accessKeyId:r,secretAccessKey:n}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Bh(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await bP(t,{binaryMediaTypes:u}),{options:f}=e.route.handler,g;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?g=yP(t,e):g=await hP(t,e,{useAwsResourcePathStyle:c}),Bh("Calling onSendingAwsLambdaEvent hook");let b=await pP(t,e,g);b.body=p,b.isBase64Encoded=m;let h=await l.fetch(d,{body:JSON.stringify(b)}),x=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&typeof f.returnAmazonTraceIdHeader=="boolean"?f.returnAmazonTraceIdHeader:!1;try{return gP(h,{returnLambdaTraceIdHeader:x})}catch(v){if(v instanceof tt){let C=x&&v.traceId?{[Br]:v.traceId}:void 0;return D.internalServerError(t,e,void 0,C)}throw v}}s(fP,"awsLambdaHandler");async function gP(t,{returnLambdaTraceIdHeader:e}){let r;try{r=await t.json()}catch{throw new tt("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw r&&typeof r=="object"&&"message"in r&&typeof r.message=="string"?new tt(r.message,t.headers):new tt(`Status: ${t.statusText}`,t.headers);if(r&&typeof r=="object"&&"errorMessage"in r&&typeof r.errorMessage=="string")throw new tt(r.errorMessage,t.headers);if(!r||typeof r!="object"||!("statusCode"in r)||typeof r.statusCode!="number"){let a=t.headers.get(Br);return new Response(JSON.stringify(r),{status:t.status,headers:{"content-type":"application/json",...e&&a?{[Br]:a}:{}}})}let n=new Headers;if("headers"in r&&r.headers){if(typeof r.headers!="object")throw new tt(`Response headers must be an object. Received ${typeof r.headers}`,t.headers);for(let[a,c]of Object.entries(r.headers))n.set(a,c)}if("cookies"in r&&r.cookies){if(!Array.isArray(r.cookies))throw new tt(`Response cookies must be an array. Received ${typeof r.cookies}`,t.headers);n.set("cookie",r.cookies.join(";"))}let o;if("isBase64Encoded"in r&&typeof r.isBase64Encoded!="boolean")throw new tt(`Response property isBase64Encoded must be a boolean. Received ${typeof r.isBase64Encoded}`,t.headers);if("isBase64Encoded"in r&&r.isBase64Encoded===!0){if(!("body"in r))throw new tt("Response was set to base64 encoded but no body was set",t.headers);if(typeof r.body!="string")throw new tt("Response was set to base64 encoded but body was not a string",t.headers);o=Hh(r.body)}else"body"in r&&typeof r.body=="string"?o=r.statusCode===204&&r.body===""?null:r.body:"body"in r&&r.body!==null&&r.body!==void 0?o=JSON.stringify(r.body):o=null;if(o!==null&&"bodyEncoding"in r){if(typeof r.bodyEncoding!="string"||!(r.bodyEncoding==="gzip"||r.bodyEncoding==="deflate"))throw new tt(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${r.bodyEncoding}`,t.headers);let a=new Blob([o]).stream().pipeThrough(new DecompressionStream(r.bodyEncoding));o=await new Response(a).arrayBuffer()}let i=t.headers.get(Br);return e&&i&&n.set(Br,i),new Response(o,{headers:n,status:r.statusCode})}s(gP,"getResponse");async function hP(t,e,{useAwsResourcePathStyle:r}){let n={},o={};t.headers.forEach((l,d)=>{n[d]=l,o[d]=[l]});let i=t.query,a={};for(let[l,d]of Object.entries(i))a[l]||(a[l]=[]),a[l].push(d);let c=new URL(t.url);return{version:"1.0",resource:c.pathname,path:c.pathname,httpMethod:t.method,headers:n,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:c.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:c.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Cc(),requestTimeEpoch:Date.now(),resourceId:e.route.operationId??null,resourcePath:vP(e.route.path,r),stage:null},pathParameters:t.params,stageVariables:null}}s(hP,"buildEventVersion1");function yP(t,e){let r={};t.headers.forEach((i,a)=>{r[a]=i});let n=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:n.pathname,rawQueryString:n.search,cookies:[],headers:r,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:n.hostname,domainPrefix:null,http:{method:t.method,path:n.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Cc(),timeEpoch:Date.now()},pathParameters:t.params,stageVariables:null}}s(yP,"buildEventVersion2");async function bP(t,{binaryMediaTypes:e}){let r,n=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")r=null;else if(e&&o&&wP(e,o)){let i=await t.arrayBuffer();r=Gh(new Uint8Array(i)),n=!0}else r=await t.clone().text();return[r,n]}s(bP,"getBodyResult");function wP(t,e){let r=e.split(";")[0].trim().toLowerCase();return t.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}s(wP,"matchesContentType");function vP(t,e=!1){if(!e)return t;let r=Ic(t),n=jh(t),o={};return r.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),n(o)}s(vP,"getResourcePath");var xP=[502,503,504];async function Vr(t,e){if(xP.includes(t.status)){let r=Q.getLogger(e),o=await t.clone().text(),i={};for(let[a,c]of t.headers)i[a]=c;r.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(Vr,"logBadGatewayResponses");var Ec;function Kt(t){if(Ec===void 0){let r=P.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),Ec=r}return t.log[Ec]}s(Kt,"getHandlerUserLogFunction");async function RP(t,e){R("handler.open-api");let r=P.instance.build.BUILD_ID,{buildAssetsUrl:n}=P.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new w("Open API Spec Handler must have 'openApiFilePath' specified");let a=PP(i);if(!a.isValid)throw new w(a.error);let c=`${n}/${r}${i.substring(1)}`,u=await j.fetch(c,{method:t.method,body:t.body,headers:t.headers});if(u.status!==200)return D.notFound(t,e,{detail:"OpenAPI file could not be found."});let l={"content-type":"application/json",vary:"Accept-Encoding"};P.instance.isDeno||(l["content-encoding"]=u.headers.get("content-encoding")||"");let d=new Response(u.body,{headers:l,status:u.status,statusText:u.statusText});return Vr(d,e),d}s(RP,"openApiSpecHandler");var PP=s(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function IP(t,e){R("handler.redirect");let r=e.route.handler.options;if(!r.location)throw new w("Redirect Handler must have 'location' specified");let n=r.status??302;return new Response(null,{status:n,headers:{location:r.location}})}s(IP,"redirectHandler");async function SP(t){if(R("handler.zuplo-service-proxy"),Object.entries(t.params).length!==1)throw new w("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(t.params.path,P.instance.zuploEdgeApiUrl),r=new Headers(t.headers);return r.set("Authorization",`Bearer ${P.instance.authApiJWT}`),j.fetch(e,{method:t.method,headers:r,body:t.body})}s(SP,"zuploServiceProxy");function kP(t,e){let r=t.endsWith("/"),n=e.startsWith("/");return r&&n?`${t.substring(0,t.length-1)}${e}`:!r&&!n?`${t}/${e}`:`${t}${e}`}s(kP,"join");async function TP(t,e){R("handler.url-forward");let r=Kt(e),n=e.route.handler.options,o=n.forwardSearch!==!1,i;if(P.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?i=n.followRedirects===!0?"follow":"manual":typeof n.followRedirects<"u"&&R("handler.url-forward.follow-redirects"),!n.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!n||typeof n.__rewriteFunction!="function")throw new w("Invalid options for this route");let a=Wt(e),c=new URL(t.url),u=n.__rewriteFunction(t,a),l=kP(u,c.pathname),d=o?`${l}${c.search}`:l.toString(),p=Date.now();r(`URL Forwarding to '${d}'`);let m=t.body;if(i==="follow"&&t.body)try{m=await t.arrayBuffer()}catch(b){throw new Error(`Failed to buffer request body for redirect handling: ${b}`)}let f=await fetch(d,{method:t.method,body:m,headers:t.headers,redirect:i,zuplo:n.clientCertificate?{clientCertificate:n.clientCertificate}:void 0}),g=Date.now()-p;return r(`URL Forward received response ${f.status} - ${f.statusText} in ${g}ms`),Vr(f,e),f}s(TP,"urlForwardHandler");var CP=s((t,e)=>{let r=new URL(t),n=new URL(e);for(let[o,i]of n.searchParams.entries())r.searchParams.append(o,i);return r.toString()},"addQuery");async function EP(t,e){R("handler.url-rewrite");let r=Kt(e),n=e.route.handler.options,o=n.forwardSearch!==!1,i=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new w("Invalid options for this route");let a=Wt(e),c=n.__rewriteFunction(t,a),u=o?CP(c,t.url):c,l=Date.now();r(`URL Rewriting to '${u}'`);let d=await fetch(u.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual",zuplo:n.clientCertificate?{clientCertificate:n.clientCertificate}:void 0}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Vr(d,e),d}s(EP,"urlRewriteHandler");function _P(t,e,r){t.addEventListener("close",()=>{e.close()}),e.addEventListener("close",()=>{t.close()}),t.addEventListener("error",n=>{r.log.error(`Incoming WebSocket error: ${JSON.stringify(n)}`),e.send(JSON.stringify(n))}),e.addEventListener("error",n=>{r.log.error(`Outgoing WebSocket error: ${JSON.stringify(n)}`),t.send(JSON.stringify(n))}),t.addEventListener("message",n=>{e.send(n.data)}),e.addEventListener("message",n=>{t.send(n.data)})}s(_P,"wireUpPassthrough");async function OP(t,e){R("handler.websocket");let r=e.route.handler.options,n=Kt(e);if(!r||!r.rewritePattern)throw new w("WebSocket Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return D.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new w("Invalid options for this route");let i=Wt(e),a=r.__rewriteFunction(t,i);if(n(`Attempting WebSocket connection to '${a}'`),P.instance.isDeno){if(!t.originalRequest)throw new Error("Original websocket request is not available");let c=new WebSocket(a);await new Promise((d,p)=>{let m=s(()=>{g(),n("WebSocket connection established with upstream"),d()},"onOpen"),f=s(b=>{g(),n(`WebSocket connection error: ${b}`),p(new Error("Upstream open failed"))},"onErr"),g=s(()=>{c.removeEventListener("open",m),c.removeEventListener("error",f)},"cleanup");c.addEventListener("open",m),c.addEventListener("error",f)}).catch(d=>{throw new Error(`Failed to open outgoing socket: ${d.message}`)});let{socket:u,response:l}=globalThis.Deno.upgradeWebSocket(t.originalRequest);return _P(u,c,e),l}else{a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:t.method,headers:t.headers,body:t.body});if(c.status!==101||!c.webSocket){let u=await c.text(),l=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${u}'`;throw new Error(l)}return n(`WebSocket connected, received response ${c.status} - ${c.statusText}`),new Response(null,{status:101,webSocket:c.webSocket})}}s(OP,"webSocketHandler");async function $P(t,e){let r=we.instance.runtimeSettings.developerPortal.urls?.urls?.[0];if(!r)throw new w("Developer portal URL is not configured.");let n=AP(t.url,r);return e.log.info(`Redirecting from legacy dev portal to ${n}`),new Response(null,{status:301,headers:{location:n}})}s($P,"redirectLegacyDevPortal");function AP(t,e){let r=new URL(t),n=r.pathname.split("/")[1];if(!n)throw new w("The request URL does not contain a valid developer portal base path. This handler cannot be used on a root path");return r.hostname=new URL(e).hostname,r.pathname=r.pathname.substring(n.length+1),r.toString()}s(AP,"getDevPortalRedirectUrl");var _c=s((t,e)=>t.map((n,o)=>{let i;if(typeof n.module=="object"&&(i=n.module[n.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${o+1}, export name: ${n.export}`;throw new w(`${a} - Websocket policy must be a valid function (${c})`)}return i}),"getWebSocketPolicyFunctions"),Jh=s(async(t,e,r,n,o,i)=>{let a=t.data;if(i&&i.length>0){let c=[...i];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,r,e,n,o),a===void 0)return}}return a},"webSocketPolicyProcessor");async function NP(t,e,r){r(`Attempting WebSocket connection to '${e}'`);let n=new WebSocket(e);await new Promise((a,c)=>{let u=s(()=>{d(),r("WebSocket connection established with upstream"),a()},"onOpen"),l=s(p=>{d(),r(`WebSocket connection error: ${p}`),c(new Error("Upstream open failed"))},"onErr"),d=s(()=>{n.removeEventListener("open",u),n.removeEventListener("error",l)},"cleanup");n.addEventListener("open",u),n.addEventListener("error",l)}).catch(a=>{throw new Error(`Failed to open outgoing socket: ${a.message}`)});let{socket:o,response:i}=globalThis.Deno.upgradeWebSocket(t);return{clientSocket:o,outgoingSocket:n,response:i}}s(NP,"getDenoClientAndServerSockets");async function LP(t,e,r){r(`Attempting WebSocket connection to '${e}'`);let n=await fetch(e,{method:t.method,headers:t.headers,body:t.body});if(n.status!==101||!n.webSocket){let u=await n.text(),l=`WebSocket connection error - ${n.status}: ${n.statusText}, content: '${u}'`;throw new Error(l)}let o=new WebSocketPair,[i,a]=Object.values(o);r(`WebSocket connected, received response ${n.status} - ${n.statusText}`),n.webSocket.accept(),a.accept();let c=new Response(null,{status:101,webSocket:i});return{clientSocket:i,outgoingSocket:n.webSocket,serverSocket:a,response:c}}s(LP,"getCfClientAndServerSockets");function Wh(t,e,r,n,o,i){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",a=>{n.log.error(`WebSocket error: ${JSON.stringify(a)}, direction: ${i}`),e.send(JSON.stringify(a))}),t.addEventListener("message",a=>{try{let u=s(async l=>{let d=await Jh(l,t,e,r,n,o);d!==void 0&&e.send(d)},"innerPipeline")(a).catch(n.log.error);n.waitUntil(u)}catch(c){n.log.error(c)}})}s(Wh,"wireUpListeners");async function MP(t,e){R("handler.websocket-pipeline");let r=e.route.handler.options,n=Kt(e);if(!r||!r.rewritePattern)throw new w("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return D.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new w("Invalid options for this route");let i=Wt(e),a=r.__rewriteFunction(t,i),c=r.policies?.inbound?_c(r.policies.inbound,"inbound"):[],u=r.policies?.outbound?_c(r.policies.outbound,"outbound"):[],l,d,p,m;if(P.instance.isDeno){if(!t.originalRequest)throw new Error("Original websocket request is not available");let f=await NP(t.originalRequest,a,n);p=f.clientSocket,l=p,d=f.outgoingSocket,m=f.response}else{a=a.replace(/^(ws)/,"http");let f=await LP(t,a,n);l=f.serverSocket,d=f.outgoingSocket,p=f.clientSocket,m=f.response}return Wh(l,d,t,e,c,"inbound"),Wh(d,l,t,e,u,"outbound"),m}s(MP,"webSocketPipelineHandler");Ze();Yt();Yt();function Ir({id:t,method:e,params:r}){return{jsonrpc:dt,id:t,method:e,params:r}}s(Ir,"newJSONRPCRequest");function Ct({id:t,result:e}){return{jsonrpc:dt,id:t,result:e}}s(Ct,"newJSONRPCReponse");function Se({id:t,code:e,message:r,data:n}){return{jsonrpc:dt,id:t,error:{code:e,message:r,data:n}}}s(Se,"newJSONRPCError");Ze();Yt();Fs();var Lw=y.object({jsonrpc:y.literal(dt),id:Nw,error:y.object({code:y.number().int(),message:y.string(),data:y.optional(y.unknown())})}).strict();Mo();Sr();kr();var Do=s(t=>Dw.safeParse(t).success,"isJSONRPCRequest"),zw=s(t=>Mw.safeParse(t).success,"isJSONRPCNotification"),nn=s(t=>Uw.safeParse(t).success,"isJSONRPCResponse"),tr=s(t=>Lw.safeParse(t).success,"isJSONRPCError");var Uo=class{static{s(this,"NoOpLogger")}debug(){}info(){}warn(){}error(){}};function rr(){return new Uo}s(rr,"createDefaultLogger");Ze();Sr();kr();Ze();var jw=y.object({experimental:y.optional(y.object({}).loose()),roots:y.optional(y.object({listChanged:y.optional(y.boolean())}).loose()),sampling:y.optional(y.object({}).loose()),elicitation:y.optional(y.object({}).loose())}).loose(),Zw=y.object({experimental:y.optional(y.object({}).loose()),logging:y.optional(y.object({}).loose()),completions:y.optional(y.object({}).loose()),prompts:y.optional(y.object({listChanged:y.optional(y.boolean())}).loose()),resources:y.optional(y.object({subscribe:y.optional(y.boolean()),listChanged:y.optional(y.boolean())}).loose()),tools:y.optional(y.object({listChanged:y.optional(y.boolean())}).loose())}).loose();Ze();on();var om=Et.extend({version:y.string()});var qw=it.extend({method:y.literal("initialize"),params:ot.extend({protocolVersion:y.string(),capabilities:jw,clientInfo:om})}),FF=pt.extend({protocolVersion:y.string(),capabilities:Zw,serverInfo:om,instructions:y.optional(y.string())});Ze();Mo();Sr();kr();on();Hs();var UC=Et.extend({description:y.optional(y.string()),required:y.optional(y.boolean())}),zC=Et.extend({description:y.optional(y.string()),arguments:y.optional(y.array(UC)),_meta:y.optional(y.object({}).loose())}),jC=y.lazy(()=>{let{TextContentSchema:t,ImageContentSchema:e,AudioContentSchema:r,EmbeddedResourceSchema:n}=(am(),ei(sm)),{ResourceLinkSchema:o}=(Gs(),ei(mm));return y.object({role:y.enum(["user","assistant"]),content:y.discriminatedUnion("type",[t,e,r,o,n])}).loose()}),Jw=or.extend({method:y.literal("prompts/list")}),fH=ir.extend({prompts:y.array(zC)}),Ww=it.extend({method:y.literal("prompts/get"),params:ot.extend({name:y.string(),arguments:y.optional(y.record(y.string(),y.string()))})}),gH=pt.extend({description:y.optional(y.string()),messages:y.array(jC)}),hH=er.extend({method:y.literal("notifications/prompts/list_changed")});Gs();Ze();Mo();Sr();kr();on();Hs();var ZC=y.object({title:y.optional(y.string()),readOnlyHint:y.optional(y.boolean()),destructiveHint:y.optional(y.boolean()),idempotentHint:y.optional(y.boolean()),openWorldHint:y.optional(y.boolean())}).loose(),qC=Et.extend({description:y.optional(y.string()),inputSchema:y.object({type:y.literal("object"),properties:y.optional(y.record(y.string(),y.object({}).loose())),required:y.optional(y.array(y.string()))}).loose(),outputSchema:y.optional(y.object({type:y.literal("object"),properties:y.optional(y.record(y.string(),y.object({}).loose())),required:y.optional(y.array(y.string()))}).loose()),annotations:y.optional(ZC),_meta:y.optional(y.object({}).loose())}),IH=or.extend({method:y.literal("tools/list")}),SH=ir.extend({tools:y.array(qC)}),Kw=it.extend({method:y.literal("tools/call"),params:ot.extend({name:y.string(),arguments:y.optional(y.record(y.string(),y.unknown()))})}),kH=y.lazy(()=>{let{TextContentSchema:t,ImageContentSchema:e,AudioContentSchema:r,EmbeddedResourceSchema:n}=(am(),ei(sm)),{ResourceLinkSchema:o}=(Gs(),ei(mm));return pt.extend({content:y.array(y.discriminatedUnion("type",[t,e,r,o,n])),structuredContent:y.optional(y.record(y.string(),y.unknown())),isError:y.optional(y.boolean())})}),TH=er.extend({method:y.literal("notifications/tools/list_changed")});var zo="2025-06-18",fm="2025-03-26",gm="2024-11-05",hm="2024-10-07",ym=[zo,fm,gm,hm];var FC="MCP Server",HC="0.0.0",Bs=class{static{s(this,"MCPServer")}capabilities;tools=new Map;prompts=new Map;resources=new Map;name;version;instructions;logger;constructor(e){this.name=e.name||FC,this.version=e.version||HC,this.instructions=e.instructions||void 0,this.logger=e.logger||rr(),this.capabilities={tools:{supported:!0,available:[]},prompts:{},resources:{},...e.capabilities}}withTransport(e){e.onMessage(async r=>{try{if(Do(r)){let n=await this.handleRequest(r);if(n)return await e.send(n),n}else{if(zw(r))return await this.handleNotification(r),null;if(nn(r))return this.logger.debug("Received response:",r),null}}catch(n){if(this.logger.error("Error processing message:",n),Do(r)){let o=Se({id:r.id,code:Ie.InternalError,message:n instanceof Error?n.message:"Internal error"});return await e.send(o),o}}return null})}getTool(e){return this.tools.get(e)?.tool}getTools(){let e=new Map;for(let[r,n]of this.tools.entries())e.set(r,n.tool);return e}getCapabilities(){return{...this.capabilities}}addTool(e){let{name:r,validator:n,handler:o,description:i=`Execute the ${r} tool`,outputSchema:a}=e,u={tool:{name:r,description:i,inputSchema:n.jsonSchema,...a&&{outputSchema:a}},validator:n,handler:o};this.tools.set(r,u),this.updateAvailableTools()}removeTool(e){let r=this.tools.delete(e);return r&&this.updateAvailableTools(),r}getToolDefinitions(){return Array.from(this.tools.values()).map(e=>e.tool)}addPrompt(e){let{name:r,validator:n,generator:o,description:i}=e,a=n.jsonSchema,c;if(a.properties&&typeof a.properties=="object"){let d=new Set(a.required||[]);c=Object.entries(a.properties).map(([p,m])=>({name:p,description:m.description??`Prompt for ${p}`,required:d.has(p)}))}let l={prompt:{name:r,description:i,...c&&{arguments:c}},validator:n,generator:o};this.prompts.set(r,l)}removePrompt(e){return this.prompts.delete(e)}getPrompt(e){return this.prompts.get(e)?.prompt}getPromptDefinitions(){return Array.from(this.prompts.values()).map(e=>e.prompt)}addResource(e,r,n,o){if(typeof r=="string"){let a={type:"resource",resource:{name:e,uri:r,...n},reader:o};this.resources.set(e,a)}else{let a={type:"template",template:{name:e,uriTemplate:r.template,...n},reader:o};this.resources.set(e,a)}}removeResource(e){return this.resources.delete(e)}getResource(e){let r=this.resources.get(e);if(r)return r.type==="resource"?r.resource:void 0}getResourceTemplate(e){let r=this.resources.get(e);if(r)return r.type==="template"?r.template:void 0}getResourceDefinitions(){return Array.from(this.resources.values()).filter(e=>e.type==="resource").map(e=>e.resource)}getResourceTemplateDefinitions(){return Array.from(this.resources.values()).filter(e=>e.type==="template").map(e=>e.template)}async handleRequest(e){try{switch(e.method){case"ping":return this.handlePing(e);case"initialize":return this.handleInitialize(e);case"tools/list":return this.handleToolListRequest(e);case"tools/call":return this.handleToolCallRequest(e);case"prompts/list":return this.handlePromptListRequest(e);case"prompts/get":return this.handlePromptGetRequest(e);case"resources/list":return this.handleResourceListRequest(e);case"resources/templates/list":return this.handleResourceTemplateListRequest(e);case"resources/read":return this.handleResourceReadRequest(e);default:return Se({id:e.id,code:Ie.MethodNotFound,message:`Method "${e.method}" not found`})}}catch(r){return this.logger.error("Error handling request:",r),Se({id:e.id,code:Ie.InternalError,message:r instanceof Error?r.message:"Internal error"})}}async handleNotification(e){this.logger.debug("Received notification:",e.method)}handlePing(e){return Ct({id:e.id,result:{}})}handleInitialize(e){let r=qw.safeParse(e);if(!r.success){let o=y.treeifyError(r.error),i=y.prettifyError(r.error);return Se({id:e.id,code:Ie.InvalidParams,message:`Invalid request parameters: ${i}`,data:o})}let n=r.data.params.protocolVersion;switch(n){case zo:case fm:case gm:case hm:{let o={protocolVersion:n,capabilities:this.getCapabilities(),serverInfo:{name:this.name,version:this.version},...this.instructions?{instructions:this.instructions}:{}};return Ct({id:e.id,result:o})}default:return Se({id:e.id,code:Ie.InvalidParams,message:`Unsupported protocol version: ${n} - supported versions: ${ym}`,data:{supportedVersions:ym}})}}async handleToolListRequest(e){let n={tools:Array.from(this.tools.entries()).map(([o,i])=>i.tool)};return Ct({id:e.id,result:n})}async handleToolCallRequest(e){let r=Kw.safeParse(e);if(!r.success)return this.logger.warn("Could not validate tool call:",r.error),Se({id:e.id,code:Ie.InvalidRequest,message:`Invalid request ${r.error}`});let n=r.data,o=n.params.name,i=this.tools.get(o);if(!i)return Se({id:e.id,code:Ie.InvalidParams,message:`Tool "${o}" not found`});let a=n.params.arguments??{},c=i.validator.parse(a);if(!c.success)return Se({id:e.id,code:Ie.InvalidParams,message:c.errorMessage?`Invalid arguments for tool '${o}': ${c.errorMessage}`:`Invalid arguments for tool '${o}'`,data:c.errorData});try{let u=c.data,l=await i.handler(u);return Ct({id:e.id,result:l})}catch(u){return this.logger.error(`Error executing tool "${o}":`,u),Se({id:e.id,code:Ie.InternalError,message:u instanceof Error?u.message:"Tool execution error"})}}async handlePromptListRequest(e){let r=Jw.safeParse(e);if(!r.success){let i=y.treeifyError(r.error),a=y.prettifyError(r.error);return Se({id:e.id,code:Ie.InvalidParams,message:`Invalid request parameters: ${a}`,data:i})}let o={prompts:Array.from(this.prompts.values()).map(i=>i.prompt)};return Ct({id:e.id,result:o})}async handlePromptGetRequest(e){let r=Ww.safeParse(e);if(!r.success){let c=y.treeifyError(r.error),u=y.prettifyError(r.error);return Se({id:e.id,code:Ie.InvalidParams,message:`Invalid request parameters: ${u}`,data:c})}let n=r.data.params.name,o=this.prompts.get(n);if(!o)return Se({id:e.id,code:Ie.InvalidParams,message:`Prompt "${n}" not found`});let i=r.data.params.arguments??{},a=o.validator.parse(i);if(!a.success)return Se({id:e.id,code:Ie.InvalidParams,message:a.errorMessage?`Invalid arguments for prompt '${n}': ${a.errorMessage}`:`Invalid arguments for prompt '${n}'`,data:a.errorData});try{let c=a.data,u=await o.generator(c),l={...o.prompt.description&&{description:o.prompt.description},messages:u};return Ct({id:e.id,result:l})}catch(c){return this.logger.error(`Error generating prompt "${n}":`,c),Se({id:e.id,code:Ie.InternalError,message:c instanceof Error?c.message:"Prompt generation error"})}}updateAvailableTools(){this.capabilities.tools&&(this.capabilities.tools.available=Array.from(this.tools.keys()))}async handleResourceListRequest(e){let r=lm.safeParse(e);if(!r.success){let i=y.treeifyError(r.error),a=y.prettifyError(r.error);return Se({id:e.id,code:Ie.InvalidParams,message:`Invalid request parameters: ${a}`,data:i})}let o={resources:Array.from(this.resources.values()).filter(i=>i.type==="resource").map(i=>i.resource)};return Ct({id:e.id,result:o})}async handleResourceTemplateListRequest(e){let r=dm.safeParse(e);if(!r.success){let i=y.treeifyError(r.error),a=y.prettifyError(r.error);return Se({id:e.id,code:Ie.InvalidParams,message:`Invalid request parameters: ${a}`,data:i})}let o={resourceTemplates:Array.from(this.resources.values()).filter(i=>i.type==="template").map(i=>i.template)};return Ct({id:e.id,result:o})}async handleResourceReadRequest(e){let r=pm.safeParse(e);if(!r.success){let a=y.treeifyError(r.error),c=y.prettifyError(r.error);return Se({id:e.id,code:Ie.InvalidParams,message:`Invalid request parameters: ${c}`,data:a})}let n=r.data.params.uri;function o(a,c){let u=c.replace(/\{[^}]+\}/g,"([^/]+)");return new RegExp(`^${u}$`).test(a)}s(o,"matchesTemplate");let i=Array.from(this.resources.values()).find(a=>a.type==="resource"&&a.resource.uri===n||a.type==="template"&&o(n,a.template.uriTemplate));if(!i)return Se({id:e.id,code:Ie.ResourceNotFound,message:`Resource not found: ${n}`,data:{uri:n}});try{let a=await i.reader(n);return Ct({id:e.id,result:a})}catch(a){return this.logger.error(`Error reading resource "${n}":`,a),Se({id:e.id,code:Ie.ResourceNotFound,message:a instanceof Error?a.message:"Resource not found",data:{uri:n}})}}};var sr=class{static{s(this,"CustomValidator")}jsonSchema;parseFn;constructor(e,r){this.jsonSchema=e,this.parseFn=r}parse(e){return this.parseFn(e)}};Yt();var Vs=class{static{s(this,"HTTPStreamableTransport")}messageHandler=null;closeCallback=null;headers;options;connected=!1;enableStreaming=!1;sessions=new Map;streams=new Map;logger;setHeaders(e){this.headers={...this.headers,...e}}constructor(e={},r=!1){this.options={timeout:30*60*1e3,enableSessions:!1,...e},this.headers={"Content-Type":"application/json",...e.headers},this.logger=e.logger||rr(),r&&this.startSessionCleanup()}onError(e){throw new Error("Method not implemented.")}getSessionId(){throw new Error("Method not implemented.")}setSessionId(e){throw new Error("Method not implemented.")}async connect(){this.connected=!0}async send(e){if(!this.connected)throw new Error("Transport not connected");if(nn(e)){for(let[r,n]of this.sessions.entries())for(let[o,i]of n.streams.entries())if(i.pendingRequests.has(e.id)){await this.sendToStream(i,e),i.pendingRequests.delete(e.id),i.pendingRequests.size===0&&await this.closeStream(r,o);return}}else for(let r of this.sessions.values()){let n=[...r.streams.values()][0];n&&(await this.sendToStream(n,e),Do(e)&&n.pendingRequests.add(e.id))}}onMessage(e){this.messageHandler=e}onClose(e){this.closeCallback=e}async close(){this.connected=!1;for(let e of this.sessions.values()){for(let[r,n]of e.streams.entries())try{await n.writer.close()}catch(o){this.logger.warn("Error closing stream:",o)}e.streams.clear()}this.sessions.clear(),this.closeCallback&&this.closeCallback()}async handleRequest(e){if(!this.connected)return new Response(JSON.stringify(Se({code:-32e3,message:"Transport not connected",id:null})),{status:503,headers:this.headers});if(!this.messageHandler)return new Response(JSON.stringify(Se({code:-32e3,message:"No message handler registered",id:null})),{status:500,headers:this.headers});let r=e.method.toUpperCase();try{this.validateOrigin(e);let n=e.headers.get("Mcp-Session-Id"),o;if(n&&(o=this.sessions.get(n),!o&&r!=="DELETE"))return new Response(null,{status:404});switch(r){case"POST":return await this.handlePostRequest(e,o);case"GET":return await this.handleGetRequest(e,o);case"DELETE":return await this.handleDeleteRequest(e,o?.id);default:return new Response(null,{status:405,headers:{Allow:"POST, GET, DELETE"}})}}catch(n){return this.logger.error("Error handling request:",n),new Response(JSON.stringify(Se({code:Ie.InternalError,message:"Internal server error",id:null})),{status:400,headers:this.headers})}}async handlePostRequest(e,r){let n=e.headers.get("Accept")||"";if(!n.includes("application/json")&&!n.includes("text/event-stream"))return new Response(JSON.stringify(Se({code:Ie.InvalidRequest,message:"Not Acceptable: Client must accept application/json and text/event-stream",id:null})),{status:406,headers:this.headers});let o=await this.extractJSONRPC(e);if(!o||Array.isArray(o)&&o.length===0)return new Response(JSON.stringify(Se({code:Ie.ParseError,message:"Parse error: received invalid JSON",id:null})),{status:400,headers:this.headers});let i=Array.isArray(o)?o:[o],a=i.some(u=>this.isRequest(u)),c=r;if(this.options.enableSessions&&!c&&i.some(u=>this.isRequest(u)&&u.method==="initialize")){let u=this.generateFallbackUUID();c=this.createSession(u)}try{if(!a){for(let p of i)await this.messageHandler?.(p);return new Response(null,{status:202,headers:{...this.headers,...c&&{"Mcp-Session-Id":c.id}}})}if(!this.enableStreaming){let p=[];for(let f of i)if(this.isRequest(f)){let g=await this.messageHandler?.(f);g&&p.push(g)}else await this.messageHandler?.(f);let m=p.length===1?p[0]:p;return new Response(JSON.stringify(m),{status:200,headers:{...this.headers,...c&&{"Mcp-Session-Id":c.id}}})}let{stream:u,streamId:l}=this.createStream(c),d=[];for(let p of i)if(this.isRequest(p)){this.streams.get(l)?.pendingRequests.add(p.id);let m=this.messageHandler?.(p);d.push(m)}else await this.messageHandler?.(p);return new Response(u.readable,{headers:{"Cache-Control":"no-cache",Connection:"keep-alive",...this.headers,...c&&{"Mcp-Session-Id":c.id}}})}catch{return new Response(JSON.stringify(Se({code:Ie.InternalError,message:"Internal server error",id:null})),{status:500,headers:this.headers})}}async handleGetRequest(e,r){if(!(e.headers.get("Accept")||"").includes("text/event-stream"))return new Response(null,{status:406,headers:this.headers});if(this.options.enableSessions&&!r)return new Response(JSON.stringify(Se({code:Ie.InvalidRequest,message:"Session ID required",id:null})),{status:400,headers:this.headers});let{stream:o,streamId:i}=this.createStream(r),a=e.headers.get("Last-Event-ID");return a&&r&&await this.replayMessages(r,i,a),new Response(o.readable,{headers:{"Cache-Control":"no-cache",Connection:"keep-alive",...this.headers,...r&&{"Mcp-Session-Id":r.id}}})}async handleDeleteRequest(e,r){if(!r)return new Response(null,{status:400});if(this.options.enableSessions&&r){let n=this.sessions.get(r);if(n){for(let[o,i]of n.streams.entries())await this.closeStream(r,o);return this.sessions.delete(r),new Response(null,{status:204})}}return new Response(null,{status:404})}async sendToStream(e,r){try{let n=String(++e.eventCounter),o=JSON.stringify(r);e.messages.push(r),e.messages.length>100&&e.messages.shift();let i=`id: ${n}
|
|
87
|
+
`)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new F("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Sc(await qh(this.body||""))}return e}};async function Jn(t,e){let r=await crypto.subtle.importKey("raw",typeof t=="string"?kc.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,kc.encode(e))}s(Jn,"hmac");async function qh(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?kc.encode(t):t)}s(qh,"hash");function Sc(t){return Array.prototype.map.call(new Uint8Array(t),e=>`0${e.toString(16)}`.slice(-2)).join("")}s(Sc,"buf2hex");function Fh(t){return t.replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}s(Fh,"encodeRfc3986");function cP(t,e){let{hostname:r,pathname:n}=t,o=r.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",i="s3";else if(i==="iot")r.startsWith("iot.")?i="execute-api":r.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let c=(e.get("X-Amz-Target")||"").split(".")[0];c==="AnyScaleFrontendService"?i="application-autoscaling":c==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in Zh?[Zh[i],a]:[i,a]}s(cP,"guessServiceRegion");function uP(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}s(uP,"b64ToUint6");function Hh(t,e){let r=t.replace(/[^A-Za-z0-9+/]/g,""),n=r.length,o=e?Math.ceil((n*3+1>>2)/e)*e:n*3+1>>2,i=new Uint8Array(o),a,c,u=0,l=0;for(let d=0;d<n;d++)if(c=d&3,u|=uP(r.charCodeAt(d))<<6*(3-c),c===3||n-d===1){for(a=0;a<3&&l<o;)i[l]=u>>>(16>>>a&24)&255,a++,l++;u=0}return i}s(Hh,"base64Decode");function Ui(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Ui,"uint6ToB64");function Gh(t){let e=2,r="",n=t.length,o=0;for(let i=0;i<n;i++)e=i%3,o|=t[i]<<(16>>>e&24),(e===2||t.length-i===1)&&(r+=String.fromCodePoint(Ui(o>>>18&63),Ui(o>>>12&63),Ui(o>>>6&63),Ui(o&63)),o=0);return r.substring(0,r.length-2+e)+(e===2?"":e===1?"=":"==")}s(Gh,"base64Encode");function Gr(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(Gr,"numberToString");function lP(t){let e=t.getTimezoneOffset(),r=Math.abs(e),n=e>0?"-":"+",o=Gr(Math.floor(r/60)),i=Gr(r%60);return`${n}${o}${i}`}s(lP,"getCLFOffset");function Cc(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],r=Gr(t.getDate()),n=e[t.getMonth()],o=t.getFullYear(),i=Gr(t.getHours()),a=Gr(t.getMinutes()),c=Gr(t.getSeconds()),u=lP(t);return`${r}/${n}/${o}:${i}:${a}:${c} ${u}`}s(Cc,"toCLFDate");var Bh=Ne("zuplo:runtime"),Br="X-Amzn-Trace-Id",dP="x-amzn-errortype",Vh=[],pP=s(async(t,e,r)=>{let n=r;for await(let o of Vh)n=await o(t,e,r);return n},"onSendingAwsLambdaEvent"),tt=class extends F{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,r){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=r.get(Br)??void 0,this.errorType=r.get(dP)??void 0}},mP={addSendingAwsLambdaEventHook:s(t=>{Vh.push(t)},"addSendingAwsLambdaEventHook")};async function fP(t,e){R("handler.aws-lambda");let{accessKeyId:r,secretAccessKey:n,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:c=!1,binaryMediaTypes:u}=e.route.handler.options;if(!r)throw new w("awsAccessKeyId is not set in the handler options");if(!n)throw new w("secretAccessKey is not set in the handler options");if(!o)throw new w("region is not set in the handler options");if(!i)throw new w("functionName is not set in the handler options");let l=new Hr({accessKeyId:r,secretAccessKey:n}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(Bh(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await bP(t,{binaryMediaTypes:u}),{options:f}=e.route.handler,g;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?g=yP(t,e):g=await hP(t,e,{useAwsResourcePathStyle:c}),Bh("Calling onSendingAwsLambdaEvent hook");let b=await pP(t,e,g);b.body=p,b.isBase64Encoded=m;let h=await l.fetch(d,{body:JSON.stringify(b)}),x=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&typeof f.returnAmazonTraceIdHeader=="boolean"?f.returnAmazonTraceIdHeader:!1;try{return gP(h,{returnLambdaTraceIdHeader:x})}catch(v){if(v instanceof tt){let C=x&&v.traceId?{[Br]:v.traceId}:void 0;return D.internalServerError(t,e,void 0,C)}throw v}}s(fP,"awsLambdaHandler");async function gP(t,{returnLambdaTraceIdHeader:e}){let r;try{r=await t.json()}catch{throw new tt("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw r&&typeof r=="object"&&"message"in r&&typeof r.message=="string"?new tt(r.message,t.headers):new tt(`Status: ${t.statusText}`,t.headers);if(r&&typeof r=="object"&&"errorMessage"in r&&typeof r.errorMessage=="string")throw new tt(r.errorMessage,t.headers);if(!r||typeof r!="object"||!("statusCode"in r)||typeof r.statusCode!="number"){let a=t.headers.get(Br);return new Response(JSON.stringify(r),{status:t.status,headers:{"content-type":"application/json",...e&&a?{[Br]:a}:{}}})}let n=new Headers;if("headers"in r&&r.headers){if(typeof r.headers!="object")throw new tt(`Response headers must be an object. Received ${typeof r.headers}`,t.headers);for(let[a,c]of Object.entries(r.headers))n.set(a,c)}if("cookies"in r&&r.cookies){if(!Array.isArray(r.cookies))throw new tt(`Response cookies must be an array. Received ${typeof r.cookies}`,t.headers);n.set("cookie",r.cookies.join(";"))}let o;if("isBase64Encoded"in r&&typeof r.isBase64Encoded!="boolean")throw new tt(`Response property isBase64Encoded must be a boolean. Received ${typeof r.isBase64Encoded}`,t.headers);if("isBase64Encoded"in r&&r.isBase64Encoded===!0){if(!("body"in r))throw new tt("Response was set to base64 encoded but no body was set",t.headers);if(typeof r.body!="string")throw new tt("Response was set to base64 encoded but body was not a string",t.headers);o=Hh(r.body)}else"body"in r&&typeof r.body=="string"?o=r.statusCode===204&&r.body===""?null:r.body:"body"in r&&r.body!==null&&r.body!==void 0?o=JSON.stringify(r.body):o=null;if(o!==null&&"bodyEncoding"in r){if(typeof r.bodyEncoding!="string"||!(r.bodyEncoding==="gzip"||r.bodyEncoding==="deflate"))throw new tt(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${r.bodyEncoding}`,t.headers);let a=new Blob([o]).stream().pipeThrough(new DecompressionStream(r.bodyEncoding));o=await new Response(a).arrayBuffer()}let i=t.headers.get(Br);return e&&i&&n.set(Br,i),new Response(o,{headers:n,status:r.statusCode})}s(gP,"getResponse");async function hP(t,e,{useAwsResourcePathStyle:r}){let n={},o={};t.headers.forEach((l,d)=>{n[d]=l,o[d]=[l]});let i=t.query,a={};for(let[l,d]of Object.entries(i))a[l]||(a[l]=[]),a[l].push(d);let c=new URL(t.url);return{version:"1.0",resource:c.pathname,path:c.pathname,httpMethod:t.method,headers:n,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:c.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:c.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Cc(),requestTimeEpoch:Date.now(),resourceId:e.route.operationId??null,resourcePath:vP(e.route.path,r),stage:null},pathParameters:t.params,stageVariables:null}}s(hP,"buildEventVersion1");function yP(t,e){let r={};t.headers.forEach((i,a)=>{r[a]=i});let n=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:n.pathname,rawQueryString:n.search,cookies:[],headers:r,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:n.hostname,domainPrefix:null,http:{method:t.method,path:n.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Cc(),timeEpoch:Date.now()},pathParameters:t.params,stageVariables:null}}s(yP,"buildEventVersion2");async function bP(t,{binaryMediaTypes:e}){let r,n=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")r=null;else if(e&&o&&wP(e,o)){let i=await t.arrayBuffer();r=Gh(new Uint8Array(i)),n=!0}else r=await t.clone().text();return[r,n]}s(bP,"getBodyResult");function wP(t,e){let r=e.split(";")[0].trim().toLowerCase();return t.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}s(wP,"matchesContentType");function vP(t,e=!1){if(!e)return t;let r=Ic(t),n=jh(t),o={};return r.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),n(o)}s(vP,"getResourcePath");var xP=[502,503,504];async function Vr(t,e){if(xP.includes(t.status)){let r=Q.getLogger(e),o=await t.clone().text(),i={};for(let[a,c]of t.headers)i[a]=c;r.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:i})}}s(Vr,"logBadGatewayResponses");var Ec;function Kt(t){if(Ec===void 0){let r=P.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),Ec=r}return t.log[Ec]}s(Kt,"getHandlerUserLogFunction");async function RP(t,e){R("handler.open-api");let r=P.instance.build.BUILD_ID,{buildAssetsUrl:n}=P.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new w("Open API Spec Handler must have 'openApiFilePath' specified");let a=PP(i);if(!a.isValid)throw new w(a.error);let c=`${n}/${r}${i.substring(1)}`,u=await j.fetch(c,{method:t.method,body:t.body,headers:t.headers});if(u.status!==200)return D.notFound(t,e,{detail:"OpenAPI file could not be found."});let l={"content-type":"application/json",vary:"Accept-Encoding"};P.instance.isDeno||(l["content-encoding"]=u.headers.get("content-encoding")||"");let d=new Response(u.body,{headers:l,status:u.status,statusText:u.statusText});return Vr(d,e),d}s(RP,"openApiSpecHandler");var PP=s(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function IP(t,e){R("handler.redirect");let r=e.route.handler.options;if(!r.location)throw new w("Redirect Handler must have 'location' specified");let n=r.status??302;return new Response(null,{status:n,headers:{location:r.location}})}s(IP,"redirectHandler");async function SP(t){if(R("handler.zuplo-service-proxy"),Object.entries(t.params).length!==1)throw new w("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(t.params.path,P.instance.zuploEdgeApiUrl),r=new Headers(t.headers);return r.set("Authorization",`Bearer ${P.instance.authApiJWT}`),j.fetch(e,{method:t.method,headers:r,body:t.body})}s(SP,"zuploServiceProxy");function kP(t,e){let r=t.endsWith("/"),n=e.startsWith("/");return r&&n?`${t.substring(0,t.length-1)}${e}`:!r&&!n?`${t}/${e}`:`${t}${e}`}s(kP,"join");async function TP(t,e){R("handler.url-forward");let r=Kt(e),n=e.route.handler.options,o=n.forwardSearch!==!1,i;if(P.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?i=n.followRedirects===!0?"follow":"manual":typeof n.followRedirects<"u"&&R("handler.url-forward.follow-redirects"),!n.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!n||typeof n.__rewriteFunction!="function")throw new w("Invalid options for this route");let a=Wt(e),c=new URL(t.url),u=n.__rewriteFunction(t,a),l=kP(u,c.pathname),d=o?`${l}${c.search}`:l.toString(),p=Date.now();r(`URL Forwarding to '${d}'`);let m=t.body;if(i==="follow"&&t.body)try{m=await t.arrayBuffer()}catch(b){throw new Error(`Failed to buffer request body for redirect handling: ${b}`)}let f=await fetch(d,{method:t.method,body:m,headers:t.headers,redirect:i,zuplo:n.mtlsCertificate?{mtlsCertificate:n.mtlsCertificate}:void 0}),g=Date.now()-p;return r(`URL Forward received response ${f.status} - ${f.statusText} in ${g}ms`),Vr(f,e),f}s(TP,"urlForwardHandler");var CP=s((t,e)=>{let r=new URL(t),n=new URL(e);for(let[o,i]of n.searchParams.entries())r.searchParams.append(o,i);return r.toString()},"addQuery");async function EP(t,e){R("handler.url-rewrite");let r=Kt(e),n=e.route.handler.options,o=n.forwardSearch!==!1,i=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new w("Invalid options for this route");let a=Wt(e),c=n.__rewriteFunction(t,a),u=o?CP(c,t.url):c,l=Date.now();r(`URL Rewriting to '${u}'`);let d=await fetch(u.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:i?"follow":"manual",zuplo:n.mtlsCertificate?{mtlsCertificate:n.mtlsCertificate}:void 0}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Vr(d,e),d}s(EP,"urlRewriteHandler");function _P(t,e,r){t.addEventListener("close",()=>{e.close()}),e.addEventListener("close",()=>{t.close()}),t.addEventListener("error",n=>{r.log.error(`Incoming WebSocket error: ${JSON.stringify(n)}`),e.send(JSON.stringify(n))}),e.addEventListener("error",n=>{r.log.error(`Outgoing WebSocket error: ${JSON.stringify(n)}`),t.send(JSON.stringify(n))}),t.addEventListener("message",n=>{e.send(n.data)}),e.addEventListener("message",n=>{t.send(n.data)})}s(_P,"wireUpPassthrough");async function OP(t,e){R("handler.websocket");let r=e.route.handler.options,n=Kt(e);if(!r||!r.rewritePattern)throw new w("WebSocket Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return D.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new w("Invalid options for this route");let i=Wt(e),a=r.__rewriteFunction(t,i);if(n(`Attempting WebSocket connection to '${a}'`),P.instance.isDeno){if(!t.originalRequest)throw new Error("Original websocket request is not available");let c=new WebSocket(a);await new Promise((d,p)=>{let m=s(()=>{g(),n("WebSocket connection established with upstream"),d()},"onOpen"),f=s(b=>{g(),n(`WebSocket connection error: ${b}`),p(new Error("Upstream open failed"))},"onErr"),g=s(()=>{c.removeEventListener("open",m),c.removeEventListener("error",f)},"cleanup");c.addEventListener("open",m),c.addEventListener("error",f)}).catch(d=>{throw new Error(`Failed to open outgoing socket: ${d.message}`)});let{socket:u,response:l}=globalThis.Deno.upgradeWebSocket(t.originalRequest);return _P(u,c,e),l}else{a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:t.method,headers:t.headers,body:t.body});if(c.status!==101||!c.webSocket){let u=await c.text(),l=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${u}'`;throw new Error(l)}return n(`WebSocket connected, received response ${c.status} - ${c.statusText}`),new Response(null,{status:101,webSocket:c.webSocket})}}s(OP,"webSocketHandler");async function $P(t,e){let r=we.instance.runtimeSettings.developerPortal.urls?.urls?.[0];if(!r)throw new w("Developer portal URL is not configured.");let n=AP(t.url,r);return e.log.info(`Redirecting from legacy dev portal to ${n}`),new Response(null,{status:301,headers:{location:n}})}s($P,"redirectLegacyDevPortal");function AP(t,e){let r=new URL(t),n=r.pathname.split("/")[1];if(!n)throw new w("The request URL does not contain a valid developer portal base path. This handler cannot be used on a root path");return r.hostname=new URL(e).hostname,r.pathname=r.pathname.substring(n.length+1),r.toString()}s(AP,"getDevPortalRedirectUrl");var _c=s((t,e)=>t.map((n,o)=>{let i;if(typeof n.module=="object"&&(i=n.module[n.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${o+1}, export name: ${n.export}`;throw new w(`${a} - Websocket policy must be a valid function (${c})`)}return i}),"getWebSocketPolicyFunctions"),Jh=s(async(t,e,r,n,o,i)=>{let a=t.data;if(i&&i.length>0){let c=[...i];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,r,e,n,o),a===void 0)return}}return a},"webSocketPolicyProcessor");async function NP(t,e,r){r(`Attempting WebSocket connection to '${e}'`);let n=new WebSocket(e);await new Promise((a,c)=>{let u=s(()=>{d(),r("WebSocket connection established with upstream"),a()},"onOpen"),l=s(p=>{d(),r(`WebSocket connection error: ${p}`),c(new Error("Upstream open failed"))},"onErr"),d=s(()=>{n.removeEventListener("open",u),n.removeEventListener("error",l)},"cleanup");n.addEventListener("open",u),n.addEventListener("error",l)}).catch(a=>{throw new Error(`Failed to open outgoing socket: ${a.message}`)});let{socket:o,response:i}=globalThis.Deno.upgradeWebSocket(t);return{clientSocket:o,outgoingSocket:n,response:i}}s(NP,"getDenoClientAndServerSockets");async function LP(t,e,r){r(`Attempting WebSocket connection to '${e}'`);let n=await fetch(e,{method:t.method,headers:t.headers,body:t.body});if(n.status!==101||!n.webSocket){let u=await n.text(),l=`WebSocket connection error - ${n.status}: ${n.statusText}, content: '${u}'`;throw new Error(l)}let o=new WebSocketPair,[i,a]=Object.values(o);r(`WebSocket connected, received response ${n.status} - ${n.statusText}`),n.webSocket.accept(),a.accept();let c=new Response(null,{status:101,webSocket:i});return{clientSocket:i,outgoingSocket:n.webSocket,serverSocket:a,response:c}}s(LP,"getCfClientAndServerSockets");function Wh(t,e,r,n,o,i){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",a=>{n.log.error(`WebSocket error: ${JSON.stringify(a)}, direction: ${i}`),e.send(JSON.stringify(a))}),t.addEventListener("message",a=>{try{let u=s(async l=>{let d=await Jh(l,t,e,r,n,o);d!==void 0&&e.send(d)},"innerPipeline")(a).catch(n.log.error);n.waitUntil(u)}catch(c){n.log.error(c)}})}s(Wh,"wireUpListeners");async function MP(t,e){R("handler.websocket-pipeline");let r=e.route.handler.options,n=Kt(e);if(!r||!r.rewritePattern)throw new w("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return D.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new w("Invalid options for this route");let i=Wt(e),a=r.__rewriteFunction(t,i),c=r.policies?.inbound?_c(r.policies.inbound,"inbound"):[],u=r.policies?.outbound?_c(r.policies.outbound,"outbound"):[],l,d,p,m;if(P.instance.isDeno){if(!t.originalRequest)throw new Error("Original websocket request is not available");let f=await NP(t.originalRequest,a,n);p=f.clientSocket,l=p,d=f.outgoingSocket,m=f.response}else{a=a.replace(/^(ws)/,"http");let f=await LP(t,a,n);l=f.serverSocket,d=f.outgoingSocket,p=f.clientSocket,m=f.response}return Wh(l,d,t,e,c,"inbound"),Wh(d,l,t,e,u,"outbound"),m}s(MP,"webSocketPipelineHandler");Ze();Yt();Yt();function Ir({id:t,method:e,params:r}){return{jsonrpc:dt,id:t,method:e,params:r}}s(Ir,"newJSONRPCRequest");function Ct({id:t,result:e}){return{jsonrpc:dt,id:t,result:e}}s(Ct,"newJSONRPCReponse");function Se({id:t,code:e,message:r,data:n}){return{jsonrpc:dt,id:t,error:{code:e,message:r,data:n}}}s(Se,"newJSONRPCError");Ze();Yt();Fs();var Lw=y.object({jsonrpc:y.literal(dt),id:Nw,error:y.object({code:y.number().int(),message:y.string(),data:y.optional(y.unknown())})}).strict();Mo();Sr();kr();var Do=s(t=>Dw.safeParse(t).success,"isJSONRPCRequest"),zw=s(t=>Mw.safeParse(t).success,"isJSONRPCNotification"),nn=s(t=>Uw.safeParse(t).success,"isJSONRPCResponse"),tr=s(t=>Lw.safeParse(t).success,"isJSONRPCError");var Uo=class{static{s(this,"NoOpLogger")}debug(){}info(){}warn(){}error(){}};function rr(){return new Uo}s(rr,"createDefaultLogger");Ze();Sr();kr();Ze();var jw=y.object({experimental:y.optional(y.object({}).loose()),roots:y.optional(y.object({listChanged:y.optional(y.boolean())}).loose()),sampling:y.optional(y.object({}).loose()),elicitation:y.optional(y.object({}).loose())}).loose(),Zw=y.object({experimental:y.optional(y.object({}).loose()),logging:y.optional(y.object({}).loose()),completions:y.optional(y.object({}).loose()),prompts:y.optional(y.object({listChanged:y.optional(y.boolean())}).loose()),resources:y.optional(y.object({subscribe:y.optional(y.boolean()),listChanged:y.optional(y.boolean())}).loose()),tools:y.optional(y.object({listChanged:y.optional(y.boolean())}).loose())}).loose();Ze();on();var om=Et.extend({version:y.string()});var qw=it.extend({method:y.literal("initialize"),params:ot.extend({protocolVersion:y.string(),capabilities:jw,clientInfo:om})}),FF=pt.extend({protocolVersion:y.string(),capabilities:Zw,serverInfo:om,instructions:y.optional(y.string())});Ze();Mo();Sr();kr();on();Hs();var UC=Et.extend({description:y.optional(y.string()),required:y.optional(y.boolean())}),zC=Et.extend({description:y.optional(y.string()),arguments:y.optional(y.array(UC)),_meta:y.optional(y.object({}).loose())}),jC=y.lazy(()=>{let{TextContentSchema:t,ImageContentSchema:e,AudioContentSchema:r,EmbeddedResourceSchema:n}=(am(),ei(sm)),{ResourceLinkSchema:o}=(Gs(),ei(mm));return y.object({role:y.enum(["user","assistant"]),content:y.discriminatedUnion("type",[t,e,r,o,n])}).loose()}),Jw=or.extend({method:y.literal("prompts/list")}),fH=ir.extend({prompts:y.array(zC)}),Ww=it.extend({method:y.literal("prompts/get"),params:ot.extend({name:y.string(),arguments:y.optional(y.record(y.string(),y.string()))})}),gH=pt.extend({description:y.optional(y.string()),messages:y.array(jC)}),hH=er.extend({method:y.literal("notifications/prompts/list_changed")});Gs();Ze();Mo();Sr();kr();on();Hs();var ZC=y.object({title:y.optional(y.string()),readOnlyHint:y.optional(y.boolean()),destructiveHint:y.optional(y.boolean()),idempotentHint:y.optional(y.boolean()),openWorldHint:y.optional(y.boolean())}).loose(),qC=Et.extend({description:y.optional(y.string()),inputSchema:y.object({type:y.literal("object"),properties:y.optional(y.record(y.string(),y.object({}).loose())),required:y.optional(y.array(y.string()))}).loose(),outputSchema:y.optional(y.object({type:y.literal("object"),properties:y.optional(y.record(y.string(),y.object({}).loose())),required:y.optional(y.array(y.string()))}).loose()),annotations:y.optional(ZC),_meta:y.optional(y.object({}).loose())}),IH=or.extend({method:y.literal("tools/list")}),SH=ir.extend({tools:y.array(qC)}),Kw=it.extend({method:y.literal("tools/call"),params:ot.extend({name:y.string(),arguments:y.optional(y.record(y.string(),y.unknown()))})}),kH=y.lazy(()=>{let{TextContentSchema:t,ImageContentSchema:e,AudioContentSchema:r,EmbeddedResourceSchema:n}=(am(),ei(sm)),{ResourceLinkSchema:o}=(Gs(),ei(mm));return pt.extend({content:y.array(y.discriminatedUnion("type",[t,e,r,o,n])),structuredContent:y.optional(y.record(y.string(),y.unknown())),isError:y.optional(y.boolean())})}),TH=er.extend({method:y.literal("notifications/tools/list_changed")});var zo="2025-06-18",fm="2025-03-26",gm="2024-11-05",hm="2024-10-07",ym=[zo,fm,gm,hm];var FC="MCP Server",HC="0.0.0",Bs=class{static{s(this,"MCPServer")}capabilities;tools=new Map;prompts=new Map;resources=new Map;name;version;instructions;logger;constructor(e){this.name=e.name||FC,this.version=e.version||HC,this.instructions=e.instructions||void 0,this.logger=e.logger||rr(),this.capabilities={tools:{supported:!0,available:[]},prompts:{},resources:{},...e.capabilities}}withTransport(e){e.onMessage(async r=>{try{if(Do(r)){let n=await this.handleRequest(r);if(n)return await e.send(n),n}else{if(zw(r))return await this.handleNotification(r),null;if(nn(r))return this.logger.debug("Received response:",r),null}}catch(n){if(this.logger.error("Error processing message:",n),Do(r)){let o=Se({id:r.id,code:Ie.InternalError,message:n instanceof Error?n.message:"Internal error"});return await e.send(o),o}}return null})}getTool(e){return this.tools.get(e)?.tool}getTools(){let e=new Map;for(let[r,n]of this.tools.entries())e.set(r,n.tool);return e}getCapabilities(){return{...this.capabilities}}addTool(e){let{name:r,validator:n,handler:o,description:i=`Execute the ${r} tool`,outputSchema:a}=e,u={tool:{name:r,description:i,inputSchema:n.jsonSchema,...a&&{outputSchema:a}},validator:n,handler:o};this.tools.set(r,u),this.updateAvailableTools()}removeTool(e){let r=this.tools.delete(e);return r&&this.updateAvailableTools(),r}getToolDefinitions(){return Array.from(this.tools.values()).map(e=>e.tool)}addPrompt(e){let{name:r,validator:n,generator:o,description:i}=e,a=n.jsonSchema,c;if(a.properties&&typeof a.properties=="object"){let d=new Set(a.required||[]);c=Object.entries(a.properties).map(([p,m])=>({name:p,description:m.description??`Prompt for ${p}`,required:d.has(p)}))}let l={prompt:{name:r,description:i,...c&&{arguments:c}},validator:n,generator:o};this.prompts.set(r,l)}removePrompt(e){return this.prompts.delete(e)}getPrompt(e){return this.prompts.get(e)?.prompt}getPromptDefinitions(){return Array.from(this.prompts.values()).map(e=>e.prompt)}addResource(e,r,n,o){if(typeof r=="string"){let a={type:"resource",resource:{name:e,uri:r,...n},reader:o};this.resources.set(e,a)}else{let a={type:"template",template:{name:e,uriTemplate:r.template,...n},reader:o};this.resources.set(e,a)}}removeResource(e){return this.resources.delete(e)}getResource(e){let r=this.resources.get(e);if(r)return r.type==="resource"?r.resource:void 0}getResourceTemplate(e){let r=this.resources.get(e);if(r)return r.type==="template"?r.template:void 0}getResourceDefinitions(){return Array.from(this.resources.values()).filter(e=>e.type==="resource").map(e=>e.resource)}getResourceTemplateDefinitions(){return Array.from(this.resources.values()).filter(e=>e.type==="template").map(e=>e.template)}async handleRequest(e){try{switch(e.method){case"ping":return this.handlePing(e);case"initialize":return this.handleInitialize(e);case"tools/list":return this.handleToolListRequest(e);case"tools/call":return this.handleToolCallRequest(e);case"prompts/list":return this.handlePromptListRequest(e);case"prompts/get":return this.handlePromptGetRequest(e);case"resources/list":return this.handleResourceListRequest(e);case"resources/templates/list":return this.handleResourceTemplateListRequest(e);case"resources/read":return this.handleResourceReadRequest(e);default:return Se({id:e.id,code:Ie.MethodNotFound,message:`Method "${e.method}" not found`})}}catch(r){return this.logger.error("Error handling request:",r),Se({id:e.id,code:Ie.InternalError,message:r instanceof Error?r.message:"Internal error"})}}async handleNotification(e){this.logger.debug("Received notification:",e.method)}handlePing(e){return Ct({id:e.id,result:{}})}handleInitialize(e){let r=qw.safeParse(e);if(!r.success){let o=y.treeifyError(r.error),i=y.prettifyError(r.error);return Se({id:e.id,code:Ie.InvalidParams,message:`Invalid request parameters: ${i}`,data:o})}let n=r.data.params.protocolVersion;switch(n){case zo:case fm:case gm:case hm:{let o={protocolVersion:n,capabilities:this.getCapabilities(),serverInfo:{name:this.name,version:this.version},...this.instructions?{instructions:this.instructions}:{}};return Ct({id:e.id,result:o})}default:return Se({id:e.id,code:Ie.InvalidParams,message:`Unsupported protocol version: ${n} - supported versions: ${ym}`,data:{supportedVersions:ym}})}}async handleToolListRequest(e){let n={tools:Array.from(this.tools.entries()).map(([o,i])=>i.tool)};return Ct({id:e.id,result:n})}async handleToolCallRequest(e){let r=Kw.safeParse(e);if(!r.success)return this.logger.warn("Could not validate tool call:",r.error),Se({id:e.id,code:Ie.InvalidRequest,message:`Invalid request ${r.error}`});let n=r.data,o=n.params.name,i=this.tools.get(o);if(!i)return Se({id:e.id,code:Ie.InvalidParams,message:`Tool "${o}" not found`});let a=n.params.arguments??{},c=i.validator.parse(a);if(!c.success)return Se({id:e.id,code:Ie.InvalidParams,message:c.errorMessage?`Invalid arguments for tool '${o}': ${c.errorMessage}`:`Invalid arguments for tool '${o}'`,data:c.errorData});try{let u=c.data,l=await i.handler(u);return Ct({id:e.id,result:l})}catch(u){return this.logger.error(`Error executing tool "${o}":`,u),Se({id:e.id,code:Ie.InternalError,message:u instanceof Error?u.message:"Tool execution error"})}}async handlePromptListRequest(e){let r=Jw.safeParse(e);if(!r.success){let i=y.treeifyError(r.error),a=y.prettifyError(r.error);return Se({id:e.id,code:Ie.InvalidParams,message:`Invalid request parameters: ${a}`,data:i})}let o={prompts:Array.from(this.prompts.values()).map(i=>i.prompt)};return Ct({id:e.id,result:o})}async handlePromptGetRequest(e){let r=Ww.safeParse(e);if(!r.success){let c=y.treeifyError(r.error),u=y.prettifyError(r.error);return Se({id:e.id,code:Ie.InvalidParams,message:`Invalid request parameters: ${u}`,data:c})}let n=r.data.params.name,o=this.prompts.get(n);if(!o)return Se({id:e.id,code:Ie.InvalidParams,message:`Prompt "${n}" not found`});let i=r.data.params.arguments??{},a=o.validator.parse(i);if(!a.success)return Se({id:e.id,code:Ie.InvalidParams,message:a.errorMessage?`Invalid arguments for prompt '${n}': ${a.errorMessage}`:`Invalid arguments for prompt '${n}'`,data:a.errorData});try{let c=a.data,u=await o.generator(c),l={...o.prompt.description&&{description:o.prompt.description},messages:u};return Ct({id:e.id,result:l})}catch(c){return this.logger.error(`Error generating prompt "${n}":`,c),Se({id:e.id,code:Ie.InternalError,message:c instanceof Error?c.message:"Prompt generation error"})}}updateAvailableTools(){this.capabilities.tools&&(this.capabilities.tools.available=Array.from(this.tools.keys()))}async handleResourceListRequest(e){let r=lm.safeParse(e);if(!r.success){let i=y.treeifyError(r.error),a=y.prettifyError(r.error);return Se({id:e.id,code:Ie.InvalidParams,message:`Invalid request parameters: ${a}`,data:i})}let o={resources:Array.from(this.resources.values()).filter(i=>i.type==="resource").map(i=>i.resource)};return Ct({id:e.id,result:o})}async handleResourceTemplateListRequest(e){let r=dm.safeParse(e);if(!r.success){let i=y.treeifyError(r.error),a=y.prettifyError(r.error);return Se({id:e.id,code:Ie.InvalidParams,message:`Invalid request parameters: ${a}`,data:i})}let o={resourceTemplates:Array.from(this.resources.values()).filter(i=>i.type==="template").map(i=>i.template)};return Ct({id:e.id,result:o})}async handleResourceReadRequest(e){let r=pm.safeParse(e);if(!r.success){let a=y.treeifyError(r.error),c=y.prettifyError(r.error);return Se({id:e.id,code:Ie.InvalidParams,message:`Invalid request parameters: ${c}`,data:a})}let n=r.data.params.uri;function o(a,c){let u=c.replace(/\{[^}]+\}/g,"([^/]+)");return new RegExp(`^${u}$`).test(a)}s(o,"matchesTemplate");let i=Array.from(this.resources.values()).find(a=>a.type==="resource"&&a.resource.uri===n||a.type==="template"&&o(n,a.template.uriTemplate));if(!i)return Se({id:e.id,code:Ie.ResourceNotFound,message:`Resource not found: ${n}`,data:{uri:n}});try{let a=await i.reader(n);return Ct({id:e.id,result:a})}catch(a){return this.logger.error(`Error reading resource "${n}":`,a),Se({id:e.id,code:Ie.ResourceNotFound,message:a instanceof Error?a.message:"Resource not found",data:{uri:n}})}}};var sr=class{static{s(this,"CustomValidator")}jsonSchema;parseFn;constructor(e,r){this.jsonSchema=e,this.parseFn=r}parse(e){return this.parseFn(e)}};Yt();var Vs=class{static{s(this,"HTTPStreamableTransport")}messageHandler=null;closeCallback=null;headers;options;connected=!1;enableStreaming=!1;sessions=new Map;streams=new Map;logger;setHeaders(e){this.headers={...this.headers,...e}}constructor(e={},r=!1){this.options={timeout:30*60*1e3,enableSessions:!1,...e},this.headers={"Content-Type":"application/json",...e.headers},this.logger=e.logger||rr(),r&&this.startSessionCleanup()}onError(e){throw new Error("Method not implemented.")}getSessionId(){throw new Error("Method not implemented.")}setSessionId(e){throw new Error("Method not implemented.")}async connect(){this.connected=!0}async send(e){if(!this.connected)throw new Error("Transport not connected");if(nn(e)){for(let[r,n]of this.sessions.entries())for(let[o,i]of n.streams.entries())if(i.pendingRequests.has(e.id)){await this.sendToStream(i,e),i.pendingRequests.delete(e.id),i.pendingRequests.size===0&&await this.closeStream(r,o);return}}else for(let r of this.sessions.values()){let n=[...r.streams.values()][0];n&&(await this.sendToStream(n,e),Do(e)&&n.pendingRequests.add(e.id))}}onMessage(e){this.messageHandler=e}onClose(e){this.closeCallback=e}async close(){this.connected=!1;for(let e of this.sessions.values()){for(let[r,n]of e.streams.entries())try{await n.writer.close()}catch(o){this.logger.warn("Error closing stream:",o)}e.streams.clear()}this.sessions.clear(),this.closeCallback&&this.closeCallback()}async handleRequest(e){if(!this.connected)return new Response(JSON.stringify(Se({code:-32e3,message:"Transport not connected",id:null})),{status:503,headers:this.headers});if(!this.messageHandler)return new Response(JSON.stringify(Se({code:-32e3,message:"No message handler registered",id:null})),{status:500,headers:this.headers});let r=e.method.toUpperCase();try{this.validateOrigin(e);let n=e.headers.get("Mcp-Session-Id"),o;if(n&&(o=this.sessions.get(n),!o&&r!=="DELETE"))return new Response(null,{status:404});switch(r){case"POST":return await this.handlePostRequest(e,o);case"GET":return await this.handleGetRequest(e,o);case"DELETE":return await this.handleDeleteRequest(e,o?.id);default:return new Response(null,{status:405,headers:{Allow:"POST, GET, DELETE"}})}}catch(n){return this.logger.error("Error handling request:",n),new Response(JSON.stringify(Se({code:Ie.InternalError,message:"Internal server error",id:null})),{status:400,headers:this.headers})}}async handlePostRequest(e,r){let n=e.headers.get("Accept")||"";if(!n.includes("application/json")&&!n.includes("text/event-stream"))return new Response(JSON.stringify(Se({code:Ie.InvalidRequest,message:"Not Acceptable: Client must accept application/json and text/event-stream",id:null})),{status:406,headers:this.headers});let o=await this.extractJSONRPC(e);if(!o||Array.isArray(o)&&o.length===0)return new Response(JSON.stringify(Se({code:Ie.ParseError,message:"Parse error: received invalid JSON",id:null})),{status:400,headers:this.headers});let i=Array.isArray(o)?o:[o],a=i.some(u=>this.isRequest(u)),c=r;if(this.options.enableSessions&&!c&&i.some(u=>this.isRequest(u)&&u.method==="initialize")){let u=this.generateFallbackUUID();c=this.createSession(u)}try{if(!a){for(let p of i)await this.messageHandler?.(p);return new Response(null,{status:202,headers:{...this.headers,...c&&{"Mcp-Session-Id":c.id}}})}if(!this.enableStreaming){let p=[];for(let f of i)if(this.isRequest(f)){let g=await this.messageHandler?.(f);g&&p.push(g)}else await this.messageHandler?.(f);let m=p.length===1?p[0]:p;return new Response(JSON.stringify(m),{status:200,headers:{...this.headers,...c&&{"Mcp-Session-Id":c.id}}})}let{stream:u,streamId:l}=this.createStream(c),d=[];for(let p of i)if(this.isRequest(p)){this.streams.get(l)?.pendingRequests.add(p.id);let m=this.messageHandler?.(p);d.push(m)}else await this.messageHandler?.(p);return new Response(u.readable,{headers:{"Cache-Control":"no-cache",Connection:"keep-alive",...this.headers,...c&&{"Mcp-Session-Id":c.id}}})}catch{return new Response(JSON.stringify(Se({code:Ie.InternalError,message:"Internal server error",id:null})),{status:500,headers:this.headers})}}async handleGetRequest(e,r){if(!(e.headers.get("Accept")||"").includes("text/event-stream"))return new Response(null,{status:406,headers:this.headers});if(this.options.enableSessions&&!r)return new Response(JSON.stringify(Se({code:Ie.InvalidRequest,message:"Session ID required",id:null})),{status:400,headers:this.headers});let{stream:o,streamId:i}=this.createStream(r),a=e.headers.get("Last-Event-ID");return a&&r&&await this.replayMessages(r,i,a),new Response(o.readable,{headers:{"Cache-Control":"no-cache",Connection:"keep-alive",...this.headers,...r&&{"Mcp-Session-Id":r.id}}})}async handleDeleteRequest(e,r){if(!r)return new Response(null,{status:400});if(this.options.enableSessions&&r){let n=this.sessions.get(r);if(n){for(let[o,i]of n.streams.entries())await this.closeStream(r,o);return this.sessions.delete(r),new Response(null,{status:204})}}return new Response(null,{status:404})}async sendToStream(e,r){try{let n=String(++e.eventCounter),o=JSON.stringify(r);e.messages.push(r),e.messages.length>100&&e.messages.shift();let i=`id: ${n}
|
|
88
88
|
data: ${o}
|
|
89
89
|
|
|
90
90
|
`;await e.writer.write(new TextEncoder().encode(i))}catch(n){this.logger.warn("Error sending to stream:",n)}}async closeStream(e,r){let n=this.sessions.get(e);if(!n)return;let o=n.streams.get(r);if(o){try{await o.writer.close()}catch(i){this.logger.warn("Error closing stream:",i)}n.streams.delete(r),this.streams.delete(r)}}createSession(e){let r={id:e,createdAt:Date.now(),lastActivity:Date.now(),streams:new Map};return this.sessions.set(e,r),r}createStream(e){let r=new TransformStream,n=r.writable.getWriter(),o=crypto.randomUUID?.()||this.generateFallbackUUID(),i={id:o,writer:n,eventCounter:0,messages:[],pendingRequests:new Set};return this.streams.set(o,i),e&&(e.streams.set(o,i),e.lastActivity=Date.now()),{stream:r,streamId:o}}async replayMessages(e,r,n){for(let o of e.streams.values()){if(o.id===r)continue;let i=Number.parseInt(n,10);if(Number.isNaN(i))continue;let a=o.messages.slice(i),c=this.streams.get(r);if(c&&a.length>0)for(let u of a)await this.sendToStream(c,u)}}startSessionCleanup(){setInterval(()=>{let e=Date.now();for(let[r,n]of this.sessions.entries()){let o=this.options.timeout??6e4;if(e-n.lastActivity>o){for(let[i,a]of n.streams.entries()){try{a.writer.close().catch(c=>this.logger.warn("Error closing stream:",c))}catch(c){this.logger.warn("Error closing stream:",c)}this.streams.delete(i)}this.sessions.delete(r)}}},6e4)}async extractJSONRPC(e){try{let n=await e.clone().text();if(!n)throw new Error("Empty request body");return JSON.parse(n)}catch(r){throw new Error(`Failed to parse JSON-RPC message: ${r}`)}}validateOrigin(e){let r=e.headers.get("Origin");if(r&&!this.isValidOrigin(r))throw new Error("Invalid origin")}isValidOrigin(e){return!0}isRequest(e){return e!==null&&typeof e=="object"&&"jsonrpc"in e&&e.jsonrpc==="2.0"&&"method"in e&&"id"in e&&e.id!==null&&e.id!==void 0}generateFallbackUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}};function Js(t){let e={descriptions:!0,specifiedByUrl:!1,directiveIsRepeatable:!1,schemaDescription:!1,inputValueDeprecation:!1,oneOf:!1,...t},r=e.descriptions?"description":"",n=e.specifiedByUrl?"specifiedByURL":"",o=e.directiveIsRepeatable?"isRepeatable":"",i=e.schemaDescription?r:"";function a(u){return e.inputValueDeprecation?u:""}s(a,"inputDeprecation");let c=e.oneOf?"isOneOf":"";return`
|