@zuplo/runtime 6.62.5 → 6.62.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/out/esm/index.js CHANGED
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as Ht,d as ke,e as Jx,f as Ea,g as _a,h as Wx,i as Kx}from"./chunk-VRVJDH3L.js";import{a as Oe,b as Ng}from"./chunk-DZW2OPG5.js";import{A as Rg,B as Pg,C as Xo,D as Yo,E as ei,F as ti,G as ri,H as ni,I as Ig,J as Sg,K as oi,L as ii,M as kg,N as si,O as ai,P as Tg,Q as Cg,R as Eg,S as _g,T as Og,U as $g,V as Ag,W as kn,X as Tn,Y as ci,Z as j,a as s,b as te,c as Bx,d as Nt,e as Vx,f as Qo,g as Ne,h as le,i as F,j as w,k as P,l as ug,m as Sn,n as lg,o as Nr,p as dg,q as pg,r as mg,s as fg,t as gg,u as hg,v as yg,w as bg,x as wg,y as vg,z as xg}from"./chunk-S3E3TWYD.js";var mh=Bx(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.parse=_R;Ii.serialize=OR;var IR=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,SR=/^[\u0021-\u003A\u003C-\u007E]*$/,kR=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,TR=/^[\u0020-\u003A\u003D-\u007E]*$/,CR=Object.prototype.toString,ER=(()=>{let t=s(function(){},"C");return t.prototype=Object.create(null),t})();function _R(t,e){let r=new ER,n=t.length;if(n<2)return r;let o=e?.decode||$R,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=dh(t,i,a),d=ph(t,a,l),p=t.slice(l,d);if(r[p]===void 0){let m=dh(t,a+1,u),f=ph(t,u,m),g=o(t.slice(m,f));r[p]=g}i=u+1}while(i<n);return r}s(_R,"parse");function dh(t,e,r){do{let n=t.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<r);return r}s(dh,"startIndex");function ph(t,e,r){for(;e>r;){let n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}s(ph,"endIndex");function OR(t,e,r){let n=r?.encode||encodeURIComponent;if(!IR.test(t))throw new TypeError(`argument name is invalid: ${t}`);let o=n(e);if(!SR.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(!kR.test(r.domain))throw new TypeError(`option domain is invalid: ${r.domain}`);i+="; Domain="+r.domain}if(r.path){if(!TR.test(r.path))throw new TypeError(`option path is invalid: ${r.path}`);i+="; Path="+r.path}if(r.expires){if(!AR(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(OR,"serialize");function $R(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}s($R,"decode");function AR(t){return CR.call(t)==="[object Date]"}s(AR,"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(Vn,t),Vn}var Mi,St,Vn,Jr=te(()=>{s(T,"$constructor");Mi=Symbol("zod_brand"),St=class extends Error{static{s(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Vn={};s(ze,"config")});var ee={};Nt(ee,{BIGINT_FORMAT_RANGES:()=>Dc,Class:()=>Ec,NUMBER_FORMAT_RANGES:()=>Mc,aborted:()=>br,allowsEval:()=>Ac,assert:()=>MP,assertEqual:()=>$P,assertIs:()=>NP,assertNever:()=>LP,assertNotEqual:()=>AP,assignProp:()=>$c,cached:()=>Wn,cleanEnum:()=>WP,cleanRegex:()=>Kn,clone:()=>rt,createTransparentProxy:()=>qP,defineLazy:()=>Pe,esc:()=>yr,escapeRegex:()=>kt,extend:()=>GP,finalizeIssue:()=>nt,floatSafeRemainder:()=>Oc,getElementAtPath:()=>UP,getLengthableOrigin:()=>eo,getParsedType:()=>ZP,getSizableOrigin:()=>Yn,getValidEnumValues:()=>DP,isObject:()=>Ui,isPlainObject:()=>Qn,issue:()=>Uc,joinValues:()=>q,jsonStringifyReplacer:()=>_c,merge:()=>BP,normalizeParams:()=>K,nullish:()=>Qt,numKeys:()=>jP,omit:()=>HP,optionalKeys:()=>Lc,partial:()=>VP,pick:()=>FP,prefixIssues:()=>Je,primitiveTypes:()=>Nc,promiseAllObject:()=>zP,propertyKeyTypes:()=>Xn,randomString:()=>Di,required:()=>JP,stringifyPrimitive:()=>re,unwrapMessage:()=>Jn});function $P(t){return t}function AP(t){return t}function NP(t){}function LP(t){throw new Error}function MP(t){}function DP(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 _c(t,e){return typeof e=="bigint"?e.toString():e}function Wn(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 Kn(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Oc(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 $c(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function UP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function zP(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 Di(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 Ui(t){return typeof t=="object"&&t!==null}function Qn(t){return typeof t=="object"&&t!==null&&Object.getPrototypeOf(t)===Object.prototype}function jP(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 qP(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 Lc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional")}function FP(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 HP(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 GP(t,e){let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return $c(this,"shape",n),n},checks:[]};return rt(t,r)}function BP(t,e){return rt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return $c(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function VP(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 JP(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 Jn(t){return typeof t=="string"?t:t?.message}function nt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Jn(t.inst?._zod.def?.error?.(t))??Jn(e?.error?.(t))??Jn(r.customError?.(t))??Jn(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Yn(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function eo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Uc(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function WP(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ac,ZP,Xn,Nc,Mc,Dc,Ec,me=te(()=>{s($P,"assertEqual");s(AP,"assertNotEqual");s(NP,"assertIs");s(LP,"assertNever");s(MP,"assert");s(DP,"getValidEnumValues");s(q,"joinValues");s(_c,"jsonStringifyReplacer");s(Wn,"cached");s(Qt,"nullish");s(Kn,"cleanRegex");s(Oc,"floatSafeRemainder");s(Pe,"defineLazy");s($c,"assignProp");s(UP,"getElementAtPath");s(zP,"promiseAllObject");s(Di,"randomString");s(yr,"esc");s(Ui,"isObject");Ac=Wn(()=>{try{let t=Function;return new t(""),!0}catch{return!1}});s(Qn,"isPlainObject");s(jP,"numKeys");ZP=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"),Xn=new Set(["string","number","symbol"]),Nc=new Set(["string","number","bigint","boolean","symbol","undefined"]);s(kt,"escapeRegex");s(rt,"clone");s(K,"normalizeParams");s(qP,"createTransparentProxy");s(re,"stringifyPrimitive");s(Lc,"optionalKeys");Mc={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]},Dc={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};s(FP,"pick");s(HP,"omit");s(GP,"extend");s(BP,"merge");s(VP,"partial");s(JP,"required");s(br,"aborted");s(Je,"prefixIssues");s(Jn,"unwrapMessage");s(nt,"finalizeIssue");s(Yn,"getSizableOrigin");s(eo,"getLengthableOrigin");s(Uc,"issue");s(WP,"cleanEnum");Ec=class{static{s(this,"Class")}constructor(...e){}}});function ro(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 no(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 zc(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 Bh(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 jc(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 ${Bh(n.path)}`);return e.join(`
25
+ import{a as Ht,d as ke,e as Jx,f as Ea,g as _a,h as Wx,i as Kx}from"./chunk-2TEG5A7U.js";import{a as Oe,b as Ng}from"./chunk-CRSNWVTX.js";import{A as Rg,B as Pg,C as Xo,D as Yo,E as ei,F as ti,G as ri,H as ni,I as Ig,J as Sg,K as oi,L as ii,M as kg,N as si,O as ai,P as Tg,Q as Cg,R as Eg,S as _g,T as Og,U as $g,V as Ag,W as kn,X as Tn,Y as ci,Z as j,a as s,b as te,c as Bx,d as Nt,e as Vx,f as Qo,g as Ne,h as le,i as F,j as w,k as P,l as ug,m as Sn,n as lg,o as Nr,p as dg,q as pg,r as mg,s as fg,t as gg,u as hg,v as yg,w as bg,x as wg,y as vg,z as xg}from"./chunk-BHPOLR2W.js";var mh=Bx(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.parse=_R;Ii.serialize=OR;var IR=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,SR=/^[\u0021-\u003A\u003C-\u007E]*$/,kR=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,TR=/^[\u0020-\u003A\u003D-\u007E]*$/,CR=Object.prototype.toString,ER=(()=>{let t=s(function(){},"C");return t.prototype=Object.create(null),t})();function _R(t,e){let r=new ER,n=t.length;if(n<2)return r;let o=e?.decode||$R,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=dh(t,i,a),d=ph(t,a,l),p=t.slice(l,d);if(r[p]===void 0){let m=dh(t,a+1,u),f=ph(t,u,m),g=o(t.slice(m,f));r[p]=g}i=u+1}while(i<n);return r}s(_R,"parse");function dh(t,e,r){do{let n=t.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<r);return r}s(dh,"startIndex");function ph(t,e,r){for(;e>r;){let n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}s(ph,"endIndex");function OR(t,e,r){let n=r?.encode||encodeURIComponent;if(!IR.test(t))throw new TypeError(`argument name is invalid: ${t}`);let o=n(e);if(!SR.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(!kR.test(r.domain))throw new TypeError(`option domain is invalid: ${r.domain}`);i+="; Domain="+r.domain}if(r.path){if(!TR.test(r.path))throw new TypeError(`option path is invalid: ${r.path}`);i+="; Path="+r.path}if(r.expires){if(!AR(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(OR,"serialize");function $R(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}s($R,"decode");function AR(t){return CR.call(t)==="[object Date]"}s(AR,"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(Vn,t),Vn}var Mi,St,Vn,Jr=te(()=>{s(T,"$constructor");Mi=Symbol("zod_brand"),St=class extends Error{static{s(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Vn={};s(ze,"config")});var ee={};Nt(ee,{BIGINT_FORMAT_RANGES:()=>Dc,Class:()=>Ec,NUMBER_FORMAT_RANGES:()=>Mc,aborted:()=>br,allowsEval:()=>Ac,assert:()=>MP,assertEqual:()=>$P,assertIs:()=>NP,assertNever:()=>LP,assertNotEqual:()=>AP,assignProp:()=>$c,cached:()=>Wn,cleanEnum:()=>WP,cleanRegex:()=>Kn,clone:()=>rt,createTransparentProxy:()=>qP,defineLazy:()=>Pe,esc:()=>yr,escapeRegex:()=>kt,extend:()=>GP,finalizeIssue:()=>nt,floatSafeRemainder:()=>Oc,getElementAtPath:()=>UP,getLengthableOrigin:()=>eo,getParsedType:()=>ZP,getSizableOrigin:()=>Yn,getValidEnumValues:()=>DP,isObject:()=>Ui,isPlainObject:()=>Qn,issue:()=>Uc,joinValues:()=>q,jsonStringifyReplacer:()=>_c,merge:()=>BP,normalizeParams:()=>K,nullish:()=>Qt,numKeys:()=>jP,omit:()=>HP,optionalKeys:()=>Lc,partial:()=>VP,pick:()=>FP,prefixIssues:()=>Je,primitiveTypes:()=>Nc,promiseAllObject:()=>zP,propertyKeyTypes:()=>Xn,randomString:()=>Di,required:()=>JP,stringifyPrimitive:()=>re,unwrapMessage:()=>Jn});function $P(t){return t}function AP(t){return t}function NP(t){}function LP(t){throw new Error}function MP(t){}function DP(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 _c(t,e){return typeof e=="bigint"?e.toString():e}function Wn(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 Kn(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Oc(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 $c(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function UP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function zP(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 Di(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 Ui(t){return typeof t=="object"&&t!==null}function Qn(t){return typeof t=="object"&&t!==null&&Object.getPrototypeOf(t)===Object.prototype}function jP(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 qP(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 Lc(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional")}function FP(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 HP(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 GP(t,e){let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return $c(this,"shape",n),n},checks:[]};return rt(t,r)}function BP(t,e){return rt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return $c(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function VP(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 JP(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 Jn(t){return typeof t=="string"?t:t?.message}function nt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Jn(t.inst?._zod.def?.error?.(t))??Jn(e?.error?.(t))??Jn(r.customError?.(t))??Jn(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Yn(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function eo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Uc(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function WP(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ac,ZP,Xn,Nc,Mc,Dc,Ec,me=te(()=>{s($P,"assertEqual");s(AP,"assertNotEqual");s(NP,"assertIs");s(LP,"assertNever");s(MP,"assert");s(DP,"getValidEnumValues");s(q,"joinValues");s(_c,"jsonStringifyReplacer");s(Wn,"cached");s(Qt,"nullish");s(Kn,"cleanRegex");s(Oc,"floatSafeRemainder");s(Pe,"defineLazy");s($c,"assignProp");s(UP,"getElementAtPath");s(zP,"promiseAllObject");s(Di,"randomString");s(yr,"esc");s(Ui,"isObject");Ac=Wn(()=>{try{let t=Function;return new t(""),!0}catch{return!1}});s(Qn,"isPlainObject");s(jP,"numKeys");ZP=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"),Xn=new Set(["string","number","symbol"]),Nc=new Set(["string","number","bigint","boolean","symbol","undefined"]);s(kt,"escapeRegex");s(rt,"clone");s(K,"normalizeParams");s(qP,"createTransparentProxy");s(re,"stringifyPrimitive");s(Lc,"optionalKeys");Mc={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]},Dc={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};s(FP,"pick");s(HP,"omit");s(GP,"extend");s(BP,"merge");s(VP,"partial");s(JP,"required");s(br,"aborted");s(Je,"prefixIssues");s(Jn,"unwrapMessage");s(nt,"finalizeIssue");s(Yn,"getSizableOrigin");s(eo,"getLengthableOrigin");s(Uc,"issue");s(WP,"cleanEnum");Ec=class{static{s(this,"Class")}constructor(...e){}}});function ro(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 no(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 zc(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 Bh(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 jc(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 ${Bh(n.path)}`);return e.join(`
26
26
  `)}var Gh,to,Wr,Zc=te(()=>{Jr();me();Gh=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,_c,2)},enumerable:!0})},"initializer"),to=T("$ZodError",Gh),Wr=T("$ZodError",Gh,{Parent:Error});s(ro,"flattenError");s(no,"formatError");s(zc,"treeifyError");s(Bh,"toDotPath");s(jc,"prettifyError")});var zi,ji,Zi,qi,Fi,qc,Hi,Fc,Gi=te(()=>{Jr();Zc();me();zi=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"),ji=zi(Wr),Zi=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"),qi=Zi(Wr),Fi=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??to)(i.issues.map(a=>nt(a,o,ze())))}:{success:!0,data:i.value}},"_safeParse"),qc=Fi(Wr),Hi=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"),Fc=Hi(Wr)});var vr={};Nt(vr,{_emoji:()=>Vh,base64:()=>ru,base64url:()=>Ji,bigint:()=>cu,boolean:()=>du,browserEmail:()=>oI,cidrv4:()=>eu,cidrv6:()=>tu,cuid:()=>Hc,cuid2:()=>Gc,date:()=>ou,datetime:()=>su,duration:()=>Kc,e164:()=>nu,email:()=>Xc,emoji:()=>Yc,extendedDuration:()=>QP,guid:()=>Qc,hostname:()=>oo,html5Email:()=>tI,integer:()=>uu,ip:()=>iI,ipv4:()=>Bi,ipv6:()=>Vi,ksuid:()=>Jc,lowercase:()=>fu,nanoid:()=>Wc,null:()=>pu,number:()=>lu,rfc5322Email:()=>rI,string:()=>au,time:()=>iu,ulid:()=>Bc,undefined:()=>mu,unicodeEmail:()=>nI,uppercase:()=>gu,uuid:()=>wr,uuid4:()=>XP,uuid6:()=>YP,uuid7:()=>eI,xid:()=>Vc});function Yc(){return new RegExp(Vh,"u")}function Wh(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 iu(t){return new RegExp(`^${Wh(t)}$`)}function su(t){let e=`${Jh}T${Wh(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 Hc,Gc,Bc,Vc,Jc,Wc,Kc,QP,Qc,wr,XP,YP,eI,Xc,tI,rI,nI,oI,Vh,Bi,Vi,eu,tu,iI,ru,Ji,oo,nu,Jh,ou,au,cu,uu,lu,du,pu,mu,fu,gu,Wi=te(()=>{Hc=/^[cC][^\s-]{8,}$/,Gc=/^[0-9a-z]+$/,Bc=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Vc=/^[0-9a-vA-V]{20}$/,Jc=/^[A-Za-z0-9]{27}$/,Wc=/^[a-zA-Z0-9_-]{21}$/,Kc=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,QP=/^[-+]?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)?)??$/,Qc=/^([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"),XP=wr(4),YP=wr(6),eI=wr(7),Xc=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,tI=/^[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])?)*$/,rI=/^(([^<>()\[\]\\.,;:\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,}))$/,nI=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,oI=/^[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])?)*$/,Vh="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";s(Yc,"emoji");Bi=/^(?:(?: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])$/,Vi=/^(([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})$/,eu=/^((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])$/,tu=/^(([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])$/,iI=new RegExp(`(${Bi.source})|(${Vi.source})`),ru=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ji=/^[A-Za-z0-9_-]*$/,oo=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,nu=/^\+(?:[0-9]){6,14}[0-9]$/,Jh="((\\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])))",ou=new RegExp(`^${Jh}$`);s(Wh,"timeSource");s(iu,"time");s(su,"datetime");au=s(t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},"string"),cu=/^\d+n?$/,uu=/^\d+$/,lu=/^-?\d+(?:\.\d+)?/i,du=/true|false/i,pu=/null/i,mu=/undefined/i,fu=/^[^A-Z]*$/,gu=/^[^a-z]*$/});function Kh(t,e,r){t.issues.length&&e.issues.push(...Je(r,t.issues))}var Ae,Qh,Ki,Qi,hu,yu,bu,wu,vu,xu,Ru,Pu,Iu,Kr,Su,ku,Tu,Cu,Eu,_u,Ou,$u,Au,Xi=te(()=>{Jr();Wi();me();Ae=T("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Qh={number:"number",bigint:"bigint",object:"date"},Ki=T("$ZodCheckLessThan",(t,e)=>{Ae.init(t,e);let r=Qh[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})}}),Qi=T("$ZodCheckGreaterThan",(t,e)=>{Ae.init(t,e);let r=Qh[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})}}),hu=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):Oc(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})}}),yu=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]=Mc[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=uu)}),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})}}),bu=T("$ZodCheckBigIntFormat",(t,e)=>{Ae.init(t,e);let[r,n]=Dc[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})}}),wu=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:Yn(n),code:"too_big",maximum:e.maximum,input:n,inst:t,continue:!e.abort})}}),vu=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:Yn(n),code:"too_small",minimum:e.minimum,input:n,inst:t,continue:!e.abort})}}),xu=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:Yn(n),...i?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},input:r.value,inst:t,continue:!e.abort})}}),Ru=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=eo(n);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,input:n,inst:t,continue:!e.abort})}}),Pu=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=eo(n);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,input:n,inst:t,continue:!e.abort})}}),Iu=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=eo(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})})}),Su=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})}}),ku=T("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=fu),Kr.init(t,e)}),Tu=T("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=gu),Kr.init(t,e)}),Cu=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})}}),Eu=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})}}),_u=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(Kh,"handleCheckPropertyResult");Ou=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=>Kh(o,r,e.property));Kh(n,r,e.property)}}),$u=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})}}),Au=T("$ZodCheckOverwrite",(t,e)=>{Ae.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var io,Nu=te(()=>{io=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 Lu,Mu=te(()=>{Lu={major:4,minor:0,patch:0}});function nl(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function ly(t){if(!Ji.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return nl(r)}function dy(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 Yh(t,e,r){t.issues.length&&e.issues.push(...Je(r,t.issues)),e.value[r]=t.value}function Yi(t,e,r){t.issues.length&&e.issues.push(...Je(r,t.issues)),e.value[r]=t.value}function ey(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 ty(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 py(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)sI(o,i)||(n=!1);return n}function sI(t,e){let r=!0;for(let[n,o]of e)py(t,n,o)||(r=!1);return r}function Du(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(Qn(t)&&Qn(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=Du(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=Du(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 ry(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=Du(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 es(t,e,r){t.issues.length&&e.issues.push(...Je(r,t.issues)),e.value[r]=t.value}function ny(t,e,r,n,o,i,a){t.issues.length&&(Xn.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&&(Xn.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 oy(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function iy(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function sy(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 ay(t,e,r){return br(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function cy(t){return t.value=Object.freeze(t.value),t}function uy(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(Uc(o))}}var ue,so,Ce,Uu,zu,ju,Zu,qu,Fu,Hu,Gu,Bu,Vu,Ju,Wu,Ku,Qu,Xu,Yu,el,tl,rl,ol,il,sl,al,ts,cl,ao,rs,ul,ll,dl,pl,ml,co,fl,gl,hl,yl,bl,ns,wl,vl,xr,xl,Rl,Pl,Il,Sl,kl,Tl,Cl,El,_l,Ol,$l,Al,Nl,Ll,uo,Ml,Dl,Ul,zl,jl,lo=te(()=>{Xi();Jr();Nu();Gi();Wi();me();Mu();me();ue=T("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.id=e.type+"_"+Di(10),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Lu;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=qc(t,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Fc(t,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},"validate"),vendor:"zod",version:1}}),so=T("$ZodString",(t,e)=>{ue.init(t,e),t._zod.pattern=t?._zod.bag?.pattern??au(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),so.init(t,e)}),Uu=T("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Qc),Ce.init(t,e)}),zu=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)}),ju=T("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Xc),Ce.init(t,e)}),Zu=T("$ZodURL",(t,e)=>{Ce.init(t,e),t._zod.check=r=>{try{let n=new URL(r.value);oo.lastIndex=0,oo.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:oo.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})}}}),qu=T("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Yc()),Ce.init(t,e)}),Fu=T("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Wc),Ce.init(t,e)}),Hu=T("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Hc),Ce.init(t,e)}),Gu=T("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Gc),Ce.init(t,e)}),Bu=T("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Bc),Ce.init(t,e)}),Vu=T("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Vc),Ce.init(t,e)}),Ju=T("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Jc),Ce.init(t,e)}),Wu=T("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=su(e)),Ce.init(t,e)}),Ku=T("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=ou),Ce.init(t,e)}),Qu=T("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=iu(e)),Ce.init(t,e)}),Xu=T("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Kc),Ce.init(t,e)}),Yu=T("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Bi),Ce.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.format="ipv4"})}),el=T("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Vi),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})}}}),tl=T("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=eu),Ce.init(t,e)}),rl=T("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=tu),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(nl,"isValidBase64");ol=T("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=ru),Ce.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{nl(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t})}});s(ly,"isValidBase64URL");il=T("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Ji),Ce.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{ly(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t})}}),sl=T("$ZodE164",(t,e)=>{e.pattern??(e.pattern=nu),Ce.init(t,e)});s(dy,"isValidJWT");al=T("$ZodJWT",(t,e)=>{Ce.init(t,e),t._zod.check=r=>{dy(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t})}}),ts=T("$ZodNumber",(t,e)=>{ue.init(t,e),t._zod.pattern=t._zod.bag.pattern??lu,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}}),cl=T("$ZodNumber",(t,e)=>{yu.init(t,e),ts.init(t,e)}),ao=T("$ZodBoolean",(t,e)=>{ue.init(t,e),t._zod.pattern=du,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}}),rs=T("$ZodBigInt",(t,e)=>{ue.init(t,e),t._zod.pattern=cu,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}}),ul=T("$ZodBigInt",(t,e)=>{bu.init(t,e),rs.init(t,e)}),ll=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}}),dl=T("$ZodUndefined",(t,e)=>{ue.init(t,e),t._zod.pattern=mu,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}}),pl=T("$ZodNull",(t,e)=>{ue.init(t,e),t._zod.pattern=pu,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}}),ml=T("$ZodAny",(t,e)=>{ue.init(t,e),t._zod.parse=r=>r}),co=T("$ZodUnknown",(t,e)=>{ue.init(t,e),t._zod.parse=r=>r}),fl=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)}),gl=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}}),hl=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(Yh,"handleArrayResult");yl=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=>Yh(l,r,a))):Yh(u,r,a)}return i.length?Promise.all(i).then(()=>r):r}});s(Yi,"handleObjectResult");s(ey,"handleOptionalObjectResult");bl=T("$ZodObject",(t,e)=>{ue.init(t,e);let r=Wn(()=>{let p=Object.keys(e.shape),m=Lc(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 io(["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]=Di(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=Uh(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=>Uh(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 Bn(`AWS4${this.secretAccessKey}`,e),i=await Bn(o,this.region),a=await Bn(i,this.service);n=await Bn(a,"aws4_request"),this.cache.set(r,n)}return Rc(await Bn(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Rc(await Dh(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=Rc(await Dh(this.body||""))}return e}};async function Bn(t,e){let r=await crypto.subtle.importKey("raw",typeof t=="string"?Pc.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,Pc.encode(e))}s(Bn,"hmac");async function Dh(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Pc.encode(t):t)}s(Dh,"hash");function Rc(t){return Array.prototype.map.call(new Uint8Array(t),e=>`0${e.toString(16)}`.slice(-2)).join("")}s(Rc,"buf2hex");function Uh(t){return t.replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}s(Uh,"encodeRfc3986");function nP(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 Mh?[Mh[i],a]:[i,a]}s(nP,"guessServiceRegion");function oP(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(oP,"b64ToUint6");function zh(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|=oP(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(zh,"base64Decode");function Li(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Li,"uint6ToB64");function jh(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(Li(o>>>18&63),Li(o>>>12&63),Li(o>>>6&63),Li(o&63)),o=0);return r.substring(0,r.length-2+e)+(e===2?"":e===1?"=":"==")}s(jh,"base64Encode");function Gr(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(Gr,"numberToString");function iP(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(iP,"getCLFOffset");function Sc(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=iP(t);return`${r}/${n}/${o}:${i}:${a}:${c} ${u}`}s(Sc,"toCLFDate");var Zh=Ne("zuplo:runtime"),Br="X-Amzn-Trace-Id",sP="x-amzn-errortype",qh=[],aP=s(async(t,e,r)=>{let n=r;for await(let o of qh)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(sP)??void 0}},cP={addSendingAwsLambdaEventHook:s(t=>{qh.push(t)},"addSendingAwsLambdaEventHook")};async function uP(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(Zh(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await mP(t,{binaryMediaTypes:u}),{options:f}=e.route.handler,g;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?g=pP(t,e):g=await dP(t,e,{useAwsResourcePathStyle:c}),Zh("Calling onSendingAwsLambdaEvent hook");let b=await aP(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 lP(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(uP,"awsLambdaHandler");async function lP(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=zh(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(lP,"getResponse");async function dP(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:Sc(),requestTimeEpoch:Date.now(),resourceId:e.route.operationId??null,resourcePath:gP(e.route.path,r),stage:null},pathParameters:t.params,stageVariables:null}}s(dP,"buildEventVersion1");function pP(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:Sc(),timeEpoch:Date.now()},pathParameters:t.params,stageVariables:null}}s(pP,"buildEventVersion2");async function mP(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&&fP(e,o)){let i=await t.arrayBuffer();r=jh(new Uint8Array(i)),n=!0}else r=await t.clone().text();return[r,n]}s(mP,"getBodyResult");function fP(t,e){let r=e.split(";")[0].trim().toLowerCase();return t.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}s(fP,"matchesContentType");function gP(t,e=!1){if(!e)return t;let r=xc(t),n=Lh(t),o={};return r.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),n(o)}s(gP,"getResourcePath");var hP=[502,503,504];async function Vr(t,e){if(hP.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 kc;function Kt(t){if(kc===void 0){let r=P.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),kc=r}return t.log[kc]}s(Kt,"getHandlerUserLogFunction");async function yP(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=bP(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(yP,"openApiSpecHandler");var bP=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 wP(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(wP,"redirectHandler");async function vP(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(vP,"zuploServiceProxy");function xP(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(xP,"join");async function RP(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=xP(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}),g=Date.now()-p;return r(`URL Forward received response ${f.status} - ${f.statusText} in ${g}ms`),Vr(f,e),f}s(RP,"urlForwardHandler");var PP=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 IP(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?PP(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"}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Vr(d,e),d}s(IP,"urlRewriteHandler");function SP(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(SP,"wireUpPassthrough");async function kP(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 SP(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(kP,"webSocketHandler");async function TP(t,e){let r=we.instance.runtimeSettings.developerPortal.urls?.urls?.[0];if(!r)throw new w("Developer portal URL is not configured.");let n=CP(t.url,r);return e.log.info(`Redirecting from legacy dev portal to ${n}`),new Response(null,{status:301,headers:{location:n}})}s(TP,"redirectLegacyDevPortal");function CP(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(CP,"getDevPortalRedirectUrl");var Tc=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"),Fh=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 EP(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(EP,"getDenoClientAndServerSockets");async function _P(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(_P,"getCfClientAndServerSockets");function Hh(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 Fh(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(Hh,"wireUpListeners");async function OP(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?Tc(r.policies.inbound,"inbound"):[],u=r.policies?.outbound?Tc(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 EP(t.originalRequest,a,n);p=f.clientSocket,l=p,d=f.outgoingSocket,m=f.response}else{a=a.replace(/^(ws)/,"http");let f=await _P(t,a,n);l=f.serverSocket,d=f.outgoingSocket,p=f.clientSocket,m=f.response}return Hh(l,d,t,e,c,"inbound"),Hh(d,l,t,e,u,"outbound"),m}s(OP,"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();js();var _w=y.object({jsonrpc:y.literal(dt),id:Ew,error:y.object({code:y.number().int(),message:y.string(),data:y.optional(y.unknown())})}).strict();No();Sr();kr();var Lo=s(t=>$w.safeParse(t).success,"isJSONRPCRequest"),Nw=s(t=>Ow.safeParse(t).success,"isJSONRPCNotification"),nn=s(t=>Aw.safeParse(t).success,"isJSONRPCResponse"),tr=s(t=>_w.safeParse(t).success,"isJSONRPCError");var Mo=class{static{s(this,"NoOpLogger")}debug(){}info(){}warn(){}error(){}};function rr(){return new Mo}s(rr,"createDefaultLogger");Ze();Sr();kr();Ze();var Lw=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(),Mw=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 tm=Et.extend({version:y.string()});var Dw=it.extend({method:y.literal("initialize"),params:ot.extend({protocolVersion:y.string(),capabilities:Lw,clientInfo:tm})}),MF=pt.extend({protocolVersion:y.string(),capabilities:Mw,serverInfo:tm,instructions:y.optional(y.string())});Ze();No();Sr();kr();on();Zs();var AC=Et.extend({description:y.optional(y.string()),required:y.optional(y.boolean())}),NC=Et.extend({description:y.optional(y.string()),arguments:y.optional(y.array(AC)),_meta:y.optional(y.object({}).loose())}),LC=y.lazy(()=>{let{TextContentSchema:t,ImageContentSchema:e,AudioContentSchema:r,EmbeddedResourceSchema:n}=(om(),Qo(nm)),{ResourceLinkSchema:o}=(qs(),Qo(lm));return y.object({role:y.enum(["user","assistant"]),content:y.discriminatedUnion("type",[t,e,r,o,n])}).loose()}),Fw=or.extend({method:y.literal("prompts/list")}),aH=ir.extend({prompts:y.array(NC)}),Hw=it.extend({method:y.literal("prompts/get"),params:ot.extend({name:y.string(),arguments:y.optional(y.record(y.string(),y.string()))})}),cH=pt.extend({description:y.optional(y.string()),messages:y.array(LC)}),uH=er.extend({method:y.literal("notifications/prompts/list_changed")});qs();Ze();No();Sr();kr();on();Zs();var MC=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(),DC=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(MC),_meta:y.optional(y.object({}).loose())}),yH=or.extend({method:y.literal("tools/list")}),bH=ir.extend({tools:y.array(DC)}),Gw=it.extend({method:y.literal("tools/call"),params:ot.extend({name:y.string(),arguments:y.optional(y.record(y.string(),y.unknown()))})}),wH=y.lazy(()=>{let{TextContentSchema:t,ImageContentSchema:e,AudioContentSchema:r,EmbeddedResourceSchema:n}=(om(),Qo(nm)),{ResourceLinkSchema:o}=(qs(),Qo(lm));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())})}),vH=er.extend({method:y.literal("notifications/tools/list_changed")});var Do="2025-06-18",dm="2025-03-26",pm="2024-11-05",mm="2024-10-07",fm=[Do,dm,pm,mm];var UC="MCP Server",zC="0.0.0",Fs=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||UC,this.version=e.version||zC,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(Lo(r)){let n=await this.handleRequest(r);if(n)return await e.send(n),n}else{if(Nw(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),Lo(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=Dw.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 Do:case dm:case pm:case mm:{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: ${fm}`,data:{supportedVersions:fm}})}}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=Gw.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=Fw.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=Hw.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=am.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=cm.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=um.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 Hs=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),Lo(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=Rc(await Dh(this.body||""))}return e}};async function Bn(t,e){let r=await crypto.subtle.importKey("raw",typeof t=="string"?Pc.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,Pc.encode(e))}s(Bn,"hmac");async function Dh(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Pc.encode(t):t)}s(Dh,"hash");function Rc(t){return Array.prototype.map.call(new Uint8Array(t),e=>`0${e.toString(16)}`.slice(-2)).join("")}s(Rc,"buf2hex");function Uh(t){return t.replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}s(Uh,"encodeRfc3986");function nP(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 Mh?[Mh[i],a]:[i,a]}s(nP,"guessServiceRegion");function oP(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(oP,"b64ToUint6");function zh(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|=oP(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(zh,"base64Decode");function Li(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}s(Li,"uint6ToB64");function jh(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(Li(o>>>18&63),Li(o>>>12&63),Li(o>>>6&63),Li(o&63)),o=0);return r.substring(0,r.length-2+e)+(e===2?"":e===1?"=":"==")}s(jh,"base64Encode");function Gr(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}s(Gr,"numberToString");function iP(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(iP,"getCLFOffset");function Sc(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=iP(t);return`${r}/${n}/${o}:${i}:${a}:${c} ${u}`}s(Sc,"toCLFDate");var Zh=Ne("zuplo:runtime"),Br="X-Amzn-Trace-Id",sP="x-amzn-errortype",qh=[],aP=s(async(t,e,r)=>{let n=r;for await(let o of qh)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(sP)??void 0}},cP={addSendingAwsLambdaEventHook:s(t=>{qh.push(t)},"addSendingAwsLambdaEventHook")};async function uP(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(Zh(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await mP(t,{binaryMediaTypes:u}),{options:f}=e.route.handler,g;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?g=pP(t,e):g=await dP(t,e,{useAwsResourcePathStyle:c}),Zh("Calling onSendingAwsLambdaEvent hook");let b=await aP(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 lP(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(uP,"awsLambdaHandler");async function lP(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=zh(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(lP,"getResponse");async function dP(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:Sc(),requestTimeEpoch:Date.now(),resourceId:e.route.operationId??null,resourcePath:gP(e.route.path,r),stage:null},pathParameters:t.params,stageVariables:null}}s(dP,"buildEventVersion1");function pP(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:Sc(),timeEpoch:Date.now()},pathParameters:t.params,stageVariables:null}}s(pP,"buildEventVersion2");async function mP(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&&fP(e,o)){let i=await t.arrayBuffer();r=jh(new Uint8Array(i)),n=!0}else r=await t.clone().text();return[r,n]}s(mP,"getBodyResult");function fP(t,e){let r=e.split(";")[0].trim().toLowerCase();return t.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}s(fP,"matchesContentType");function gP(t,e=!1){if(!e)return t;let r=xc(t),n=Lh(t),o={};return r.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),n(o)}s(gP,"getResourcePath");var hP=[502,503,504];async function Vr(t,e){if(hP.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 kc;function Kt(t){if(kc===void 0){let r=P.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),kc=r}return t.log[kc]}s(Kt,"getHandlerUserLogFunction");async function yP(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=bP(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(yP,"openApiSpecHandler");var bP=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 wP(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(wP,"redirectHandler");async function vP(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(vP,"zuploServiceProxy");function xP(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(xP,"join");async function RP(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=xP(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(RP,"urlForwardHandler");var PP=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 IP(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?PP(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(IP,"urlRewriteHandler");function SP(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(SP,"wireUpPassthrough");async function kP(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 SP(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(kP,"webSocketHandler");async function TP(t,e){let r=we.instance.runtimeSettings.developerPortal.urls?.urls?.[0];if(!r)throw new w("Developer portal URL is not configured.");let n=CP(t.url,r);return e.log.info(`Redirecting from legacy dev portal to ${n}`),new Response(null,{status:301,headers:{location:n}})}s(TP,"redirectLegacyDevPortal");function CP(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(CP,"getDevPortalRedirectUrl");var Tc=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"),Fh=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 EP(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(EP,"getDenoClientAndServerSockets");async function _P(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(_P,"getCfClientAndServerSockets");function Hh(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 Fh(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(Hh,"wireUpListeners");async function OP(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?Tc(r.policies.inbound,"inbound"):[],u=r.policies?.outbound?Tc(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 EP(t.originalRequest,a,n);p=f.clientSocket,l=p,d=f.outgoingSocket,m=f.response}else{a=a.replace(/^(ws)/,"http");let f=await _P(t,a,n);l=f.serverSocket,d=f.outgoingSocket,p=f.clientSocket,m=f.response}return Hh(l,d,t,e,c,"inbound"),Hh(d,l,t,e,u,"outbound"),m}s(OP,"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();js();var _w=y.object({jsonrpc:y.literal(dt),id:Ew,error:y.object({code:y.number().int(),message:y.string(),data:y.optional(y.unknown())})}).strict();No();Sr();kr();var Lo=s(t=>$w.safeParse(t).success,"isJSONRPCRequest"),Nw=s(t=>Ow.safeParse(t).success,"isJSONRPCNotification"),nn=s(t=>Aw.safeParse(t).success,"isJSONRPCResponse"),tr=s(t=>_w.safeParse(t).success,"isJSONRPCError");var Mo=class{static{s(this,"NoOpLogger")}debug(){}info(){}warn(){}error(){}};function rr(){return new Mo}s(rr,"createDefaultLogger");Ze();Sr();kr();Ze();var Lw=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(),Mw=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 tm=Et.extend({version:y.string()});var Dw=it.extend({method:y.literal("initialize"),params:ot.extend({protocolVersion:y.string(),capabilities:Lw,clientInfo:tm})}),MF=pt.extend({protocolVersion:y.string(),capabilities:Mw,serverInfo:tm,instructions:y.optional(y.string())});Ze();No();Sr();kr();on();Zs();var AC=Et.extend({description:y.optional(y.string()),required:y.optional(y.boolean())}),NC=Et.extend({description:y.optional(y.string()),arguments:y.optional(y.array(AC)),_meta:y.optional(y.object({}).loose())}),LC=y.lazy(()=>{let{TextContentSchema:t,ImageContentSchema:e,AudioContentSchema:r,EmbeddedResourceSchema:n}=(om(),Qo(nm)),{ResourceLinkSchema:o}=(qs(),Qo(lm));return y.object({role:y.enum(["user","assistant"]),content:y.discriminatedUnion("type",[t,e,r,o,n])}).loose()}),Fw=or.extend({method:y.literal("prompts/list")}),aH=ir.extend({prompts:y.array(NC)}),Hw=it.extend({method:y.literal("prompts/get"),params:ot.extend({name:y.string(),arguments:y.optional(y.record(y.string(),y.string()))})}),cH=pt.extend({description:y.optional(y.string()),messages:y.array(LC)}),uH=er.extend({method:y.literal("notifications/prompts/list_changed")});qs();Ze();No();Sr();kr();on();Zs();var MC=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(),DC=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(MC),_meta:y.optional(y.object({}).loose())}),yH=or.extend({method:y.literal("tools/list")}),bH=ir.extend({tools:y.array(DC)}),Gw=it.extend({method:y.literal("tools/call"),params:ot.extend({name:y.string(),arguments:y.optional(y.record(y.string(),y.unknown()))})}),wH=y.lazy(()=>{let{TextContentSchema:t,ImageContentSchema:e,AudioContentSchema:r,EmbeddedResourceSchema:n}=(om(),Qo(nm)),{ResourceLinkSchema:o}=(qs(),Qo(lm));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())})}),vH=er.extend({method:y.literal("notifications/tools/list_changed")});var Do="2025-06-18",dm="2025-03-26",pm="2024-11-05",mm="2024-10-07",fm=[Do,dm,pm,mm];var UC="MCP Server",zC="0.0.0",Fs=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||UC,this.version=e.version||zC,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(Lo(r)){let n=await this.handleRequest(r);if(n)return await e.send(n),n}else{if(Nw(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),Lo(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=Dw.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 Do:case dm:case pm:case mm:{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: ${fm}`,data:{supportedVersions:fm}})}}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=Gw.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=Fw.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=Hw.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=am.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=cm.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=um.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 Hs=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),Lo(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 Gs(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`
@@ -197,7 +197,7 @@ data: ${o}
197
197
  `;break;case"id":c=h.includes("\0")?void 0:h;break;case"retry":/^\d+$/.test(h)?n(parseInt(h,10)):r(new ta(`Invalid \`retry\` value: "${h}"`,{type:"invalid-retry",value:h,line:x}));break;default:r(new ta(`Unknown field "${b.length>20?`${b.slice(0,20)}\u2026`:b}"`,{type:"unknown-field",field:b,value:h,line:x}));break}}s(m,"processField");function f(){u.length>0&&e({id:c,event:l||void 0,data:u.endsWith(`
198
198
  `)?u.slice(0,-1):u}),c=void 0,u="",l=""}s(f,"dispatchEvent");function g(b={}){i&&b.consume&&p(i),a=!0,c=void 0,u="",l="",i=""}return s(g,"reset"),{feed:d,reset:g}}s(iv,"createParser");function pE(t){let e=[],r="",n=0;for(;n<t.length;){let o=t.indexOf("\r",n),i=t.indexOf(`
199
199
  `,n),a=-1;if(o!==-1&&i!==-1?a=Math.min(o,i):o!==-1?o===t.length-1?a=-1:a=o:i!==-1&&(a=i),a===-1){r=t.slice(n);break}else{let c=t.slice(n,a);e.push(c),n=a+1,t[n-1]==="\r"&&t[n]===`
200
- `&&n++}}return[e,r]}s(pE,"splitLines");var ra=class extends TransformStream{static{s(this,"EventSourceParserStream")}constructor({onError:e,onRetry:r,onComment:n}={}){let o;super({start(i){o=iv({onEvent:s(a=>{i.enqueue(a)},"onEvent"),onError(a){e==="terminate"?i.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(i){o.feed(i)}})}};var na=class{static{s(this,"HTTPClientTransport")}url;timeout;headers;fetch;logger;sessionId;messageHandler;errorCallback;closeCallback;isConnected=!1;constructor(e){this.url=e.url,this.timeout=e.timeout||3e4,this.headers={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...e.headers},this.fetch=e.fetch||globalThis.fetch,this.logger=e.logger||rr(),e.enableSessions&&this.logger.debug("Session support not yet implemented for HTTP client transport")}setHeaders(e){this.headers={...this.headers,...e}}async connect(){try{new URL(this.url),this.isConnected=!0,this.logger.info("HTTP Client Transport connected to:",this.url)}catch{let r=new Error(`Invalid URL: ${this.url}`);throw this.errorCallback&&this.errorCallback(r),r}}async send(e){if(!this.isConnected)throw new Error("Transport not connected. Call connect() first.");let r;try{let n={...this.headers};this.sessionId&&(n["Mcp-Session-Id"]=this.sessionId);let o=new AbortController;r=setTimeout(()=>o.abort(),this.timeout);let i=await this.fetch(this.url,{method:"POST",headers:{...this.headers,...this.sessionId&&{"Mcp-Session-Id":this.sessionId}},body:JSON.stringify(e),signal:o.signal});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);(i.headers.get("Content-Type")||"").includes("text/event-stream")?await this.handleSSEResponse(i):await this.handleJSONResponse(i)}catch(n){if(n instanceof Error&&n.name==="AbortError")throw this.errorCallback&&this.errorCallback(n),new Error(`Request timeout after ${this.timeout}ms`);let o=new Error(`A client error occurred: ${n}`);throw this.errorCallback&&this.errorCallback(o),o}finally{r&&clearTimeout(r)}}onMessage(e){this.messageHandler=e}async close(){this.logger.debug("Closing HTTP Client Transport"),this.isConnected=!1,this.messageHandler=void 0,this.closeCallback&&this.closeCallback(),this.logger.info("HTTP Client Transport closed")}onClose(e){this.closeCallback=e}onError(e){this.errorCallback=e}getSessionId(){return this.sessionId}setSessionId(e){this.sessionId=e,this.logger.debug("Session ID set:",e?"***":"undefined")}async handleJSONResponse(e){let r=await e.text();if(!r.trim()){this.logger.debug("Received empty response");return}let n;try{n=JSON.parse(r)}catch{throw new Error(`Invalid JSON response: ${r}`)}this.logger.debug("Received JSON-RPC response:",n),this.messageHandler&&await this.messageHandler(n)}async handleSSEResponse(e){if(!e.body)throw new Error("SSE response has no body");this.logger.debug("Handling SSE response");let r=s(o=>{if(!o.event||o.event==="message")try{let i=JSON.parse(o.data);this.logger.debug("Received SSE message:",i),this.messageHandler&&this.messageHandler(i)}catch(i){this.logger.warn("Failed to parse SSE message data:",o.data,i)}},"onEvent"),n=e.body.pipeThrough(new TextDecoderStream).pipeThrough(new ra).getReader();try{for(;;){let{done:o,value:i}=await n.read();if(o)return;r(i)}}catch(o){throw this.logger.error("Error processing SSE stream:",o),new Error(`SSE stream error: ${o}`)}}};var mE="MCP Client",fE="0.0.0",oa=class{static{s(this,"MCPClient")}name;version;capabilities;transport;isInitialized=!1;protocolVersion;logger;requestId=1;transportOptions;constructor(e={}){this.name=e.name||mE,this.version=e.version||fE,this.logger=e.logger||rr(),this.transportOptions=e.transportOptions||{},this.capabilities={experimental:{},sampling:{},...e.capabilities}}async connect(e){this.transportOptions.headers&&e.setHeaders(this.transportOptions.headers),this.transport=e,await e.connect()}async initialize(e=Do){if(!this.transport)throw new Error("No transport connected. Call connect() first.");let r=Ir({id:this.requestId,method:"initialize",params:{protocolVersion:e,capabilities:this.capabilities,clientInfo:{name:this.name,version:this.version}}}),n=await this.sendRequest(r);if(tr(n))throw new Error(`Initialization failed: ${n.error.message}`);let o=n.result;return this.isInitialized=!0,this.protocolVersion=o.protocolVersion,this.logger.info("Successfully initialized MCP client",{serverInfo:o,protocolVersion:this.protocolVersion}),o}async ping(){if(!this.isInitialized)throw new Error("Client not initialized. Call initialize() first.");let e=Ir({id:this.requestId,method:"ping"}),r=await this.sendRequest(e);if(tr(r))throw new Error(`Ping failed: ${r.error.message}`)}async listTools(){if(!this.isInitialized)throw new Error("Client not initialized. Call initialize() first.");let e=Ir({id:this.requestId,method:"tools/list",params:{}}),r=await this.sendRequest(e);if(tr(r))throw new Error(`Failed to list tools: ${r.error.message}`);return r.result.tools}async callTool(e,r={}){if(!this.isInitialized)throw new Error("Client not initialized. Call initialize() first.");let n=Ir({id:this.requestId,method:"tools/call",params:{name:e,arguments:r}}),o=await this.sendRequest(n);if(tr(o))throw new Error(`Failed to call tool '${e}': ${o.error.message}`);return o.result}async listPrompts(){if(!this.isInitialized)throw new Error("Client not initialized. Call initialize() first.");let e=Ir({id:this.requestId,method:"prompts/list",params:{}}),r=await this.sendRequest(e);if(tr(r))throw new Error(`Failed to list prompts: ${r.error.message}`);return r.result.prompts}async getPrompt(e,r={}){if(!this.isInitialized)throw new Error("Client not initialized. Call initialize() first.");let n=Ir({id:this.requestId,method:"prompts/get",params:{name:e,arguments:r}}),o=await this.sendRequest(n);if(tr(o))throw new Error(`Failed to get prompt '${e}': ${o.error.message}`);return o.result}async disconnect(){this.transport&&(await this.transport.close(),this.transport=void 0),this.isInitialized=!1,this.protocolVersion=void 0}async sendRequest(e){return new Promise((r,n)=>{let o=e.id;this.transport?.onMessage(async i=>((nn(i)||tr(i))&&i.id===o&&r(i),null)),this.transport?.send(e).catch(n)})}};var ia=class{constructor(e,r,n=!1){this.baseUrl=e;this.originToolName=r;this.debugMode=n}static{s(this,"ProxyMcpToolExecutor")}async execute(e){let r=ur(),n=Date.now(),o=new oa({name:"Zuplo MCP Gateway Proxy Client",version:"0.0.1"});try{this.debugMode&&r.log.debug("Proxying MCP tool call",{originToolName:this.originToolName,baseUrl:this.baseUrl,args:e});let i=new na({url:this.baseUrl});i.setHeaders({"Content-Type":"application/json",...ea()});let a,c=Date.now();try{await o.connect(i),await o.initialize(),a=await o.callTool(this.originToolName,e)}catch(l){throw new Error(`could not call tool: ${this.originToolName}`,l)}let u=Date.now()-c;return this.debugMode&&r.log.debug("Proxy MCP response received",{originToolName:this.originToolName,upstreamElapsedMs:u,proxyResult:a}),a}catch(i){let a=Date.now()-n,c=i instanceof Error?`${i.name}: ${i.message}`:String(i);return r.log.error("Proxy MCP tool execution failed",{originToolName:this.originToolName,baseUrl:this.baseUrl,totalElapsedMs:a,err:i}),{content:[{type:"text",text:`Tool execution failed for '${this.originToolName}': ${c}`}],isError:!0}}finally{await o.disconnect()}}};var cn=class t{static{s(this,"ZuploMcpServer")}static instances=new Map;static async getInstance({opts:e,context:r,key:n,origins:o}){let i=e.debugMode??!1,a=t.instances.get(n);if(a)i&&r.log.debug("MCP Server warm reuse",{routeKey:n});else{let c=Date.now();if(a=new t(e,r,o??[]),a.registerToolsFromOptions(a.opts.openApiTools??[]),a.registerToolsFromFiles(a.opts.openApiFilePaths??[]),a.registerToolsFromFileSources(a.opts.files??[]),a.registerPromptsFromFileSources(a.opts.prompts??[]),a.registerResourcesFromFileSources(a.opts.resources??[]),await a.registerProxyTools(a.origins??[]),await a.transport.connect(),a.server.withTransport(a.transport),t.instances.set(n,a),i){let u=a.server.getTools(),l=u?u.size:0,d=a.server.getPromptDefinitions(),p=d?d.length:0,m=a.server.getResourceDefinitions(),f=m?m.length:0,g=Date.now()-c;r.log.debug("MCP Server cold start",{routeKey:n,toolCount:l,promptCount:p,resourceCount:f,totalElapsedMs:g,debugMode:i,includeOutputSchema:a.includeOutputSchema,includeStructuredContent:a.includeStructuredContent})}}return a}transport;server;opts;origins;context;includeOutputSchema;includeStructuredContent;debugMode;constructor(e,r,n){this.debugMode=e.debugMode??!1;let o;this.debugMode?o=r.log:o=new Mo,this.context=r,this.opts=e,this.origins=n??[],this.server=new Fs({name:e.name??"Zuplo MCP Server",version:e.version??"0.0.0",logger:o}),this.transport=new Hs({logger:o}),this.includeOutputSchema=e.includeOutputSchema??!1,this.includeStructuredContent=e.includeStructuredContent??!1}async handleRequest(e,r){let n=Date.now();try{let o=await e.clone().json().catch(()=>({}));if(this.debugMode&&r.log.debug("MCP Server request start",{method:o.method,requestId:o.id,routePath:r.route?.path}),this.debugMode&&o.method==="tools/list"){let c=this.server.getTools(),u=c?Array.from(c.keys()):[];r.log.debug("MCP Server list tools request",{toolCount:u.length,toolNames:u})}if(this.debugMode&&o.method==="prompts/list"){let c=this.server.getPromptDefinitions(),u=c?c.map(l=>l.name):[];r.log.debug("MCP Server list prompts request",{promptCount:u.length,promptNames:u})}if(this.debugMode&&o.method==="resources/list"){let c=this.server.getResourceDefinitions(),u=c?c.map(l=>l.name):[];r.log.debug("MCP Server list resources request",{resourceCount:u.length,resourceNames:u})}let i=await this.transport.handleRequest(e),a=Date.now()-n;if(this.debugMode){let c=await i.clone().json().catch(()=>({}));r.log.debug("MCP Server response complete",{status:i.status,requestMethod:o.method,requestId:o.id,totalElapsedMs:a,respData:c})}return i}catch(o){let i=Date.now()-n;return r.log.error("MCP server internal error",{elapsedMs:i,err:o}),new Response("Internal error",{status:500})}}generatePromptDescriptionFromSpec(e){let r=e.raw();return r?.description?r.description:r?.summary?r.summary:`Generate content for operation for ${e.path}`}generateToolNameFromSpec(e,r){let n=e.raw();if(n?.operationId)return`${n.operationId}`;let o=`${r}_${e.path}`.replace(/[^\w]/g,"_");return this.context.log.warn(`No operationId found for route ${r} ${e.path}. Using auto-generated name "${o}". To improve AI tool selection, add a descriptive operationId to your OpenAPI spec (e.g., "get_user_by_id" instead of "GET_/users/{id}")`),o}generateToolDescriptionFromSpec(e,r){let n=e.raw();return n?.description?n.description:n?.summary?n.summary:`Call ${r.toUpperCase()} ${e.path}`}registerToolsFromOptions(e){let r=new Set;for(let n of e){if(this.context.log.warn(`DEPRECATED: Registering MCP tool with name: "${n.name}", operationId: "${n.operationId}", method: "${n.method}" from "options.openApiTools" will soon be deprecated: migrate to using "options.files" configurations`),n.name){if(typeof n.name!="string"||n.name.trim()==="")throw new Error("MCP Tool configuration error: Tool name must be a non-empty string if provided.");if(r.has(n.name))throw new Error(`MCP Tool configuration error: Duplicate tool name "${n.name}". Tool names must be unique across all configured tools.`)}let o=this.getRouteDataForOptions(n);if(!o){let l=n.operationId?`operationId: "${n.operationId}"`:`path: "${n.path}"`;throw new Error(`MCP Tool configuration error: Could not find gateway route data for ${n.method.toUpperCase()} ${l}. Verify that the route exists in your OpenAPI specification and that the provided metadata matches OpenAPI specification data.`)}if(!o.handler){let l=n.operationId?`operationId: "${n.operationId}"`:`path: "${n.path}"`;throw new Error(`MCP Tool configuration error: Route ${n.method.toUpperCase()} ${l} has no handler configured. Ensure the route has a proper handler defined in your OpenAPI specification.`)}let i=n.name??this.generateToolNameFromSpec(o,n.method);if(r.has(i))throw new Error(`MCP Tool configuration error: Tool name conflict detected. The name "${i}" is already in use. Consider providing a unique 'name' in your tool configuration or ensure your operationIds are unique.`);r.add(i);let a=n.description??this.generateToolDescriptionFromSpec(o,n.method),c=n.includeOutputSchema??this.includeOutputSchema??!0,u=n.includeStructuredContent??this.includeStructuredContent??!0;this.registerToolsForMethod(o,n.method,i,a,c,u)}}static getOperationsMetadataForFile(e){let{routes:r}=we.instance.routeData,o=r.find(u=>u.metadata?.filepath)?.metadata?.filepath?.includes("\\")?"\\":"/",i=e.split("/").join(o),a=r.filter(u=>u.metadata?.filepath===i);if(a.length===0)throw new Error(`MCP Tool configuration error: No routes found for file path ${e}. Verify that the OpenAPI file exists and is properly loaded in your Gateway configuration with routes.`);let c=new Map;for(let u of a){let l=u?.raw().operationId;if(l){c.set(l,{routeConfig:u});let d=u?.raw()["x-zuplo-mcp-tool"],p=u?.raw()["x-zuplo-mcp-prompt"],m=u?.raw()["x-zuplo-mcp-graphql"],f=u?.raw()["x-zuplo-mcp-resource"];(d||p||m||f)&&c.set(l,{routeConfig:u,toolExtension:d||void 0,promptExtension:p||void 0,graphqlExtension:m||void 0,resourceExtension:f||void 0})}}return c}registerPromptsFromFileSources(e){for(let r of e){let n=t.getOperationsMetadataForFile(r.path),o=new Set;for(let i of r.operationIds){let a=n.get(i);if(!a)throw new Error(`MCP Prompt configuration error: Could not find operation with ID "${i}" in file ${r.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,promptExtension:u}=a,l=u?.name??i;if(o.has(l))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${l}". Prompt names must be unique across all configured prompts.`);o.add(l);let d=u?.description??this.generatePromptDescriptionFromSpec(c);if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by extension",{promptName:l,operationId:i});continue}this.registerPromptForOperation(l,d,c,i)}}}registerPromptForOperation(e,r,n,o){try{if(n.handler?.export==="mcpServerHandler")return;let a=Cr.createPromptValidatorBuilder(n).build();this.server.addPrompt({name:e,description:r,validator:a,generator:s(async c=>{let u=ur(),l=Date.now();try{this.debugMode&&u.log.debug("MCP prompt invoked",{promptName:e,operationId:n.raw()?.operationId,path:n.path,args:c});let d=this.buildToolUrl(n,{body:c}),p=this.buildToolRequest("POST","application/json",{body:c});this.debugMode&&u.log.debug("MCP prompt downstream call",{promptName:e,url:d,method:"POST",bodyPreview:c});let m=Date.now(),f=await u.invokeRoute(d,p),g=Date.now()-m,b=await f.json();if(!f.ok)throw new Error(`Route returned ${f.status}: ${b}`);let h;try{if(h=b.messages||b,!Array.isArray(h))throw new Error("Response must contain a 'messages' array or be an array of messages")}catch(v){throw new Error(`Invalid JSON response or missing messages array: ${v instanceof Error?v.message:String(v)}`)}let x=Date.now()-l;return this.debugMode&&u.log.debug("MCP prompt response complete",{promptName:e,operationId:n.raw()?.operationId,status:f.status,elapsedMs:x,downstreamElapsedMs:g,messageCount:h.length}),h}catch(d){let p=Date.now()-l,m=d instanceof Error?`${d.name}: ${d.message}`:String(d);throw u.log.error("MCP prompt invocation failed",{promptName:e,operationId:n.raw()?.operationId,path:n.path,elapsedMs:p,err:d}),new Error(`MCP tool call failed for tool '${e}': ${m}`)}},"generator")}),this.debugMode&&this.context.log.debug("MCP prompt registered from file source",{promptName:e,operationId:o,path:n.path})}catch(i){throw this.context.log.error("Failed to register MCP prompt",{promptName:e,operationId:o,error:i instanceof Error?i.message:String(i)}),new Error(`Failed to register prompt "${e}" for operation "${o}": ${i instanceof Error?i.message:String(i)}`)}}registerResourcesFromFileSources(e){let r=new Set;for(let n of e){let o=t.getOperationsMetadataForFile(n.path);for(let i of n.operationIds){let a=o.get(i);if(!a)throw new Error(`MCP Resource configuration error: Could not find operation with ID "${i}" in file ${n.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,resourceExtension:u}=a;if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by extension",{operationId:i});continue}if(!c.methods||c.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${i}" has no HTTP methods defined. Resources must use GET method.`);if(c.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${i}" has multiple HTTP methods (${c.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let d=c.methods[0].toUpperCase();if(d!=="GET")throw new Error(`MCP Resource configuration error: Operation "${i}" uses ${d} method. Resources are read-only and must use GET method only.`);let p=u?.name?.trim()||i.trim()||"";if(!p)throw new Error(`MCP Resource configuration error: Could not determine resource name for operation "${i}". Ensure the operation has an operationId or provide a name in x-zuplo-mcp-resource extension.`);if(r.has(p))throw new Error(`MCP Resource configuration error: Duplicate resource name "${p}". Resource names must be unique across all configured resources.`);r.add(p);let m=u?.description?.trim()||c.raw()?.description?.trim()||c.raw()?.summary?.trim()||`Resource for ${p}`,f=u?.uri?.trim()||`mcp://resources/${encodeURIComponent(p)}`,g=u?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(p,f,m,c,i,g)}}}registerResourceForOperation(e,r,n,o,i,a){try{if(o.handler?.export==="mcpServerHandler")return;this.server.addResource(e,r,{title:e,description:n,mimeType:a},async()=>{let c=ur(),u=Date.now();try{this.debugMode&&c.log.debug("MCP resource invoked",{resourceName:e,operationId:o.raw()?.operationId,path:o.path,uri:r});let l=this.buildToolUrl(o,{}),d=this.buildToolRequest("GET",null,{});this.debugMode&&c.log.debug("MCP resource downstream call",{resourceName:e,url:l,method:"GET"});let p=Date.now(),m=await c.invokeRoute(l,d),f=Date.now()-p,g=await m.text(),b=Date.now()-u;return this.debugMode&&c.log.debug("MCP resource response complete",{resourceName:e,operationId:o.raw()?.operationId,status:m.status,elapsedMs:b,downstreamElapsedMs:f,declaredMimeType:a,contentLength:g.length}),{contents:[{uri:r,declaredMimeType:a,text:g}]}}catch(l){let d=Date.now()-u,p=l instanceof Error?`${l.name}: ${l.message}`:String(l);throw c.log.error("MCP resource invocation failed",{resourceName:e,operationId:o.raw()?.operationId,path:o.path,elapsedMs:d,err:l}),new Error(`MCP resource call failed for resource '${e}': ${p}`)}}),this.debugMode&&this.context.log.debug("MCP resource registered from file source",{resourceName:e,operationId:i,path:o.path,uri:r,mimeType:a||"auto-detected"})}catch(c){throw this.context.log.error("Failed to register MCP resource",{resourceName:e,operationId:i,error:c instanceof Error?c.message:String(c)}),new Error(`Failed to register resource "${e}" for operation "${i}": ${c instanceof Error?c.message:String(c)}`)}}registerToolsFromFileSources(e){let r=new Set;for(let n of e){let o=t.getOperationsMetadataForFile(n.path);this.debugMode&&this.context.log.debug("Processing file source",{path:n.path,operationIds:n.operationIds,availableOperationIds:Array.from(o.keys())});for(let i of n.operationIds){let a=o.get(i);if(!a)throw new Error(`MCP Tool configuration error: Operation ID "${i}" not found in OpenAPI spec at ${n.path}. Available operation IDs: ${Array.from(o.keys()).join(", ")}`);if(a.toolExtension?.enabled===!1){this.debugMode&&this.context.log.debug("Skipping disabled tool",{operationId:i,path:n.path});continue}let c=a.toolExtension?.name?.trim()??i,u=(a.toolExtension?.description?.trim()||null)??(a.routeConfig.raw().description?.trim()||null)??(a.routeConfig.raw().summary?.trim()||null)??`Executes tool: ${c}`;if(!u)throw new Error(`MCP Tool configuration error: no tool description found for operationId: "${i}" in file "${n.path}"`);if(r.has(c))throw new Error(`MCP Tool configuration error: Tool name conflict detected. The name "${c}" is already in use. Consider providing a unique 'name' in the x-zuplo-mcp-tool extension for operation "${i}".`);r.add(c);let l=a.toolExtension?.includeOutputSchema??this.includeOutputSchema??!1,d=a.toolExtension?.includeStructuredContent??this.includeStructuredContent??!1;if(a.routeConfig.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${a.routeConfig.methods.join(", ")}" on operation "${i}" not permitted. Only tools with one singular method is permitted.`);a.graphqlExtension?(a.graphqlExtension.enabled??!0)&&this.registerGraphQLTools(i,a.routeConfig,a.graphqlExtension,r):this.registerToolsForMethod(a.routeConfig,a.routeConfig.methods[0],c,u,l,d)}}}registerGraphQLTools(e,r,n,o){let i=n.introspectionToolName??`${e}_introspect`,a=n.executeToolName??`${e}_execute_query`;if(o.has(i))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The introspection tool name "${i}" is already in use. Provide a unique 'introspectionToolName' in the x-zuplo-graphql extension.`);if(o.has(a))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The execute tool name "${a}" is already in use. Provide a unique 'executeToolName' in the x-zuplo-graphql extension.`);o.add(i),o.add(a);let c=n.introspectionToolDescription??`Get the GraphQL schema for ${e}`,u=n.executeToolDescription??`Execute a GraphQL query on ${e}`,l=r.path,p=Cr.createObjectValidatorBuilder({}).build();this.server.addTool({name:i,description:c,validator:p,handler:s(async()=>{let f=ur(),g=Date.now();try{this.debugMode&&f.log.debug("MCP GraphQL introspection tool invoked",{toolName:i,operationId:e,path:l});let b=Gs(),h=this.buildToolUrl(r,{}),x=this.buildToolRequest("POST","application/json",{body:{query:b}}),v=Date.now(),C=await f.invokeRoute(h,x),A=Date.now()-v,O=await C.text(),S=Date.now()-g;this.debugMode&&(C.ok?f.log.debug("MCP GraphQL introspection tool ok response",{toolName:i,operationId:e,status:C.status,elapsedMs:S,downstreamElapsedMs:A}):f.log.debug("MCP GraphQL introspection tool 'isError' response",{toolName:i,operationId:e,status:C.status,elapsedMs:S,downstreamElapsedMs:A,response:O}));let M;try{M=JSON.parse(O)}catch(z){this.debugMode&&f.log.debug("MCP GraphQL introspection structuredContent JSON parse failed",{toolName:i,body:O,parseErr:z})}return{content:[{type:"text",text:O}],...M&&{structuredContent:M},isError:!C.ok}}catch(b){let h=Date.now()-g,x=b instanceof Error?`${b.name}: ${b.message}`:String(b);throw f.log.error("MCP GraphQL introspection tool invocation failed",{toolName:i,operationId:e,path:l,elapsedMs:h,err:b}),new Error(`MCP GraphQL introspection tool call failed for '${i}': ${x}`)}},"handler")});let m={type:"object",properties:{query:{type:"string",description:"The GraphQL query to execute"},variables:{type:"object",description:"Optional variables for the GraphQL query"}},required:["query"],additionalProperties:!1};this.server.addTool({name:a,description:u,validator:new sr(m,f=>typeof f=="object"&&f!==null&&"query"in f&&typeof f?.query=="string"?{success:!0,data:f,errorData:null}:{success:!1,data:null,errorMessage:"Invalid input: query field is required and must be a string",errorData:null}),handler:s(async f=>{let g=ur(),b=Date.now();try{this.debugMode&&g.log.debug("MCP GraphQL execute tool invoked",{toolName:a,operationId:e,path:l,queryPreview:f.query.substring(0,100)});let h=this.buildToolUrl(r,{}),x={query:f.query};f.variables&&(x.variables=f.variables);let v=this.buildToolRequest("POST","application/json",{body:x}),C=Date.now(),A=await g.invokeRoute(h,v),O=Date.now()-C,S=await A.text(),M=Date.now()-b;this.debugMode&&(A.ok?g.log.debug("MCP GraphQL execute tool ok response",{toolName:a,operationId:e,status:A.status,elapsedMs:M,downstreamElapsedMs:O}):g.log.debug("MCP GraphQL execute tool 'isError' response",{toolName:a,operationId:e,status:A.status,elapsedMs:M,downstreamElapsedMs:O,response:S}));let z;try{z=JSON.parse(S)}catch(Z){this.debugMode&&g.log.debug("MCP GraphQL execute structuredContent JSON parse failed",{toolName:a,body:S,parseErr:Z})}return{content:[{type:"text",text:S}],...z&&{structuredContent:z},isError:!A.ok}}catch(h){let x=Date.now()-b,v=h instanceof Error?`${h.name}: ${h.message}`:String(h);throw g.log.error("MCP GraphQL execute tool invocation failed",{toolName:a,operationId:e,path:l,elapsedMs:x,err:h}),new Error(`MCP GraphQL execute tool call failed for '${a}': ${v}`)}},"handler")}),this.debugMode&&this.context.log.debug("MCP GraphQL tools registered",{operationId:e,introspectionToolName:i,executeToolName:a,path:l})}registerToolsFromFiles(e){let r=new Set(e.map(i=>i.filePath)),n=new Set;for(let i of we.instance.routeData.routes){let a=i.metadata?.filepath;a&&r.has(a)&&(this.context.log.warn(`DEPRECATED: Registering MCP tool with operationId: "${i.raw()?.operationId}"from file: "${a}" with "options.openApiFilePaths" will soon be removed: migrate to using "options.files" configurations`),n.add(a),this.registerToolsForRawRoutedata(i,this.includeOutputSchema,this.includeStructuredContent))}let o=e.map(i=>i.filePath).filter(i=>!n.has(i));if(o.length>0)throw new Error(`MCP Tool configuration error: Could not find routes for the following file paths: ${o.join(", ")}. Verify that these OpenAPI files exist and are properly loaded in your Gateway configuration.`)}registerToolsForRawRoutedata(e,r,n){if(e.mcp?.enabled!==!1){if(!e)throw new Error("MCP Tool configuration error: Route data cannot be null or undefined.");if(!e.methods||e.methods.length===0)throw new Error(`MCP Tool configuration error: Route "${e.path}" has no HTTP methods defined. Ensure the route has at least one HTTP method (GET, POST, etc.) in your OpenAPI specification.`);if(!e.handler)throw new Error(`MCP Tool configuration error: Route "${e.path}" has no handler configured. Ensure the route has a proper handler defined in your OpenAPI specification.`);for(let o of e.methods){let i=this.generateToolNameFromSpec(e,o),a=this.generateToolDescriptionFromSpec(e,o);this.registerToolsForMethod(e,o,i,a,r,n)}}}registerToolsForMethod(e,r,n,o,i,a){if(e.handler?.export!=="mcpServerHandler")if(e.raw().requestBody?.content)for(let c of Object.keys(e.raw().requestBody?.content)){let l=Object.keys(e.raw().requestBody?.content).length>1?`${n}_${c.replace(/[^\w]/g,"_")}`:n;this.registerGenericToolSpec(l,o,e,r,c,i,a)}else this.registerGenericToolSpec(n,o,e,r,null,i,a)}registerGenericToolSpec(e,r,n,o,i,a,c){let u=this.buildUniversalValidator(n,i);if(!u)throw new Error(`MCP Tool registration error: Could not build parameter validator for ${o.toUpperCase()} ${n.path}. This may indicate an issue with the OpenAPI parameter definitions for this route.`);let l=a?this.extractOutputSchema(n):void 0;try{this.server.addTool({name:e,description:r,validator:u,...l&&{outputSchema:l},handler:s(async d=>{let p=ur(),m=Date.now();try{this.debugMode&&p.log.debug("MCP tool invoked",{toolName:e,operationId:n.raw()?.operationId,method:o,path:n.path,args:d});let f=this.buildToolUrl(n,d),g=this.buildToolRequest(o,i,d);this.debugMode&&p.log.debug("MCP tool downstream call",{toolName:e,url:f,method:o,headers:g.headers?Object.keys(g.headers).join(", "):"",bodyPreview:d.body}),p.analyticsContext.addAnalyticsEvent(1,Oe.MCP_TOOL_USAGE,{toolName:e,toolPath:n.path,toolMethod:o,toolOperationId:n.raw()?.operationId??"unknown"});let b=Date.now(),h=await p.invokeRoute(f,g),x=Date.now()-b,v=await h.text(),C;if(c)try{C=JSON.parse(v)}catch(O){this.debugMode&&p.log.debug("MCP tool structuredContent JSON parse failed",{toolName:e,body:v,parseErr:O})}let A=Date.now()-m;return this.debugMode&&(h.ok?p.log.debug("MCP tool ok response",{toolName:e,operationId:n.raw()?.operationId,status:h.status,elapsedMs:A,downstreamElapsedMs:x}):p.log.debug("MCP tool 'isError' response",{toolName:e,operationId:n.raw()?.operationId,status:h.status,elapsedMs:A,downstreamElapsedMs:x,response:v})),{content:[{type:"text",text:v}],...C&&{structuredContent:C},isError:!h.ok}}catch(f){let g=Date.now()-m,b=f instanceof Error?`${f.name}: ${f.message}`:String(f);return p.log.error("MCP server tool invocation failed",{toolName:e,operationId:n.raw()?.operationId,method:o,path:n.path,elapsedMs:g,err:f}),{content:[{type:"text",text:`MCP tool call failed for tool '${e}': ${b}`}],isError:!0}}},"handler")}),this.debugMode&&this.context.log.debug("MCP tool registered",{toolName:e,method:o.toUpperCase(),path:n.path,operationId:n.raw()?.operationId,contentType:i||"none",includeOutputSchema:a,includeStructuredContent:c,hasValidator:!!u,hasOutputSchema:!!l})}catch(d){throw new Error(`Failed to add tool ${o} ${n.path}`,d)}}async registerProxyTools(e){let r=new Set;for(let n of e){if(n.enabled===!1){this.debugMode&&this.context.log.debug("Skipping disabled origin",{origin:n.name});continue}let o=n.toolNamePrefix??"";this.debugMode&&this.context.log.debug("Registering origin tools",{origin:n.name,baseUrl:n.baseUrl,toolCount:n.tools.length,toolNamePrefix:o||"none",tools:n.tools});for(let i of n.tools){let a=`${o}${i.name}`;if(r.has(a))throw new Error(`MCP origin configuration error: Tool name conflict detected. The name "${a}" is already in use. Consider using different tool names or toolNamePrefix for origin "${n.name}".`);r.add(a);let u=Cr.createObjectValidatorBuilder(i.inputSchema).build();try{let l=new ia(n.baseUrl,i.name,this.debugMode);this.server.addTool({name:a,description:i.description,validator:u,handler:s(async d=>await l.execute(d),"handler")}),this.debugMode&&this.context.log.debug("origin tool registered",{localToolName:a,originToolName:i.name,origin:n.name,baseUrl:n.baseUrl})}catch(l){throw new Error(`Failed to register origin tool ${a} from ${n.name}`,{cause:l})}}}this.debugMode&&e.length>0&&this.context.log.debug("origin tool registration complete",{totaloOigins:e.length,totalOriginTools:r.size,originToolNames:Array.from(r)})}buildToolUrl(e,r){return new Js(e).build(r.pathParams,r.queryParams)}buildToolRequest(e,r,n){let o=this.buildToolHeaders(e,r,n),i={method:e,headers:o};return this.shouldIncludeBody(e,r,n)&&(i.body=this.serializeBody(n.body,r)),i}buildToolHeaders(e,r,n){let o={...ea()};return n.headers&&Object.entries(n.headers).forEach(([i,a])=>{o[i.toLowerCase()]=a}),r&&n.body!==void 0&&(o["content-type"]=r),this.isBodyMethod(e||"")&&n.body!==void 0&&!o["content-type"]&&(o["content-type"]="application/json"),o}shouldIncludeBody(e,r,n){return n.body===void 0?!1:this.isBodyMethod(e)?!0:r!==null}isBodyMethod(e){return["POST","PUT","PATCH"].includes(e.toUpperCase())}serializeBody(e,r){return JSON.stringify(e)}buildUniversalValidator(e,r){try{let o=Cr.createValidatorBuilder(e,r).build();return this.debugMode&&this.context.log.debug("MCP validator built successfully",{method:e.methods?.[0],path:e.path,contentType:r||"none",operationId:e.raw()?.operationId}),o}catch(n){let o=n instanceof Error?n.message:String(n);throw this.context.log.warn("MCP validator build failed",{method:e.methods?.[0],path:e.path,contentType:r||"none",operationId:e.raw()?.operationId,error:o}),n}}getRouteDataForOptions(e){let{routes:r}=we.instance.routeData,n=!!e.operationId,o=!!e.path;if(!n&&!o)throw new Error("MCP Tool configuration error: Either 'operationId' or 'path' must be provided in your tool specification.");return n?r.find(i=>i?.raw().operationId===e.operationId&&i?.methods?.some(a=>a.toUpperCase()===e.method.toUpperCase())):r.find(i=>i?.path===e.path&&i?.methods?.some(a=>a.toUpperCase()===e.method.toUpperCase()))}extractOutputSchema(e){try{let r=e.raw(),n=r?.responses;if(!n){this.context.log.warn("No responses found in OpenAPI spec for outputSchema",{path:e.path,operationId:r?.operationId});return}for(let o of Object.keys(n))if(o.startsWith("2")){let a=n[o]?.content;if(a){for(let c of["application/json","application/json; charset=utf-8"])if(a[c]?.schema){let u=a[c].schema;return this.debugMode&&this.context.log.debug("Output schema extracted successfully",{path:e.path,operationId:r?.operationId,statusCode:o,contentType:c,schemaKeys:u&&typeof u=="object"?Object.keys(u).join(", "):"none"}),u}}}this.debugMode&&this.context.log.debug("No OpenAPI spec 2xx responses fond for outputSchema",{path:e.path,operationId:r?.operationId,statusCodes:Object.keys(n).join(", ")});return}catch(r){this.context.log.warn("Failed to extract outputSchema",{path:e.path,operationId:e.raw()?.operationId,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0});return}}};async function gE(t,e){if(R("handler.mcp-server"),e.route.methods.some(a=>a.toUpperCase()!=="POST"))throw new w(`Invalid route config: mcpServerHandler may only use POST. Route '${e.route.path}' declares methods: [${e.route.methods.join(", ")}]`);let r={};t.headers.forEach((a,c)=>{r[c]=a});let n=e.route?.handler?.options??{},o=e.route?.path??"unknown-route",i=await cn.getInstance({opts:n,context:e,key:o});return Ys(r,e,()=>i.handleRequest(t,e))}s(gE,"mcpServerHandler");var sv=10,av=3e4,Er=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,r){if(typeof r=="number"){let n=r;this.#n=n*1e3,this.#o=av,this.#r=sv}else{let n=r;this.#n=n.ttlSeconds*1e3,this.#o=n.loaderTimeoutSeconds?n.loaderTimeoutSeconds*1e3:av,this.#r=sv}this.#t=e}#s(e){return e.expiry<=new Date}#c(e){let r=this.#i[e];return!(r===void 0||r===0)}#u(e){let r=this.#e.get(e);if(r&&!this.#s(r))return r.data}async get(e){let r=this.#u(e);if(r)return this.#l(e),r;if(this.#c(e))try{await hE(()=>this.#u(e)!==void 0||!this.#c(e),this.#o+this.#r+1,this.#r);let n=this.#u(e);if(n)return n}catch{}return this.#a(e)}#l(e){if(!this.#c(e)){let r=this.#a(e);Jt().waitUntil(r)}}async#a(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let r=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(r===void 0)throw new w(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:r,expiry:new Date(Date.now()+this.#n)}),r}finally{this.#i[e]--}}};async function hE(t,e,r){let n=Date.now();for(;!t();){let o=Date.now()-n;if(o>e)throw new w(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(r)}}s(hE,"waitUntilTrue");var yE={ttlSeconds:600,loaderTimeoutSeconds:30},cv=new Er(async()=>{let t=P.instance.zuploEdgeApiUrl;if(!t)throw new w("Zuplo edge API URL not configured");let e=P.instance.authApiJWT;if(!e)throw new w("Zuplo auth API JWT not configured");let r=P.instance.deploymentName;if(!r)throw new w("Deployment name not configured");let n=ke.ZUPLO_SERVICE_BUCKET_ID;if(!n)throw new w("ZUPLO_SERVICE_BUCKET_ID env not configured");let o=`${t}/zups/v1/buckets/${n}/mcp/resolve`,i=await j.fetch(o,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-Agent":P.instance.systemUserAgent,"Content-Type":"application/json"},body:JSON.stringify({deployment:r})});if(!i.ok){let u=await i.text().catch(()=>"");throw new w(`Failed to resolve MCP gateway configuration from ${o}: ${i.status} ${i.statusText}${u?` - ${u}`:""}`)}let c=(await i.json()).mcpGatewayConfig;if(!c||typeof c!="object")throw new w("Invalid MCP gateway configuration: not an object");if(!Array.isArray(c.servers))throw new w("Invalid MCP gateway configuration: servers must be an array");return c},yE);async function bE(t,e){if(R("handler.mcp-gateway"),e.route.methods.some(f=>f.toUpperCase()!=="POST"))throw new w(`Invalid route config: mcpGatewayHandler may only use POST. Route '${e.route.path}' declares methods: [${e.route.methods.join(", ")}]`);let r=e.route?.handler?.options??{},n=await cv.get("NO_KEY");e.log.debug(`Loaded configuration with ${n.servers?.length??0} servers`);let o=t.params.slug;if(!o)throw new Error("No MCP gateway slug provided in request");let i=n.servers.find(f=>f.slug===o);if(!i)throw new Error(`No MCP server configuration found for slug: ${o}`);let a={name:i.name,debugMode:r.debugMode},u=new TextEncoder().encode(JSON.stringify(i)),l=await crypto.subtle.digest("SHA-256",u),d=new Uint8Array(l),p=Array.from(d).map(f=>f.toString(16).padStart(2,"0")).join(""),m=`mcp-origin-config:${o}:${p.substring(0,32)}`;return e.log.debug(`Using MCP server key: ${m}`),wE({request:t,context:e,opts:a,key:m,origins:i.origins})}s(bE,"mcpGatewayHandler");async function wE({request:t,context:e,opts:r,key:n,origins:o}){let i={};t.headers.forEach((c,u)=>{i[u]=c});let a=await cn.getInstance({opts:r,context:e,key:n,origins:o});return Ys(i,e,()=>a.handleRequest(t,e))}s(wE,"mcpServerProxyHandler");function Be(t,e){let r={};for(let n in t){let o=t[n];Array.isArray(o)||(o=[o]);for(let i of o)if(i.param){if(n in e){let a=vE(n,e,i);a!==void 0&&uv(r,i.param,a)}else if(i?.required&&i.default!==void 0){let a=typeof i.default=="function"?i.default(e):i.default;uv(r,i.param,a)}}}return r}s(Be,"validateAndTransformRequest");function vE(t,e,r){let n=e[t];return r.transform&&(n=r.transform(e)),n===void 0&&r.default!==void 0&&(n=typeof r.default=="function"?r.default(e):r.default),typeof n=="number"&&(r.min!==void 0&&n<r.min&&(n=r.min),r.max!==void 0&&n>r.max&&(n=r.max)),n}s(vE,"getValue");function uv(t,e,r){if(r===void 0)return;let n=e.split("."),o=t;for(let i=0;i<n.length-1;i++){let a=n[i];o[a]||(o[a]={}),o=o[a]}o[n[n.length-1]]=r}s(uv,"setNestedProperty");async function _r(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(r)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(_r,"sha256");var lv=new Map;async function xe(t,e,r){let n,o=`${t}-${e}`,i=lv.get(o);return i!==void 0?n=i:(n=`zuplo-policy-${await _r(JSON.stringify({policyName:t,options:r}))}`,lv.set(t,n)),n}s(xe,"getPolicyCacheName");var xE=60,RE={openai:{"gpt-5":{model:"gpt-5",kind:"completions",status:"active",inputCostPerToken:125e-8,outputCostPerToken:1e-5},"gpt-5-nano":{model:"gpt-5-nano",kind:"completions",status:"active",inputCostPerToken:5e-8,outputCostPerToken:4e-7},"gpt-5-mini":{model:"gpt-5-mini",kind:"completions",status:"active",inputCostPerToken:25e-8,outputCostPerToken:2e-6},"gpt-5-nano-2025-08-07":{model:"gpt-5-nano-2025-08-07",kind:"completions",status:"active",inputCostPerToken:5e-8,outputCostPerToken:4e-7},"gpt-5-mini-2025-08-07":{model:"gpt-5-mini-2025-08-07",kind:"completions",status:"active",inputCostPerToken:25e-8,outputCostPerToken:2e-6},"gpt-5-2025-08-07":{model:"gpt-5-2025-08-07",kind:"completions",status:"active",inputCostPerToken:125e-8,outputCostPerToken:1e-5},"gpt-5-chat-latest":{model:"gpt-5-chat-latest",kind:"completions",status:"active",inputCostPerToken:125e-8,outputCostPerToken:1e-5},"gpt-4o":{model:"gpt-4o",kind:"completions",status:"active",inputCostPerToken:25e-7,outputCostPerToken:1e-5},"gpt-4o-2024-11-20":{model:"gpt-4o-2024-11-20",kind:"completions",status:"active",inputCostPerToken:25e-7,outputCostPerToken:1e-5},"gpt-4o-2024-08-06":{model:"gpt-4o-2024-08-06",kind:"completions",status:"active",inputCostPerToken:25e-7,outputCostPerToken:1e-5},"gpt-4o-2024-05-13":{model:"gpt-4o-2024-05-13",kind:"completions",status:"active",inputCostPerToken:5e-6,outputCostPerToken:15e-6},"gpt-4o-mini":{model:"gpt-4o-mini",kind:"completions",status:"active",inputCostPerToken:15e-8,outputCostPerToken:6e-7},"gpt-4o-mini-2024-07-18":{model:"gpt-4o-mini-2024-07-18",kind:"completions",status:"active",inputCostPerToken:15e-8,outputCostPerToken:6e-7},"gpt-4.1":{model:"gpt-4.1",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:8e-6},"gpt-4.1-mini":{model:"gpt-4.1-mini",kind:"completions",status:"active",inputCostPerToken:4e-7,outputCostPerToken:16e-7},"gpt-4.1-nano":{model:"gpt-4.1-nano",kind:"completions",status:"active",inputCostPerToken:1e-7,outputCostPerToken:4e-7},"gpt-4-turbo":{model:"gpt-4-turbo",kind:"completions",status:"active",inputCostPerToken:1e-5,outputCostPerToken:3e-5},"gpt-4-turbo-2024-04-09":{model:"gpt-4-turbo-2024-04-09",kind:"completions",status:"active",inputCostPerToken:1e-5,outputCostPerToken:3e-5},"gpt-4-turbo-preview":{model:"gpt-4-turbo-preview",kind:"completions",status:"active",inputCostPerToken:1e-5,outputCostPerToken:3e-5},"gpt-4-0125-preview":{model:"gpt-4-0125-preview",kind:"completions",status:"active",inputCostPerToken:1e-5,outputCostPerToken:3e-5},"gpt-4-1106-preview":{model:"gpt-4-1106-preview",kind:"completions",status:"active",inputCostPerToken:1e-5,outputCostPerToken:3e-5},"gpt-4-vision-preview":{model:"gpt-4-vision-preview",kind:"completions",status:"deprecated",inputCostPerToken:1e-5,outputCostPerToken:3e-5},"gpt-4":{model:"gpt-4",kind:"completions",status:"active",inputCostPerToken:3e-5,outputCostPerToken:6e-5},"gpt-4-0613":{model:"gpt-4-0613",kind:"completions",status:"active",inputCostPerToken:3e-5,outputCostPerToken:6e-5},"gpt-4-32k":{model:"gpt-4-32k",kind:"completions",status:"deprecated",inputCostPerToken:6e-5,outputCostPerToken:12e-5},"gpt-4-32k-0613":{model:"gpt-4-32k-0613",kind:"completions",status:"deprecated",inputCostPerToken:6e-5,outputCostPerToken:12e-5},"gpt-3.5-turbo":{model:"gpt-3.5-turbo",kind:"completions",status:"active",inputCostPerToken:5e-7,outputCostPerToken:15e-7},"gpt-3.5-turbo-0125":{model:"gpt-3.5-turbo-0125",kind:"completions",status:"active",inputCostPerToken:5e-7,outputCostPerToken:15e-7},"gpt-3.5-turbo-1106":{model:"gpt-3.5-turbo-1106",kind:"completions",status:"active",inputCostPerToken:1e-6,outputCostPerToken:2e-6},"gpt-3.5-turbo-16k":{model:"gpt-3.5-turbo-16k",kind:"completions",status:"active",inputCostPerToken:3e-6,outputCostPerToken:4e-6},"text-embedding-3-large":{model:"text-embedding-3-large",kind:"embeddings",status:"active",inputCostPerToken:13e-8,outputCostPerToken:0},"text-embedding-3-small":{model:"text-embedding-3-small",kind:"embeddings",status:"active",inputCostPerToken:2e-8,outputCostPerToken:0},"text-embedding-ada-002":{model:"text-embedding-ada-002",kind:"embeddings",status:"active",inputCostPerToken:1e-7,outputCostPerToken:0}},anthropic:{"claude-opus-4-20250514":{model:"claude-opus-4-20250514",kind:"completions",status:"active",inputCostPerToken:15e-6,outputCostPerToken:75e-6},"claude-sonnet-4-20250514":{model:"claude-sonnet-4-20250514",kind:"completions",status:"active",inputCostPerToken:3e-6,outputCostPerToken:15e-6},"claude-3-7-sonnet-20250219":{model:"claude-3-7-sonnet-20250219",kind:"completions",status:"active",inputCostPerToken:3e-6,outputCostPerToken:15e-6},"claude-3-5-sonnet-20241022":{model:"claude-3-5-sonnet-20241022",kind:"completions",status:"active",inputCostPerToken:3e-6,outputCostPerToken:15e-6},"claude-3-5-sonnet-20240620":{model:"claude-3-5-sonnet-20240620",kind:"completions",status:"active",inputCostPerToken:3e-6,outputCostPerToken:15e-6},"claude-3-5-haiku-20241022":{model:"claude-3-5-haiku-20241022",kind:"completions",status:"active",inputCostPerToken:8e-7,outputCostPerToken:4e-6},"claude-3-opus-20240229":{model:"claude-3-opus-20240229",kind:"completions",status:"active",inputCostPerToken:15e-6,outputCostPerToken:75e-6},"claude-3-haiku-20240307":{model:"claude-3-haiku-20240307",kind:"completions",status:"active",inputCostPerToken:25e-8,outputCostPerToken:125e-8},"claude-2.1":{model:"claude-2.1",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:8e-6},"claude-2.0":{model:"claude-2.0",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:8e-6},"claude-instant-1.2":{model:"claude-instant-1.2",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:8e-6}},google:{"gemini-2.0-flash-exp":{model:"gemini-2.0-flash-exp",kind:"completions",status:"active",inputCostPerToken:15e-8,outputCostPerToken:6e-7},"gemini-2.0-flash":{model:"gemini-2.0-flash",kind:"completions",status:"active",inputCostPerToken:1e-7,outputCostPerToken:4e-7},"gemini-2.0-flash-lite":{model:"gemini-2.0-flash-lite",kind:"completions",status:"active",inputCostPerToken:75e-9,outputCostPerToken:3e-7},"gemini-2.5-pro":{model:"gemini-2.5-pro",kind:"completions",status:"active",inputCostPerToken:125e-8,outputCostPerToken:1e-5},"gemini-pro":{model:"gemini-pro",kind:"completions",status:"active",inputCostPerToken:5e-7,outputCostPerToken:15e-7},"gemini-embedding-001":{model:"gemini-embedding-001",kind:"embeddings",status:"active",inputCostPerToken:15e-8,outputCostPerToken:0}},mistral:{"mistral-large-latest":{model:"mistral-large-latest",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:6e-6},"mistral-large-2411":{model:"mistral-large-2411",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:6e-6},"mistral-large-2407":{model:"mistral-large-2407",kind:"completions",status:"active",inputCostPerToken:3e-6,outputCostPerToken:9e-6},"mistral-medium-latest":{model:"mistral-medium-latest",kind:"completions",status:"active",inputCostPerToken:4e-7,outputCostPerToken:2e-6},"mistral-small-latest":{model:"mistral-small-latest",kind:"completions",status:"active",inputCostPerToken:1e-7,outputCostPerToken:3e-7},"mistral-small-2409":{model:"mistral-small-2409",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:8e-6},"open-mistral-7b":{model:"open-mistral-7b",kind:"completions",status:"active",inputCostPerToken:25e-8,outputCostPerToken:25e-8},"open-mixtral-8x7b":{model:"open-mixtral-8x7b",kind:"completions",status:"active",inputCostPerToken:7e-7,outputCostPerToken:7e-7},"open-mixtral-8x22b":{model:"open-mixtral-8x22b",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:6e-6},"open-mistral-nemo":{model:"open-mistral-nemo",kind:"completions",status:"active",inputCostPerToken:3e-7,outputCostPerToken:3e-7},"codestral-latest":{model:"codestral-latest",kind:"completions",status:"active",inputCostPerToken:1e-6,outputCostPerToken:3e-6},"ministral-3b-latest":{model:"ministral-3b-latest",kind:"completions",status:"active",inputCostPerToken:4e-8,outputCostPerToken:4e-8},"ministral-8b-latest":{model:"ministral-8b-latest",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:8e-6},"mistral-embed":{model:"mistral-embed",kind:"embeddings",status:"active",inputCostPerToken:1e-7,outputCostPerToken:0}}};async function ft(t){let e=Q.getLogger(t),r=await xe("supported-models","models",{}),n=new be(r,t),o=await n.get("models");if(o)return e.info("Using cached supported models data",{providersCount:Object.keys(o.modelsByProvider).length,providers:Object.keys(o.modelsByProvider)}),o.modelsByProvider;let i=new Headers({"content-type":"application/json"});je(i,t.requestId);let a=`${P.instance.zuploEdgeApiUrl}/v1/buckets/${ke.ZUPLO_SERVICE_BUCKET_ID}/providers`,c=await Te({retryDelayMs:100,retries:5},a,{method:"GET",headers:i}),u;if(c.status!==200){try{let d=await c.text(),p=JSON.parse(d);e.error("Gateway service unavailable, using fallback models",p)}catch{e.error("Gateway service unavailable, using fallback models")}t.log.info("AI Gateway: Using fallback model data due to service unavailability"),u=RE}else{let d=await c.json();e.info("Gateway service response received",{providersCount:Object.keys(d.data).length,providers:Object.keys(d.data),totalModels:Object.values(d.data).reduce((p,m)=>p+m.length,0)}),u={};for(let[p,m]of Object.entries(d.data)){let f=p.toLowerCase();u[f]={};for(let g of m)u[f][g.model]=g}}let l={modelsByProvider:u};return n.put("models",l,xE),u}s(ft,"getSupportedModels");function _t(t,e,r,n,o,i){let a=e.toLowerCase(),c=o[a];if(!c)return i.warn("Provider not found in supported models list",{provider:e,model:t}),0;let u=c[t];if(!u)return i.warn("Model not found in supported models list for provider",{provider:e,model:t}),0;let l=r*u.inputCostPerToken,d=n*u.outputCostPerToken;return l+d}s(_t,"calculateModelCost");function dv(t,e,r,n){let o=e.toLowerCase(),i=n[o];if(!i)return!1;let a=i[t];return a?a.kind===r&&a.status==="active":!1}s(dv,"isModelSupported");function pv(t,e,r){let n=t.toLowerCase(),o=r[n];return o?Object.values(o).filter(i=>i.kind===e&&i.status==="active").map(i=>i.model):[]}s(pv,"getModelsByProviderAndKind");var xm=class{static{s(this,"GatewayServiceClient")}baseUrl;constructor(e){this.baseUrl=e??P.instance.zuploEdgeApiUrl}async fetchCurrentMeters(e,r){let n=`${this.baseUrl}/v1/hierarchical-quota/${e}`,o=new Headers({"Content-Type":"application/json"});je(o,r.requestId);let i=await fetch(n,{method:"GET",headers:o});if(!i.ok)throw new le(`Failed to fetch meters: ${i.status} ${i.statusText}`);return await i.json()}async checkHierarchicalQuotaLimits(e,r){let n=`${this.baseUrl}/v1/hierarchical-quota/${e}/limits`,o=new Headers({"Content-Type":"application/json"});je(o,r.requestId);let i=await fetch(n,{method:"GET",headers:o});if(!i.ok)throw new le(`Failed to check quota limits: ${i.status} ${i.statusText}`);return await i.json()}async incrementMeters(e,r,n){let o=`${this.baseUrl}/v1/hierarchical-quota/${e}`,i=new Headers({"Content-Type":"application/json"});je(i,n.requestId);let a=await fetch(o,{method:"POST",headers:i,body:JSON.stringify({increments:r})});if(!a.ok)throw new le(`Failed to increment meters: ${a.status} ${a.statusText}`)}},vm=null,sa={get instance(){return vm===null&&(vm=new xm),vm}};var mv=Ne("zuplo:policies:AIGatewayMeteringInboundPolicy"),fv=Symbol("ai-gateway-meter-increments"),st=class t extends Re{static{s(this,"AIGatewayMeteringInboundPolicy")}static setIncrements(e,r){pe.set(e,fv,r)}static getIncrements(e){return pe.get(e,fv)??{}}constructor(e,r){super(e,r),R("policy.inbound.ai-gateway-metering-inbound")}async handler(e,r){let n=Date.now(),o=Q.getLogger(r),i=s((a,c)=>{if(this.options.throwOnFailure)throw new le(a,{cause:c});o.error(c,a)},"throwOrLog");try{let a=e.user?.configuration;if(!a)throw new w(`AIGatewayMeteringInboundPolicy '${this.policyName}' - No configuration found in request.user. Ensure ai-gateway-inbound policy runs first.`);let c=a;if(!c.id)throw new w(`AIGatewayMeteringInboundPolicy '${this.policyName}' - Configuration ID not found.`);let u=await this.fetchCurrentMeters(c.id,r,o),l=this.checkWarnings(c,u);for(let p of l)r.analyticsContext.addAnalyticsEvent(1,Oe.AI_GATEWAY_WARNING_COUNT,{type:`quota-${p.type}-${p.period}`,configId:c.id});let d=await this.checkHierarchicalQuotaLimits(c.id,r,o);return d.violation?(r.analyticsContext.addAnalyticsEvent(1,Oe.AI_GATEWAY_BLOCKED_COUNT,{type:`quota-${d.violation.meter}-${d.violation.period}`,configId:c.id}),this.createHierarchicalQuotaExceededResponse(e,r,d.violation)):(r.addResponseSendingFinalHook(async()=>{try{let p=t.getIncrements(r);mv(`AIGatewayMeteringInboundPolicy '${this.policyName}' - increments ${JSON.stringify(p)}`),Object.keys(p).length>0&&await t.incrementMetersInternal(c.id,p,r,o)}catch(p){i(`AIGatewayMeteringInboundPolicy '${this.policyName}' - Failed to increment meters`,p)}}),e)}catch(a){if(a instanceof w)throw a;return i(`AIGatewayMeteringInboundPolicy '${this.policyName}' - Error`,a),e}finally{let a=Date.now()-n;mv(`AIGatewayMeteringInboundPolicy '${this.policyName}' - latency ${a}ms`)}}async fetchCurrentMeters(e,r,n){try{return await sa.instance.fetchCurrentMeters(e,r)}catch(o){throw n.error(o,`AIGatewayMeteringInboundPolicy '${this.policyName}' - Failed to fetch meters`),o}}async checkHierarchicalQuotaLimits(e,r,n){try{return await sa.instance.checkHierarchicalQuotaLimits(e,r)}catch(o){throw n.error(o,`AIGatewayMeteringInboundPolicy '${this.policyName}' - Failed to check hierarchical quota limits`),o}}static async incrementMeters(e,r,n){let o=Q.getLogger(n);return t.incrementMetersInternal(e,r,n,o)}static async incrementMetersInternal(e,r,n,o){try{await sa.instance.incrementMeters(e,r,n)}catch(i){throw o.error(i,"AIGatewayMeteringInboundPolicy - Failed to increment meters"),i}}checkWarnings(e,r){let n=[];for(let[o,i]of Object.entries(e.limits)){if(!i)continue;let a=r.meters[o];if(!a)continue;let c=this.checkQuotaWarning(i.daily,a.daily,o,"daily");c&&n.push(c);let u=this.checkQuotaWarning(i.monthly,a.monthly,o,"monthly");u&&n.push(u)}return n}checkQuotaWarning(e,r,n,o){if(!e?.warning?.enabled||!e?.warning?.threshold||!e?.limit)return null;let i=e.warning.threshold/100*e.limit;return r>=i?{type:n,period:o}:null}createHierarchicalQuotaExceededResponse(e,r,n){let o=`${n.period} ${n.meter} quota exceeded in configuration '${n.configLabel}'. Limit: ${n.limit}, Current: ${n.currentUsage}`;return D.tooManyRequests(e,r,{detail:o})}};async function lr(t,e){if(!P.instance.remoteLogURL){Q.getLogger(t).debug("Remote log URL is not configured, skipping analytics");return}t.analyticsContext.addAnalyticsEvent(parseFloat(e.cost.toFixed(10)),Oe.AI_GATEWAY_COST_SUM,{model:e.model,provider:e.provider,configId:e.configId}),t.analyticsContext.addAnalyticsEvent(1,Oe.AI_GATEWAY_REQUEST_COUNT,{model:e.model,provider:e.provider,configId:e.configId}),t.analyticsContext.addAnalyticsEvent(e.promptTokens,Oe.AI_GATEWAY_TOKEN_SUM,{model:e.model,provider:e.provider,configId:e.configId,tokenType:"prompt"}),t.analyticsContext.addAnalyticsEvent(e.completionTokens,Oe.AI_GATEWAY_TOKEN_SUM,{model:e.model,provider:e.provider,configId:e.configId,tokenType:"completion"});let r=t.analyticsContext.flushAnalyticsEvents();new Fr(t,{endpoint:`${P.instance.remoteLogURL}/v2/analytics`}).pushEvents(r)}s(lr,"sendStreamAnalytics");var gv={model:{param:"model",required:!0,default:"gpt-4o-mini"},messages:{param:"messages",required:!0},temperature:{param:"temperature",default:1,min:0,max:2},top_p:{param:"top_p",default:1,min:0,max:1},n:{param:"n",default:1,min:1,max:128},stream:{param:"stream",default:!1},stop:{param:"stop"},max_tokens:{param:"max_tokens",min:0},presence_penalty:{param:"presence_penalty",default:0,min:-2,max:2},frequency_penalty:{param:"frequency_penalty",default:0,min:-2,max:2},logit_bias:{param:"logit_bias"},user:{param:"user"},seed:{param:"seed"},functions:{param:"functions"},function_call:{param:"function_call"},tools:{param:"tools"},tool_choice:{param:"tool_choice"},parallel_tool_calls:{param:"parallel_tool_calls"},response_format:{param:"response_format"},logprobs:{param:"logprobs",default:!1},top_logprobs:{param:"top_logprobs",min:0,max:20},max_completion_tokens:{param:"max_completion_tokens"},service_tier:{param:"service_tier"},stream_options:{param:"stream_options"}},PE={model:{param:"model",required:!0,default:"text-embedding-3-small"},input:{param:"input",required:!0},user:{param:"user"},dimensions:{param:"dimensions"},encoding_format:{param:"encoding_format",default:"float"}},aa=class{static{s(this,"OpenAIProvider")}name="openai";async chatComplete(e,r){let n=Be(gv,e),o=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let a=await o.json();throw new Error(`OpenAI API error: ${a.error?.message||"Unknown error"}`)}return{...await o.json(),provider:"openai"}}async chatCompleteStream(e,r,n){let o=Be(gv,{...e,stream:!0,stream_options:{include_usage:!0}}),i=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok){let m=await i.json();throw new Error(`OpenAI API error: ${m.error?.message||"Unknown error"}`)}if(!i.body)throw new Error("No response body received from OpenAI API");let a=n.custom.userContext,c="",u=new TextDecoder,l=new TransformStream({transform(m,f){f.enqueue(m);let g=u.decode(m);c+=g,!c.includes('"usage"')&&c.length>4096&&(c=c.slice(-32));let b;for(;(b=c.indexOf(`
200
+ `&&n++}}return[e,r]}s(pE,"splitLines");var ra=class extends TransformStream{static{s(this,"EventSourceParserStream")}constructor({onError:e,onRetry:r,onComment:n}={}){let o;super({start(i){o=iv({onEvent:s(a=>{i.enqueue(a)},"onEvent"),onError(a){e==="terminate"?i.error(a):typeof e=="function"&&e(a)},onRetry:r,onComment:n})},transform(i){o.feed(i)}})}};var na=class{static{s(this,"HTTPClientTransport")}url;timeout;headers;fetch;logger;sessionId;messageHandler;errorCallback;closeCallback;isConnected=!1;constructor(e){this.url=e.url,this.timeout=e.timeout||3e4,this.headers={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...e.headers},this.fetch=e.fetch||globalThis.fetch,this.logger=e.logger||rr(),e.enableSessions&&this.logger.debug("Session support not yet implemented for HTTP client transport")}setHeaders(e){this.headers={...this.headers,...e}}async connect(){try{new URL(this.url),this.isConnected=!0,this.logger.info("HTTP Client Transport connected to:",this.url)}catch{let r=new Error(`Invalid URL: ${this.url}`);throw this.errorCallback&&this.errorCallback(r),r}}async send(e){if(!this.isConnected)throw new Error("Transport not connected. Call connect() first.");let r;try{let n={...this.headers};this.sessionId&&(n["Mcp-Session-Id"]=this.sessionId);let o=new AbortController;r=setTimeout(()=>o.abort(),this.timeout);let i=await this.fetch(this.url,{method:"POST",headers:{...this.headers,...this.sessionId&&{"Mcp-Session-Id":this.sessionId}},body:JSON.stringify(e),signal:o.signal});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);(i.headers.get("Content-Type")||"").includes("text/event-stream")?await this.handleSSEResponse(i):await this.handleJSONResponse(i)}catch(n){if(n instanceof Error&&n.name==="AbortError")throw this.errorCallback&&this.errorCallback(n),new Error(`Request timeout after ${this.timeout}ms`);let o=new Error(`A client error occurred: ${n}`);throw this.errorCallback&&this.errorCallback(o),o}finally{r&&clearTimeout(r)}}onMessage(e){this.messageHandler=e}async close(){this.logger.debug("Closing HTTP Client Transport"),this.isConnected=!1,this.messageHandler=void 0,this.closeCallback&&this.closeCallback(),this.logger.info("HTTP Client Transport closed")}onClose(e){this.closeCallback=e}onError(e){this.errorCallback=e}getSessionId(){return this.sessionId}setSessionId(e){this.sessionId=e,this.logger.debug("Session ID set:",e?"***":"undefined")}async handleJSONResponse(e){let r=await e.text();if(!r.trim()){this.logger.debug("Received empty response");return}let n;try{n=JSON.parse(r)}catch{throw new Error(`Invalid JSON response: ${r}`)}this.logger.debug("Received JSON-RPC response:",n),this.messageHandler&&await this.messageHandler(n)}async handleSSEResponse(e){if(!e.body)throw new Error("SSE response has no body");this.logger.debug("Handling SSE response");let r=s(o=>{if(!o.event||o.event==="message")try{let i=JSON.parse(o.data);this.logger.debug("Received SSE message:",i),this.messageHandler&&this.messageHandler(i)}catch(i){this.logger.warn("Failed to parse SSE message data:",o.data,i)}},"onEvent"),n=e.body.pipeThrough(new TextDecoderStream).pipeThrough(new ra).getReader();try{for(;;){let{done:o,value:i}=await n.read();if(o)return;r(i)}}catch(o){throw this.logger.error("Error processing SSE stream:",o),new Error(`SSE stream error: ${o}`)}}};var mE="MCP Client",fE="0.0.0",oa=class{static{s(this,"MCPClient")}name;version;capabilities;transport;isInitialized=!1;protocolVersion;logger;requestId=1;transportOptions;constructor(e={}){this.name=e.name||mE,this.version=e.version||fE,this.logger=e.logger||rr(),this.transportOptions=e.transportOptions||{},this.capabilities={experimental:{},sampling:{},...e.capabilities}}async connect(e){this.transportOptions.headers&&e.setHeaders(this.transportOptions.headers),this.transport=e,await e.connect()}async initialize(e=Do){if(!this.transport)throw new Error("No transport connected. Call connect() first.");let r=Ir({id:this.requestId,method:"initialize",params:{protocolVersion:e,capabilities:this.capabilities,clientInfo:{name:this.name,version:this.version}}}),n=await this.sendRequest(r);if(tr(n))throw new Error(`Initialization failed: ${n.error.message}`);let o=n.result;return this.isInitialized=!0,this.protocolVersion=o.protocolVersion,this.logger.info("Successfully initialized MCP client",{serverInfo:o,protocolVersion:this.protocolVersion}),o}async ping(){if(!this.isInitialized)throw new Error("Client not initialized. Call initialize() first.");let e=Ir({id:this.requestId,method:"ping"}),r=await this.sendRequest(e);if(tr(r))throw new Error(`Ping failed: ${r.error.message}`)}async listTools(){if(!this.isInitialized)throw new Error("Client not initialized. Call initialize() first.");let e=Ir({id:this.requestId,method:"tools/list",params:{}}),r=await this.sendRequest(e);if(tr(r))throw new Error(`Failed to list tools: ${r.error.message}`);return r.result.tools}async callTool(e,r={}){if(!this.isInitialized)throw new Error("Client not initialized. Call initialize() first.");let n=Ir({id:this.requestId,method:"tools/call",params:{name:e,arguments:r}}),o=await this.sendRequest(n);if(tr(o))throw new Error(`Failed to call tool '${e}': ${o.error.message}`);return o.result}async listPrompts(){if(!this.isInitialized)throw new Error("Client not initialized. Call initialize() first.");let e=Ir({id:this.requestId,method:"prompts/list",params:{}}),r=await this.sendRequest(e);if(tr(r))throw new Error(`Failed to list prompts: ${r.error.message}`);return r.result.prompts}async getPrompt(e,r={}){if(!this.isInitialized)throw new Error("Client not initialized. Call initialize() first.");let n=Ir({id:this.requestId,method:"prompts/get",params:{name:e,arguments:r}}),o=await this.sendRequest(n);if(tr(o))throw new Error(`Failed to get prompt '${e}': ${o.error.message}`);return o.result}async disconnect(){this.transport&&(await this.transport.close(),this.transport=void 0),this.isInitialized=!1,this.protocolVersion=void 0}async sendRequest(e){return new Promise((r,n)=>{let o=e.id;this.transport?.onMessage(async i=>((nn(i)||tr(i))&&i.id===o&&r(i),null)),this.transport?.send(e).catch(n)})}};var ia=class{constructor(e,r,n=!1,o){this.baseUrl=e;this.originToolName=r;this.debugMode=n;this.originHeaders=o}static{s(this,"ProxyMcpToolExecutor")}async execute(e){let r=ur(),n=Date.now(),o=new oa({name:"Zuplo MCP Gateway Proxy Client",version:"0.0.1"});try{this.debugMode&&r.log.debug("Proxying MCP tool call",{originToolName:this.originToolName,baseUrl:this.baseUrl,args:e});let i=new na({url:this.baseUrl});i.setHeaders({"Content-Type":"application/json",...ea(),...this.originHeaders??{}});let a,c=Date.now();try{await o.connect(i),await o.initialize(),a=await o.callTool(this.originToolName,e)}catch(l){throw new Error(`could not call tool: ${this.originToolName}`,l)}let u=Date.now()-c;return this.debugMode&&r.log.debug("Proxy MCP response received",{originToolName:this.originToolName,upstreamElapsedMs:u,proxyResult:a}),a}catch(i){let a=Date.now()-n,c=i instanceof Error?`${i.name}: ${i.message}`:String(i);return r.log.error("Proxy MCP tool execution failed",{originToolName:this.originToolName,baseUrl:this.baseUrl,totalElapsedMs:a,err:i}),{content:[{type:"text",text:`Tool execution failed for '${this.originToolName}': ${c}`}],isError:!0}}finally{await o.disconnect()}}};var cn=class t{static{s(this,"ZuploMcpServer")}static instances=new Map;static async getInstance({opts:e,context:r,key:n,origins:o}){let i=e.debugMode??!1,a=t.instances.get(n);if(a)i&&r.log.debug("MCP Server warm reuse",{routeKey:n});else{let c=Date.now();if(a=new t(e,r,o??[]),a.registerToolsFromOptions(a.opts.openApiTools??[]),a.registerToolsFromFiles(a.opts.openApiFilePaths??[]),a.registerToolsFromFileSources(a.opts.files??[]),a.registerPromptsFromFileSources(a.opts.prompts??[]),a.registerResourcesFromFileSources(a.opts.resources??[]),await a.registerProxyTools(a.origins??[]),await a.transport.connect(),a.server.withTransport(a.transport),t.instances.set(n,a),i){let u=a.server.getTools(),l=u?u.size:0,d=a.server.getPromptDefinitions(),p=d?d.length:0,m=a.server.getResourceDefinitions(),f=m?m.length:0,g=Date.now()-c;r.log.debug("MCP Server cold start",{routeKey:n,toolCount:l,promptCount:p,resourceCount:f,totalElapsedMs:g,debugMode:i,includeOutputSchema:a.includeOutputSchema,includeStructuredContent:a.includeStructuredContent})}}return a}transport;server;opts;origins;context;includeOutputSchema;includeStructuredContent;debugMode;constructor(e,r,n){this.debugMode=e.debugMode??!1;let o;this.debugMode?o=r.log:o=new Mo,this.context=r,this.opts=e,this.origins=n??[],this.server=new Fs({name:e.name??"Zuplo MCP Server",version:e.version??"0.0.0",logger:o}),this.transport=new Hs({logger:o}),this.includeOutputSchema=e.includeOutputSchema??!1,this.includeStructuredContent=e.includeStructuredContent??!1}async handleRequest(e,r){let n=Date.now();try{let o=await e.clone().json().catch(()=>({}));if(this.debugMode&&r.log.debug("MCP Server request start",{method:o.method,requestId:o.id,routePath:r.route?.path}),this.debugMode&&o.method==="tools/list"){let c=this.server.getTools(),u=c?Array.from(c.keys()):[];r.log.debug("MCP Server list tools request",{toolCount:u.length,toolNames:u})}if(this.debugMode&&o.method==="prompts/list"){let c=this.server.getPromptDefinitions(),u=c?c.map(l=>l.name):[];r.log.debug("MCP Server list prompts request",{promptCount:u.length,promptNames:u})}if(this.debugMode&&o.method==="resources/list"){let c=this.server.getResourceDefinitions(),u=c?c.map(l=>l.name):[];r.log.debug("MCP Server list resources request",{resourceCount:u.length,resourceNames:u})}let i=await this.transport.handleRequest(e),a=Date.now()-n;if(this.debugMode){let c=await i.clone().json().catch(()=>({}));r.log.debug("MCP Server response complete",{status:i.status,requestMethod:o.method,requestId:o.id,totalElapsedMs:a,respData:c})}return i}catch(o){let i=Date.now()-n;return r.log.error("MCP server internal error",{elapsedMs:i,err:o}),new Response("Internal error",{status:500})}}generatePromptDescriptionFromSpec(e){let r=e.raw();return r?.description?r.description:r?.summary?r.summary:`Generate content for operation for ${e.path}`}generateToolNameFromSpec(e,r){let n=e.raw();if(n?.operationId)return`${n.operationId}`;let o=`${r}_${e.path}`.replace(/[^\w]/g,"_");return this.context.log.warn(`No operationId found for route ${r} ${e.path}. Using auto-generated name "${o}". To improve AI tool selection, add a descriptive operationId to your OpenAPI spec (e.g., "get_user_by_id" instead of "GET_/users/{id}")`),o}generateToolDescriptionFromSpec(e,r){let n=e.raw();return n?.description?n.description:n?.summary?n.summary:`Call ${r.toUpperCase()} ${e.path}`}registerToolsFromOptions(e){let r=new Set;for(let n of e){if(this.context.log.warn(`DEPRECATED: Registering MCP tool with name: "${n.name}", operationId: "${n.operationId}", method: "${n.method}" from "options.openApiTools" will soon be deprecated: migrate to using "options.files" configurations`),n.name){if(typeof n.name!="string"||n.name.trim()==="")throw new Error("MCP Tool configuration error: Tool name must be a non-empty string if provided.");if(r.has(n.name))throw new Error(`MCP Tool configuration error: Duplicate tool name "${n.name}". Tool names must be unique across all configured tools.`)}let o=this.getRouteDataForOptions(n);if(!o){let l=n.operationId?`operationId: "${n.operationId}"`:`path: "${n.path}"`;throw new Error(`MCP Tool configuration error: Could not find gateway route data for ${n.method.toUpperCase()} ${l}. Verify that the route exists in your OpenAPI specification and that the provided metadata matches OpenAPI specification data.`)}if(!o.handler){let l=n.operationId?`operationId: "${n.operationId}"`:`path: "${n.path}"`;throw new Error(`MCP Tool configuration error: Route ${n.method.toUpperCase()} ${l} has no handler configured. Ensure the route has a proper handler defined in your OpenAPI specification.`)}let i=n.name??this.generateToolNameFromSpec(o,n.method);if(r.has(i))throw new Error(`MCP Tool configuration error: Tool name conflict detected. The name "${i}" is already in use. Consider providing a unique 'name' in your tool configuration or ensure your operationIds are unique.`);r.add(i);let a=n.description??this.generateToolDescriptionFromSpec(o,n.method),c=n.includeOutputSchema??this.includeOutputSchema??!0,u=n.includeStructuredContent??this.includeStructuredContent??!0;this.registerToolsForMethod(o,n.method,i,a,c,u)}}static getOperationsMetadataForFile(e){let{routes:r}=we.instance.routeData,n=r.filter(i=>i.metadata?.filepath===e);if(n.length===0)throw new Error(`MCP Tool configuration error: No routes found for file path ${e}. Verify that the OpenAPI file exists and is properly loaded in your Gateway configuration with routes.`);let o=new Map;for(let i of n){let a=i?.raw().operationId;if(a){o.set(a,{routeConfig:i});let c=i?.raw()["x-zuplo-mcp-tool"],u=i?.raw()["x-zuplo-mcp-prompt"],l=i?.raw()["x-zuplo-mcp-graphql"],d=i?.raw()["x-zuplo-mcp-resource"];(c||u||l||d)&&o.set(a,{routeConfig:i,toolExtension:c||void 0,promptExtension:u||void 0,graphqlExtension:l||void 0,resourceExtension:d||void 0})}}return o}registerPromptsFromFileSources(e){for(let r of e){let n=t.getOperationsMetadataForFile(r.path),o=new Set;for(let i of r.operationIds){let a=n.get(i);if(!a)throw new Error(`MCP Prompt configuration error: Could not find operation with ID "${i}" in file ${r.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,promptExtension:u}=a,l=u?.name??i;if(o.has(l))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${l}". Prompt names must be unique across all configured prompts.`);o.add(l);let d=u?.description??this.generatePromptDescriptionFromSpec(c);if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by extension",{promptName:l,operationId:i});continue}this.registerPromptForOperation(l,d,c,i)}}}registerPromptForOperation(e,r,n,o){try{if(n.handler?.export==="mcpServerHandler")return;let a=Cr.createPromptValidatorBuilder(n).build();this.server.addPrompt({name:e,description:r,validator:a,generator:s(async c=>{let u=ur(),l=Date.now();try{this.debugMode&&u.log.debug("MCP prompt invoked",{promptName:e,operationId:n.raw()?.operationId,path:n.path,args:c});let d=this.buildToolUrl(n,{body:c}),p=this.buildToolRequest("POST","application/json",{body:c});this.debugMode&&u.log.debug("MCP prompt downstream call",{promptName:e,url:d,method:"POST",bodyPreview:c});let m=Date.now(),f=await u.invokeRoute(d,p),g=Date.now()-m,b=await f.json();if(!f.ok)throw new Error(`Route returned ${f.status}: ${b}`);let h;try{if(h=b.messages||b,!Array.isArray(h))throw new Error("Response must contain a 'messages' array or be an array of messages")}catch(v){throw new Error(`Invalid JSON response or missing messages array: ${v instanceof Error?v.message:String(v)}`)}let x=Date.now()-l;return this.debugMode&&u.log.debug("MCP prompt response complete",{promptName:e,operationId:n.raw()?.operationId,status:f.status,elapsedMs:x,downstreamElapsedMs:g,messageCount:h.length}),h}catch(d){let p=Date.now()-l,m=d instanceof Error?`${d.name}: ${d.message}`:String(d);throw u.log.error("MCP prompt invocation failed",{promptName:e,operationId:n.raw()?.operationId,path:n.path,elapsedMs:p,err:d}),new Error(`MCP tool call failed for tool '${e}': ${m}`)}},"generator")}),this.debugMode&&this.context.log.debug("MCP prompt registered from file source",{promptName:e,operationId:o,path:n.path})}catch(i){throw this.context.log.error("Failed to register MCP prompt",{promptName:e,operationId:o,error:i instanceof Error?i.message:String(i)}),new Error(`Failed to register prompt "${e}" for operation "${o}": ${i instanceof Error?i.message:String(i)}`)}}registerResourcesFromFileSources(e){let r=new Set;for(let n of e){let o=t.getOperationsMetadataForFile(n.path);for(let i of n.operationIds){let a=o.get(i);if(!a)throw new Error(`MCP Resource configuration error: Could not find operation with ID "${i}" in file ${n.path}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:c,resourceExtension:u}=a;if(!(u?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by extension",{operationId:i});continue}if(!c.methods||c.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${i}" has no HTTP methods defined. Resources must use GET method.`);if(c.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${i}" has multiple HTTP methods (${c.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let d=c.methods[0].toUpperCase();if(d!=="GET")throw new Error(`MCP Resource configuration error: Operation "${i}" uses ${d} method. Resources are read-only and must use GET method only.`);let p=u?.name?.trim()||i.trim()||"";if(!p)throw new Error(`MCP Resource configuration error: Could not determine resource name for operation "${i}". Ensure the operation has an operationId or provide a name in x-zuplo-mcp-resource extension.`);if(r.has(p))throw new Error(`MCP Resource configuration error: Duplicate resource name "${p}". Resource names must be unique across all configured resources.`);r.add(p);let m=u?.description?.trim()||c.raw()?.description?.trim()||c.raw()?.summary?.trim()||`Resource for ${p}`,f=u?.uri?.trim()||`mcp://resources/${encodeURIComponent(p)}`,g=u?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(p,f,m,c,i,g)}}}registerResourceForOperation(e,r,n,o,i,a){try{if(o.handler?.export==="mcpServerHandler")return;this.server.addResource(e,r,{title:e,description:n,mimeType:a},async()=>{let c=ur(),u=Date.now();try{this.debugMode&&c.log.debug("MCP resource invoked",{resourceName:e,operationId:o.raw()?.operationId,path:o.path,uri:r});let l=this.buildToolUrl(o,{}),d=this.buildToolRequest("GET",null,{});this.debugMode&&c.log.debug("MCP resource downstream call",{resourceName:e,url:l,method:"GET"});let p=Date.now(),m=await c.invokeRoute(l,d),f=Date.now()-p,g=await m.text(),b=Date.now()-u;return this.debugMode&&c.log.debug("MCP resource response complete",{resourceName:e,operationId:o.raw()?.operationId,status:m.status,elapsedMs:b,downstreamElapsedMs:f,declaredMimeType:a,contentLength:g.length}),{contents:[{uri:r,declaredMimeType:a,text:g}]}}catch(l){let d=Date.now()-u,p=l instanceof Error?`${l.name}: ${l.message}`:String(l);throw c.log.error("MCP resource invocation failed",{resourceName:e,operationId:o.raw()?.operationId,path:o.path,elapsedMs:d,err:l}),new Error(`MCP resource call failed for resource '${e}': ${p}`)}}),this.debugMode&&this.context.log.debug("MCP resource registered from file source",{resourceName:e,operationId:i,path:o.path,uri:r,mimeType:a||"auto-detected"})}catch(c){throw this.context.log.error("Failed to register MCP resource",{resourceName:e,operationId:i,error:c instanceof Error?c.message:String(c)}),new Error(`Failed to register resource "${e}" for operation "${i}": ${c instanceof Error?c.message:String(c)}`)}}registerToolsFromFileSources(e){let r=new Set;for(let n of e){let o=t.getOperationsMetadataForFile(n.path);this.debugMode&&this.context.log.debug("Processing file source",{path:n.path,operationIds:n.operationIds,availableOperationIds:Array.from(o.keys())});for(let i of n.operationIds){let a=o.get(i);if(!a)throw new Error(`MCP Tool configuration error: Operation ID "${i}" not found in OpenAPI spec at ${n.path}. Available operation IDs: ${Array.from(o.keys()).join(", ")}`);if(a.toolExtension?.enabled===!1){this.debugMode&&this.context.log.debug("Skipping disabled tool",{operationId:i,path:n.path});continue}let c=a.toolExtension?.name?.trim()??i,u=(a.toolExtension?.description?.trim()||null)??(a.routeConfig.raw().description?.trim()||null)??(a.routeConfig.raw().summary?.trim()||null)??`Executes tool: ${c}`;if(!u)throw new Error(`MCP Tool configuration error: no tool description found for operationId: "${i}" in file "${n.path}"`);if(r.has(c))throw new Error(`MCP Tool configuration error: Tool name conflict detected. The name "${c}" is already in use. Consider providing a unique 'name' in the x-zuplo-mcp-tool extension for operation "${i}".`);r.add(c);let l=a.toolExtension?.includeOutputSchema??this.includeOutputSchema??!1,d=a.toolExtension?.includeStructuredContent??this.includeStructuredContent??!1;if(a.routeConfig.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${a.routeConfig.methods.join(", ")}" on operation "${i}" not permitted. Only tools with one singular method is permitted.`);a.graphqlExtension?(a.graphqlExtension.enabled??!0)&&this.registerGraphQLTools(i,a.routeConfig,a.graphqlExtension,r):this.registerToolsForMethod(a.routeConfig,a.routeConfig.methods[0],c,u,l,d)}}}registerGraphQLTools(e,r,n,o){let i=n.introspectionToolName??`${e}_introspect`,a=n.executeToolName??`${e}_execute_query`;if(o.has(i))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The introspection tool name "${i}" is already in use. Provide a unique 'introspectionToolName' in the x-zuplo-graphql extension.`);if(o.has(a))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The execute tool name "${a}" is already in use. Provide a unique 'executeToolName' in the x-zuplo-graphql extension.`);o.add(i),o.add(a);let c=n.introspectionToolDescription??`Get the GraphQL schema for ${e}`,u=n.executeToolDescription??`Execute a GraphQL query on ${e}`,l=r.path,p=Cr.createObjectValidatorBuilder({}).build();this.server.addTool({name:i,description:c,validator:p,handler:s(async()=>{let f=ur(),g=Date.now();try{this.debugMode&&f.log.debug("MCP GraphQL introspection tool invoked",{toolName:i,operationId:e,path:l});let b=Gs(),h=this.buildToolUrl(r,{}),x=this.buildToolRequest("POST","application/json",{body:{query:b}}),v=Date.now(),C=await f.invokeRoute(h,x),A=Date.now()-v,O=await C.text(),S=Date.now()-g;this.debugMode&&(C.ok?f.log.debug("MCP GraphQL introspection tool ok response",{toolName:i,operationId:e,status:C.status,elapsedMs:S,downstreamElapsedMs:A}):f.log.debug("MCP GraphQL introspection tool 'isError' response",{toolName:i,operationId:e,status:C.status,elapsedMs:S,downstreamElapsedMs:A,response:O}));let M;try{M=JSON.parse(O)}catch(z){this.debugMode&&f.log.debug("MCP GraphQL introspection structuredContent JSON parse failed",{toolName:i,body:O,parseErr:z})}return{content:[{type:"text",text:O}],...M&&{structuredContent:M},isError:!C.ok}}catch(b){let h=Date.now()-g,x=b instanceof Error?`${b.name}: ${b.message}`:String(b);throw f.log.error("MCP GraphQL introspection tool invocation failed",{toolName:i,operationId:e,path:l,elapsedMs:h,err:b}),new Error(`MCP GraphQL introspection tool call failed for '${i}': ${x}`)}},"handler")});let m={type:"object",properties:{query:{type:"string",description:"The GraphQL query to execute"},variables:{type:"object",description:"Optional variables for the GraphQL query"}},required:["query"],additionalProperties:!1};this.server.addTool({name:a,description:u,validator:new sr(m,f=>typeof f=="object"&&f!==null&&"query"in f&&typeof f?.query=="string"?{success:!0,data:f,errorData:null}:{success:!1,data:null,errorMessage:"Invalid input: query field is required and must be a string",errorData:null}),handler:s(async f=>{let g=ur(),b=Date.now();try{this.debugMode&&g.log.debug("MCP GraphQL execute tool invoked",{toolName:a,operationId:e,path:l,queryPreview:f.query.substring(0,100)});let h=this.buildToolUrl(r,{}),x={query:f.query};f.variables&&(x.variables=f.variables);let v=this.buildToolRequest("POST","application/json",{body:x}),C=Date.now(),A=await g.invokeRoute(h,v),O=Date.now()-C,S=await A.text(),M=Date.now()-b;this.debugMode&&(A.ok?g.log.debug("MCP GraphQL execute tool ok response",{toolName:a,operationId:e,status:A.status,elapsedMs:M,downstreamElapsedMs:O}):g.log.debug("MCP GraphQL execute tool 'isError' response",{toolName:a,operationId:e,status:A.status,elapsedMs:M,downstreamElapsedMs:O,response:S}));let z;try{z=JSON.parse(S)}catch(Z){this.debugMode&&g.log.debug("MCP GraphQL execute structuredContent JSON parse failed",{toolName:a,body:S,parseErr:Z})}return{content:[{type:"text",text:S}],...z&&{structuredContent:z},isError:!A.ok}}catch(h){let x=Date.now()-b,v=h instanceof Error?`${h.name}: ${h.message}`:String(h);throw g.log.error("MCP GraphQL execute tool invocation failed",{toolName:a,operationId:e,path:l,elapsedMs:x,err:h}),new Error(`MCP GraphQL execute tool call failed for '${a}': ${v}`)}},"handler")}),this.debugMode&&this.context.log.debug("MCP GraphQL tools registered",{operationId:e,introspectionToolName:i,executeToolName:a,path:l})}registerToolsFromFiles(e){let r=new Set(e.map(i=>i.filePath)),n=new Set;for(let i of we.instance.routeData.routes){let a=i.metadata?.filepath;a&&r.has(a)&&(this.context.log.warn(`DEPRECATED: Registering MCP tool with operationId: "${i.raw()?.operationId}"from file: "${a}" with "options.openApiFilePaths" will soon be removed: migrate to using "options.files" configurations`),n.add(a),this.registerToolsForRawRoutedata(i,this.includeOutputSchema,this.includeStructuredContent))}let o=e.map(i=>i.filePath).filter(i=>!n.has(i));if(o.length>0)throw new Error(`MCP Tool configuration error: Could not find routes for the following file paths: ${o.join(", ")}. Verify that these OpenAPI files exist and are properly loaded in your Gateway configuration.`)}registerToolsForRawRoutedata(e,r,n){if(e.mcp?.enabled!==!1){if(!e)throw new Error("MCP Tool configuration error: Route data cannot be null or undefined.");if(!e.methods||e.methods.length===0)throw new Error(`MCP Tool configuration error: Route "${e.path}" has no HTTP methods defined. Ensure the route has at least one HTTP method (GET, POST, etc.) in your OpenAPI specification.`);if(!e.handler)throw new Error(`MCP Tool configuration error: Route "${e.path}" has no handler configured. Ensure the route has a proper handler defined in your OpenAPI specification.`);for(let o of e.methods){let i=this.generateToolNameFromSpec(e,o),a=this.generateToolDescriptionFromSpec(e,o);this.registerToolsForMethod(e,o,i,a,r,n)}}}registerToolsForMethod(e,r,n,o,i,a){if(e.handler?.export!=="mcpServerHandler")if(e.raw().requestBody?.content)for(let c of Object.keys(e.raw().requestBody?.content)){let l=Object.keys(e.raw().requestBody?.content).length>1?`${n}_${c.replace(/[^\w]/g,"_")}`:n;this.registerGenericToolSpec(l,o,e,r,c,i,a)}else this.registerGenericToolSpec(n,o,e,r,null,i,a)}registerGenericToolSpec(e,r,n,o,i,a,c){let u=this.buildUniversalValidator(n,i);if(!u)throw new Error(`MCP Tool registration error: Could not build parameter validator for ${o.toUpperCase()} ${n.path}. This may indicate an issue with the OpenAPI parameter definitions for this route.`);let l=a?this.extractOutputSchema(n):void 0;try{this.server.addTool({name:e,description:r,validator:u,...l&&{outputSchema:l},handler:s(async d=>{let p=ur(),m=Date.now();try{this.debugMode&&p.log.debug("MCP tool invoked",{toolName:e,operationId:n.raw()?.operationId,method:o,path:n.path,args:d});let f=this.buildToolUrl(n,d),g=this.buildToolRequest(o,i,d);this.debugMode&&p.log.debug("MCP tool downstream call",{toolName:e,url:f,method:o,headers:g.headers?Object.keys(g.headers).join(", "):"",bodyPreview:d.body}),p.analyticsContext.addAnalyticsEvent(1,Oe.MCP_TOOL_USAGE,{toolName:e,toolPath:n.path,toolMethod:o,toolOperationId:n.raw()?.operationId??"unknown"});let b=Date.now(),h=await p.invokeRoute(f,g),x=Date.now()-b,v=await h.text(),C;if(c)try{C=JSON.parse(v)}catch(O){this.debugMode&&p.log.debug("MCP tool structuredContent JSON parse failed",{toolName:e,body:v,parseErr:O})}let A=Date.now()-m;return this.debugMode&&(h.ok?p.log.debug("MCP tool ok response",{toolName:e,operationId:n.raw()?.operationId,status:h.status,elapsedMs:A,downstreamElapsedMs:x}):p.log.debug("MCP tool 'isError' response",{toolName:e,operationId:n.raw()?.operationId,status:h.status,elapsedMs:A,downstreamElapsedMs:x,response:v})),{content:[{type:"text",text:v}],...C&&{structuredContent:C},isError:!h.ok}}catch(f){let g=Date.now()-m,b=f instanceof Error?`${f.name}: ${f.message}`:String(f);return p.log.error("MCP server tool invocation failed",{toolName:e,operationId:n.raw()?.operationId,method:o,path:n.path,elapsedMs:g,err:f}),{content:[{type:"text",text:`MCP tool call failed for tool '${e}': ${b}`}],isError:!0}}},"handler")}),this.debugMode&&this.context.log.debug("MCP tool registered",{toolName:e,method:o.toUpperCase(),path:n.path,operationId:n.raw()?.operationId,contentType:i||"none",includeOutputSchema:a,includeStructuredContent:c,hasValidator:!!u,hasOutputSchema:!!l})}catch(d){throw new Error(`Failed to add tool ${o} ${n.path}`,d)}}async registerProxyTools(e){let r=new Set;for(let n of e){if(n.enabled===!1){this.debugMode&&this.context.log.debug("Skipping disabled origin",{origin:n.name});continue}let o=n.toolNamePrefix??"";this.debugMode&&this.context.log.debug("Registering origin tools",{origin:n.name,baseUrl:n.baseUrl,toolCount:n.tools.length,toolNamePrefix:o||"none",tools:n.tools});for(let i of n.tools){let a=`${o}${i.name}`;if(r.has(a))throw new Error(`MCP origin configuration error: Tool name conflict detected. The name "${a}" is already in use. Consider using different tool names or toolNamePrefix for origin "${n.name}".`);r.add(a);let u=Cr.createObjectValidatorBuilder(i.inputSchema).build();try{let l=new ia(n.baseUrl,i.name,this.debugMode,n.headers);this.server.addTool({name:a,description:i.description,validator:u,handler:s(async d=>await l.execute(d),"handler")}),this.debugMode&&this.context.log.debug("origin tool registered",{localToolName:a,originToolName:i.name,origin:n.name,baseUrl:n.baseUrl})}catch(l){throw new Error(`Failed to register origin tool ${a} from ${n.name}`,{cause:l})}}}this.debugMode&&e.length>0&&this.context.log.debug("origin tool registration complete",{totaloOigins:e.length,totalOriginTools:r.size,originToolNames:Array.from(r)})}buildToolUrl(e,r){return new Js(e).build(r.pathParams,r.queryParams)}buildToolRequest(e,r,n){let o=this.buildToolHeaders(e,r,n),i={method:e,headers:o};return this.shouldIncludeBody(e,r,n)&&(i.body=this.serializeBody(n.body,r)),i}buildToolHeaders(e,r,n){let o={...ea()};return n.headers&&Object.entries(n.headers).forEach(([i,a])=>{o[i.toLowerCase()]=a}),r&&n.body!==void 0&&(o["content-type"]=r),this.isBodyMethod(e||"")&&n.body!==void 0&&!o["content-type"]&&(o["content-type"]="application/json"),o}shouldIncludeBody(e,r,n){return n.body===void 0?!1:this.isBodyMethod(e)?!0:r!==null}isBodyMethod(e){return["POST","PUT","PATCH"].includes(e.toUpperCase())}serializeBody(e,r){return JSON.stringify(e)}buildUniversalValidator(e,r){try{let o=Cr.createValidatorBuilder(e,r).build();return this.debugMode&&this.context.log.debug("MCP validator built successfully",{method:e.methods?.[0],path:e.path,contentType:r||"none",operationId:e.raw()?.operationId}),o}catch(n){let o=n instanceof Error?n.message:String(n);throw this.context.log.warn("MCP validator build failed",{method:e.methods?.[0],path:e.path,contentType:r||"none",operationId:e.raw()?.operationId,error:o}),n}}getRouteDataForOptions(e){let{routes:r}=we.instance.routeData,n=!!e.operationId,o=!!e.path;if(!n&&!o)throw new Error("MCP Tool configuration error: Either 'operationId' or 'path' must be provided in your tool specification.");return n?r.find(i=>i?.raw().operationId===e.operationId&&i?.methods?.some(a=>a.toUpperCase()===e.method.toUpperCase())):r.find(i=>i?.path===e.path&&i?.methods?.some(a=>a.toUpperCase()===e.method.toUpperCase()))}extractOutputSchema(e){try{let r=e.raw(),n=r?.responses;if(!n){this.context.log.warn("No responses found in OpenAPI spec for outputSchema",{path:e.path,operationId:r?.operationId});return}for(let o of Object.keys(n))if(o.startsWith("2")){let a=n[o]?.content;if(a){for(let c of["application/json","application/json; charset=utf-8"])if(a[c]?.schema){let u=a[c].schema;return this.debugMode&&this.context.log.debug("Output schema extracted successfully",{path:e.path,operationId:r?.operationId,statusCode:o,contentType:c,schemaKeys:u&&typeof u=="object"?Object.keys(u).join(", "):"none"}),u}}}this.debugMode&&this.context.log.debug("No OpenAPI spec 2xx responses fond for outputSchema",{path:e.path,operationId:r?.operationId,statusCodes:Object.keys(n).join(", ")});return}catch(r){this.context.log.warn("Failed to extract outputSchema",{path:e.path,operationId:e.raw()?.operationId,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0});return}}};async function gE(t,e){if(R("handler.mcp-server"),e.route.methods.some(a=>a.toUpperCase()!=="POST"))throw new w(`Invalid route config: mcpServerHandler may only use POST. Route '${e.route.path}' declares methods: [${e.route.methods.join(", ")}]`);let r={};t.headers.forEach((a,c)=>{r[c]=a});let n=e.route?.handler?.options??{},o=e.route?.path??"unknown-route",i=await cn.getInstance({opts:n,context:e,key:o});return Ys(r,e,()=>i.handleRequest(t,e))}s(gE,"mcpServerHandler");var sv=10,av=3e4,Er=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,r){if(typeof r=="number"){let n=r;this.#n=n*1e3,this.#o=av,this.#r=sv}else{let n=r;this.#n=n.ttlSeconds*1e3,this.#o=n.loaderTimeoutSeconds?n.loaderTimeoutSeconds*1e3:av,this.#r=sv}this.#t=e}#s(e){return e.expiry<=new Date}#c(e){let r=this.#i[e];return!(r===void 0||r===0)}#u(e){let r=this.#e.get(e);if(r&&!this.#s(r))return r.data}async get(e){let r=this.#u(e);if(r)return this.#l(e),r;if(this.#c(e))try{await hE(()=>this.#u(e)!==void 0||!this.#c(e),this.#o+this.#r+1,this.#r);let n=this.#u(e);if(n)return n}catch{}return this.#a(e)}#l(e){if(!this.#c(e)){let r=this.#a(e);Jt().waitUntil(r)}}async#a(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let r=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(r===void 0)throw new w(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:r,expiry:new Date(Date.now()+this.#n)}),r}finally{this.#i[e]--}}};async function hE(t,e,r){let n=Date.now();for(;!t();){let o=Date.now()-n;if(o>e)throw new w(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(r)}}s(hE,"waitUntilTrue");var yE={ttlSeconds:600,loaderTimeoutSeconds:30},cv=new Er(async()=>{let t=P.instance.zuploEdgeApiUrl;if(!t)throw new w("Zuplo edge API URL not configured");let e=P.instance.authApiJWT;if(!e)throw new w("Zuplo auth API JWT not configured");let r=P.instance.deploymentName;if(!r)throw new w("Deployment name not configured");let n=ke.ZUPLO_SERVICE_BUCKET_ID;if(!n)throw new w("ZUPLO_SERVICE_BUCKET_ID env not configured");let o=`${t}/zups/v1/buckets/${n}/mcp/resolve`,i=await j.fetch(o,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-Agent":P.instance.systemUserAgent,"Content-Type":"application/json"},body:JSON.stringify({deployment:r})});if(!i.ok){let u=await i.text().catch(()=>"");throw new w(`Failed to resolve MCP gateway configuration from ${o}: ${i.status} ${i.statusText}${u?` - ${u}`:""}`)}let c=(await i.json()).mcpGatewayConfig;if(!c||typeof c!="object")throw new w("Invalid MCP gateway configuration: not an object");if(!Array.isArray(c.servers))throw new w("Invalid MCP gateway configuration: servers must be an array");return c},yE);async function bE(t,e){if(R("handler.mcp-gateway"),e.route.methods.some(f=>f.toUpperCase()!=="POST"))throw new w(`Invalid route config: mcpGatewayHandler may only use POST. Route '${e.route.path}' declares methods: [${e.route.methods.join(", ")}]`);let r=e.route?.handler?.options??{},n=await cv.get("NO_KEY");e.log.debug(`Loaded configuration with ${n.servers?.length??0} servers`);let o=t.params.slug;if(!o)throw new Error("No MCP gateway slug provided in request");let i=n.servers.find(f=>f.slug===o);if(!i)throw new Error(`No MCP server configuration found for slug: ${o}`);let a={name:i.name,debugMode:r.debugMode},u=new TextEncoder().encode(JSON.stringify(i)),l=await crypto.subtle.digest("SHA-256",u),d=new Uint8Array(l),p=Array.from(d).map(f=>f.toString(16).padStart(2,"0")).join(""),m=`mcp-origin-config:${o}:${p.substring(0,32)}`;return e.log.debug(`Using MCP server key: ${m}`),wE({request:t,context:e,opts:a,key:m,origins:i.origins})}s(bE,"mcpGatewayHandler");async function wE({request:t,context:e,opts:r,key:n,origins:o}){let i={};t.headers.forEach((c,u)=>{i[u]=c});let a=await cn.getInstance({opts:r,context:e,key:n,origins:o});return Ys(i,e,()=>a.handleRequest(t,e))}s(wE,"mcpServerProxyHandler");function Be(t,e){let r={};for(let n in t){let o=t[n];Array.isArray(o)||(o=[o]);for(let i of o)if(i.param){if(n in e){let a=vE(n,e,i);a!==void 0&&uv(r,i.param,a)}else if(i?.required&&i.default!==void 0){let a=typeof i.default=="function"?i.default(e):i.default;uv(r,i.param,a)}}}return r}s(Be,"validateAndTransformRequest");function vE(t,e,r){let n=e[t];return r.transform&&(n=r.transform(e)),n===void 0&&r.default!==void 0&&(n=typeof r.default=="function"?r.default(e):r.default),typeof n=="number"&&(r.min!==void 0&&n<r.min&&(n=r.min),r.max!==void 0&&n>r.max&&(n=r.max)),n}s(vE,"getValue");function uv(t,e,r){if(r===void 0)return;let n=e.split("."),o=t;for(let i=0;i<n.length-1;i++){let a=n[i];o[a]||(o[a]={}),o=o[a]}o[n[n.length-1]]=r}s(uv,"setNestedProperty");async function _r(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(r)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(_r,"sha256");var lv=new Map;async function xe(t,e,r){let n,o=`${t}-${e}`,i=lv.get(o);return i!==void 0?n=i:(n=`zuplo-policy-${await _r(JSON.stringify({policyName:t,options:r}))}`,lv.set(t,n)),n}s(xe,"getPolicyCacheName");var xE=60,RE={openai:{"gpt-5":{model:"gpt-5",kind:"completions",status:"active",inputCostPerToken:125e-8,outputCostPerToken:1e-5},"gpt-5-nano":{model:"gpt-5-nano",kind:"completions",status:"active",inputCostPerToken:5e-8,outputCostPerToken:4e-7},"gpt-5-mini":{model:"gpt-5-mini",kind:"completions",status:"active",inputCostPerToken:25e-8,outputCostPerToken:2e-6},"gpt-5-nano-2025-08-07":{model:"gpt-5-nano-2025-08-07",kind:"completions",status:"active",inputCostPerToken:5e-8,outputCostPerToken:4e-7},"gpt-5-mini-2025-08-07":{model:"gpt-5-mini-2025-08-07",kind:"completions",status:"active",inputCostPerToken:25e-8,outputCostPerToken:2e-6},"gpt-5-2025-08-07":{model:"gpt-5-2025-08-07",kind:"completions",status:"active",inputCostPerToken:125e-8,outputCostPerToken:1e-5},"gpt-5-chat-latest":{model:"gpt-5-chat-latest",kind:"completions",status:"active",inputCostPerToken:125e-8,outputCostPerToken:1e-5},"gpt-4o":{model:"gpt-4o",kind:"completions",status:"active",inputCostPerToken:25e-7,outputCostPerToken:1e-5},"gpt-4o-2024-11-20":{model:"gpt-4o-2024-11-20",kind:"completions",status:"active",inputCostPerToken:25e-7,outputCostPerToken:1e-5},"gpt-4o-2024-08-06":{model:"gpt-4o-2024-08-06",kind:"completions",status:"active",inputCostPerToken:25e-7,outputCostPerToken:1e-5},"gpt-4o-2024-05-13":{model:"gpt-4o-2024-05-13",kind:"completions",status:"active",inputCostPerToken:5e-6,outputCostPerToken:15e-6},"gpt-4o-mini":{model:"gpt-4o-mini",kind:"completions",status:"active",inputCostPerToken:15e-8,outputCostPerToken:6e-7},"gpt-4o-mini-2024-07-18":{model:"gpt-4o-mini-2024-07-18",kind:"completions",status:"active",inputCostPerToken:15e-8,outputCostPerToken:6e-7},"gpt-4.1":{model:"gpt-4.1",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:8e-6},"gpt-4.1-mini":{model:"gpt-4.1-mini",kind:"completions",status:"active",inputCostPerToken:4e-7,outputCostPerToken:16e-7},"gpt-4.1-nano":{model:"gpt-4.1-nano",kind:"completions",status:"active",inputCostPerToken:1e-7,outputCostPerToken:4e-7},"gpt-4-turbo":{model:"gpt-4-turbo",kind:"completions",status:"active",inputCostPerToken:1e-5,outputCostPerToken:3e-5},"gpt-4-turbo-2024-04-09":{model:"gpt-4-turbo-2024-04-09",kind:"completions",status:"active",inputCostPerToken:1e-5,outputCostPerToken:3e-5},"gpt-4-turbo-preview":{model:"gpt-4-turbo-preview",kind:"completions",status:"active",inputCostPerToken:1e-5,outputCostPerToken:3e-5},"gpt-4-0125-preview":{model:"gpt-4-0125-preview",kind:"completions",status:"active",inputCostPerToken:1e-5,outputCostPerToken:3e-5},"gpt-4-1106-preview":{model:"gpt-4-1106-preview",kind:"completions",status:"active",inputCostPerToken:1e-5,outputCostPerToken:3e-5},"gpt-4-vision-preview":{model:"gpt-4-vision-preview",kind:"completions",status:"deprecated",inputCostPerToken:1e-5,outputCostPerToken:3e-5},"gpt-4":{model:"gpt-4",kind:"completions",status:"active",inputCostPerToken:3e-5,outputCostPerToken:6e-5},"gpt-4-0613":{model:"gpt-4-0613",kind:"completions",status:"active",inputCostPerToken:3e-5,outputCostPerToken:6e-5},"gpt-4-32k":{model:"gpt-4-32k",kind:"completions",status:"deprecated",inputCostPerToken:6e-5,outputCostPerToken:12e-5},"gpt-4-32k-0613":{model:"gpt-4-32k-0613",kind:"completions",status:"deprecated",inputCostPerToken:6e-5,outputCostPerToken:12e-5},"gpt-3.5-turbo":{model:"gpt-3.5-turbo",kind:"completions",status:"active",inputCostPerToken:5e-7,outputCostPerToken:15e-7},"gpt-3.5-turbo-0125":{model:"gpt-3.5-turbo-0125",kind:"completions",status:"active",inputCostPerToken:5e-7,outputCostPerToken:15e-7},"gpt-3.5-turbo-1106":{model:"gpt-3.5-turbo-1106",kind:"completions",status:"active",inputCostPerToken:1e-6,outputCostPerToken:2e-6},"gpt-3.5-turbo-16k":{model:"gpt-3.5-turbo-16k",kind:"completions",status:"active",inputCostPerToken:3e-6,outputCostPerToken:4e-6},"text-embedding-3-large":{model:"text-embedding-3-large",kind:"embeddings",status:"active",inputCostPerToken:13e-8,outputCostPerToken:0},"text-embedding-3-small":{model:"text-embedding-3-small",kind:"embeddings",status:"active",inputCostPerToken:2e-8,outputCostPerToken:0},"text-embedding-ada-002":{model:"text-embedding-ada-002",kind:"embeddings",status:"active",inputCostPerToken:1e-7,outputCostPerToken:0}},anthropic:{"claude-opus-4-20250514":{model:"claude-opus-4-20250514",kind:"completions",status:"active",inputCostPerToken:15e-6,outputCostPerToken:75e-6},"claude-sonnet-4-20250514":{model:"claude-sonnet-4-20250514",kind:"completions",status:"active",inputCostPerToken:3e-6,outputCostPerToken:15e-6},"claude-3-7-sonnet-20250219":{model:"claude-3-7-sonnet-20250219",kind:"completions",status:"active",inputCostPerToken:3e-6,outputCostPerToken:15e-6},"claude-3-5-sonnet-20241022":{model:"claude-3-5-sonnet-20241022",kind:"completions",status:"active",inputCostPerToken:3e-6,outputCostPerToken:15e-6},"claude-3-5-sonnet-20240620":{model:"claude-3-5-sonnet-20240620",kind:"completions",status:"active",inputCostPerToken:3e-6,outputCostPerToken:15e-6},"claude-3-5-haiku-20241022":{model:"claude-3-5-haiku-20241022",kind:"completions",status:"active",inputCostPerToken:8e-7,outputCostPerToken:4e-6},"claude-3-opus-20240229":{model:"claude-3-opus-20240229",kind:"completions",status:"active",inputCostPerToken:15e-6,outputCostPerToken:75e-6},"claude-3-haiku-20240307":{model:"claude-3-haiku-20240307",kind:"completions",status:"active",inputCostPerToken:25e-8,outputCostPerToken:125e-8},"claude-2.1":{model:"claude-2.1",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:8e-6},"claude-2.0":{model:"claude-2.0",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:8e-6},"claude-instant-1.2":{model:"claude-instant-1.2",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:8e-6}},google:{"gemini-2.0-flash-exp":{model:"gemini-2.0-flash-exp",kind:"completions",status:"active",inputCostPerToken:15e-8,outputCostPerToken:6e-7},"gemini-2.0-flash":{model:"gemini-2.0-flash",kind:"completions",status:"active",inputCostPerToken:1e-7,outputCostPerToken:4e-7},"gemini-2.0-flash-lite":{model:"gemini-2.0-flash-lite",kind:"completions",status:"active",inputCostPerToken:75e-9,outputCostPerToken:3e-7},"gemini-2.5-pro":{model:"gemini-2.5-pro",kind:"completions",status:"active",inputCostPerToken:125e-8,outputCostPerToken:1e-5},"gemini-pro":{model:"gemini-pro",kind:"completions",status:"active",inputCostPerToken:5e-7,outputCostPerToken:15e-7},"gemini-embedding-001":{model:"gemini-embedding-001",kind:"embeddings",status:"active",inputCostPerToken:15e-8,outputCostPerToken:0}},mistral:{"mistral-large-latest":{model:"mistral-large-latest",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:6e-6},"mistral-large-2411":{model:"mistral-large-2411",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:6e-6},"mistral-large-2407":{model:"mistral-large-2407",kind:"completions",status:"active",inputCostPerToken:3e-6,outputCostPerToken:9e-6},"mistral-medium-latest":{model:"mistral-medium-latest",kind:"completions",status:"active",inputCostPerToken:4e-7,outputCostPerToken:2e-6},"mistral-small-latest":{model:"mistral-small-latest",kind:"completions",status:"active",inputCostPerToken:1e-7,outputCostPerToken:3e-7},"mistral-small-2409":{model:"mistral-small-2409",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:8e-6},"open-mistral-7b":{model:"open-mistral-7b",kind:"completions",status:"active",inputCostPerToken:25e-8,outputCostPerToken:25e-8},"open-mixtral-8x7b":{model:"open-mixtral-8x7b",kind:"completions",status:"active",inputCostPerToken:7e-7,outputCostPerToken:7e-7},"open-mixtral-8x22b":{model:"open-mixtral-8x22b",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:6e-6},"open-mistral-nemo":{model:"open-mistral-nemo",kind:"completions",status:"active",inputCostPerToken:3e-7,outputCostPerToken:3e-7},"codestral-latest":{model:"codestral-latest",kind:"completions",status:"active",inputCostPerToken:1e-6,outputCostPerToken:3e-6},"ministral-3b-latest":{model:"ministral-3b-latest",kind:"completions",status:"active",inputCostPerToken:4e-8,outputCostPerToken:4e-8},"ministral-8b-latest":{model:"ministral-8b-latest",kind:"completions",status:"active",inputCostPerToken:2e-6,outputCostPerToken:8e-6},"mistral-embed":{model:"mistral-embed",kind:"embeddings",status:"active",inputCostPerToken:1e-7,outputCostPerToken:0}}};async function ft(t){let e=Q.getLogger(t),r=await xe("supported-models","models",{}),n=new be(r,t),o=await n.get("models");if(o)return e.info("Using cached supported models data",{providersCount:Object.keys(o.modelsByProvider).length,providers:Object.keys(o.modelsByProvider)}),o.modelsByProvider;let i=new Headers({"content-type":"application/json"});je(i,t.requestId);let a=`${P.instance.zuploEdgeApiUrl}/v1/buckets/${ke.ZUPLO_SERVICE_BUCKET_ID}/providers`,c=await Te({retryDelayMs:100,retries:5},a,{method:"GET",headers:i}),u;if(c.status!==200){try{let d=await c.text(),p=JSON.parse(d);e.error("Gateway service unavailable, using fallback models",p)}catch{e.error("Gateway service unavailable, using fallback models")}t.log.info("AI Gateway: Using fallback model data due to service unavailability"),u=RE}else{let d=await c.json();e.info("Gateway service response received",{providersCount:Object.keys(d.data).length,providers:Object.keys(d.data),totalModels:Object.values(d.data).reduce((p,m)=>p+m.length,0)}),u={};for(let[p,m]of Object.entries(d.data)){let f=p.toLowerCase();u[f]={};for(let g of m)u[f][g.model]=g}}let l={modelsByProvider:u};return n.put("models",l,xE),u}s(ft,"getSupportedModels");function _t(t,e,r,n,o,i){let a=e.toLowerCase(),c=o[a];if(!c)return i.warn("Provider not found in supported models list",{provider:e,model:t}),0;let u=c[t];if(!u)return i.warn("Model not found in supported models list for provider",{provider:e,model:t}),0;let l=r*u.inputCostPerToken,d=n*u.outputCostPerToken;return l+d}s(_t,"calculateModelCost");function dv(t,e,r,n){let o=e.toLowerCase(),i=n[o];if(!i)return!1;let a=i[t];return a?a.kind===r&&a.status==="active":!1}s(dv,"isModelSupported");function pv(t,e,r){let n=t.toLowerCase(),o=r[n];return o?Object.values(o).filter(i=>i.kind===e&&i.status==="active").map(i=>i.model):[]}s(pv,"getModelsByProviderAndKind");var xm=class{static{s(this,"GatewayServiceClient")}baseUrl;constructor(e){this.baseUrl=e??P.instance.zuploEdgeApiUrl}async fetchCurrentMeters(e,r){let n=`${this.baseUrl}/v1/hierarchical-quota/${e}`,o=new Headers({"Content-Type":"application/json"});je(o,r.requestId);let i=await fetch(n,{method:"GET",headers:o});if(!i.ok)throw new le(`Failed to fetch meters: ${i.status} ${i.statusText}`);return await i.json()}async checkHierarchicalQuotaLimits(e,r){let n=`${this.baseUrl}/v1/hierarchical-quota/${e}/limits`,o=new Headers({"Content-Type":"application/json"});je(o,r.requestId);let i=await fetch(n,{method:"GET",headers:o});if(!i.ok)throw new le(`Failed to check quota limits: ${i.status} ${i.statusText}`);return await i.json()}async incrementMeters(e,r,n){let o=`${this.baseUrl}/v1/hierarchical-quota/${e}`,i=new Headers({"Content-Type":"application/json"});je(i,n.requestId);let a=await fetch(o,{method:"POST",headers:i,body:JSON.stringify({increments:r})});if(!a.ok)throw new le(`Failed to increment meters: ${a.status} ${a.statusText}`)}},vm=null,sa={get instance(){return vm===null&&(vm=new xm),vm}};var mv=Ne("zuplo:policies:AIGatewayMeteringInboundPolicy"),fv=Symbol("ai-gateway-meter-increments"),st=class t extends Re{static{s(this,"AIGatewayMeteringInboundPolicy")}static setIncrements(e,r){pe.set(e,fv,r)}static getIncrements(e){return pe.get(e,fv)??{}}constructor(e,r){super(e,r),R("policy.inbound.ai-gateway-metering-inbound")}async handler(e,r){let n=Date.now(),o=Q.getLogger(r),i=s((a,c)=>{if(this.options.throwOnFailure)throw new le(a,{cause:c});o.error(c,a)},"throwOrLog");try{let a=e.user?.configuration;if(!a)throw new w(`AIGatewayMeteringInboundPolicy '${this.policyName}' - No configuration found in request.user. Ensure ai-gateway-inbound policy runs first.`);let c=a;if(!c.id)throw new w(`AIGatewayMeteringInboundPolicy '${this.policyName}' - Configuration ID not found.`);let u=await this.fetchCurrentMeters(c.id,r,o),l=this.checkWarnings(c,u);for(let p of l)r.analyticsContext.addAnalyticsEvent(1,Oe.AI_GATEWAY_WARNING_COUNT,{type:`quota-${p.type}-${p.period}`,configId:c.id});let d=await this.checkHierarchicalQuotaLimits(c.id,r,o);return d.violation?(r.analyticsContext.addAnalyticsEvent(1,Oe.AI_GATEWAY_BLOCKED_COUNT,{type:`quota-${d.violation.meter}-${d.violation.period}`,configId:c.id}),this.createHierarchicalQuotaExceededResponse(e,r,d.violation)):(r.addResponseSendingFinalHook(async()=>{try{let p=t.getIncrements(r);mv(`AIGatewayMeteringInboundPolicy '${this.policyName}' - increments ${JSON.stringify(p)}`),Object.keys(p).length>0&&await t.incrementMetersInternal(c.id,p,r,o)}catch(p){i(`AIGatewayMeteringInboundPolicy '${this.policyName}' - Failed to increment meters`,p)}}),e)}catch(a){if(a instanceof w)throw a;return i(`AIGatewayMeteringInboundPolicy '${this.policyName}' - Error`,a),e}finally{let a=Date.now()-n;mv(`AIGatewayMeteringInboundPolicy '${this.policyName}' - latency ${a}ms`)}}async fetchCurrentMeters(e,r,n){try{return await sa.instance.fetchCurrentMeters(e,r)}catch(o){throw n.error(o,`AIGatewayMeteringInboundPolicy '${this.policyName}' - Failed to fetch meters`),o}}async checkHierarchicalQuotaLimits(e,r,n){try{return await sa.instance.checkHierarchicalQuotaLimits(e,r)}catch(o){throw n.error(o,`AIGatewayMeteringInboundPolicy '${this.policyName}' - Failed to check hierarchical quota limits`),o}}static async incrementMeters(e,r,n){let o=Q.getLogger(n);return t.incrementMetersInternal(e,r,n,o)}static async incrementMetersInternal(e,r,n,o){try{await sa.instance.incrementMeters(e,r,n)}catch(i){throw o.error(i,"AIGatewayMeteringInboundPolicy - Failed to increment meters"),i}}checkWarnings(e,r){let n=[];for(let[o,i]of Object.entries(e.limits)){if(!i)continue;let a=r.meters[o];if(!a)continue;let c=this.checkQuotaWarning(i.daily,a.daily,o,"daily");c&&n.push(c);let u=this.checkQuotaWarning(i.monthly,a.monthly,o,"monthly");u&&n.push(u)}return n}checkQuotaWarning(e,r,n,o){if(!e?.warning?.enabled||!e?.warning?.threshold||!e?.limit)return null;let i=e.warning.threshold/100*e.limit;return r>=i?{type:n,period:o}:null}createHierarchicalQuotaExceededResponse(e,r,n){let o=`${n.period} ${n.meter} quota exceeded in configuration '${n.configLabel}'. Limit: ${n.limit}, Current: ${n.currentUsage}`;return D.tooManyRequests(e,r,{detail:o})}};async function lr(t,e){if(!P.instance.remoteLogURL){Q.getLogger(t).debug("Remote log URL is not configured, skipping analytics");return}t.analyticsContext.addAnalyticsEvent(parseFloat(e.cost.toFixed(10)),Oe.AI_GATEWAY_COST_SUM,{model:e.model,provider:e.provider,configId:e.configId}),t.analyticsContext.addAnalyticsEvent(1,Oe.AI_GATEWAY_REQUEST_COUNT,{model:e.model,provider:e.provider,configId:e.configId}),t.analyticsContext.addAnalyticsEvent(e.promptTokens,Oe.AI_GATEWAY_TOKEN_SUM,{model:e.model,provider:e.provider,configId:e.configId,tokenType:"prompt"}),t.analyticsContext.addAnalyticsEvent(e.completionTokens,Oe.AI_GATEWAY_TOKEN_SUM,{model:e.model,provider:e.provider,configId:e.configId,tokenType:"completion"});let r=t.analyticsContext.flushAnalyticsEvents();new Fr(t,{endpoint:`${P.instance.remoteLogURL}/v2/analytics`}).pushEvents(r)}s(lr,"sendStreamAnalytics");var gv={model:{param:"model",required:!0,default:"gpt-4o-mini"},messages:{param:"messages",required:!0},temperature:{param:"temperature",default:1,min:0,max:2},top_p:{param:"top_p",default:1,min:0,max:1},n:{param:"n",default:1,min:1,max:128},stream:{param:"stream",default:!1},stop:{param:"stop"},max_tokens:{param:"max_tokens",min:0},presence_penalty:{param:"presence_penalty",default:0,min:-2,max:2},frequency_penalty:{param:"frequency_penalty",default:0,min:-2,max:2},logit_bias:{param:"logit_bias"},user:{param:"user"},seed:{param:"seed"},functions:{param:"functions"},function_call:{param:"function_call"},tools:{param:"tools"},tool_choice:{param:"tool_choice"},parallel_tool_calls:{param:"parallel_tool_calls"},response_format:{param:"response_format"},logprobs:{param:"logprobs",default:!1},top_logprobs:{param:"top_logprobs",min:0,max:20},max_completion_tokens:{param:"max_completion_tokens"},service_tier:{param:"service_tier"},stream_options:{param:"stream_options"}},PE={model:{param:"model",required:!0,default:"text-embedding-3-small"},input:{param:"input",required:!0},user:{param:"user"},dimensions:{param:"dimensions"},encoding_format:{param:"encoding_format",default:"float"}},aa=class{static{s(this,"OpenAIProvider")}name="openai";async chatComplete(e,r){let n=Be(gv,e),o=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let a=await o.json();throw new Error(`OpenAI API error: ${a.error?.message||"Unknown error"}`)}return{...await o.json(),provider:"openai"}}async chatCompleteStream(e,r,n){let o=Be(gv,{...e,stream:!0,stream_options:{include_usage:!0}}),i=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok){let m=await i.json();throw new Error(`OpenAI API error: ${m.error?.message||"Unknown error"}`)}if(!i.body)throw new Error("No response body received from OpenAI API");let a=n.custom.userContext,c="",u=new TextDecoder,l=new TransformStream({transform(m,f){f.enqueue(m);let g=u.decode(m);c+=g,!c.includes('"usage"')&&c.length>4096&&(c=c.slice(-32));let b;for(;(b=c.indexOf(`
201
201
 
202
202
  `))!==-1;){let h=c.slice(0,b);if(c=c.slice(b+2),!h.includes('"usage"'))continue;let x="";for(let v of h.split(`
203
203
  `))if(v.startsWith("data: ")){x=v.slice(6);break}if(x&&x.trim()!=="[DONE]")try{let v=JSON.parse(x);if(v.usage&&v.usage.total_tokens>0){if(a){let C=v.usage;n.waitUntil((async()=>{try{let A=C.prompt_tokens||0,O=C.completion_tokens||0,S=C.total_tokens||0,M=Q.getLogger(n),z=await ft(n),Z=_t(e.model,"openai",A,O,z,M);M.info("OpenAI streaming usage tracked",{userId:a.sub,promptTokens:A,completionTokens:O,totalTokens:S,model:e.model,provider:"openai",cost:Z});let $=a.configuration?.id;if($){let E={requests:1,tokens:S,costs:Z};await st.incrementMeters($,E,n)}else n.log.warn("No configuration ID found for streaming usage metering");await lr(n,{promptTokens:A,completionTokens:O,model:e.model,provider:"openai",configId:$||"unknown",cost:Z})}catch(A){n.log.error("Error processing OpenAI streaming token usage",{error:A})}})())}c="";break}}catch{}}if(c.length>8192){let h=c.lastIndexOf(`