@zuplo/runtime 6.70.36 → 6.70.39

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.
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{d as Ze,f as Qa,g as Ya}from"./chunk-TOF2KNST.js";import{a as ce,b as jh}from"./chunk-A2CSR4RF.js";import{$ as ye,A as bi,B as vi,C as wi,D as xh,E as Rh,F as Ih,G as Ph,H as Sh,I as Th,J as kh,K as Eh,L as xi,M as Ch,N as _h,O as Ri,P as Ii,Q as Oh,R as Pi,S as Si,T as Ah,U as $h,V as Lh,W as Nh,X as Mh,Y as Dh,Z as Uh,_ as Ti,a as s,aa as z,b as K,ba as R,c as rI,ca as T,d as Ht,da as D,e as nI,f as gi,g as Ce,h as sh,i as zr,j as ah,k as Zr,l as ch,m as uh,n as lh,o as dh,p as ph,q as mh,r as fh,s as gh,t as hh,u as yh,v as bh,w as vh,x as wh,y as hi,z as yi}from"./chunk-2VLXJLVI.js";var Py=rI(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.parse=FI;Hi.serialize=HI;var DI=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,UI=/^[\u0021-\u003A\u003C-\u007E]*$/,jI=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,zI=/^[\u0020-\u003A\u003D-\u007E]*$/,ZI=Object.prototype.toString,qI=(()=>{let t=s(function(){},"C");return t.prototype=Object.create(null),t})();function FI(t,e){let r=new qI,o=t.length;if(o<2)return r;let n=e?.decode||BI,i=0;do{let a=t.indexOf("=",i);if(a===-1)break;let c=t.indexOf(";",i),u=c===-1?o:c;if(a>u){i=t.lastIndexOf(";",a-1)+1;continue}let l=Ry(t,i,a),d=Iy(t,a,l),p=t.slice(l,d);if(r[p]===void 0){let m=Ry(t,a+1,u),y=Iy(t,u,m),g=n(t.slice(m,y));r[p]=g}i=u+1}while(i<o);return r}s(FI,"parse");function Ry(t,e,r){do{let o=t.charCodeAt(e);if(o!==32&&o!==9)return e}while(++e<r);return r}s(Ry,"startIndex");function Iy(t,e,r){for(;e>r;){let o=t.charCodeAt(--e);if(o!==32&&o!==9)return e+1}return r}s(Iy,"endIndex");function HI(t,e,r){let o=r?.encode||encodeURIComponent;if(!DI.test(t))throw new TypeError(`argument name is invalid: ${t}`);let n=o(e);if(!UI.test(n))throw new TypeError(`argument val is invalid: ${e}`);let i=t+"="+n;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(!jI.test(r.domain))throw new TypeError(`option domain is invalid: ${r.domain}`);i+="; Domain="+r.domain}if(r.path){if(!zI.test(r.path))throw new TypeError(`option path is invalid: ${r.path}`);i+="; Path="+r.path}if(r.expires){if(!GI(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(HI,"serialize");function BI(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}s(BI,"decode");function GI(t){return ZI.call(t)==="[object Date]"}s(GI,"isDate")});function E(t,e,r){function o(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)d in c||Object.defineProperty(c,d,{value:a.prototype[d].bind(c)});c._zod.constr=a,c._zod.def=u}s(o,"init");let n=r?.Parent??Object;class i extends n{static{s(this,"Definition")}}Object.defineProperty(i,"name",{value:t});function a(c){var u;let l=r?.Parent?new i:this;o(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:o}),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 Fe(t){return t&&Object.assign(co,t),co}var Xc,eu,Ut,co,on=K(()=>{Xc=Object.freeze({status:"aborted"});s(E,"$constructor");eu=Symbol("zod_brand"),Ut=class extends Error{static{s(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},co={};s(Fe,"config")});var W={};Ht(W,{BIGINT_FORMAT_RANGES:()=>lu,Class:()=>ru,NUMBER_FORMAT_RANGES:()=>uu,aborted:()=>kr,allowsEval:()=>su,assert:()=>BP,assertEqual:()=>ZP,assertIs:()=>FP,assertNever:()=>HP,assertNotEqual:()=>qP,assignProp:()=>iu,cached:()=>po,captureStackTrace:()=>cs,cleanEnum:()=>oS,cleanRegex:()=>mo,clone:()=>mt,createTransparentProxy:()=>QP,defineLazy:()=>Se,esc:()=>Tr,escapeRegex:()=>Jt,extend:()=>eS,finalizeIssue:()=>ft,floatSafeRemainder:()=>ou,getElementAtPath:()=>GP,getEnumValues:()=>lo,getLengthableOrigin:()=>ho,getParsedType:()=>KP,getSizableOrigin:()=>go,isObject:()=>sn,isPlainObject:()=>an,issue:()=>du,joinValues:()=>N,jsonStringifyReplacer:()=>nu,merge:()=>tS,normalizeParams:()=>H,nullish:()=>cr,numKeys:()=>WP,omit:()=>XP,optionalKeys:()=>cu,partial:()=>rS,pick:()=>YP,prefixIssues:()=>st,primitiveTypes:()=>au,promiseAllObject:()=>VP,propertyKeyTypes:()=>fo,randomString:()=>JP,required:()=>nS,stringifyPrimitive:()=>J,unwrapMessage:()=>uo});function ZP(t){return t}function qP(t){return t}function FP(t){}function HP(t){throw new Error}function BP(t){}function lo(t){let e=Object.values(t).filter(o=>typeof o=="number");return Object.entries(t).filter(([o,n])=>e.indexOf(+o)===-1).map(([o,n])=>n)}function N(t,e="|"){return t.map(r=>J(r)).join(e)}function nu(t,e){return typeof e=="bigint"?e.toString():e}function po(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function cr(t){return t==null}function mo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ou(t,e){let r=(t.toString().split(".")[1]||"").length,o=(e.toString().split(".")[1]||"").length,n=r>o?r:o,i=Number.parseInt(t.toFixed(n).replace(".","")),a=Number.parseInt(e.toFixed(n).replace(".",""));return i%a/10**n}function Se(t,e,r){Object.defineProperty(t,e,{get(){{let n=r();return t[e]=n,n}throw new Error("cached value already set")},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function iu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function GP(t,e){return e?e.reduce((r,o)=>r?.[o],t):t}function VP(t){let e=Object.keys(t),r=e.map(o=>t[o]);return Promise.all(r).then(o=>{let n={};for(let i=0;i<e.length;i++)n[e[i]]=o[i];return n})}function JP(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<t;o++)r+=e[Math.floor(Math.random()*e.length)];return r}function Tr(t){return JSON.stringify(t)}function sn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function an(t){if(sn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(sn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function WP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Jt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mt(t,e,r){let o=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(o._zod.parent=t),o}function H(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,o,n){return e??(e=t()),Reflect.get(e,o,n)},set(r,o,n,i){return e??(e=t()),Reflect.set(e,o,n,i)},has(r,o){return e??(e=t()),Reflect.has(e,o)},deleteProperty(r,o){return e??(e=t()),Reflect.deleteProperty(e,o)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,o){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,o)},defineProperty(r,o,n){return e??(e=t()),Reflect.defineProperty(e,o,n)}})}function J(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function cu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function YP(t,e){let r={},o=t._zod.def;for(let n in e){if(!(n in o.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&(r[n]=o.shape[n])}return mt(t,{...t._zod.def,shape:r,checks:[]})}function XP(t,e){let r={...t._zod.def.shape},o=t._zod.def;for(let n in e){if(!(n in o.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&delete r[n]}return mt(t,{...t._zod.def,shape:r,checks:[]})}function eS(t,e){if(!an(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let o={...t._zod.def.shape,...e};return iu(this,"shape",o),o},checks:[]};return mt(t,r)}function tS(t,e){return mt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return iu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function rS(t,e,r){let o=e._zod.def.shape,n={...o};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(n[i]=t?new t({type:"optional",innerType:o[i]}):o[i])}else for(let i in o)n[i]=t?new t({type:"optional",innerType:o[i]}):o[i];return mt(e,{...e._zod.def,shape:n,checks:[]})}function nS(t,e,r){let o=e._zod.def.shape,n={...o};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(n[i]=new t({type:"nonoptional",innerType:o[i]}))}else for(let i in o)n[i]=new t({type:"nonoptional",innerType:o[i]});return mt(e,{...e._zod.def,shape:n,checks:[]})}function kr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function st(t,e){return e.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(t),r})}function uo(t){return typeof t=="string"?t:t?.message}function ft(t,e,r){let o={...t,path:t.path??[]};if(!t.message){let n=uo(t.inst?._zod.def?.error?.(t))??uo(e?.error?.(t))??uo(r.customError?.(t))??uo(r.localeError?.(t))??"Invalid input";o.message=n}return delete o.inst,delete o.continue,e?.reportInput||delete o.input,o}function go(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ho(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function du(...t){let[e,r,o]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:o}:{...e}}function oS(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var cs,su,KP,fo,au,uu,lu,ru,le=K(()=>{s(ZP,"assertEqual");s(qP,"assertNotEqual");s(FP,"assertIs");s(HP,"assertNever");s(BP,"assert");s(lo,"getEnumValues");s(N,"joinValues");s(nu,"jsonStringifyReplacer");s(po,"cached");s(cr,"nullish");s(mo,"cleanRegex");s(ou,"floatSafeRemainder");s(Se,"defineLazy");s(iu,"assignProp");s(GP,"getElementAtPath");s(VP,"promiseAllObject");s(JP,"randomString");s(Tr,"esc");cs=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};s(sn,"isObject");su=po(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});s(an,"isPlainObject");s(WP,"numKeys");KP=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"),fo=new Set(["string","number","symbol"]),au=new Set(["string","number","bigint","boolean","symbol","undefined"]);s(Jt,"escapeRegex");s(mt,"clone");s(H,"normalizeParams");s(QP,"createTransparentProxy");s(J,"stringifyPrimitive");s(cu,"optionalKeys");uu={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]},lu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};s(YP,"pick");s(XP,"omit");s(eS,"extend");s(tS,"merge");s(rS,"partial");s(nS,"required");s(kr,"aborted");s(st,"prefixIssues");s(uo,"unwrapMessage");s(ft,"finalizeIssue");s(go,"getSizableOrigin");s(ho,"getLengthableOrigin");s(du,"issue");s(oS,"cleanEnum");ru=class{static{s(this,"Class")}constructor(...e){}}});function bo(t,e=r=>r.message){let r={},o=[];for(let n of t.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(e(n))):o.push(e(n));return{formErrors:o,fieldErrors:r}}function vo(t,e){let r=e||function(i){return i.message},o={_errors:[]},n=s(i=>{for(let a of i.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(c=>n({issues:c}));else if(a.code==="invalid_key")n({issues:a.issues});else if(a.code==="invalid_element")n({issues:a.issues});else if(a.path.length===0)o._errors.push(r(a));else{let c=o,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 n(t),o}function pu(t,e){let r=e||function(i){return i.message},o={errors:[]},n=s((i,a=[])=>{var c,u;for(let l of i.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(d=>n({issues:d},l.path));else if(l.code==="invalid_key")n({issues:l.issues},l.path);else if(l.code==="invalid_element")n({issues:l.issues},l.path);else{let d=[...a,...l.path];if(d.length===0){o.errors.push(r(l));continue}let p=o,m=0;for(;m<d.length;){let y=d[m],g=m===d.length-1;typeof y=="string"?(p.properties??(p.properties={}),(c=p.properties)[y]??(c[y]={errors:[]}),p=p.properties[y]):(p.items??(p.items=[]),(u=p.items)[y]??(u[y]={errors:[]}),p=p.items[y]),g&&p.errors.push(r(l)),m++}}},"processError");return n(t),o}function db(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 mu(t){let e=[],r=[...t.issues].sort((o,n)=>o.path.length-n.path.length);for(let o of r)e.push(`\u2716 ${o.message}`),o.path?.length&&e.push(` \u2192 at ${db(o.path)}`);return e.join(`
25
+ import{d as Ze,f as Qa,g as Ya}from"./chunk-JRXZBVXH.js";import{a as ce,b as jh}from"./chunk-4SACVMDH.js";import{$ as ye,A as bi,B as vi,C as wi,D as xh,E as Rh,F as Ih,G as Ph,H as Sh,I as Th,J as kh,K as Eh,L as xi,M as Ch,N as _h,O as Ri,P as Ii,Q as Oh,R as Pi,S as Si,T as Ah,U as $h,V as Lh,W as Nh,X as Mh,Y as Dh,Z as Uh,_ as Ti,a as s,aa as z,b as K,ba as R,c as rI,ca as T,d as Ht,da as D,e as nI,f as gi,g as Ce,h as sh,i as zr,j as ah,k as Zr,l as ch,m as uh,n as lh,o as dh,p as ph,q as mh,r as fh,s as gh,t as hh,u as yh,v as bh,w as vh,x as wh,y as hi,z as yi}from"./chunk-ZIKV2LUM.js";var Py=rI(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.parse=FI;Hi.serialize=HI;var DI=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,UI=/^[\u0021-\u003A\u003C-\u007E]*$/,jI=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,zI=/^[\u0020-\u003A\u003D-\u007E]*$/,ZI=Object.prototype.toString,qI=(()=>{let t=s(function(){},"C");return t.prototype=Object.create(null),t})();function FI(t,e){let r=new qI,o=t.length;if(o<2)return r;let n=e?.decode||BI,i=0;do{let a=t.indexOf("=",i);if(a===-1)break;let c=t.indexOf(";",i),u=c===-1?o:c;if(a>u){i=t.lastIndexOf(";",a-1)+1;continue}let l=Ry(t,i,a),d=Iy(t,a,l),p=t.slice(l,d);if(r[p]===void 0){let m=Ry(t,a+1,u),y=Iy(t,u,m),g=n(t.slice(m,y));r[p]=g}i=u+1}while(i<o);return r}s(FI,"parse");function Ry(t,e,r){do{let o=t.charCodeAt(e);if(o!==32&&o!==9)return e}while(++e<r);return r}s(Ry,"startIndex");function Iy(t,e,r){for(;e>r;){let o=t.charCodeAt(--e);if(o!==32&&o!==9)return e+1}return r}s(Iy,"endIndex");function HI(t,e,r){let o=r?.encode||encodeURIComponent;if(!DI.test(t))throw new TypeError(`argument name is invalid: ${t}`);let n=o(e);if(!UI.test(n))throw new TypeError(`argument val is invalid: ${e}`);let i=t+"="+n;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(!jI.test(r.domain))throw new TypeError(`option domain is invalid: ${r.domain}`);i+="; Domain="+r.domain}if(r.path){if(!zI.test(r.path))throw new TypeError(`option path is invalid: ${r.path}`);i+="; Path="+r.path}if(r.expires){if(!GI(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(HI,"serialize");function BI(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}s(BI,"decode");function GI(t){return ZI.call(t)==="[object Date]"}s(GI,"isDate")});function E(t,e,r){function o(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)d in c||Object.defineProperty(c,d,{value:a.prototype[d].bind(c)});c._zod.constr=a,c._zod.def=u}s(o,"init");let n=r?.Parent??Object;class i extends n{static{s(this,"Definition")}}Object.defineProperty(i,"name",{value:t});function a(c){var u;let l=r?.Parent?new i:this;o(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:o}),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 Fe(t){return t&&Object.assign(co,t),co}var Xc,eu,Ut,co,on=K(()=>{Xc=Object.freeze({status:"aborted"});s(E,"$constructor");eu=Symbol("zod_brand"),Ut=class extends Error{static{s(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},co={};s(Fe,"config")});var W={};Ht(W,{BIGINT_FORMAT_RANGES:()=>lu,Class:()=>ru,NUMBER_FORMAT_RANGES:()=>uu,aborted:()=>kr,allowsEval:()=>su,assert:()=>BP,assertEqual:()=>ZP,assertIs:()=>FP,assertNever:()=>HP,assertNotEqual:()=>qP,assignProp:()=>iu,cached:()=>po,captureStackTrace:()=>cs,cleanEnum:()=>oS,cleanRegex:()=>mo,clone:()=>mt,createTransparentProxy:()=>QP,defineLazy:()=>Se,esc:()=>Tr,escapeRegex:()=>Jt,extend:()=>eS,finalizeIssue:()=>ft,floatSafeRemainder:()=>ou,getElementAtPath:()=>GP,getEnumValues:()=>lo,getLengthableOrigin:()=>ho,getParsedType:()=>KP,getSizableOrigin:()=>go,isObject:()=>sn,isPlainObject:()=>an,issue:()=>du,joinValues:()=>N,jsonStringifyReplacer:()=>nu,merge:()=>tS,normalizeParams:()=>H,nullish:()=>cr,numKeys:()=>WP,omit:()=>XP,optionalKeys:()=>cu,partial:()=>rS,pick:()=>YP,prefixIssues:()=>st,primitiveTypes:()=>au,promiseAllObject:()=>VP,propertyKeyTypes:()=>fo,randomString:()=>JP,required:()=>nS,stringifyPrimitive:()=>J,unwrapMessage:()=>uo});function ZP(t){return t}function qP(t){return t}function FP(t){}function HP(t){throw new Error}function BP(t){}function lo(t){let e=Object.values(t).filter(o=>typeof o=="number");return Object.entries(t).filter(([o,n])=>e.indexOf(+o)===-1).map(([o,n])=>n)}function N(t,e="|"){return t.map(r=>J(r)).join(e)}function nu(t,e){return typeof e=="bigint"?e.toString():e}function po(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function cr(t){return t==null}function mo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ou(t,e){let r=(t.toString().split(".")[1]||"").length,o=(e.toString().split(".")[1]||"").length,n=r>o?r:o,i=Number.parseInt(t.toFixed(n).replace(".","")),a=Number.parseInt(e.toFixed(n).replace(".",""));return i%a/10**n}function Se(t,e,r){Object.defineProperty(t,e,{get(){{let n=r();return t[e]=n,n}throw new Error("cached value already set")},set(n){Object.defineProperty(t,e,{value:n})},configurable:!0})}function iu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function GP(t,e){return e?e.reduce((r,o)=>r?.[o],t):t}function VP(t){let e=Object.keys(t),r=e.map(o=>t[o]);return Promise.all(r).then(o=>{let n={};for(let i=0;i<e.length;i++)n[e[i]]=o[i];return n})}function JP(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<t;o++)r+=e[Math.floor(Math.random()*e.length)];return r}function Tr(t){return JSON.stringify(t)}function sn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function an(t){if(sn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(sn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function WP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Jt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mt(t,e,r){let o=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(o._zod.parent=t),o}function H(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,o,n){return e??(e=t()),Reflect.get(e,o,n)},set(r,o,n,i){return e??(e=t()),Reflect.set(e,o,n,i)},has(r,o){return e??(e=t()),Reflect.has(e,o)},deleteProperty(r,o){return e??(e=t()),Reflect.deleteProperty(e,o)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,o){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,o)},defineProperty(r,o,n){return e??(e=t()),Reflect.defineProperty(e,o,n)}})}function J(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function cu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function YP(t,e){let r={},o=t._zod.def;for(let n in e){if(!(n in o.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&(r[n]=o.shape[n])}return mt(t,{...t._zod.def,shape:r,checks:[]})}function XP(t,e){let r={...t._zod.def.shape},o=t._zod.def;for(let n in e){if(!(n in o.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&delete r[n]}return mt(t,{...t._zod.def,shape:r,checks:[]})}function eS(t,e){if(!an(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let o={...t._zod.def.shape,...e};return iu(this,"shape",o),o},checks:[]};return mt(t,r)}function tS(t,e){return mt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return iu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function rS(t,e,r){let o=e._zod.def.shape,n={...o};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(n[i]=t?new t({type:"optional",innerType:o[i]}):o[i])}else for(let i in o)n[i]=t?new t({type:"optional",innerType:o[i]}):o[i];return mt(e,{...e._zod.def,shape:n,checks:[]})}function nS(t,e,r){let o=e._zod.def.shape,n={...o};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(n[i]=new t({type:"nonoptional",innerType:o[i]}))}else for(let i in o)n[i]=new t({type:"nonoptional",innerType:o[i]});return mt(e,{...e._zod.def,shape:n,checks:[]})}function kr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function st(t,e){return e.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(t),r})}function uo(t){return typeof t=="string"?t:t?.message}function ft(t,e,r){let o={...t,path:t.path??[]};if(!t.message){let n=uo(t.inst?._zod.def?.error?.(t))??uo(e?.error?.(t))??uo(r.customError?.(t))??uo(r.localeError?.(t))??"Invalid input";o.message=n}return delete o.inst,delete o.continue,e?.reportInput||delete o.input,o}function go(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ho(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function du(...t){let[e,r,o]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:o}:{...e}}function oS(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var cs,su,KP,fo,au,uu,lu,ru,le=K(()=>{s(ZP,"assertEqual");s(qP,"assertNotEqual");s(FP,"assertIs");s(HP,"assertNever");s(BP,"assert");s(lo,"getEnumValues");s(N,"joinValues");s(nu,"jsonStringifyReplacer");s(po,"cached");s(cr,"nullish");s(mo,"cleanRegex");s(ou,"floatSafeRemainder");s(Se,"defineLazy");s(iu,"assignProp");s(GP,"getElementAtPath");s(VP,"promiseAllObject");s(JP,"randomString");s(Tr,"esc");cs=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};s(sn,"isObject");su=po(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});s(an,"isPlainObject");s(WP,"numKeys");KP=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"),fo=new Set(["string","number","symbol"]),au=new Set(["string","number","bigint","boolean","symbol","undefined"]);s(Jt,"escapeRegex");s(mt,"clone");s(H,"normalizeParams");s(QP,"createTransparentProxy");s(J,"stringifyPrimitive");s(cu,"optionalKeys");uu={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]},lu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};s(YP,"pick");s(XP,"omit");s(eS,"extend");s(tS,"merge");s(rS,"partial");s(nS,"required");s(kr,"aborted");s(st,"prefixIssues");s(uo,"unwrapMessage");s(ft,"finalizeIssue");s(go,"getSizableOrigin");s(ho,"getLengthableOrigin");s(du,"issue");s(oS,"cleanEnum");ru=class{static{s(this,"Class")}constructor(...e){}}});function bo(t,e=r=>r.message){let r={},o=[];for(let n of t.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(e(n))):o.push(e(n));return{formErrors:o,fieldErrors:r}}function vo(t,e){let r=e||function(i){return i.message},o={_errors:[]},n=s(i=>{for(let a of i.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(c=>n({issues:c}));else if(a.code==="invalid_key")n({issues:a.issues});else if(a.code==="invalid_element")n({issues:a.issues});else if(a.path.length===0)o._errors.push(r(a));else{let c=o,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 n(t),o}function pu(t,e){let r=e||function(i){return i.message},o={errors:[]},n=s((i,a=[])=>{var c,u;for(let l of i.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(d=>n({issues:d},l.path));else if(l.code==="invalid_key")n({issues:l.issues},l.path);else if(l.code==="invalid_element")n({issues:l.issues},l.path);else{let d=[...a,...l.path];if(d.length===0){o.errors.push(r(l));continue}let p=o,m=0;for(;m<d.length;){let y=d[m],g=m===d.length-1;typeof y=="string"?(p.properties??(p.properties={}),(c=p.properties)[y]??(c[y]={errors:[]}),p=p.properties[y]):(p.items??(p.items=[]),(u=p.items)[y]??(u[y]={errors:[]}),p=p.items[y]),g&&p.errors.push(r(l)),m++}}},"processError");return n(t),o}function db(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 mu(t){let e=[],r=[...t.issues].sort((o,n)=>o.path.length-n.path.length);for(let o of r)e.push(`\u2716 ${o.message}`),o.path?.length&&e.push(` \u2192 at ${db(o.path)}`);return e.join(`
26
26
  `)}var lb,yo,cn,fu=K(()=>{on();le();lb=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,nu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:s(()=>t.message,"value"),enumerable:!1})},"initializer"),yo=E("$ZodError",lb),cn=E("$ZodError",lb,{Parent:Error});s(bo,"flattenError");s(vo,"formatError");s(pu,"treeifyError");s(db,"toDotPath");s(mu,"prettifyError")});var us,ls,ds,ps,ms,gu,fs,hu,gs=K(()=>{on();fu();le();us=s(t=>(e,r,o,n)=>{let i=o?Object.assign(o,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new Ut;if(a.issues.length){let c=new(n?.Err??t)(a.issues.map(u=>ft(u,i,Fe())));throw cs(c,n?.callee),c}return a.value},"_parse"),ls=us(cn),ds=s(t=>async(e,r,o,n)=>{let i=o?Object.assign(o,{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(n?.Err??t)(a.issues.map(u=>ft(u,i,Fe())));throw cs(c,n?.callee),c}return a.value},"_parseAsync"),ps=ds(cn),ms=s(t=>(e,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new Ut;return i.issues.length?{success:!1,error:new(t??yo)(i.issues.map(a=>ft(a,n,Fe())))}:{success:!0,data:i.value}},"_safeParse"),gu=ms(cn),fs=s(t=>async(e,r,o)=>{let n=o?Object.assign(o,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(a=>ft(a,n,Fe())))}:{success:!0,data:i.value}},"_safeParseAsync"),hu=fs(cn)});var Cr={};Ht(Cr,{_emoji:()=>pb,base64:()=>Ou,base64url:()=>hs,bigint:()=>Uu,boolean:()=>Zu,browserEmail:()=>mS,cidrv4:()=>Cu,cidrv6:()=>_u,cuid:()=>yu,cuid2:()=>bu,date:()=>Lu,datetime:()=>Mu,domain:()=>fS,duration:()=>Iu,e164:()=>$u,email:()=>Su,emoji:()=>Tu,extendedDuration:()=>sS,guid:()=>Pu,hostname:()=>Au,html5Email:()=>lS,integer:()=>ju,ipv4:()=>ku,ipv6:()=>Eu,ksuid:()=>xu,lowercase:()=>Hu,nanoid:()=>Ru,null:()=>qu,number:()=>zu,rfc5322Email:()=>dS,string:()=>Du,time:()=>Nu,ulid:()=>vu,undefined:()=>Fu,unicodeEmail:()=>pS,uppercase:()=>Bu,uuid:()=>Er,uuid4:()=>aS,uuid6:()=>cS,uuid7:()=>uS,xid:()=>wu});function Tu(){return new RegExp(pb,"u")}function fb(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Nu(t){return new RegExp(`^${fb(t)}$`)}function Mu(t){let e=fb({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let o=`${e}(?:${r.join("|")})`;return new RegExp(`^${mb}T(?:${o})$`)}var yu,bu,vu,wu,xu,Ru,Iu,sS,Pu,Er,aS,cS,uS,Su,lS,dS,pS,mS,pb,ku,Eu,Cu,_u,Ou,hs,Au,fS,$u,mb,Lu,Du,Uu,ju,zu,Zu,qu,Fu,Hu,Bu,ys=K(()=>{yu=/^[cC][^\s-]{8,}$/,bu=/^[0-9a-z]+$/,vu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,wu=/^[0-9a-vA-V]{20}$/,xu=/^[A-Za-z0-9]{27}$/,Ru=/^[a-zA-Z0-9_-]{21}$/,Iu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,sS=/^[-+]?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)?)??$/,Pu=/^([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})$/,Er=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"),aS=Er(4),cS=Er(6),uS=Er(7),Su=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,lS=/^[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])?)*$/,dS=/^(([^<>()\[\]\\.,;:\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,}))$/,pS=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,mS=/^[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])?)*$/,pb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";s(Tu,"emoji");ku=/^(?:(?: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])$/,Eu=/^(([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})$/,Cu=/^((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])$/,_u=/^(([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])$/,Ou=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,hs=/^[A-Za-z0-9_-]*$/,Au=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,fS=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,$u=/^\+(?:[0-9]){6,14}[0-9]$/,mb="(?:(?:\\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])))",Lu=new RegExp(`^${mb}$`);s(fb,"timeSource");s(Nu,"time");s(Mu,"datetime");Du=s(t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},"string"),Uu=/^\d+n?$/,ju=/^\d+$/,zu=/^-?\d+(?:\.\d+)?/i,Zu=/true|false/i,qu=/null/i,Fu=/undefined/i,Hu=/^[^A-Z]*$/,Bu=/^[^a-z]*$/});function gb(t,e,r){t.issues.length&&e.issues.push(...st(r,t.issues))}var Me,hb,bs,vs,Gu,Vu,Ju,Wu,Ku,Qu,Yu,Xu,el,un,tl,rl,nl,ol,il,sl,al,cl,ul,ws=K(()=>{on();ys();le();Me=E("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),hb={number:"number",bigint:"bigint",object:"date"},bs=E("$ZodCheckLessThan",(t,e)=>{Me.init(t,e);let r=hb[typeof e.value];t._zod.onattach.push(o=>{let n=o._zod.bag,i=(e.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?n.maximum=e.value:n.exclusiveMaximum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value<=e.value:o.value<e.value)||o.issues.push({origin:r,code:"too_big",maximum:e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),vs=E("$ZodCheckGreaterThan",(t,e)=>{Me.init(t,e);let r=hb[typeof e.value];t._zod.onattach.push(o=>{let n=o._zod.bag,i=(e.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?n.minimum=e.value:n.exclusiveMinimum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value>=e.value:o.value>e.value)||o.issues.push({origin:r,code:"too_small",minimum:e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Gu=E("$ZodCheckMultipleOf",(t,e)=>{Me.init(t,e),t._zod.onattach.push(r=>{var o;(o=r._zod.bag).multipleOf??(o.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):ou(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Vu=E("$ZodCheckNumberFormat",(t,e)=>{Me.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),o=r?"int":"number",[n,i]=uu[e.format];t._zod.onattach.push(a=>{let c=a._zod.bag;c.format=e.format,c.minimum=n,c.maximum=i,r&&(c.pattern=ju)}),t._zod.check=a=>{let c=a.value;if(r){if(!Number.isInteger(c)){a.issues.push({expected:o,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:o,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:o,continue:!e.abort});return}}c<n&&a.issues.push({origin:"number",input:c,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),c>i&&a.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inst:t})}}),Ju=E("$ZodCheckBigIntFormat",(t,e)=>{Me.init(t,e);let[r,o]=lu[e.format];t._zod.onattach.push(n=>{let i=n._zod.bag;i.format=e.format,i.minimum=r,i.maximum=o}),t._zod.check=n=>{let i=n.value;i<r&&n.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:t,continue:!e.abort}),i>o&&n.issues.push({origin:"bigint",input:i,code:"too_big",maximum:o,inst:t})}}),Wu=E("$ZodCheckMaxSize",(t,e)=>{var r;Me.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!cr(n)&&n.size!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(o._zod.bag.maximum=e.maximum)}),t._zod.check=o=>{let n=o.value;n.size<=e.maximum||o.issues.push({origin:go(n),code:"too_big",maximum:e.maximum,input:n,inst:t,continue:!e.abort})}}),Ku=E("$ZodCheckMinSize",(t,e)=>{var r;Me.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!cr(n)&&n.size!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(o._zod.bag.minimum=e.minimum)}),t._zod.check=o=>{let n=o.value;n.size>=e.minimum||o.issues.push({origin:go(n),code:"too_small",minimum:e.minimum,input:n,inst:t,continue:!e.abort})}}),Qu=E("$ZodCheckSizeEquals",(t,e)=>{var r;Me.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!cr(n)&&n.size!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=e.size,n.maximum=e.size,n.size=e.size}),t._zod.check=o=>{let n=o.value,i=n.size;if(i===e.size)return;let a=i>e.size;o.issues.push({origin:go(n),...a?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:o.value,inst:t,continue:!e.abort})}}),Yu=E("$ZodCheckMaxLength",(t,e)=>{var r;Me.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!cr(n)&&n.length!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(o._zod.bag.maximum=e.maximum)}),t._zod.check=o=>{let n=o.value;if(n.length<=e.maximum)return;let a=ho(n);o.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),Xu=E("$ZodCheckMinLength",(t,e)=>{var r;Me.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!cr(n)&&n.length!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(o._zod.bag.minimum=e.minimum)}),t._zod.check=o=>{let n=o.value;if(n.length>=e.minimum)return;let a=ho(n);o.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),el=E("$ZodCheckLengthEquals",(t,e)=>{var r;Me.init(t,e),(r=t._zod.def).when??(r.when=o=>{let n=o.value;return!cr(n)&&n.length!==void 0}),t._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=o=>{let n=o.value,i=n.length;if(i===e.length)return;let a=ho(n),c=i>e.length;o.issues.push({origin:a,...c?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:o.value,inst:t,continue:!e.abort})}}),un=E("$ZodCheckStringFormat",(t,e)=>{var r,o;Me.init(t,e),t._zod.onattach.push(n=>{let i=n._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=n=>{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})}):(o=t._zod).check??(o.check=()=>{})}),tl=E("$ZodCheckRegex",(t,e)=>{un.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})}}),rl=E("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Hu),un.init(t,e)}),nl=E("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Bu),un.init(t,e)}),ol=E("$ZodCheckIncludes",(t,e)=>{Me.init(t,e);let r=Jt(e.includes),o=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=o,t._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),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})}}),il=E("$ZodCheckStartsWith",(t,e)=>{Me.init(t,e);let r=new RegExp(`^${Jt(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=o=>{o.value.startsWith(e.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:o.value,inst:t,continue:!e.abort})}}),sl=E("$ZodCheckEndsWith",(t,e)=>{Me.init(t,e);let r=new RegExp(`.*${Jt(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=o=>{o.value.endsWith(e.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:o.value,inst:t,continue:!e.abort})}});s(gb,"handleCheckPropertyResult");al=E("$ZodCheckProperty",(t,e)=>{Me.init(t,e),t._zod.check=r=>{let o=e.schema._zod.run({value:r.value[e.property],issues:[]},{});if(o instanceof Promise)return o.then(n=>gb(n,r,e.property));gb(o,r,e.property)}}),cl=E("$ZodCheckMimeType",(t,e)=>{Me.init(t,e);let r=new Set(e.mime);t._zod.onattach.push(o=>{o._zod.bag.mime=e.mime}),t._zod.check=o=>{r.has(o.value.type)||o.issues.push({code:"invalid_value",values:e.mime,input:o.value.type,inst:t})}}),ul=E("$ZodCheckOverwrite",(t,e)=>{Me.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var wo,ll=K(()=>{wo=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 o=e.split(`
27
27
  `).filter(a=>a),n=Math.min(...o.map(a=>a.length-a.trimStart().length)),i=o.map(a=>a.slice(n)).map(a=>" ".repeat(this.indent*2)+a);for(let a of i)this.content.push(a)}compile(){let e=Function,r=this?.args,n=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...r,n.join(`
28
28
  `))}}});var dl,pl=K(()=>{dl={major:4,minor:0,patch:0}});function $l(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function Cb(t){if(!hs.test(t))return!1;let e=t.replace(/[-_]/g,o=>o==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return $l(r)}function _b(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));return!("typ"in n&&n?.typ!=="JWT"||!n.alg||e&&(!("alg"in n)||n.alg!==e))}catch{return!1}}function bb(t,e,r){t.issues.length&&e.issues.push(...st(r,t.issues)),e.value[r]=t.value}function xs(t,e,r){t.issues.length&&e.issues.push(...st(r,t.issues)),e.value[r]=t.value}function vb(t,e,r,o){t.issues.length?o[r]===void 0?r in o?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...st(r,t.issues)):t.value===void 0?r in o&&(e.value[r]=void 0):e.value[r]=t.value}function wb(t,e,r,o){for(let n of t)if(n.issues.length===0)return e.value=n.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(n=>n.issues.map(i=>ft(i,o,Fe())))}),e}function ml(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(an(t)&&an(e)){let r=Object.keys(e),o=Object.keys(t).filter(i=>r.indexOf(i)!==-1),n={...t,...e};for(let i of o){let a=ml(t[i],e[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n[i]=a.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<t.length;o++){let n=t[o],i=e[o],a=ml(n,i);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function xb(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),kr(t))return t;let o=ml(e.value,r.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return t.value=o.data,t}function Rs(t,e,r){t.issues.length&&e.issues.push(...st(r,t.issues)),e.value[r]=t.value}function Rb(t,e,r,o,n,i,a){t.issues.length&&(fo.has(typeof o)?r.issues.push(...st(o,t.issues)):r.issues.push({origin:"map",code:"invalid_key",input:n,inst:i,issues:t.issues.map(c=>ft(c,a,Fe()))})),e.issues.length&&(fo.has(typeof o)?r.issues.push(...st(o,e.issues)):r.issues.push({origin:"map",code:"invalid_element",input:n,inst:i,key:o,issues:e.issues.map(c=>ft(c,a,Fe()))})),r.value.set(t.value,e.value)}function Ib(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function Pb(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Sb(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 Tb(t,e,r){return kr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function kb(t){return t.value=Object.freeze(t.value),t}function Eb(t,e,r,o){if(!t){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(n.params=o._zod.def.params),e.issues.push(du(n))}}var pe,_r,_e,fl,gl,hl,yl,bl,vl,wl,xl,Rl,Il,Pl,Sl,Tl,kl,El,Cl,_l,Ol,Al,Ll,Nl,Ml,Dl,Ul,Is,jl,xo,Ps,zl,Zl,ql,Fl,Hl,ln,Bl,Gl,Vl,Ro,Jl,Ss,Wl,Kl,Or,Ql,Yl,Xl,ed,td,rd,Io,nd,od,id,sd,ad,cd,ud,ld,Po,dd,pd,md,fd,gd,So=K(()=>{ws();on();ll();gs();ys();le();pl();le();pe=E("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=dl;let o=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&o.unshift(t);for(let n of o)for(let i of n._zod.onattach)i(t);if(o.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let n=s((i,a,c)=>{let u=kr(i),l;for(let d of a){if(d._zod.def.when){if(!d._zod.def.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 Ut;if(l||m instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await m,i.issues.length!==p&&(u||(u=kr(i,p)))});else{if(i.issues.length===p)continue;u||(u=kr(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 Ut;return c.then(u=>n(u,o,a))}return n(c,o,a)}}t["~standard"]={validate:s(n=>{try{let i=gu(t,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return hu(t,n).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},"validate"),vendor:"zod",version:1}}),_r=E("$ZodString",(t,e)=>{pe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Du(t._zod.bag),t._zod.parse=(r,o)=>{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}}),_e=E("$ZodStringFormat",(t,e)=>{un.init(t,e),_r.init(t,e)}),fl=E("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Pu),_e.init(t,e)}),gl=E("$ZodUUID",(t,e)=>{if(e.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(o===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Er(o))}else e.pattern??(e.pattern=Er());_e.init(t,e)}),hl=E("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Su),_e.init(t,e)}),yl=E("$ZodURL",(t,e)=>{_e.init(t,e),t._zod.check=r=>{try{let o=r.value,n=new URL(o),i=n.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Au.source,input:r.value,inst:t,continue:!e.abort})),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,continue:!e.abort})),!o.endsWith("/")&&i.endsWith("/")?r.value=i.slice(0,-1):r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),bl=E("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Tu()),_e.init(t,e)}),vl=E("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Ru),_e.init(t,e)}),wl=E("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=yu),_e.init(t,e)}),xl=E("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=bu),_e.init(t,e)}),Rl=E("$ZodULID",(t,e)=>{e.pattern??(e.pattern=vu),_e.init(t,e)}),Il=E("$ZodXID",(t,e)=>{e.pattern??(e.pattern=wu),_e.init(t,e)}),Pl=E("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=xu),_e.init(t,e)}),Sl=E("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Mu(e)),_e.init(t,e)}),Tl=E("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Lu),_e.init(t,e)}),kl=E("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Nu(e)),_e.init(t,e)}),El=E("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Iu),_e.init(t,e)}),Cl=E("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=ku),_e.init(t,e),t._zod.onattach.push(r=>{let o=r._zod.bag;o.format="ipv4"})}),_l=E("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Eu),_e.init(t,e),t._zod.onattach.push(r=>{let o=r._zod.bag;o.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,continue:!e.abort})}}}),Ol=E("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Cu),_e.init(t,e)}),Al=E("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=_u),_e.init(t,e),t._zod.check=r=>{let[o,n]=r.value.split("/");try{if(!n)throw new Error;let i=Number(n);if(`${i}`!==n)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});s($l,"isValidBase64");Ll=E("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ou),_e.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{$l(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});s(Cb,"isValidBase64URL");Nl=E("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=hs),_e.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Cb(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Ml=E("$ZodE164",(t,e)=>{e.pattern??(e.pattern=$u),_e.init(t,e)});s(_b,"isValidJWT");Dl=E("$ZodJWT",(t,e)=>{_e.init(t,e),t._zod.check=r=>{_b(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ul=E("$ZodCustomStringFormat",(t,e)=>{_e.init(t,e),t._zod.check=r=>{e.fn(r.value)||r.issues.push({code:"invalid_format",format:e.format,input:r.value,inst:t,continue:!e.abort})}}),Is=E("$ZodNumber",(t,e)=>{pe.init(t,e),t._zod.pattern=t._zod.bag.pattern??zu,t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:t,...i?{received:i}:{}}),r}}),jl=E("$ZodNumber",(t,e)=>{Vu.init(t,e),Is.init(t,e)}),xo=E("$ZodBoolean",(t,e)=>{pe.init(t,e),t._zod.pattern=Zu,t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=!!r.value}catch{}let n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:t}),r}}),Ps=E("$ZodBigInt",(t,e)=>{pe.init(t,e),t._zod.pattern=Uu,t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:t}),r}}),zl=E("$ZodBigInt",(t,e)=>{Ju.init(t,e),Ps.init(t,e)}),Zl=E("$ZodSymbol",(t,e)=>{pe.init(t,e),t._zod.parse=(r,o)=>{let n=r.value;return typeof n=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:n,inst:t}),r}}),ql=E("$ZodUndefined",(t,e)=>{pe.init(t,e),t._zod.pattern=Fu,t._zod.values=new Set([void 0]),t._zod.optin="optional",t._zod.optout="optional",t._zod.parse=(r,o)=>{let n=r.value;return typeof n>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:t}),r}}),Fl=E("$ZodNull",(t,e)=>{pe.init(t,e),t._zod.pattern=qu,t._zod.values=new Set([null]),t._zod.parse=(r,o)=>{let n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:t}),r}}),Hl=E("$ZodAny",(t,e)=>{pe.init(t,e),t._zod.parse=r=>r}),ln=E("$ZodUnknown",(t,e)=>{pe.init(t,e),t._zod.parse=r=>r}),Bl=E("$ZodNever",(t,e)=>{pe.init(t,e),t._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)}),Gl=E("$ZodVoid",(t,e)=>{pe.init(t,e),t._zod.parse=(r,o)=>{let n=r.value;return typeof n>"u"||r.issues.push({expected:"void",code:"invalid_type",input:n,inst:t}),r}}),Vl=E("$ZodDate",(t,e)=>{pe.init(t,e),t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let n=r.value,i=n instanceof Date;return i&&!Number.isNaN(n.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:n,...i?{received:"Invalid Date"}:{},inst:t}),r}});s(bb,"handleArrayResult");Ro=E("$ZodArray",(t,e)=>{pe.init(t,e),t._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:t}),r;r.value=Array(n.length);let i=[];for(let a=0;a<n.length;a++){let c=n[a],u=e.element._zod.run({value:c,issues:[]},o);u instanceof Promise?i.push(u.then(l=>bb(l,r,a))):bb(u,r,a)}return i.length?Promise.all(i).then(()=>r):r}});s(xs,"handleObjectResult");s(vb,"handleOptionalObjectResult");Jl=E("$ZodObject",(t,e)=>{pe.init(t,e);let r=po(()=>{let p=Object.keys(e.shape);for(let y of p)if(!(e.shape[y]instanceof pe))throw new Error(`Invalid element at key "${y}": expected a Zod schema`);let m=cu(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(m)}});Se(t._zod,"propValues",()=>{let p=e.shape,m={};for(let y in p){let g=p[y]._zod;if(g.values){m[y]??(m[y]=new Set);for(let w of g.values)m[y].add(w)}}return m});let o=s(p=>{let m=new wo(["shape","payload","ctx"]),y=r.value,g=s(I=>{let k=Tr(I);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`},"parseStr");m.write("const input = payload.value;");let w=Object.create(null),v=0;for(let I of y.keys)w[I]=`key_${v++}`;m.write("const newResult = {}");for(let I of y.keys)if(y.optionalKeys.has(I)){let k=w[I];m.write(`const ${k} = ${g(I)};`);let C=Tr(I);m.write(`
@@ -237,7 +237,7 @@ data: ${n}
237
237
  }
238
238
  }
239
239
  }
240
- `}s(ya,"getIntrospectionQuery");var cE=2,jw=4,uE=24,lE=16,zw=512,dE=/(token|secret|authorization|password|cookie|credential|client[_-]?secret|code[_-]?verifier|(^|[_-])(code|state|verifier)($|[_-]))/i,pE=/("(?:access_token|refresh_token|id_token|client_secret|authorization|password|cookie|code|state|code_verifier)"\s*:\s*")([^"]*)(")/gi,mE=/\b(access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|password|cookie|code|state|code[_-]?verifier)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&]+)/gi,fE=/\b(authorization)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|(?:Bearer|Basic)\s+[^\s,;]+|[^\s,;]+)/gi,gE=/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,hE=/\bBasic\s+[A-Za-z0-9+/=-]+/gi;function Zw(t){let e=t.route;return e&&typeof e=="object"?e:void 0}s(Zw,"readRoute");function yE(t){let e=Zw(t)?.path;return typeof e=="string"&&e.length>0?e:void 0}s(yE,"readRoutePath");function bE(t){let e=Zw(t)?.raw;if(typeof e!="function")return;let r=e();if(!r||typeof r!="object")return;let o=r.operationId;return typeof o=="string"&&o.length>0?o:void 0}s(bE,"readRouteOperationId");function vE(t){if(!(t===void 0||!Number.isFinite(t)||t<100))return`${Math.trunc(t/100)}xx`}s(vE,"deriveStatusClass");function wE(t,e){if(!(!t&&!e))return t==="user"?e==="user-oauth"?"upstream_user_attributed":"gateway_user_attributed_only":t==="shared"?"shared_upstream_identity":t==="none"?"machine_identity":"unknown"}s(wE,"deriveOriginAttributionMode");function xE(t){if(!t)return;let e=t.toLowerCase();return e.includes("desktop")||e.includes("claude")||e.includes("chatgpt")?"desktop":e.includes("vscode")||e.includes("cursor")||e.includes("zed")||e.includes("jetbrains")||e.includes("ide")?"ide":e.includes("extension")?"extension":e.includes("agent")||e.includes("bot")||e.includes("worker")||e.includes("service")?"service":"unknown"}s(xE,"deriveClientKind");function RE(t,e){return e==="success"?"none":t===ce.MCP_REQUEST_RECEIVED||t===ce.MCP_REQUEST_REJECTED||t===ce.MCP_CLIENT_UNSUPPORTED_BEHAVIOR?"ingress":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===ce.MCP_INITIALIZE_NEGOTIATED?"routing":t.startsWith("mcp_capability_")?"upstream":t===ce.MCP_REQUEST_COMPLETED?"egress":"none"}s(RE,"deriveFailureStage");function IE(t,e){return e==="success"?"none":e==="application_error"?"mcp_application":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===ce.MCP_CAPABILITY_FAILED||t===ce.MCP_CAPABILITY_CONNECT_REQUIRED?"upstream":t===ce.MCP_REQUEST_REJECTED||t===ce.MCP_CLIENT_UNSUPPORTED_BEHAVIOR?"client":"gateway"}s(IE,"deriveFailureOrigin");function PE(t,e){return e==="success"?"none":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===ce.MCP_CLIENT_UNSUPPORTED_BEHAVIOR||t===ce.MCP_REQUEST_REJECTED?"protocol":"none"}s(PE,"deriveReasonClass");function SE(t){return t.length<=zw?t:`${t.slice(0,zw)}...`}s(SE,"truncateAnalyticsString");function TE(t){return SE(t.replace(pE,"$1[REDACTED]$3").replace(fE,"$1$2[REDACTED]").replace(mE,"$1$2[REDACTED]").replace(gE,"Bearer [REDACTED]").replace(hE,"Basic [REDACTED]"))}s(TE,"redactAnalyticsString");function qw(t,e){if(t!==void 0){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return TE(t);if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(Array.isArray(t))return e>=jw?"[DEPTH_LIMIT]":t.slice(0,lE).map(r=>qw(r,e+1)).filter(r=>r!==void 0);if(typeof t=="object")return t instanceof Date?t.toISOString():e>=jw?"[DEPTH_LIMIT]":Fw(t,e+1)}}s(qw,"sanitizeAnalyticsValue");function Fw(t,e=0){if(!t)return;let r={};for(let[o,n]of Object.entries(t).slice(0,uE)){if(dE.test(o)){r[o]="[REDACTED]";continue}let i=qw(n,e);i!==void 0&&(r[o]=i)}return Object.keys(r).length===0?void 0:r}s(Fw,"sanitizeMcpAnalyticsAttributes");function ne(t){return t===void 0?null:t}s(ne,"nullable");function kE(t){let e=t.environment;return e&&typeof e=="object"&&typeof e.name=="string"?e.name:null}s(kE,"readEnvironment");function EE(t){let e=t.requestId;return typeof e=="string"&&e.length>0?e:null}s(EE,"readRequestId");function CE(t){if(t===void 0)return null;try{return JSON.stringify(t)}catch{return null}}s(CE,"attributesToJsonString");function _E(t,e){let r=Fw(e.attributes),o=EE(t),n=e.ownerMode??null,i=e.upstreamAuthMode??null,a=e.clientKind??xE(e.clientName)??null,c=wE(n??void 0,i??void 0)??null,u=vE(e.httpStatusCode)??null,l=e.reasonClass??PE(e.eventType,e.outcome),d=e.failureOrigin??IE(e.eventType,e.outcome),p=e.failureStage??RE(e.eventType,e.outcome);return{schemaVersion:cE,outcome:e.outcome,subjectId:ne(e.subjectId),environment:kE(t),traceId:e.traceId??o,spanId:ne(e.spanId),parentEventId:ne(e.parentEventId),mcpSessionId:ne(e.mcpSessionId),routeSurface:ne(e.routeSurface),routePath:e.routePath??yE(t)??null,operationId:e.operationId??bE(t)??null,virtualServerName:ne(e.virtualServerName),virtualServerTitle:ne(e.virtualServerTitle),upstreamServerName:ne(e.upstreamServerName),upstreamServerTitle:ne(e.upstreamServerTitle),upstreamBindingId:ne(e.upstreamBindingId),clientName:ne(e.clientName),clientTitle:ne(e.clientTitle),clientVersion:ne(e.clientVersion),clientKind:a,authProfileId:ne(e.authProfileId),upstreamAuthMode:i,ownerMode:n,authMethod:ne(e.authMethod),originAttributionMode:c,apiKeySub:ne(e.apiKeySub),httpMethod:ne(e.httpMethod),httpStatusCode:ne(e.httpStatusCode),statusClass:u,mcpMethod:ne(e.mcpMethod),mcpProtocolVersion:ne(e.mcpProtocolVersion),mcpStatus:ne(e.mcpStatus),mcpErrorType:ne(e.mcpErrorType),applicationError:ne(e.applicationError),applicationErrorCode:ne(e.applicationErrorCode),toolResultIsError:ne(e.toolResultIsError),transport:ne(e.transport),sessionId:ne(e.sessionId),capabilityType:ne(e.capabilityType),capabilityName:ne(e.capabilityName),capabilityTitle:ne(e.capabilityTitle),upstreamCapabilityName:ne(e.upstreamCapabilityName),upstreamCapabilityTitle:ne(e.upstreamCapabilityTitle),capabilitySchemaHash:ne(e.capabilitySchemaHash),toolPath:ne(e.toolPath),toolMethod:ne(e.toolMethod),toolOperationId:ne(e.toolOperationId),resourceUri:ne(e.resourceUri),resourceMimeType:ne(e.resourceMimeType),policyId:ne(e.policyId),policyAction:ne(e.policyAction),guardrailType:ne(e.guardrailType),guardrailDirection:ne(e.guardrailDirection),guardrailFindingCount:ne(e.guardrailFindingCount),redactionCount:ne(e.redactionCount),requestMutated:ne(e.requestMutated),responseMutated:ne(e.responseMutated),latencyMs:ne(e.latencyMs),gatewayLatencyMs:ne(e.gatewayLatencyMs),upstreamLatencyMs:ne(e.upstreamLatencyMs),authLatencyMs:ne(e.authLatencyMs),policyLatencyMs:ne(e.policyLatencyMs),requestBytes:ne(e.requestBytes),responseBytes:ne(e.responseBytes),estimatedInputTokens:ne(e.estimatedInputTokens),estimatedOutputTokens:ne(e.estimatedOutputTokens),estimatedContextTokens:ne(e.estimatedContextTokens),contextPressureBucket:ne(e.contextPressureBucket),responseMimeTypes:ne(e.responseMimeTypes),base64Suspected:ne(e.base64Suspected),truncated:ne(e.truncated),isLargePayloadRequest:ne(e.isLargePayloadRequest),isLargePayloadResponse:ne(e.isLargePayloadResponse),payloadCaptureMode:ne(e.payloadCaptureMode),reasonCode:ne(e.reasonCode),reasonClass:l,errorType:e.errorType??e.reasonCode??null,failureOrigin:d,failureStage:p,errorCode:ne(e.errorCode),customMetadataJson:ne(e.customMetadataJson),attributesJson:CE(r)}}s(_E,"buildMcpAnalyticsMetadata");function Hw(t,e){try{t.analyticsContext.addAnalyticsEvent(e.value??1,e.eventType,_E(t,e),e.unit)}catch(r){t.log?.warn?.({event:"mcp_analytics_emit_failed",errorName:r instanceof Error?r.name:"unknown"})}}s(Hw,"emitMcpAnalyticsEvent");function Bw(t,e){let r=t.virtualServerName??e;return r===void 0?t:{...t,virtualServerName:r}}s(Bw,"injectMcpServerName");import{AsyncLocalStorage as OE}from"node:async_hooks";var Wm=new OE;function Gw(t,e,r){return Wm.run({headers:t,zuploContext:e},r)}s(Gw,"runWithInvokeContext");function Km(){return Wm.getStore()?.headers??{}}s(Km,"getInvokeHeaders");function vn(){let t=Wm.getStore();if(!t)throw new Error("No Zuplo context available in current execution context");return t.zuploContext}s(vn,"getInvokeContext");var ti=class{static{s(this,"R")}type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,e,r,o,n,i){this.type=t,this.name=e,this.prefix=r,this.value=o,this.suffix=n,this.modifier=i}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},AE=/[$_\p{ID_Start}]/u,$E=/[$_\u200C\u200D\p{ID_Continue}]/u,Ym=".*";function LE(t,e){return(e?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(t)}s(LE,"Re");function Ww(t,e=!1){let r=[],o=0;for(;o<t.length;){let n=t[o],i=s(function(a){if(!e)throw new TypeError(a);r.push({type:"INVALID_CHAR",index:o,value:t[o++]})},"c");if(n==="*"){r.push({type:"ASTERISK",index:o,value:t[o++]});continue}if(n==="+"||n==="?"){r.push({type:"OTHER_MODIFIER",index:o,value:t[o++]});continue}if(n==="\\"){r.push({type:"ESCAPED_CHAR",index:o++,value:t[o++]});continue}if(n==="{"){r.push({type:"OPEN",index:o,value:t[o++]});continue}if(n==="}"){r.push({type:"CLOSE",index:o,value:t[o++]});continue}if(n===":"){let a="",c=o+1;for(;c<t.length;){let u=t.substr(c,1);if(c===o+1&&AE.test(u)||c!==o+1&&$E.test(u)){a+=t[c++];continue}break}if(!a){i(`Missing parameter name at ${o}`);continue}r.push({type:"NAME",index:o,value:a}),o=c;continue}if(n==="("){let a=1,c="",u=o+1,l=!1;if(t[u]==="?"){i(`Pattern cannot start with "?" at ${u}`);continue}for(;u<t.length;){if(!LE(t[u],!1)){i(`Invalid character '${t[u]}' at ${u}.`),l=!0;break}if(t[u]==="\\"){c+=t[u++]+t[u++];continue}if(t[u]===")"){if(a--,a===0){u++;break}}else if(t[u]==="("&&(a++,t[u+1]!=="?")){i(`Capturing groups are not allowed at ${u}`),l=!0;break}c+=t[u++]}if(l)continue;if(a){i(`Unbalanced pattern at ${o}`);continue}if(!c){i(`Missing pattern at ${o}`);continue}r.push({type:"REGEX",index:o,value:c}),o=u;continue}r.push({type:"CHAR",index:o,value:t[o++]})}return r.push({type:"END",index:o,value:""}),r}s(Ww,"v");function Kw(t,e={}){let r=Ww(t);e.delimiter??="/#?",e.prefixes??="./";let o=`[^${Rt(e.delimiter)}]+?`,n=[],i=0,a=0,c="",u=new Set,l=s(k=>{if(a<r.length&&r[a].type===k)return r[a++].value},"a"),d=s(()=>l("OTHER_MODIFIER")??l("ASTERISK"),"f"),p=s(k=>{let C=l(k);if(C!==void 0)return C;let{type:A,index:Z}=r[a];throw new TypeError(`Unexpected ${A} at ${Z}, expected ${k}`)},"d"),m=s(()=>{let k="",C;for(;C=l("CHAR")??l("ESCAPED_CHAR");)k+=C;return k},"T"),y=s(k=>k,"Se"),g=e.encodePart||y,w="",v=s(k=>{w+=k},"U"),x=s(()=>{w.length&&(n.push(new ti(3,"","",g(w),"",3)),w="")},"$"),I=s((k,C,A,Z,V)=>{let Q=3;switch(V){case"?":Q=1;break;case"*":Q=0;break;case"+":Q=2;break}if(!C&&!A&&Q===3){v(k);return}if(x(),!C&&!A){if(!k)return;n.push(new ti(3,"","",g(k),"",Q));return}let te;A?A==="*"?te=Ym:te=A:te=o;let re=2;te===o?(re=1,te=""):te===Ym&&(re=0,te="");let se;if(C?se=C:A&&(se=i++),u.has(se))throw new TypeError(`Duplicate name '${se}'.`);u.add(se),n.push(new ti(re,se,g(k),te,g(Z),Q))},"V");for(;a<r.length;){let k=l("CHAR"),C=l("NAME"),A=l("REGEX");if(!C&&!A&&(A=l("ASTERISK")),C||A){let V=k??"";e.prefixes.indexOf(V)===-1&&(v(V),V=""),x();let Q=d();I(V,C,A,"",Q);continue}let Z=k??l("ESCAPED_CHAR");if(Z){v(Z);continue}if(l("OPEN")){let V=m(),Q=l("NAME"),te=l("REGEX");!Q&&!te&&(te=l("ASTERISK"));let re=m();p("CLOSE");let se=d();I(V,Q,te,re,se);continue}x(),p("END")}return n}s(Kw,"D");function Rt(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}s(Rt,"S");function Vw(t){return t&&t.ignoreCase?"ui":"u"}s(Vw,"X");function NE(t,e,r){return Qw(Kw(t,r),e,r)}s(NE,"Z");function wn(t){switch(t){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}s(wn,"k");function Qw(t,e,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith="";let o=r.start?"^":"";for(let c of t){if(c.type===3){c.modifier===3?o+=Rt(c.value):o+=`(?:${Rt(c.value)})${wn(c.modifier)}`;continue}e&&e.push(c.name);let u=`[^${Rt(r.delimiter)}]+?`,l=c.value;if(c.type===1?l=u:c.type===0&&(l=Ym),!c.prefix.length&&!c.suffix.length){c.modifier===3||c.modifier===1?o+=`(${l})${wn(c.modifier)}`:o+=`((?:${l})${wn(c.modifier)})`;continue}if(c.modifier===3||c.modifier===1){o+=`(?:${Rt(c.prefix)}(${l})${Rt(c.suffix)})`,o+=wn(c.modifier);continue}o+=`(?:${Rt(c.prefix)}`,o+=`((?:${l})(?:`,o+=Rt(c.suffix),o+=Rt(c.prefix),o+=`(?:${l}))*)${Rt(c.suffix)})`,c.modifier===0&&(o+="?")}let n=`[${Rt(r.endsWith)}]|$`,i=`[${Rt(r.delimiter)}]`;if(r.end)return r.strict||(o+=`${i}?`),r.endsWith.length?o+=`(?=${n})`:o+="$",new RegExp(o,Vw(r));r.strict||(o+=`(?:${i}(?=${n}))?`);let a=!1;if(t.length){let c=t[t.length-1];c.type===3&&c.modifier===3&&(a=r.delimiter.indexOf(c)>-1)}return a||(o+=`(?=${i}|${n})`),new RegExp(o,Vw(r))}s(Qw,"F");var gr={delimiter:"",prefixes:"",sensitive:!0,strict:!0},ME={delimiter:".",prefixes:"",sensitive:!0,strict:!0},DE={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function UE(t,e){return t.length?t[0]==="/"?!0:!e||t.length<2?!1:(t[0]=="\\"||t[0]=="{")&&t[1]=="/":!1}s(UE,"J");function Yw(t,e){return t.startsWith(e)?t.substring(e.length,t.length):t}s(Yw,"Q");function jE(t,e){return t.endsWith(e)?t.substr(0,t.length-e.length):t}s(jE,"Ee");function Xw(t){return!t||t.length<2?!1:t[0]==="["||(t[0]==="\\"||t[0]==="{")&&t[1]==="["}s(Xw,"W");var ex=["ftp","file","http","https","ws","wss"];function tx(t){if(!t)return!0;for(let e of ex)if(t.test(e))return!0;return!1}s(tx,"N");function zE(t,e){if(t=Yw(t,"#"),e||t==="")return t;let r=new URL("https://example.com");return r.hash=t,r.hash?r.hash.substring(1,r.hash.length):""}s(zE,"te");function ZE(t,e){if(t=Yw(t,"?"),e||t==="")return t;let r=new URL("https://example.com");return r.search=t,r.search?r.search.substring(1,r.search.length):""}s(ZE,"re");function qE(t,e){return e||t===""?t:Xw(t)?ox(t):nx(t)}s(qE,"ne");function FE(t,e){if(e||t==="")return t;let r=new URL("https://example.com");return r.password=t,r.password}s(FE,"se");function HE(t,e){if(e||t==="")return t;let r=new URL("https://example.com");return r.username=t,r.username}s(HE,"ie");function BE(t,e,r){if(r||t==="")return t;if(e&&!ex.includes(e))return new URL(`${e}:${t}`).pathname;let o=t[0]=="/";return t=new URL(o?t:"/-"+t,"https://example.com").pathname,o||(t=t.substring(2,t.length)),t}s(BE,"ae");function GE(t,e,r){return rx(e)===t&&(t=""),r||t===""?t:ix(t)}s(GE,"oe");function VE(t,e){return t=jE(t,":"),e||t===""?t:Xm(t)}s(VE,"ce");function rx(t){switch(t){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}s(rx,"_");function Xm(t){if(t==="")return t;if(/^[-+.A-Za-z0-9]*$/.test(t))return t.toLowerCase();throw new TypeError(`Invalid protocol '${t}'.`)}s(Xm,"y");function JE(t){if(t==="")return t;let e=new URL("https://example.com");return e.username=t,e.username}s(JE,"le");function WE(t){if(t==="")return t;let e=new URL("https://example.com");return e.password=t,e.password}s(WE,"fe");function nx(t){if(t==="")return t;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(t))throw new TypeError(`Invalid hostname '${t}'`);let e=new URL("https://example.com");return e.hostname=t,e.hostname}s(nx,"z");function ox(t){if(t==="")return t;if(/[^0-9a-fA-F[\]:]/g.test(t))throw new TypeError(`Invalid IPv6 hostname '${t}'`);return t.toLowerCase()}s(ox,"j");function ix(t){if(t===""||/^[0-9]*$/.test(t)&&parseInt(t)<=65535)return t;throw new TypeError(`Invalid port '${t}'.`)}s(ix,"K");function KE(t){if(t==="")return t;let e=new URL("https://example.com");return e.pathname=t[0]!=="/"?"/-"+t:t,t[0]!=="/"?e.pathname.substring(2,e.pathname.length):e.pathname}s(KE,"he");function QE(t){return t===""?t:new URL(`data:${t}`).pathname}s(QE,"ue");function YE(t){if(t==="")return t;let e=new URL("https://example.com");return e.search=t,e.search.substring(1,e.search.length)}s(YE,"de");function XE(t){if(t==="")return t;let e=new URL("https://example.com");return e.hash=t,e.hash.substring(1,e.hash.length)}s(XE,"pe");var eC=class{static{s(this,"H")}#e;#t=[];#n={};#r=0;#o=1;#i=0;#s=0;#a=0;#u=0;#l=!1;constructor(t){this.#e=t}get result(){return this.#n}parse(){for(this.#t=Ww(this.#e,!0);this.#r<this.#t.length;this.#r+=this.#o){if(this.#o=1,this.#t[this.#r].type==="END"){if(this.#s===0){this.#w(),this.#m()?this.#c(9,1):this.#g()?this.#c(8,1):this.#c(7,0);continue}else if(this.#s===2){this.#h(5);continue}this.#c(10,0);break}if(this.#a>0)if(this.#T())this.#a-=1;else continue;if(this.#S()){this.#a+=1;continue}switch(this.#s){case 0:this.#x()&&this.#h(1);break;case 1:if(this.#x()){this.#C();let t=7,e=1;this.#R()?(t=2,e=3):this.#l&&(t=2),this.#c(t,e)}break;case 2:this.#b()?this.#h(3):(this.#v()||this.#g()||this.#m())&&this.#h(5);break;case 3:this.#I()?this.#c(4,1):this.#b()&&this.#c(5,1);break;case 4:this.#b()&&this.#c(5,1);break;case 5:this.#k()?this.#u+=1:this.#E()&&(this.#u-=1),this.#P()&&!this.#u?this.#c(6,1):this.#v()?this.#c(7,0):this.#g()?this.#c(8,1):this.#m()&&this.#c(9,1);break;case 6:this.#v()?this.#c(7,0):this.#g()?this.#c(8,1):this.#m()&&this.#c(9,1);break;case 7:this.#g()?this.#c(8,1):this.#m()&&this.#c(9,1);break;case 8:this.#m()&&this.#c(9,1);break;case 9:break;case 10:break}}this.#n.hostname!==void 0&&this.#n.port===void 0&&(this.#n.port="")}#c(t,e){switch(this.#s){case 0:break;case 1:this.#n.protocol=this.#p();break;case 2:break;case 3:this.#n.username=this.#p();break;case 4:this.#n.password=this.#p();break;case 5:this.#n.hostname=this.#p();break;case 6:this.#n.port=this.#p();break;case 7:this.#n.pathname=this.#p();break;case 8:this.#n.search=this.#p();break;case 9:this.#n.hash=this.#p();break;case 10:break}this.#s!==0&&t!==10&&([1,2,3,4].includes(this.#s)&&[6,7,8,9].includes(t)&&(this.#n.hostname??=""),[1,2,3,4,5,6].includes(this.#s)&&[8,9].includes(t)&&(this.#n.pathname??=this.#l?"/":""),[1,2,3,4,5,6,7].includes(this.#s)&&t===9&&(this.#n.search??="")),this.#f(t,e)}#f(t,e){this.#s=t,this.#i=this.#r+e,this.#r+=e,this.#o=0}#w(){this.#r=this.#i,this.#o=0}#h(t){this.#w(),this.#s=t}#y(t){return t<0&&(t=this.#t.length-t),t<this.#t.length?this.#t[t]:this.#t[this.#t.length-1]}#d(t,e){let r=this.#y(t);return r.value===e&&(r.type==="CHAR"||r.type==="ESCAPED_CHAR"||r.type==="INVALID_CHAR")}#x(){return this.#d(this.#r,":")}#R(){return this.#d(this.#r+1,"/")&&this.#d(this.#r+2,"/")}#b(){return this.#d(this.#r,"@")}#I(){return this.#d(this.#r,":")}#P(){return this.#d(this.#r,":")}#v(){return this.#d(this.#r,"/")}#g(){if(this.#d(this.#r,"?"))return!0;if(this.#t[this.#r].value!=="?")return!1;let t=this.#y(this.#r-1);return t.type!=="NAME"&&t.type!=="REGEX"&&t.type!=="CLOSE"&&t.type!=="ASTERISK"}#m(){return this.#d(this.#r,"#")}#S(){return this.#t[this.#r].type=="OPEN"}#T(){return this.#t[this.#r].type=="CLOSE"}#k(){return this.#d(this.#r,"[")}#E(){return this.#d(this.#r,"]")}#p(){let t=this.#t[this.#r],e=this.#y(this.#i).index;return this.#e.substring(e,t.index)}#C(){let t={};Object.assign(t,gr),t.encodePart=Xm;let e=NE(this.#p(),void 0,t);this.#l=tx(e)}},Qm=["protocol","username","password","hostname","port","pathname","search","hash"],fr="*";function Jw(t,e){if(typeof t!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(t,e);return{protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}s(Jw,"ge");function rr(t,e){return e?ei(t):t}s(rr,"b");function Xo(t,e,r){let o;if(typeof e.baseURL=="string")try{o=new URL(e.baseURL),e.protocol===void 0&&(t.protocol=rr(o.protocol.substring(0,o.protocol.length-1),r)),!r&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&(t.username=rr(o.username,r)),!r&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&e.password===void 0&&(t.password=rr(o.password,r)),e.protocol===void 0&&e.hostname===void 0&&(t.hostname=rr(o.hostname,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&(t.port=rr(o.port,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&(t.pathname=rr(o.pathname,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&(t.search=rr(o.search.substring(1,o.search.length),r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&e.hash===void 0&&(t.hash=rr(o.hash.substring(1,o.hash.length),r))}catch{throw new TypeError(`invalid baseURL '${e.baseURL}'.`)}if(typeof e.protocol=="string"&&(t.protocol=VE(e.protocol,r)),typeof e.username=="string"&&(t.username=HE(e.username,r)),typeof e.password=="string"&&(t.password=FE(e.password,r)),typeof e.hostname=="string"&&(t.hostname=qE(e.hostname,r)),typeof e.port=="string"&&(t.port=GE(e.port,t.protocol,r)),typeof e.pathname=="string"){if(t.pathname=e.pathname,o&&!UE(t.pathname,r)){let n=o.pathname.lastIndexOf("/");n>=0&&(t.pathname=rr(o.pathname.substring(0,n+1),r)+t.pathname)}t.pathname=BE(t.pathname,t.protocol,r)}return typeof e.search=="string"&&(t.search=ZE(e.search,r)),typeof e.hash=="string"&&(t.hash=zE(e.hash,r)),t}s(Xo,"w");function ei(t){return t.replace(/([+*?:{}()\\])/g,"\\$1")}s(ei,"C");function tC(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}s(tC,"Oe");function rC(t,e){e.delimiter??="/#?",e.prefixes??="./",e.sensitive??=!1,e.strict??=!1,e.end??=!0,e.start??=!0,e.endsWith="";let r=".*",o=`[^${tC(e.delimiter)}]+?`,n=/[$_\u200C\u200D\p{ID_Continue}]/u,i="";for(let a=0;a<t.length;++a){let c=t[a];if(c.type===3){if(c.modifier===3){i+=ei(c.value);continue}i+=`{${ei(c.value)}}${wn(c.modifier)}`;continue}let u=c.hasCustomName(),l=!!c.suffix.length||!!c.prefix.length&&(c.prefix.length!==1||!e.prefixes.includes(c.prefix)),d=a>0?t[a-1]:null,p=a<t.length-1?t[a+1]:null;if(!l&&u&&c.type===1&&c.modifier===3&&p&&!p.prefix.length&&!p.suffix.length)if(p.type===3){let m=p.value.length>0?p.value[0]:"";l=n.test(m)}else l=!p.hasCustomName();if(!l&&!c.prefix.length&&d&&d.type===3){let m=d.value[d.value.length-1];l=e.prefixes.includes(m)}l&&(i+="{"),i+=ei(c.prefix),u&&(i+=`:${c.name}`),c.type===2?i+=`(${c.value})`:c.type===1?u||(i+=`(${o})`):c.type===0&&(!u&&(!d||d.type===3||d.modifier!==3||l||c.prefix!=="")?i+="*":i+=`(${r})`),c.type===1&&u&&c.suffix.length&&n.test(c.suffix[0])&&(i+="\\"),i+=ei(c.suffix),l&&(i+="}"),c.modifier!==3&&(i+=wn(c.modifier))}return i}s(rC,"ke");var ba=class{static{s(this,"me")}#e;#t={};#n={};#r={};#o={};#i=!1;constructor(t={},e,r){try{let o;if(typeof e=="string"?o=e:r=e,typeof t=="string"){let c=new eC(t);if(c.parse(),t=c.result,o===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=o}else{if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(o)throw new TypeError("parameter 1 is not of type 'string'.")}typeof r>"u"&&(r={ignoreCase:!1});let n={ignoreCase:r.ignoreCase===!0},i={pathname:fr,protocol:fr,username:fr,password:fr,hostname:fr,port:fr,search:fr,hash:fr};this.#e=Xo(i,t,!0),rx(this.#e.protocol)===this.#e.port&&(this.#e.port="");let a;for(a of Qm){if(!(a in this.#e))continue;let c={},u=this.#e[a];switch(this.#n[a]=[],a){case"protocol":Object.assign(c,gr),c.encodePart=Xm;break;case"username":Object.assign(c,gr),c.encodePart=JE;break;case"password":Object.assign(c,gr),c.encodePart=WE;break;case"hostname":Object.assign(c,ME),Xw(u)?c.encodePart=ox:c.encodePart=nx;break;case"port":Object.assign(c,gr),c.encodePart=ix;break;case"pathname":tx(this.#t.protocol)?(Object.assign(c,DE,n),c.encodePart=KE):(Object.assign(c,gr,n),c.encodePart=QE);break;case"search":Object.assign(c,gr,n),c.encodePart=YE;break;case"hash":Object.assign(c,gr,n),c.encodePart=XE;break}try{this.#o[a]=Kw(u,c),this.#t[a]=Qw(this.#o[a],this.#n[a],c),this.#r[a]=rC(this.#o[a],c),this.#i=this.#i||this.#o[a].some(l=>l.type===2)}catch{throw new TypeError(`invalid ${a} pattern '${this.#e[a]}'.`)}}}catch(o){throw new TypeError(`Failed to construct 'URLPattern': ${o.message}`)}}test(t={},e){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return!1;try{typeof t=="object"?r=Xo(r,t,!1):r=Xo(r,Jw(t,e),!1)}catch{return!1}let o;for(o of Qm)if(!this.#t[o].exec(r[o]))return!1;return!0}exec(t={},e){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?r=Xo(r,t,!1):r=Xo(r,Jw(t,e),!1)}catch{return null}let o={};e?o.inputs=[t,e]:o.inputs=[t];let n;for(n of Qm){let i=this.#t[n].exec(r[n]);if(!i)return null;let a={};for(let[c,u]of this.#n[n].entries())if(typeof u=="string"||typeof u=="number"){let l=i[c+1];a[u]=l}o[n]={input:r[n]??"",groups:a}}return o}static compareComponent(t,e,r){let o=s((c,u)=>{for(let l of["type","modifier","prefix","value","suffix"]){if(c[l]<u[l])return-1;if(c[l]!==u[l])return 1}return 0},"o"),n=new ti(3,"","","","",3),i=new ti(0,"","","","",3),a=s((c,u)=>{let l=0;for(;l<Math.min(c.length,u.length);++l){let d=o(c[l],u[l]);if(d)return d}return c.length===u.length?0:o(c[l]??n,u[l]??n)},"s");return!e.#r[t]&&!r.#r[t]?0:e.#r[t]&&!r.#r[t]?a(e.#o[t],[i]):!e.#r[t]&&r.#r[t]?a([i],r.#o[t]):a(e.#o[t],r.#o[t])}get protocol(){return this.#r.protocol}get username(){return this.#r.username}get password(){return this.#r.password}get hostname(){return this.#r.hostname}get port(){return this.#r.port}get pathname(){return this.#r.pathname}get search(){return this.#r.search}get hash(){return this.#r.hash}get hasRegExpGroups(){return this.#i}};var va=class{static{s(this,"UrlPatternBuilder")}pattern;pathParams={};searchParams=new URLSearchParams;expectedPathParams=new Set;seenPathParams=new Set;constructor(e){this.pattern=new ba({pathname:e});let r=/:(\w+)(\([^)]*\))?[*+?]?/g,o;for(;(o=r.exec(e))!==null;)this.expectedPathParams.add(o[1])}addParameter(e,r,o){let n=this.getParameterValue(e,r,o);if(n!=null)switch(e.in){case"path":if(!this.expectedPathParams.has(e.name))throw new R(`path parameter '${e.name}' missing from pattern '${this.pattern.pathname}'`);this.seenPathParams.add(e.name),this.addPathParameter(e.name,n);break;case"query":this.addQueryParameter(e.name,n);break;default:break}}getParameterValue(e,r,o){switch(e.in){case"path":return r?.[e.name];case"query":return o?.[e.name];default:return}}addPathParameter(e,r){this.pathParams[e]=String(r)}addQueryParameter(e,r){Array.isArray(r)?r.forEach(o=>{o!=null&&this.searchParams.append(e,String(o))}):typeof r=="object"&&r!==null?this.searchParams.append(e,JSON.stringify(r)):this.searchParams.append(e,String(r))}toString(){let e=[...this.expectedPathParams].filter(i=>!this.seenPathParams.has(i));if(e.length>0)throw new R(`missing path parameters in OpenAPI spec: ${e.join(", ")}`);let r=this.pattern.pathname.replace(/:(\w+)(\([^)]*\))?([*+?])?/g,(i,a)=>this.pathParams[a]?encodeURIComponent(this.pathParams[a]):i),o=this.cleanupUrlPatternSyntax(r),n=this.searchParams.toString();return n?`${o}?${n}`:o}cleanupUrlPatternSyntax(e){return e.replace(/\{\/\}\?/g,"").replace(/\{\/\}[*+]/g,"/").replace(/\{\/\}/g,"/").replace(/(\{[^}]*\})[?*+]/g,"$1").replace(/\\:/g,":")}};var wa=class{constructor(e){this.routeData=e}static{s(this,"McpUrlBuilder")}build(e,r){let o=this.routeData.pathPattern?this.routeData.pathPattern:this.routeData.path,n=this.routeData.raw()?.parameters||[],i=new va(o);for(let a of n)i.addParameter(a,e,r);return i.toString()}};je();je();je();var xa=class t{static{s(this,"ZodFormatSchemaRegistry")}static formatter=new Map([["email",()=>h.email()],["uri",()=>h.url()],["url",()=>h.url()],["date",()=>h.iso.date()],["date-time",()=>h.iso.datetime()],["time",()=>h.iso.time()],["ipv4",()=>h.ipv4()],["ipv6",()=>h.ipv6()],["uuid",()=>h.guid()],["int32",()=>h.int32()],["int64",()=>h.int64()],["float",()=>h.number()],["double",()=>h.number()]]);static get(e){return t.formatter.get(e)}static register(e,r){t.formatter.set(e,r)}},xn=class t{static{s(this,"OpenApiToZodTranspiler")}static typeTranspilers=new Map([["string",this.transpileString.bind(this)],["number",this.transpileNumber.bind(this)],["integer",this.transpileInteger.bind(this)],["boolean",this.transpileBoolean.bind(this)],["array",this.transpileArray.bind(this)],["object",this.transpileObject.bind(this)],["null",this.transpileNull.bind(this)]]);static run(e,r){let o={path:[],definitions:{},visitedRefs:new Set,...r};return t.transpileSchema(e,o)}static transpileSchema(e,r){if(!e)return h.unknown();try{if("$ref"in e)return t.resolveReference(e.$ref,r);if(e.allOf)return t.transpileAllOf(e.allOf,r);if(e.oneOf)return t.transpileOneOf(e.oneOf,r);if(e.anyOf)return t.transpileAnyOf(e.anyOf,r);if(e.not)return t.transpileNot(e.not,r);let o=t.transpileByType(e,r);return o=t.applyCommonModifiers(o,e),o}catch(o){let n=r.path.join(".");throw new Error(`Failed to transpile schema at path "${n}": ${o.message}`)}}static transpileByType(e,r){let o=e.type;!o&&e.properties&&(o="object");let n=t.typeTranspilers.get(o||"unknown");return n?n(e,r):h.unknown()}static transpileString(e,r){if(e.enum)return h.enum(e.enum);let o=e.format?xa.get(e.format):null,n=o?o():h.string();if(n instanceof h.ZodString){let i=n;return e.minLength!==void 0&&(i=i.min(e.minLength)),e.maxLength!==void 0&&(i=i.max(e.maxLength)),e.pattern&&(i=i.regex(new RegExp(e.pattern))),i}else e.minLength||e.maxLength||e.pattern;return n}static applyNumericConstraints(e,r,o){let n=e;if(r.minimum!==void 0&&(n=n.min(r.minimum)),r.maximum!==void 0&&(n=n.max(r.maximum)),r.exclusiveMinimum!==void 0){let i;if(typeof r.exclusiveMinimum=="number")i=r.exclusiveMinimum;else if(r.minimum!==void 0)i=r.minimum+Number.EPSILON;else throw new Error(`exclusiveMinimum requires minimum to be set at path "${o.path.join(".")}"`);n=n.gt(i)}if(r.exclusiveMaximum!==void 0){let i;if(typeof r.exclusiveMaximum=="number")i=r.exclusiveMaximum;else if(r.maximum!==void 0)i=r.maximum-Number.EPSILON;else throw new Error(`exclusiveMaximum requires maximum to be set at path "${o.path.join(".")}"`);n=n.lt(i)}return n}static transpileNumber(e,r){let o=h.number();return t.applyNumericConstraints(o,{...e,type:"number"},r)}static transpileInteger(e,r){let o=h.int();return t.applyNumericConstraints(o,{...e,type:"number"},r)}static transpileBoolean(e,r){return h.boolean()}static transpileArray(e,r){let o=e.items?t.transpileSchema(e.items,{...r,path:[...r.path,"items"]}):h.unknown(),n=h.array(o);return e.minItems!==void 0&&(n=n.min(e.minItems)),e.maxItems!==void 0&&(n=n.max(e.maxItems)),e.uniqueItems&&(n=n.refine(i=>new Set(i).size===i.length,{message:"Array must contain unique items"})),n}static transpileObject(e,r){let o;if(e.properties){let n={},i=new Set(e.required||[]);for(let[c,u]of Object.entries(e.properties)){let l={...r,path:[...r.path,c]},d=t.transpileSchema(u,l);i.has(c)||(d=d.optional()),n[c]=d}let a=h.object(n);e.additionalProperties===!1?a=a.strict():(e.additionalProperties,a=a.passthrough()),o=a}else if(e.additionalProperties===!1)o=h.object({}).strict();else if(typeof e.additionalProperties=="object"){let n=t.transpileSchema(e.additionalProperties,r);o=h.record(h.string(),n)}else o=h.unknown();return(e.minProperties!==void 0||e.maxProperties!==void 0)&&(o=o.refine(n=>{let i=Object.keys(n).length;return!(e.minProperties!==void 0&&i<e.minProperties||e.maxProperties!==void 0&&i>e.maxProperties)},{message:t.buildPropertyCountErrorMessage(e.minProperties,e.maxProperties)})),o}static buildPropertyCountErrorMessage(e,r){return e!==void 0&&r!==void 0?`Object must have between ${e} and ${r} properties`:e!==void 0?`Object must have at least ${e} properties`:`Object must have at most ${r} properties`}static transpileNull(e,r){return h.null()}static transpileAllOf(e,r){return e.map((n,i)=>t.transpileSchema(n,{...r,path:[...r.path,`allOf[${i}]`]})).reduce((n,i)=>n.and(i))}static transpileOneOf(e,r){let o=e.map((n,i)=>t.transpileSchema(n,{...r,path:[...r.path,`oneOf[${i}]`]}));return o.length===0?h.never():o.length===1?o[0]:h.union(o)}static transpileAnyOf(e,r){return t.transpileOneOf(e,r)}static transpileNot(e,r){let o=t.transpileSchema(e,{...r,path:[...r.path,"not"]});return h.unknown().refine(n=>!o.safeParse(n).success,{message:"Value must not match the schema"})}static resolveReference(e,r){if(r.visitedRefs?.has(e))return h.lazy(()=>t.resolveReference(e,r));r.visitedRefs?.add(e);let o=e.split("/");if(o[0]==="#"&&o[1]==="definitions"&&r.definitions){let n=r.definitions[o[2]];if(n)return t.transpileSchema(n,r)}throw new Error(`Unable to resolve reference: ${e}`)}static applyCommonModifiers(e,r){let o=e;return r.nullable&&(o=o.nullable()),r.default!==void 0&&(o=o.default(r.default)),r.description&&(o=o.describe(r.description)),r.examples&&r.examples.length>0&&(o=o.meta({examples:r.examples})),o}static registerTypeTranspiler(e,r){t.typeTranspilers.set(e,r)}static registerFormatSchema(e,r){xa.register(e,r)}};var Ra=class{constructor(e){this.schema=e}static{s(this,"JSONSchemaBuilder")}build(){return xn.run(this.schema)}},Ia=class{constructor(e,r){this.routeData=e;this.contentType=r}static{s(this,"RequestBodySchemaBuilder")}build(){let e=this.routeData.raw()?.requestBody;if(!e?.content?.[this.contentType])return null;let r=e.content[this.contentType].schema;return r?xn.run(r):null}},Pa=class{constructor(e){this.parameters=e}static{s(this,"ParameterSchemaBuilder")}build(){if(this.parameters.length===0)return null;let e={};for(let r of this.parameters)e[r.name]=this.buildParameterSchema(r);return h.object(e)}buildParameterSchema(e){let r;e.schema?r=xn.run(e.schema):r=h.string(),e.required||(r=r.optional()),e.description&&(r=r.describe(e.description));let o=[];if(e.schema?.example!==void 0&&o.push(e.schema.example),e.schema?.examples!==void 0&&Array.isArray(e.schema.examples)&&o.push(...e.schema.examples),e.examples&&(Array.isArray(e.examples)?o.push(...e.examples):typeof e.examples=="object"&&Object.values(e.examples).forEach(n=>{n?.value!==void 0&&o.push(n.value)})),e.example!==void 0&&o.push(e.example),o.length>0){let n=[...new Set(o.map(i=>JSON.stringify(i)))].map(i=>JSON.parse(i));r=r.meta({examples:n})}return r}};var Lr=class t{static{s(this,"UniversalValidatorBuilder")}root=null;components={};static withRoot(e){let r=new t;return r.root=e,r}withBody(e){return e&&(this.components.body=e),this}withQueryParams(e){return e&&(this.components.queryParams=e),this}withPathParams(e){return e&&(this.components.pathParams=e),this}withHeaders(e){return e&&(this.components.headers=e),this}build(){return this.root?this.buildFromSchema(this.root):Object.keys(this.components).length>0?this.buildFromComponents():this.buildEmptyValidator()}buildFromSchema(e){let r=h.toJSONSchema(e);return new mr(r,o=>{let n=e.safeParse(o);return n.success?{success:!0,data:n.data,errorData:null}:{success:!1,data:null,errorMessage:h.prettifyError(n.error),errorData:h.treeifyError(n.error)}})}buildFromComponents(){let e=h.object(this.components),r=h.toJSONSchema(e);return new mr(r,o=>{let n=e.safeParse(o);return n.success?{success:!0,data:n.data,errorData:null}:{success:!1,data:null,errorMessage:h.prettifyError(n.error),errorData:h.treeifyError(n.error)}})}buildEmptyValidator(){let e={type:"object",properties:{},required:[],additionalProperties:!1};return new mr(e,r=>({success:!0,data:r,errorData:null}))}},Rn=class t{static{s(this,"SchemaBuilderFactory")}static createJsonSchemaBuilder(e){return new Ra(e)}static createRequestBodyBuilder(e,r){return new Ia(e,r)}static createParameterBuilder(e,r){let o=r?e.filter(n=>n.in===r):e;return new Pa(o)}static createValidatorBuilder(e,r){let o=new Lr,n=e.raw()?.parameters||[];if(r){let u=t.createRequestBodyBuilder(e,r);o.withBody(u.build())}let i=t.createParameterBuilder(n,"query");o.withQueryParams(i.build());let a=t.createParameterBuilder(n,"path");o.withPathParams(a.build());let c=t.createParameterBuilder(n,"header");return o.withHeaders(c.build()),o}static createPromptValidatorBuilder(e){let r=new Lr,n=e.raw()?.requestBody;if(!n?.content||!n.content["application/json"])return r;let a=t.createRequestBodyBuilder(e,"application/json");return Lr.withRoot(a.build())}static createObjectValidatorBuilder(e){let r=new Lr;if(!e||Object.keys(e).length===0)return r;let o=t.createJsonSchemaBuilder(e);return Lr.withRoot(o.build())}};var Sa=class t{static{s(this,"ZuploMcpServer")}static instances=new Map;static async getInstance({opts:e,context:r,key:o}){let n=e.debugMode??!1,i=t.instances.get(o);if(i)n&&r.log.debug("MCP Server warm reuse",{routeKey:o});else{let a=Date.now();if(i=new t(e,r),i.registerFromOperations(i.opts.operations??[]),i.registerToolsFromFileSources(i.opts.files??[]),i.registerPromptsFromFileSources(i.opts.prompts??[]),i.registerResourcesFromFileSources(i.opts.resources??[]),await i.transport.connect(),i.server.withTransport(i.transport),t.instances.set(o,i),n){let c=i.server.getTools(),u=c?c.size:0,l=i.server.getPromptDefinitions(),d=l?l.length:0,p=i.server.getResourceDefinitions(),m=p?p.length:0,y=Date.now()-a;r.log.debug("MCP Server cold start",{routeKey:o,toolCount:u,promptCount:d,resourceCount:m,totalElapsedMs:y,debugMode:n,includeOutputSchema:i.includeOutputSchema,includeStructuredContent:i.includeStructuredContent})}}return i}transport;server;opts;context;serverName;serverDisplayName;registeredToolNames;registeredPromptNames;registeredResourceNames;includeOutputSchema;includeStructuredContent;debugMode;constructor(e,r){this.debugMode=e.debugMode??!1;let o;this.debugMode?o=r.log:o=new ao,this.context=r,this.opts=e,this.serverName=e.name,this.serverDisplayName=e.name??"Zuplo MCP Server",this.server=new ga({name:this.serverDisplayName,version:e.version??"0.0.0",logger:o}),this.transport=new ha({logger:o}),this.includeOutputSchema=e.includeOutputSchema??!1,this.includeStructuredContent=e.includeStructuredContent??!1,this.registeredToolNames=new Set,this.registeredPromptNames=new Set,this.registeredResourceNames=new Set}emitEvent(e,r){Hw(e,Bw(r,this.serverName))}async handleRequest(e,r){let o=Date.now(),n=e.headers.get("mcp-session-id")??e.headers.get("Mcp-Session-Id")??null;try{let i=await e.clone().json().catch(()=>({})),a=typeof i?.method=="string"?i.method:null;this.emitEvent(r,{eventType:ce.MCP_REQUEST_RECEIVED,outcome:"success",mcpMethod:a??void 0,httpMethod:e.method,transport:"http",sessionId:n??void 0,mcpSessionId:n??void 0});try{Je.getContextExtensions(r).addHandlerResponseHook(d=>{let p=Date.now()-o;this.emitEvent(r,{eventType:ce.MCP_REQUEST_COMPLETED,outcome:d.status>=400?"failure":"success",mcpMethod:a??void 0,httpMethod:e.method,httpStatusCode:d.status,transport:"http",sessionId:n??void 0,mcpSessionId:n??void 0,latencyMs:p})})}catch{}switch(this.debugMode&&r.log.debug("MCP Server request start",{method:i.method,requestId:i.id,routePath:r.route?.path}),i.method){case"tools/list":if(this.debugMode){let d=this.server.getTools(),p=d?Array.from(d.keys()):[];r.log.debug("MCP Server list tools request",{toolCount:p.length,toolNames:p})}break;case"tools/call":r.custom.mcpCallToolRequest=i;break;case"prompts/list":if(this.debugMode){let d=this.server.getPromptDefinitions(),p=d?d.map(m=>m.name):[];r.log.debug("MCP Server list prompts request",{promptCount:p.length,promptNames:p})}break;case"resources/list":if(this.debugMode){let d=this.server.getResourceDefinitions(),p=d?d.map(m=>m.name):[];r.log.debug("MCP Server list resources request",{resourceCount:p.length,resourceNames:p})}break}let c=await this.transport.handleRequest(e),u=Date.now()-o,l=c.status>=200&&c.status<300;switch(i.method){case"initialize":{let d=i?.params?.clientInfo,p=i?.params?.protocolVersion,m=typeof d?.name=="string"?d.name:void 0,y=typeof d?.title=="string"?d.title:void 0,g=typeof d?.version=="string"?d.version:void 0,w=typeof p=="string"?p:void 0;this.emitEvent(r,{eventType:ce.MCP_INITIALIZE_NEGOTIATED,outcome:l?"success":"failure",mcpMethod:"initialize",httpMethod:e.method,httpStatusCode:c.status,transport:"http",sessionId:n??void 0,mcpSessionId:n??void 0,clientName:m,clientTitle:y,clientVersion:g,mcpProtocolVersion:w,latencyMs:u}),l||this.emitEvent(r,{eventType:ce.MCP_CLIENT_UNSUPPORTED_BEHAVIOR,outcome:"failure",mcpMethod:"initialize",httpMethod:e.method,httpStatusCode:c.status,transport:"http",sessionId:n??void 0,mcpSessionId:n??void 0,clientName:m,clientVersion:g,mcpProtocolVersion:w,reasonClass:"client",reasonCode:"initialize_failed",attributes:{feature:"initialize"}});break}case"tools/list":this.emitEvent(r,{eventType:ce.MCP_CAPABILITY_LISTED,outcome:l?"success":"failure",capabilityType:"tool",mcpMethod:"tools/list",httpMethod:e.method,httpStatusCode:c.status,transport:"http",sessionId:n??void 0,mcpSessionId:n??void 0,latencyMs:u});break;case"resources/list":this.emitEvent(r,{eventType:ce.MCP_CAPABILITY_LISTED,outcome:l?"success":"failure",capabilityType:"resource",mcpMethod:"resources/list",httpMethod:e.method,httpStatusCode:c.status,transport:"http",sessionId:n??void 0,mcpSessionId:n??void 0,latencyMs:u});break;case"prompts/list":this.emitEvent(r,{eventType:ce.MCP_CAPABILITY_LISTED,outcome:l?"success":"failure",capabilityType:"prompt",mcpMethod:"prompts/list",httpMethod:e.method,httpStatusCode:c.status,transport:"http",sessionId:n??void 0,mcpSessionId:n??void 0,latencyMs:u});break}if(this.debugMode){let d=await c.clone().json().catch(()=>({}));r.log.debug("MCP Server response complete",{status:c.status,requestMethod:i.method,requestId:i.id,totalElapsedMs:u,respData:d})}return c}catch(i){let a=Date.now()-o;return r.log.error("MCP server internal error",{elapsedMs:a,err:i}),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}`}static getOperationsMetadataForFile(e){let{routes:r}=Pe.instance.routeData,o=r.filter(i=>i.metadata?.filepath===e);if(o.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 n=new Map;for(let i of o){let a=i?.raw().operationId;if(a){n.set(a,{routeConfig:i});let c=i?.raw(),u=c["x-zuplo-mcp-tool"],l=c["x-zuplo-mcp-prompt"],d=c["x-zuplo-mcp-graphql"],p=c["x-zuplo-mcp-resource"],m=c["x-zuplo-route"]?.mcp;(u||l||d||p||m)&&n.set(a,{routeConfig:i,toolExtension:u||void 0,promptExtension:l||void 0,graphqlExtension:d||void 0,resourceExtension:p||void 0,routeMcpExtension:m||void 0})}}return n}registerFromOperations(e){let r=new Map;for(let o of e){let n=r.get(o.file)??[];n.push(o.id),r.set(o.file,n)}for(let[o,n]of r.entries()){let i=t.getOperationsMetadataForFile(o);for(let a of n){let c=i.get(a);if(!c)throw new Error(`MCP configuration error: Could not find operation with ID "${a}" in file ${o}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:u,routeMcpExtension:l}=c;switch(l?.type){case"tool":this.registerTool(u,a,l);break;case"prompt":this.registerPrompt(u,a,l);break;case"resource":this.registerResource(u,a,l);break;case"graphql":this.registerGraphQLTools(a,u,l);break;default:this.context.log.warn(`Could not find "x-zuplo-route.mcp" configuration for operation: "${a}". Creating tool with fallback name and description`),this.registerTool(u,a,l)}}}}registerPromptsFromFileSources(e){for(let r of e){let o=t.getOperationsMetadataForFile(r.path),n=new Set;for(let i of r.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP prompt with operation ID: "${i}" from file: "${r.path}" with: "options.prompts" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=o.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(n.has(l))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${l}". Prompt names must be unique across all configured prompts.`);n.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,o,n){try{if(o.handler?.export==="mcpServerHandler")return;let a=Rn.createPromptValidatorBuilder(o).build();this.server.addPrompt({name:e,description:r,validator:a,generator:s(async c=>{let u=vn(),l=Date.now();try{this.debugMode&&u.log.debug("MCP prompt invoked",{promptName:e,operationId:o.raw()?.operationId,path:o.path,args:c});let d=this.buildToolUrl(o,{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(),y=await u.invokeRoute(d,p),g=Date.now()-m,w=await y.json();if(!y.ok)throw new Error(`Route returned ${y.status}: ${w}`);let v;try{if(v=w.messages||w,!Array.isArray(v))throw new Error("Response must contain a 'messages' array or be an array of messages")}catch(I){throw new Error(`Invalid JSON response or missing messages array: ${I instanceof Error?I.message:String(I)}`)}let x=Date.now()-l;return this.debugMode&&u.log.debug("MCP prompt response complete",{promptName:e,operationId:o.raw()?.operationId,status:y.status,elapsedMs:x,downstreamElapsedMs:g,messageCount:v.length}),this.emitEvent(u,{eventType:ce.MCP_CAPABILITY_COMPLETED,outcome:"success",capabilityType:"prompt",capabilityName:e,mcpMethod:"prompts/get",transport:"http",toolPath:o.path,toolMethod:"POST",toolOperationId:o.raw()?.operationId,latencyMs:x}),v}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:o.raw()?.operationId,path:o.path,elapsedMs:p,err:d}),this.emitEvent(u,{eventType:ce.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"prompt",capabilityName:e,mcpMethod:"prompts/get",transport:"http",toolPath:o.path,toolMethod:"POST",toolOperationId:o.raw()?.operationId,latencyMs:p,reasonCode:"gateway_error",reasonClass:"upstream",errorType:d instanceof Error?d.name:"unknown"}),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:n,path:o.path})}catch(i){throw this.context.log.error("Failed to register MCP prompt",{promptName:e,operationId:n,error:i instanceof Error?i.message:String(i)}),new Error(`Failed to register prompt "${e}" for operation "${n}": ${i instanceof Error?i.message:String(i)}`)}}registerResourcesFromFileSources(e){let r=new Set;for(let o of e){let n=t.getOperationsMetadataForFile(o.path);for(let i of o.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP resource with operation ID: "${i}" from file: "${o.path}" with: "options.resources" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=n.get(i);if(!a)throw new Error(`MCP Resource configuration error: Could not find operation with ID "${i}" in file ${o.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}`,y=u?.uri?.trim()||`mcp://resources/${encodeURIComponent(p)}`,g=u?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(p,y,m,c,i,g)}}}registerResourceForOperation(e,r,o,n,i,a,c){try{if(n.handler?.export==="mcpServerHandler")return;this.server.addResource(e,r,{title:e,description:o,mimeType:a,...c&&{_meta:c}},async()=>{let u=vn(),l=Date.now();try{this.debugMode&&u.log.debug("MCP resource invoked",{resourceName:e,operationId:n.raw()?.operationId,path:n.path,uri:r});let d=this.buildToolUrl(n,{}),p=this.buildToolRequest("GET",null,{});this.debugMode&&u.log.debug("MCP resource downstream call",{resourceName:e,url:d,method:"GET"});let m=Date.now(),y=await u.invokeRoute(d,p),g=Date.now()-m,w=await y.text(),v=Date.now()-l;return this.debugMode&&u.log.debug("MCP resource response complete",{resourceName:e,operationId:n.raw()?.operationId,status:y.status,elapsedMs:v,downstreamElapsedMs:g,declaredMimeType:a,contentLength:w.length}),this.emitEvent(u,{eventType:y.ok?ce.MCP_CAPABILITY_COMPLETED:ce.MCP_CAPABILITY_FAILED,outcome:y.ok?"success":"failure",capabilityType:"resource",capabilityName:e,resourceUri:r,resourceMimeType:a,mcpMethod:"resources/read",transport:"http",toolPath:n.path,toolMethod:"GET",toolOperationId:n.raw()?.operationId,latencyMs:v,...y.ok?{}:{errorCode:y.status,reasonCode:"upstream_error",reasonClass:"upstream"}}),{contents:[{uri:r,mimeType:a,text:w,...c&&{_meta:c}}]}}catch(d){let p=Date.now()-l,m=d instanceof Error?`${d.name}: ${d.message}`:String(d);throw u.log.error("MCP resource invocation failed",{resourceName:e,operationId:n.raw()?.operationId,path:n.path,elapsedMs:p,err:d}),this.emitEvent(u,{eventType:ce.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"resource",capabilityName:e,resourceUri:r,resourceMimeType:a,mcpMethod:"resources/read",transport:"http",toolPath:n.path,toolMethod:"GET",toolOperationId:n.raw()?.operationId,latencyMs:p,reasonCode:"gateway_error",reasonClass:"upstream",errorType:d instanceof Error?d.name:"unknown"}),new Error(`MCP resource call failed for resource '${e}': ${m}`)}}),this.debugMode&&this.context.log.debug("MCP resource registered from file source",{resourceName:e,operationId:i,path:n.path,uri:r,mimeType:a||"auto-detected"})}catch(u){throw this.context.log.error("Failed to register MCP resource",{resourceName:e,operationId:i,error:u instanceof Error?u.message:String(u)}),new Error(`Failed to register resource "${e}" for operation "${i}": ${u instanceof Error?u.message:String(u)}`)}}registerTool(e,r,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP tool disabled by x-zuplo-route.mcp configuration",{operationId:r});return}let i=o?.name?.trim()||r;if(this.registeredToolNames.has(i))throw new Error(`MCP Tool configuration error: Tool name conflict detected for operation: "${r}". The tool name "${i}" is already in use. Provide a unique 'name' in the x-zuplo-route.mcp configuration for operation "${r}".`);this.registeredToolNames.add(i);let a=o?.description?.trim()||e.raw().description?.trim()||e.raw().summary?.trim()||`Executes tool: ${i}`,c=o?.includeOutputSchema??this.includeOutputSchema??!1,u=o?.includeStructuredContent??this.includeStructuredContent??!1;if(e.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${e.methods.join(", ")}" on operation "${r}" not permitted. Only tools with a singular method are permitted.`);this.registerToolsForMethod({routeData:e,method:e.methods[0],name:i,description:a,includeOutputSchema:c,includeStructuredContent:u,annotations:o?.annotations,_meta:o?._meta})}registerPrompt(e,r,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by x-zuplo-route.mcp",{operationId:r});return}let i=o?.name?.trim()||r;if(this.registeredPromptNames.has(i))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${i}" for operation ID "${r}". Prompt names must be unique across all configured prompts.`);this.registeredPromptNames.add(i);let a=o?.description?.trim()||this.generatePromptDescriptionFromSpec(e);this.registerPromptForOperation(i,a,e,r)}registerResource(e,r,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by x-zuplo-route.mcp",{operationId:r});return}if(!e.methods||e.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${r}" has no HTTP methods defined. Resources must use GET method.`);if(e.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${r}" has multiple HTTP methods (${e.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let i=e.methods[0].toUpperCase();if(i!=="GET")throw new Error(`MCP Resource configuration error: Operation "${r}" uses ${i} method. Resources are read-only and must use GET method only.`);let a=o?.name?.trim()||r;if(this.registeredResourceNames.has(a))throw new Error(`MCP Resource configuration error: Duplicate resource name "${a}". Resource names must be unique across all configured resources.`);this.registeredResourceNames.add(a);let c=o?.description?.trim()||e.raw()?.description?.trim()||e.raw()?.summary?.trim()||`Resource for ${a}`,u=o?.uri?.trim()||`mcp://resources/${encodeURIComponent(a)}`,l=o?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(a,u,c,e,r,l,o?._meta)}registerToolsFromFileSources(e){let r=new Set;for(let o of e){let n=t.getOperationsMetadataForFile(o.path);this.debugMode&&this.context.log.debug("Processing file source",{path:o.path,operationIds:o.operationIds,availableOperationIds:Array.from(n.keys())});for(let i of o.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP tool with operation ID: "${i}" from file: "${o.path}" with: "options.files" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=n.get(i);if(!a)throw new Error(`MCP Tool configuration error: Operation ID "${i}" not found in OpenAPI spec at ${o.path}. Available operation IDs: ${Array.from(n.keys()).join(", ")}`);if(a.toolExtension?.enabled===!1){this.debugMode&&this.context.log.debug("Skipping disabled tool",{operationId:i,path:o.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 "${o.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,{type:"graphql",introspectionTool:{name:a.graphqlExtension.introspectionToolName??"",description:a.graphqlExtension.introspectionToolDescription??""},executeTool:{name:a.graphqlExtension.executeToolName??"",description:a.graphqlExtension.executeToolDescription??""}}):this.registerToolsForMethod({routeData:a.routeConfig,method:a.routeConfig.methods[0],name:c,description:u,includeOutputSchema:l,includeStructuredContent:d})}}}registerGraphQLTools(e,r,o){let n=o?.introspectionTool?.name?.trim()||`${e}_introspect`,i=o?.executeTool?.name?.trim()||`${e}_execute_query`;if(this.registeredToolNames.has(n))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The introspection tool name "${n}" is already in use. Provide a unique tool name.`);if(this.registeredToolNames.has(i))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The execute tool name "${i}" is already in use. Provide a unique 'executeToolName' in the x-zuplo-graphql extension.`);this.registeredToolNames.add(n),this.registeredToolNames.add(i);let a=o?.introspectionTool?.description??`Get the GraphQL schema for ${e}`,c=o?.executeTool?.description??`Execute a GraphQL query on ${e}`,u=r.path,d=Rn.createObjectValidatorBuilder({}).build();this.server.addTool({name:n,description:a,validator:d,handler:s(async()=>{let m=vn(),y=Date.now();try{this.debugMode&&m.log.debug("MCP GraphQL introspection tool invoked",{toolName:n,operationId:e,path:u});let g=ya(),w=this.buildToolUrl(r,{}),v=this.buildToolRequest("POST","application/json",{body:{query:g}}),x=Date.now(),I=await m.invokeRoute(w,v),k=Date.now()-x,C=await I.text(),A=Date.now()-y;this.debugMode&&(I.ok?m.log.debug("MCP GraphQL introspection tool ok response",{toolName:n,operationId:e,status:I.status,elapsedMs:A,downstreamElapsedMs:k}):m.log.debug("MCP GraphQL introspection tool 'isError' response",{toolName:n,operationId:e,status:I.status,elapsedMs:A,downstreamElapsedMs:k,response:C}));let Z;try{Z=JSON.parse(C)}catch(V){this.debugMode&&m.log.debug("MCP GraphQL introspection structuredContent JSON parse failed",{toolName:n,body:C,parseErr:V})}return{content:[{type:"text",text:C}],...Z&&{structuredContent:Z},isError:!I.ok}}catch(g){let w=Date.now()-y,v=g instanceof Error?`${g.name}: ${g.message}`:String(g);throw m.log.error("MCP GraphQL introspection tool invocation failed",{toolName:n,operationId:e,path:u,elapsedMs:w,err:g}),new Error(`MCP GraphQL introspection tool call failed for '${n}': ${v}`)}},"handler")});let p={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:i,description:c,validator:new mr(p,m=>typeof m=="object"&&m!==null&&"query"in m&&typeof m?.query=="string"?{success:!0,data:m,errorData:null}:{success:!1,data:null,errorMessage:"Invalid input: query field is required and must be a string",errorData:null}),handler:s(async m=>{let y=vn(),g=Date.now();try{this.debugMode&&y.log.debug("MCP GraphQL execute tool invoked",{toolName:i,operationId:e,path:u,queryPreview:m.query.substring(0,100)});let w=this.buildToolUrl(r,{}),v={query:m.query};m.variables&&(v.variables=m.variables);let x=this.buildToolRequest("POST","application/json",{body:v}),I=Date.now(),k=await y.invokeRoute(w,x),C=Date.now()-I,A=await k.text(),Z=Date.now()-g;this.debugMode&&(k.ok?y.log.debug("MCP GraphQL execute tool ok response",{toolName:i,operationId:e,status:k.status,elapsedMs:Z,downstreamElapsedMs:C}):y.log.debug("MCP GraphQL execute tool 'isError' response",{toolName:i,operationId:e,status:k.status,elapsedMs:Z,downstreamElapsedMs:C,response:A}));let V;try{V=JSON.parse(A)}catch(Q){this.debugMode&&y.log.debug("MCP GraphQL execute structuredContent JSON parse failed",{toolName:i,body:A,parseErr:Q})}return{content:[{type:"text",text:A}],...V&&{structuredContent:V},isError:!k.ok}}catch(w){let v=Date.now()-g,x=w instanceof Error?`${w.name}: ${w.message}`:String(w);throw y.log.error("MCP GraphQL execute tool invocation failed",{toolName:i,operationId:e,path:u,elapsedMs:v,err:w}),new Error(`MCP GraphQL execute tool call failed for '${i}': ${x}`)}},"handler")}),this.debugMode&&this.context.log.debug("MCP GraphQL tools registered",{operationId:e,introspectionToolName:n,executeToolName:i,path:u})}registerToolsForMethod({routeData:e,method:r,name:o,description:n,includeOutputSchema:i,includeStructuredContent:a,annotations:c,_meta:u}){if(e.handler?.export!=="mcpServerHandler")if(e.raw().requestBody?.content)for(let l of Object.keys(e.raw().requestBody?.content)){let p=Object.keys(e.raw().requestBody?.content).length>1?`${o}_${l.replace(/[^\w]/g,"_")}`:o;this.registerGenericToolSpec({name:p,description:n,routeData:e,method:r,contentType:l,includeOutputSchema:i,includeStructuredContent:a,annotations:c,_meta:u})}else this.registerGenericToolSpec({name:o,description:n,routeData:e,method:r,contentType:null,includeOutputSchema:i,includeStructuredContent:a,annotations:c,_meta:u})}registerGenericToolSpec({name:e,description:r,routeData:o,method:n,contentType:i,includeOutputSchema:a,includeStructuredContent:c,annotations:u,_meta:l}){let d=this.buildUniversalValidator(o,i);if(!d)throw new Error(`MCP Tool registration error: Could not build parameter validator for ${n.toUpperCase()} ${o.path}. This may indicate an issue with the OpenAPI parameter definitions for this route.`);let p=a?this.extractOutputSchema(o):void 0;try{this.server.addTool({name:e,description:r,validator:d,...p&&{outputSchema:p},...u&&{annotations:u},...l&&{_meta:l},handler:s(async(m,y)=>{let g=vn(),w=Date.now();try{this.debugMode&&g.log.debug("MCP tool invoked",{toolName:e,operationId:o.raw()?.operationId,method:n,path:o.path,args:m});let v=this.buildToolUrl(o,m),x=this.buildToolRequest(n,i,m);this.debugMode&&g.log.debug("MCP tool downstream call",{toolName:e,url:v,method:n,headers:x.headers?Object.keys(x.headers).join(", "):"",bodyPreview:m.body});let I=Date.now(),k=await g.invokeRoute(v,x),C=Date.now()-I,A=await k.text(),Z;if(c)try{Z=JSON.parse(A)}catch(Q){this.debugMode&&g.log.debug("MCP tool structuredContent JSON parse failed",{toolName:e,body:A,parseErr:Q})}let V=Date.now()-w;return this.emitEvent(g,{eventType:k.ok?ce.MCP_CAPABILITY_COMPLETED:ce.MCP_CAPABILITY_FAILED,outcome:k.ok?"success":"failure",capabilityType:"tool",capabilityName:e,mcpMethod:"tools/call",transport:"http",toolPath:o.path,toolMethod:n,toolOperationId:o.raw()?.operationId??"unknown",latencyMs:V,...k.ok?{}:{errorCode:k.status,reasonCode:"upstream_error",reasonClass:"upstream"}}),this.debugMode&&(k.ok?g.log.debug("MCP tool ok response",{toolName:e,operationId:o.raw()?.operationId,status:k.status,elapsedMs:V,downstreamElapsedMs:C}):g.log.debug("MCP tool 'isError' response",{toolName:e,operationId:o.raw()?.operationId,status:k.status,elapsedMs:V,downstreamElapsedMs:C,response:A})),{content:[{type:"text",text:A}],...Z&&{structuredContent:Z},isError:!k.ok,_meta:g.custom.mcpCallToolResponse?._meta??{}}}catch(v){let x=Date.now()-w,I=v instanceof Error?`${v.name}: ${v.message}`:String(v);return g.log.error("MCP server tool invocation failed",{toolName:e,operationId:o.raw()?.operationId,method:n,path:o.path,elapsedMs:x,err:v}),this.emitEvent(g,{eventType:ce.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"tool",capabilityName:e,mcpMethod:"tools/call",transport:"http",toolPath:o.path,toolMethod:n,toolOperationId:o.raw()?.operationId??"unknown",latencyMs:x,reasonCode:"gateway_error",reasonClass:"upstream",errorType:v instanceof Error?v.name:"unknown"}),{content:[{type:"text",text:`MCP tool call failed for tool '${e}': ${I}`}],isError:!0}}},"handler")}),this.debugMode&&this.context.log.debug("MCP tool registered",{toolName:e,method:n.toUpperCase(),path:o.path,operationId:o.raw()?.operationId,contentType:i||"none",includeOutputSchema:a,includeStructuredContent:c,hasValidator:!!d,hasOutputSchema:!!p})}catch(m){throw new Error(`Failed to add tool ${n} ${o.path}`,m)}}buildToolUrl(e,r){return new wa(e).build(r.pathParams,r.queryParams)}buildToolRequest(e,r,o){let n=this.buildToolHeaders(e,r,o),i={method:e,headers:n};return this.shouldIncludeBody(e,r,o)&&(i.body=this.serializeBody(o.body,r)),i}buildToolHeaders(e,r,o){let n={...Km()};return o.headers&&Object.entries(o.headers).forEach(([i,a])=>{n[i.toLowerCase()]=a}),r&&o.body!==void 0&&(n["content-type"]=r),this.isBodyMethod(e||"")&&o.body!==void 0&&!n["content-type"]&&(n["content-type"]="application/json"),n}shouldIncludeBody(e,r,o){return o.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 n=Rn.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}),n}catch(o){let n=o instanceof Error?o.message:String(o);throw this.context.log.warn("MCP validator build failed",{method:e.methods?.[0],path:e.path,contentType:r||"none",operationId:e.raw()?.operationId,error:n}),o}}extractOutputSchema(e){try{let r=e.raw(),o=r?.responses;if(!o){this.context.log.warn("No responses found in OpenAPI spec for outputSchema",{path:e.path,operationId:r?.operationId});return}for(let n of Object.keys(o))if(n.startsWith("2")){let a=o[n]?.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:n,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(o).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 nC(t,e){if(P("handler.mcp-server"),e.route.methods.some(a=>a.toUpperCase()!=="POST"))throw new R(`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 o=e.route?.handler?.options??{},n=e.route?.path??"unknown-route",i=await Sa.getInstance({opts:o,context:e,key:n});return Gw(r,e,()=>i.handleRequest(t,e))}s(nC,"mcpServerHandler");var oC=[502,503,504];async function In(t,e){if(oC.includes(t.status)){let r=B.getLogger(e),n=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:n,headers:i})}}s(In,"logBadGatewayResponses");var ef;function hr(t){if(ef===void 0){let r=T.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),ef=r}return t.log[ef]}s(hr,"getHandlerUserLogFunction");async function iC(t,e){P("handler.open-api");let r=T.instance.build.BUILD_ID,{buildAssetsUrl:o}=T.instance,n=e.route.handler.options,{openApiFilePath:i}=n;if(!i)throw new R("Open API Spec Handler must have 'openApiFilePath' specified");let a=sC(i);if(!a.isValid)throw new R(a.error);let c=`${o}/${r}${i.substring(1)}`,u=await D.fetch(c,{method:t.method,body:t.body,headers:t.headers});if(u.status!==200)return M.notFound(t,e,{detail:"OpenAPI file could not be found."});let l={"content-type":"application/json",vary:"Accept-Encoding"};T.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 In(d,e),d}s(iC,"openApiSpecHandler");var sC=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 aC(t,e){P("handler.redirect");let r=e.route.handler.options;if(!r.location)throw new R("Redirect Handler must have 'location' specified");let o=r.status??302;return new Response(null,{status:o,headers:{location:r.location}})}s(aC,"redirectHandler");async function cC(t){if(P("handler.zuplo-service-proxy"),Object.entries(t.params).length!==1)throw new R("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,T.instance.zuploEdgeApiUrl),r=new Headers(t.headers);return r.set("Authorization",`Bearer ${T.instance.authApiJWT}`),D.fetch(e,{method:t.method,headers:r,body:t.body})}s(cC,"zuploServiceProxy");function uC(t,e){let r=t.endsWith("/"),o=e.startsWith("/");return r&&o?`${t.substring(0,t.length-1)}${e}`:!r&&!o?`${t}/${e}`:`${t}${e}`}s(uC,"join");async function lC(t,e){P("handler.url-forward");let r=hr(e),o=e.route.handler.options,n=o.forwardSearch!==!1,i;if(T.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?i=o.followRedirects===!0?"follow":"manual":typeof o.followRedirects<"u"&&P("handler.url-forward.follow-redirects"),!o.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!o||typeof o.__rewriteFunction!="function")throw new R("Invalid options for this route");let a=yr(e),c=new URL(t.url),u=o.__rewriteFunction(t,a),l=uC(u,c.pathname),d=n?`${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(w){throw new Error(`Failed to buffer request body for redirect handling: ${w}`)}let y=await fetch(d,{method:t.method,body:m,headers:t.headers,redirect:i,zuplo:o.mtlsCertificate?{mtlsCertificate:o.mtlsCertificate}:void 0}),g=Date.now()-p;return r(`URL Forward received response ${y.status} - ${y.statusText} in ${g}ms`),In(y,e),y}s(lC,"urlForwardHandler");var dC=s((t,e)=>{let r=new URL(t),o=new URL(e);for(let[n,i]of o.searchParams.entries())r.searchParams.append(n,i);return r.toString()},"addQuery");async function pC(t,e){P("handler.url-rewrite");let r=hr(e),o=e.route.handler.options,n=o.forwardSearch!==!1,i=o.followRedirects??!1;if(!o||typeof o.__rewriteFunction!="function")throw new R("Invalid options for this route");let a=yr(e),c=o.__rewriteFunction(t,a),u=n?dC(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:o.mtlsCertificate?{mtlsCertificate:o.mtlsCertificate}:void 0}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),In(d,e),d}s(pC,"urlRewriteHandler");function mC(t,e,r){t.addEventListener("close",()=>{e.close()}),e.addEventListener("close",()=>{t.close()}),t.addEventListener("error",o=>{r.log.error(`Incoming WebSocket error: ${JSON.stringify(o)}`),e.send(JSON.stringify(o))}),e.addEventListener("error",o=>{r.log.error(`Outgoing WebSocket error: ${JSON.stringify(o)}`),t.send(JSON.stringify(o))}),t.addEventListener("message",o=>{e.send(o.data)}),e.addEventListener("message",o=>{t.send(o.data)})}s(mC,"wireUpPassthrough");async function fC(t,e){P("handler.websocket");let r=e.route.handler.options,o=hr(e);if(!r||!r.rewritePattern)throw new R("WebSocket Handler must have option 'rewritePattern' specified");let n=t.headers.get("Upgrade");if(!n||n!=="websocket")return M.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new R("Invalid options for this route");let i=yr(e),a=r.__rewriteFunction(t,i);if(o(`Attempting WebSocket connection to '${a}'`),T.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(),o("WebSocket connection established with upstream"),d()},"onOpen"),y=s(w=>{g(),o(`WebSocket connection error: ${w}`),p(new Error("Upstream open failed"))},"onErr"),g=s(()=>{c.removeEventListener("open",m),c.removeEventListener("error",y)},"cleanup");c.addEventListener("open",m),c.addEventListener("error",y)}).catch(d=>{throw new Error(`Failed to open outgoing socket: ${d.message}`)});let{socket:u,response:l}=globalThis.Deno.upgradeWebSocket(t.originalRequest);return mC(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 o(`WebSocket connected, received response ${c.status} - ${c.statusText}`),new Response(null,{status:101,webSocket:c.webSocket})}}s(fC,"webSocketHandler");var tf=s((t,e)=>t.map((o,n)=>{let i;if(typeof o.module=="object"&&(i=o.module[o.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${n+1}, export name: ${o.export}`;throw new R(`${a} - Websocket policy must be a valid function (${c})`)}return i}),"getWebSocketPolicyFunctions"),sx=s(async(t,e,r,o,n,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,o,n),a===void 0)return}}return a},"webSocketPolicyProcessor");async function gC(t,e,r){r(`Attempting WebSocket connection to '${e}'`);let o=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(()=>{o.removeEventListener("open",u),o.removeEventListener("error",l)},"cleanup");o.addEventListener("open",u),o.addEventListener("error",l)}).catch(a=>{throw new Error(`Failed to open outgoing socket: ${a.message}`)});let{socket:n,response:i}=globalThis.Deno.upgradeWebSocket(t);return{clientSocket:n,outgoingSocket:o,response:i}}s(gC,"getDenoClientAndServerSockets");function hC(t){return t>=400&&t<600}s(hC,"isUpstreamHttpErrorStatus");async function yC(t,e,r){r(`Attempting WebSocket connection to '${e}'`);let o=await fetch(e,{method:t.method,headers:t.headers,body:t.body});if(o.status!==101||!o.webSocket)return r(`WebSocket upgrade failed: ${o.status} ${o.statusText}`),{ok:!1,response:o};let n=new WebSocketPair,[i,a]=Object.values(n);r(`WebSocket connected, received response ${o.status} - ${o.statusText}`),o.webSocket.accept(),a.accept();let c=new Response(null,{status:101,webSocket:i});return{ok:!0,clientSocket:i,outgoingSocket:o.webSocket,serverSocket:a,response:c}}s(yC,"getCfClientAndServerSockets");function ax(t,e,r,o,n,i){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",a=>{o.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 sx(l,t,e,r,o,n);d!==void 0&&e.send(d)},"innerPipeline")(a).catch(o.log.error);o.waitUntil(u)}catch(c){o.log.error(c)}})}s(ax,"wireUpListeners");async function bC(t,e){P("handler.websocket-pipeline");let r=e.route.handler.options,o=hr(e);if(!r||!r.rewritePattern)throw new R("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let n=t.headers.get("Upgrade");if(!n||n!=="websocket")return M.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new R("Invalid options for this route");let i=yr(e),a=r.__rewriteFunction(t,i),c=r.policies?.inbound?tf(r.policies.inbound,"inbound"):[],u=r.policies?.outbound?tf(r.policies.outbound,"outbound"):[],l,d,p;if(T.instance.isDeno){if(!t.originalRequest)throw new Error("Original websocket request is not available");let m=await gC(t.originalRequest,a,o);l=m.clientSocket,d=m.outgoingSocket,p=m.response}else{a=a.replace(/^(ws)/,"http");let m=await yC(t,a,o);if(!m.ok){let y=m.response;if(hC(y.status))return y;let g=await y.text(),w=`WebSocket connection error - ${y.status}: ${y.statusText}, content: '${g}'`;return e.log.warn({outgoingUrl:a,status:y.status},w),M.badGateway(t,e,{detail:w})}l=m.serverSocket,d=m.outgoingSocket,p=m.response}return ax(l,d,t,e,c,"inbound"),ax(d,l,t,e,u,"outbound"),p}s(bC,"webSocketPipelineHandler");var rf=class extends Ne{constructor(r){super();this.options=r}static{s(this,"AWSLoggingPlugin")}getTransport(){return new nf(this.options)}},nf=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;environmentStage;logGroupName;logStreamName;region;fields;batcher=new ue("aws-log-transport",10,async e=>{if(e.length===0)return;let r=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let o=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:r,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}});o.ok||await me({level:"error",messages:[`Failed to send logs to AWS: ${o.status} - ${o.statusText}`]},o)}catch{await me({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:r,logGroupName:o,secretAccessKey:n,region:i,fields:a}){P("logging.aws"),this.awsClient=new tn({accessKeyId:e,secretAccessKey:n,service:"logs",region:i}),this.logGroupName=o,this.logStreamName=r,this.region=i,this.environmentType=T.instance.loggingEnvironmentType,this.environmentStage=T.instance.loggingEnvironmentStage,this.environment=T.instance.deploymentName,this.fields=a??{}}log(e,r){e.messages.forEach(o=>{let n={timestamp:Date.now(),message:JSON.stringify(Object.assign({data:ut(o),severity:e.level,source:e.logSource,environment:this.environment,atomicCounter:e.vectorClock,requestId:e.requestId,environmentType:this.environmentType,environmentStage:this.environmentStage,rayId:e.rayId===null?void 0:e.rayId},this.fields,r.properties??{}))};this.batcher.enqueue(n)}),r.waitUntil(this.batcher.waitUntilFlushed())}};var of=class extends Ne{constructor(r){super();this.options=r}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new sf(this.options)}},sf=class{static{s(this,"DynaTraceTransport")}constructor(e){P("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=T.instance.loggingEnvironmentType,this.#o=T.instance.loggingEnvironmentStage,this.#n=T.instance.deploymentName,this.#i=e.fields??{}}#e;#t;#n;#r;#o;#i;log(e,r){e.messages.forEach(o=>{let n=Object.assign({timestamp:new Date().toISOString(),message:ut(o),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.atomicCounter":e.vectorClock,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId},this.#i,r.properties??{});this.batcher.enqueue(n)}),r.waitUntil(this.batcher.waitUntilFlushed())}#s=s(async e=>{if(e.length!==0)try{let r=await D.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});r.ok||await me({level:"error",messages:[`Failed to send logs to Dynatrace: ${r.status} - ${r.statusText}`]},r)}catch{await me({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ue("dyna-trace-log-transport",10,this.#s)};var af=class extends Ne{constructor(r){super();this.options=r}static{s(this,"LokiLoggingPlugin")}getTransport(){return new uf(this.options)}},cf=class{static{s(this,"LokiStream")}constructor(e,r,o,n,i,a){this.level=e,this.environment=r,this.environmentType=o,this.environmentStage=n,this.requestId=a,this.job=i}job;level;environment;environmentType;environmentStage;requestId;equals=s(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function vC(t,e){return btoa(`${t}:${e}`)}s(vC,"createBasicDigest");var uf=class{static{s(this,"LokiTransport")}constructor(e){P("logging.loki"),this.#n=e.url,this.#r=vC(e.username,e.password),this.#i=T.instance.loggingEnvironmentType,this.#s=T.instance.loggingEnvironmentStage,this.#o=T.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo",this.#a=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;#a;log(e,r){let o=new cf(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(n=>{let i=Object.assign({stream:o,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:ut(n),nanoSecondEpoch:`${e.timestamp.getTime()}000000`},this.#a,r.properties??{});this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}#u=s(e=>{let r={streams:[]};return e.forEach(o=>{let n=r.streams.find(i=>i.stream.equals(o.stream));n||(n={stream:o.stream,values:[]},r.streams.push(n)),n.values.push(this.#e>1?[o.nanoSecondEpoch,o.message,{requestId:o.requestId,rayId:o.rayId,atomicCounter:JSON.stringify(o.atomicCounter)}]:[o.nanoSecondEpoch,o.message])}),r},"#convertToLokiStreamsBatch");#l=s(async e=>{if(e.length===0)return;let r=this.#u(e);try{let o=await D.fetch(this.#n,{method:"POST",body:JSON.stringify(r),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});o.ok||await me({level:"error",messages:[`Failed to send logs to Loki: ${o.status} - ${o.statusText}`]},o)}catch{await me({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ue("loki-log-transport",10,this.#l)};var lf=class extends Ne{constructor(r){super();this.options=r}static{s(this,"NewRelicLoggingPlugin")}getTransport(){return new df(this.options)}},df=class{static{s(this,"NewRelicTransport")}constructor(e){P("logging.newrelic"),this.#e=e.url??"https://log-api.newrelic.com/log/v1",this.#t=e.apiKey,this.#r=T.instance.loggingEnvironmentType,this.#o=T.instance.loggingEnvironmentStage,this.#n=T.instance.deploymentName,this.#i=e.fields??{},this.#s=e.service??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,r){e.messages.forEach(o=>{let n=Object.assign({message:ut(o),level:e.level,timestamp:Date.now(),service:this.#s,request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource},this.#i,r.properties??{});this.batcher.enqueue(n)}),r.waitUntil(this.batcher.waitUntilFlushed())}#a=s(async e=>{if(e.length!==0)try{let r=await D.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json","Api-Key":this.#t}});r.ok||await me({level:"error",messages:[`Failed to send logs to New Relic: ${r.status} - ${r.statusText}`]},r)}catch{await me({level:"error",messages:["Failed to connect to New Relic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ue("new-relic-log-transport",10,this.#a)};var pf=class extends Ne{constructor(r){super();this.options=r}static{s(this,"SplunkLoggingPlugin")}getTransport(){return new mf(this.options)}},mf=class{static{s(this,"SplunkTransport")}constructor(e){P("logging.splunk"),this.#e=e.url,this.#t=e.token,this.#r=T.instance.loggingEnvironmentType,this.#o=T.instance.loggingEnvironmentStage,this.#n=T.instance.deploymentName,this.#i=e.fields??{},this.#s=e.index??"main",this.#a=e.sourcetype??"json",this.#u=e.host??"zuplo-api",this.#l=e.channel}#e;#t;#n;#r;#o;#i;#s;#a;#u;#l;log(e,r){e.messages.forEach(o=>{let i={event:{message:ut(o),level:e.level,timestamp:new Date().toISOString(),request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource,...this.#i,...r.properties??{}},sourcetype:this.#a,host:this.#u,index:this.#s,time:Math.floor(Date.now()/1e3)};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}#c=s(async e=>{if(e.length!==0)try{for(let r of e){let o={"Content-Type":"application/json",Authorization:`Splunk ${this.#t}`};this.#l&&(o["X-Splunk-Request-Channel"]=this.#l);let n=await D.fetch(this.#e,{method:"POST",body:JSON.stringify(r),headers:o});if(!n.ok){let i=await n.text();await me({level:"error",messages:[`Failed to send logs to Splunk: ${n.status} - ${n.statusText}`,`Response: ${i}`]},n)}}}catch(r){await me({level:"error",messages:["Failed to connect to Splunk logging service. Check that the URL is correct.",`Error: ${r instanceof Error?r.message:String(r)}`]})}},"#dispatchFunction");batcher=new ue("splunk-log-transport",10,this.#c)};var ff=class extends Ne{constructor(r){super();this.options=r}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new gf(this.options)}},gf=class{static{s(this,"SumoLogicTransport")}constructor(e){P("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=T.instance.loggingEnvironmentType,this.#r=T.instance.loggingEnvironmentStage,this.#t=T.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;log(e,r){e.messages.forEach(o=>{let n=Object.assign({timestamp:new Date().toISOString(),message:ut(o),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId},this.#s,r.properties??{});this.batcher.enqueue(n)}),r.waitUntil(this.batcher.waitUntilFlushed())}#a=s(async e=>{if(e.length===0)return;let r=e.map(n=>JSON.stringify(n)).join(`
240
+ `}s(ya,"getIntrospectionQuery");var cE=2,jw=4,uE=24,lE=16,zw=512,dE=/(token|secret|authorization|password|cookie|credential|client[_-]?secret|code[_-]?verifier|(^|[_-])(code|state|verifier)($|[_-]))/i,pE=/("(?:access_token|refresh_token|id_token|client_secret|authorization|password|cookie|code|state|code_verifier)"\s*:\s*")([^"]*)(")/gi,mE=/\b(access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|password|cookie|code|state|code[_-]?verifier)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&]+)/gi,fE=/\b(authorization)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|(?:Bearer|Basic)\s+[^\s,;]+|[^\s,;]+)/gi,gE=/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,hE=/\bBasic\s+[A-Za-z0-9+/=-]+/gi;function Zw(t){let e=t.route;return e&&typeof e=="object"?e:void 0}s(Zw,"readRoute");function yE(t){let e=Zw(t)?.path;return typeof e=="string"&&e.length>0?e:void 0}s(yE,"readRoutePath");function bE(t){let e=Zw(t)?.raw;if(typeof e!="function")return;let r=e();if(!r||typeof r!="object")return;let o=r.operationId;return typeof o=="string"&&o.length>0?o:void 0}s(bE,"readRouteOperationId");function vE(t){if(!(t===void 0||!Number.isFinite(t)||t<100))return`${Math.trunc(t/100)}xx`}s(vE,"deriveStatusClass");function wE(t,e){if(!(!t&&!e))return t==="user"?e==="user-oauth"?"upstream_user_attributed":"gateway_user_attributed_only":t==="shared"?"shared_upstream_identity":t==="none"?"machine_identity":"unknown"}s(wE,"deriveOriginAttributionMode");function xE(t){if(!t)return;let e=t.toLowerCase();return e.includes("desktop")||e.includes("claude")||e.includes("chatgpt")?"desktop":e.includes("vscode")||e.includes("cursor")||e.includes("zed")||e.includes("jetbrains")||e.includes("ide")?"ide":e.includes("extension")?"extension":e.includes("agent")||e.includes("bot")||e.includes("worker")||e.includes("service")?"service":"unknown"}s(xE,"deriveClientKind");function RE(t,e){return e==="success"?"none":t===ce.MCP_REQUEST_RECEIVED||t===ce.MCP_REQUEST_REJECTED||t===ce.MCP_CLIENT_UNSUPPORTED_BEHAVIOR?"ingress":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===ce.MCP_INITIALIZE_NEGOTIATED?"routing":t.startsWith("mcp_capability_")?"upstream":t===ce.MCP_REQUEST_COMPLETED?"egress":"none"}s(RE,"deriveFailureStage");function IE(t,e){return e==="success"?"none":e==="application_error"?"mcp_application":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===ce.MCP_CAPABILITY_FAILED||t===ce.MCP_CAPABILITY_CONNECT_REQUIRED?"upstream":t===ce.MCP_REQUEST_REJECTED||t===ce.MCP_CLIENT_UNSUPPORTED_BEHAVIOR?"client":"gateway"}s(IE,"deriveFailureOrigin");function PE(t,e){return e==="success"?"none":t.startsWith("mcp_auth_")||t.startsWith("mcp_oauth_")?"auth":t===ce.MCP_CLIENT_UNSUPPORTED_BEHAVIOR||t===ce.MCP_REQUEST_REJECTED?"protocol":"none"}s(PE,"deriveReasonClass");function SE(t){return t.length<=zw?t:`${t.slice(0,zw)}...`}s(SE,"truncateAnalyticsString");function TE(t){return SE(t.replace(pE,"$1[REDACTED]$3").replace(fE,"$1$2[REDACTED]").replace(mE,"$1$2[REDACTED]").replace(gE,"Bearer [REDACTED]").replace(hE,"Basic [REDACTED]"))}s(TE,"redactAnalyticsString");function qw(t,e){if(t!==void 0){if(t===null||typeof t=="boolean")return t;if(typeof t=="string")return TE(t);if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(Array.isArray(t))return e>=jw?"[DEPTH_LIMIT]":t.slice(0,lE).map(r=>qw(r,e+1)).filter(r=>r!==void 0);if(typeof t=="object")return t instanceof Date?t.toISOString():e>=jw?"[DEPTH_LIMIT]":Fw(t,e+1)}}s(qw,"sanitizeAnalyticsValue");function Fw(t,e=0){if(!t)return;let r={};for(let[o,n]of Object.entries(t).slice(0,uE)){if(dE.test(o)){r[o]="[REDACTED]";continue}let i=qw(n,e);i!==void 0&&(r[o]=i)}return Object.keys(r).length===0?void 0:r}s(Fw,"sanitizeMcpAnalyticsAttributes");function ne(t){return t===void 0?null:t}s(ne,"nullable");function kE(t){let e=t.environment;return e&&typeof e=="object"&&typeof e.name=="string"?e.name:null}s(kE,"readEnvironment");function EE(t){let e=t.requestId;return typeof e=="string"&&e.length>0?e:null}s(EE,"readRequestId");function CE(t){if(t===void 0)return null;try{return JSON.stringify(t)}catch{return null}}s(CE,"attributesToJsonString");function _E(t,e){let r=Fw(e.attributes),o=EE(t),n=e.ownerMode??null,i=e.upstreamAuthMode??null,a=e.clientKind??xE(e.clientName)??null,c=wE(n??void 0,i??void 0)??null,u=vE(e.httpStatusCode)??null,l=e.reasonClass??PE(e.eventType,e.outcome),d=e.failureOrigin??IE(e.eventType,e.outcome),p=e.failureStage??RE(e.eventType,e.outcome);return{schemaVersion:cE,outcome:e.outcome,subjectId:ne(e.subjectId),environment:kE(t),traceId:e.traceId??o,spanId:ne(e.spanId),parentEventId:ne(e.parentEventId),mcpSessionId:ne(e.mcpSessionId),routeSurface:ne(e.routeSurface),routePath:e.routePath??yE(t)??null,operationId:e.operationId??bE(t)??null,virtualServerName:ne(e.virtualServerName),virtualServerTitle:ne(e.virtualServerTitle),upstreamServerName:ne(e.upstreamServerName),upstreamServerTitle:ne(e.upstreamServerTitle),upstreamBindingId:ne(e.upstreamBindingId),clientName:ne(e.clientName),clientTitle:ne(e.clientTitle),clientVersion:ne(e.clientVersion),clientKind:a,authProfileId:ne(e.authProfileId),upstreamAuthMode:i,ownerMode:n,authMethod:ne(e.authMethod),originAttributionMode:c,apiKeySub:ne(e.apiKeySub),httpMethod:ne(e.httpMethod),httpStatusCode:ne(e.httpStatusCode),statusClass:u,mcpMethod:ne(e.mcpMethod),mcpProtocolVersion:ne(e.mcpProtocolVersion),mcpStatus:ne(e.mcpStatus),mcpErrorType:ne(e.mcpErrorType),applicationError:ne(e.applicationError),applicationErrorCode:ne(e.applicationErrorCode),toolResultIsError:ne(e.toolResultIsError),transport:ne(e.transport),sessionId:ne(e.sessionId),capabilityType:ne(e.capabilityType),capabilityName:ne(e.capabilityName),capabilityTitle:ne(e.capabilityTitle),upstreamCapabilityName:ne(e.upstreamCapabilityName),upstreamCapabilityTitle:ne(e.upstreamCapabilityTitle),capabilitySchemaHash:ne(e.capabilitySchemaHash),toolPath:ne(e.toolPath),toolMethod:ne(e.toolMethod),toolOperationId:ne(e.toolOperationId),resourceUri:ne(e.resourceUri),resourceMimeType:ne(e.resourceMimeType),policyId:ne(e.policyId),policyAction:ne(e.policyAction),guardrailType:ne(e.guardrailType),guardrailDirection:ne(e.guardrailDirection),guardrailFindingCount:ne(e.guardrailFindingCount),redactionCount:ne(e.redactionCount),requestMutated:ne(e.requestMutated),responseMutated:ne(e.responseMutated),latencyMs:ne(e.latencyMs),gatewayLatencyMs:ne(e.gatewayLatencyMs),upstreamLatencyMs:ne(e.upstreamLatencyMs),authLatencyMs:ne(e.authLatencyMs),policyLatencyMs:ne(e.policyLatencyMs),requestBytes:ne(e.requestBytes),responseBytes:ne(e.responseBytes),estimatedInputTokens:ne(e.estimatedInputTokens),estimatedOutputTokens:ne(e.estimatedOutputTokens),estimatedContextTokens:ne(e.estimatedContextTokens),contextPressureBucket:ne(e.contextPressureBucket),responseMimeTypes:ne(e.responseMimeTypes),base64Suspected:ne(e.base64Suspected),truncated:ne(e.truncated),isLargePayloadRequest:ne(e.isLargePayloadRequest),isLargePayloadResponse:ne(e.isLargePayloadResponse),payloadCaptureMode:ne(e.payloadCaptureMode),reasonCode:ne(e.reasonCode),reasonClass:l,errorType:e.errorType??e.reasonCode??null,failureOrigin:d,failureStage:p,errorCode:ne(e.errorCode),customMetadataJson:ne(e.customMetadataJson),attributesJson:CE(r)}}s(_E,"buildMcpAnalyticsMetadata");function Hw(t,e){try{t.analyticsContext.addAnalyticsEvent(e.value??1,e.eventType,_E(t,e),e.unit)}catch(r){t.log?.warn?.({event:"mcp_analytics_emit_failed",errorName:r instanceof Error?r.name:"unknown"})}}s(Hw,"emitMcpAnalyticsEvent");function Bw(t,e){let r=t.virtualServerName??e;return r===void 0?t:{...t,virtualServerName:r}}s(Bw,"injectMcpServerName");import{AsyncLocalStorage as OE}from"node:async_hooks";var Wm=new OE;function Gw(t,e,r){return Wm.run({headers:t,zuploContext:e},r)}s(Gw,"runWithInvokeContext");function Km(){return Wm.getStore()?.headers??{}}s(Km,"getInvokeHeaders");function vn(){let t=Wm.getStore();if(!t)throw new Error("No Zuplo context available in current execution context");return t.zuploContext}s(vn,"getInvokeContext");var ti=class{static{s(this,"R")}type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,e,r,o,n,i){this.type=t,this.name=e,this.prefix=r,this.value=o,this.suffix=n,this.modifier=i}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},AE=/[$_\p{ID_Start}]/u,$E=/[$_\u200C\u200D\p{ID_Continue}]/u,Ym=".*";function LE(t,e){return(e?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(t)}s(LE,"Re");function Ww(t,e=!1){let r=[],o=0;for(;o<t.length;){let n=t[o],i=s(function(a){if(!e)throw new TypeError(a);r.push({type:"INVALID_CHAR",index:o,value:t[o++]})},"c");if(n==="*"){r.push({type:"ASTERISK",index:o,value:t[o++]});continue}if(n==="+"||n==="?"){r.push({type:"OTHER_MODIFIER",index:o,value:t[o++]});continue}if(n==="\\"){r.push({type:"ESCAPED_CHAR",index:o++,value:t[o++]});continue}if(n==="{"){r.push({type:"OPEN",index:o,value:t[o++]});continue}if(n==="}"){r.push({type:"CLOSE",index:o,value:t[o++]});continue}if(n===":"){let a="",c=o+1;for(;c<t.length;){let u=t.substr(c,1);if(c===o+1&&AE.test(u)||c!==o+1&&$E.test(u)){a+=t[c++];continue}break}if(!a){i(`Missing parameter name at ${o}`);continue}r.push({type:"NAME",index:o,value:a}),o=c;continue}if(n==="("){let a=1,c="",u=o+1,l=!1;if(t[u]==="?"){i(`Pattern cannot start with "?" at ${u}`);continue}for(;u<t.length;){if(!LE(t[u],!1)){i(`Invalid character '${t[u]}' at ${u}.`),l=!0;break}if(t[u]==="\\"){c+=t[u++]+t[u++];continue}if(t[u]===")"){if(a--,a===0){u++;break}}else if(t[u]==="("&&(a++,t[u+1]!=="?")){i(`Capturing groups are not allowed at ${u}`),l=!0;break}c+=t[u++]}if(l)continue;if(a){i(`Unbalanced pattern at ${o}`);continue}if(!c){i(`Missing pattern at ${o}`);continue}r.push({type:"REGEX",index:o,value:c}),o=u;continue}r.push({type:"CHAR",index:o,value:t[o++]})}return r.push({type:"END",index:o,value:""}),r}s(Ww,"v");function Kw(t,e={}){let r=Ww(t);e.delimiter??="/#?",e.prefixes??="./";let o=`[^${Rt(e.delimiter)}]+?`,n=[],i=0,a=0,c="",u=new Set,l=s(k=>{if(a<r.length&&r[a].type===k)return r[a++].value},"a"),d=s(()=>l("OTHER_MODIFIER")??l("ASTERISK"),"f"),p=s(k=>{let C=l(k);if(C!==void 0)return C;let{type:A,index:Z}=r[a];throw new TypeError(`Unexpected ${A} at ${Z}, expected ${k}`)},"d"),m=s(()=>{let k="",C;for(;C=l("CHAR")??l("ESCAPED_CHAR");)k+=C;return k},"T"),y=s(k=>k,"Se"),g=e.encodePart||y,w="",v=s(k=>{w+=k},"U"),x=s(()=>{w.length&&(n.push(new ti(3,"","",g(w),"",3)),w="")},"$"),I=s((k,C,A,Z,V)=>{let Q=3;switch(V){case"?":Q=1;break;case"*":Q=0;break;case"+":Q=2;break}if(!C&&!A&&Q===3){v(k);return}if(x(),!C&&!A){if(!k)return;n.push(new ti(3,"","",g(k),"",Q));return}let te;A?A==="*"?te=Ym:te=A:te=o;let re=2;te===o?(re=1,te=""):te===Ym&&(re=0,te="");let se;if(C?se=C:A&&(se=i++),u.has(se))throw new TypeError(`Duplicate name '${se}'.`);u.add(se),n.push(new ti(re,se,g(k),te,g(Z),Q))},"V");for(;a<r.length;){let k=l("CHAR"),C=l("NAME"),A=l("REGEX");if(!C&&!A&&(A=l("ASTERISK")),C||A){let V=k??"";e.prefixes.indexOf(V)===-1&&(v(V),V=""),x();let Q=d();I(V,C,A,"",Q);continue}let Z=k??l("ESCAPED_CHAR");if(Z){v(Z);continue}if(l("OPEN")){let V=m(),Q=l("NAME"),te=l("REGEX");!Q&&!te&&(te=l("ASTERISK"));let re=m();p("CLOSE");let se=d();I(V,Q,te,re,se);continue}x(),p("END")}return n}s(Kw,"D");function Rt(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}s(Rt,"S");function Vw(t){return t&&t.ignoreCase?"ui":"u"}s(Vw,"X");function NE(t,e,r){return Qw(Kw(t,r),e,r)}s(NE,"Z");function wn(t){switch(t){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}s(wn,"k");function Qw(t,e,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith="";let o=r.start?"^":"";for(let c of t){if(c.type===3){c.modifier===3?o+=Rt(c.value):o+=`(?:${Rt(c.value)})${wn(c.modifier)}`;continue}e&&e.push(c.name);let u=`[^${Rt(r.delimiter)}]+?`,l=c.value;if(c.type===1?l=u:c.type===0&&(l=Ym),!c.prefix.length&&!c.suffix.length){c.modifier===3||c.modifier===1?o+=`(${l})${wn(c.modifier)}`:o+=`((?:${l})${wn(c.modifier)})`;continue}if(c.modifier===3||c.modifier===1){o+=`(?:${Rt(c.prefix)}(${l})${Rt(c.suffix)})`,o+=wn(c.modifier);continue}o+=`(?:${Rt(c.prefix)}`,o+=`((?:${l})(?:`,o+=Rt(c.suffix),o+=Rt(c.prefix),o+=`(?:${l}))*)${Rt(c.suffix)})`,c.modifier===0&&(o+="?")}let n=`[${Rt(r.endsWith)}]|$`,i=`[${Rt(r.delimiter)}]`;if(r.end)return r.strict||(o+=`${i}?`),r.endsWith.length?o+=`(?=${n})`:o+="$",new RegExp(o,Vw(r));r.strict||(o+=`(?:${i}(?=${n}))?`);let a=!1;if(t.length){let c=t[t.length-1];c.type===3&&c.modifier===3&&(a=r.delimiter.indexOf(c)>-1)}return a||(o+=`(?=${i}|${n})`),new RegExp(o,Vw(r))}s(Qw,"F");var gr={delimiter:"",prefixes:"",sensitive:!0,strict:!0},ME={delimiter:".",prefixes:"",sensitive:!0,strict:!0},DE={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function UE(t,e){return t.length?t[0]==="/"?!0:!e||t.length<2?!1:(t[0]=="\\"||t[0]=="{")&&t[1]=="/":!1}s(UE,"J");function Yw(t,e){return t.startsWith(e)?t.substring(e.length,t.length):t}s(Yw,"Q");function jE(t,e){return t.endsWith(e)?t.substr(0,t.length-e.length):t}s(jE,"Ee");function Xw(t){return!t||t.length<2?!1:t[0]==="["||(t[0]==="\\"||t[0]==="{")&&t[1]==="["}s(Xw,"W");var ex=["ftp","file","http","https","ws","wss"];function tx(t){if(!t)return!0;for(let e of ex)if(t.test(e))return!0;return!1}s(tx,"N");function zE(t,e){if(t=Yw(t,"#"),e||t==="")return t;let r=new URL("https://example.com");return r.hash=t,r.hash?r.hash.substring(1,r.hash.length):""}s(zE,"te");function ZE(t,e){if(t=Yw(t,"?"),e||t==="")return t;let r=new URL("https://example.com");return r.search=t,r.search?r.search.substring(1,r.search.length):""}s(ZE,"re");function qE(t,e){return e||t===""?t:Xw(t)?ox(t):nx(t)}s(qE,"ne");function FE(t,e){if(e||t==="")return t;let r=new URL("https://example.com");return r.password=t,r.password}s(FE,"se");function HE(t,e){if(e||t==="")return t;let r=new URL("https://example.com");return r.username=t,r.username}s(HE,"ie");function BE(t,e,r){if(r||t==="")return t;if(e&&!ex.includes(e))return new URL(`${e}:${t}`).pathname;let o=t[0]=="/";return t=new URL(o?t:"/-"+t,"https://example.com").pathname,o||(t=t.substring(2,t.length)),t}s(BE,"ae");function GE(t,e,r){return rx(e)===t&&(t=""),r||t===""?t:ix(t)}s(GE,"oe");function VE(t,e){return t=jE(t,":"),e||t===""?t:Xm(t)}s(VE,"ce");function rx(t){switch(t){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}s(rx,"_");function Xm(t){if(t==="")return t;if(/^[-+.A-Za-z0-9]*$/.test(t))return t.toLowerCase();throw new TypeError(`Invalid protocol '${t}'.`)}s(Xm,"y");function JE(t){if(t==="")return t;let e=new URL("https://example.com");return e.username=t,e.username}s(JE,"le");function WE(t){if(t==="")return t;let e=new URL("https://example.com");return e.password=t,e.password}s(WE,"fe");function nx(t){if(t==="")return t;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(t))throw new TypeError(`Invalid hostname '${t}'`);let e=new URL("https://example.com");return e.hostname=t,e.hostname}s(nx,"z");function ox(t){if(t==="")return t;if(/[^0-9a-fA-F[\]:]/g.test(t))throw new TypeError(`Invalid IPv6 hostname '${t}'`);return t.toLowerCase()}s(ox,"j");function ix(t){if(t===""||/^[0-9]*$/.test(t)&&parseInt(t)<=65535)return t;throw new TypeError(`Invalid port '${t}'.`)}s(ix,"K");function KE(t){if(t==="")return t;let e=new URL("https://example.com");return e.pathname=t[0]!=="/"?"/-"+t:t,t[0]!=="/"?e.pathname.substring(2,e.pathname.length):e.pathname}s(KE,"he");function QE(t){return t===""?t:new URL(`data:${t}`).pathname}s(QE,"ue");function YE(t){if(t==="")return t;let e=new URL("https://example.com");return e.search=t,e.search.substring(1,e.search.length)}s(YE,"de");function XE(t){if(t==="")return t;let e=new URL("https://example.com");return e.hash=t,e.hash.substring(1,e.hash.length)}s(XE,"pe");var eC=class{static{s(this,"H")}#e;#t=[];#n={};#r=0;#o=1;#i=0;#s=0;#a=0;#u=0;#l=!1;constructor(t){this.#e=t}get result(){return this.#n}parse(){for(this.#t=Ww(this.#e,!0);this.#r<this.#t.length;this.#r+=this.#o){if(this.#o=1,this.#t[this.#r].type==="END"){if(this.#s===0){this.#w(),this.#m()?this.#c(9,1):this.#g()?this.#c(8,1):this.#c(7,0);continue}else if(this.#s===2){this.#h(5);continue}this.#c(10,0);break}if(this.#a>0)if(this.#T())this.#a-=1;else continue;if(this.#S()){this.#a+=1;continue}switch(this.#s){case 0:this.#x()&&this.#h(1);break;case 1:if(this.#x()){this.#C();let t=7,e=1;this.#R()?(t=2,e=3):this.#l&&(t=2),this.#c(t,e)}break;case 2:this.#b()?this.#h(3):(this.#v()||this.#g()||this.#m())&&this.#h(5);break;case 3:this.#I()?this.#c(4,1):this.#b()&&this.#c(5,1);break;case 4:this.#b()&&this.#c(5,1);break;case 5:this.#k()?this.#u+=1:this.#E()&&(this.#u-=1),this.#P()&&!this.#u?this.#c(6,1):this.#v()?this.#c(7,0):this.#g()?this.#c(8,1):this.#m()&&this.#c(9,1);break;case 6:this.#v()?this.#c(7,0):this.#g()?this.#c(8,1):this.#m()&&this.#c(9,1);break;case 7:this.#g()?this.#c(8,1):this.#m()&&this.#c(9,1);break;case 8:this.#m()&&this.#c(9,1);break;case 9:break;case 10:break}}this.#n.hostname!==void 0&&this.#n.port===void 0&&(this.#n.port="")}#c(t,e){switch(this.#s){case 0:break;case 1:this.#n.protocol=this.#p();break;case 2:break;case 3:this.#n.username=this.#p();break;case 4:this.#n.password=this.#p();break;case 5:this.#n.hostname=this.#p();break;case 6:this.#n.port=this.#p();break;case 7:this.#n.pathname=this.#p();break;case 8:this.#n.search=this.#p();break;case 9:this.#n.hash=this.#p();break;case 10:break}this.#s!==0&&t!==10&&([1,2,3,4].includes(this.#s)&&[6,7,8,9].includes(t)&&(this.#n.hostname??=""),[1,2,3,4,5,6].includes(this.#s)&&[8,9].includes(t)&&(this.#n.pathname??=this.#l?"/":""),[1,2,3,4,5,6,7].includes(this.#s)&&t===9&&(this.#n.search??="")),this.#f(t,e)}#f(t,e){this.#s=t,this.#i=this.#r+e,this.#r+=e,this.#o=0}#w(){this.#r=this.#i,this.#o=0}#h(t){this.#w(),this.#s=t}#y(t){return t<0&&(t=this.#t.length-t),t<this.#t.length?this.#t[t]:this.#t[this.#t.length-1]}#d(t,e){let r=this.#y(t);return r.value===e&&(r.type==="CHAR"||r.type==="ESCAPED_CHAR"||r.type==="INVALID_CHAR")}#x(){return this.#d(this.#r,":")}#R(){return this.#d(this.#r+1,"/")&&this.#d(this.#r+2,"/")}#b(){return this.#d(this.#r,"@")}#I(){return this.#d(this.#r,":")}#P(){return this.#d(this.#r,":")}#v(){return this.#d(this.#r,"/")}#g(){if(this.#d(this.#r,"?"))return!0;if(this.#t[this.#r].value!=="?")return!1;let t=this.#y(this.#r-1);return t.type!=="NAME"&&t.type!=="REGEX"&&t.type!=="CLOSE"&&t.type!=="ASTERISK"}#m(){return this.#d(this.#r,"#")}#S(){return this.#t[this.#r].type=="OPEN"}#T(){return this.#t[this.#r].type=="CLOSE"}#k(){return this.#d(this.#r,"[")}#E(){return this.#d(this.#r,"]")}#p(){let t=this.#t[this.#r],e=this.#y(this.#i).index;return this.#e.substring(e,t.index)}#C(){let t={};Object.assign(t,gr),t.encodePart=Xm;let e=NE(this.#p(),void 0,t);this.#l=tx(e)}},Qm=["protocol","username","password","hostname","port","pathname","search","hash"],fr="*";function Jw(t,e){if(typeof t!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(t,e);return{protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}s(Jw,"ge");function rr(t,e){return e?ei(t):t}s(rr,"b");function Xo(t,e,r){let o;if(typeof e.baseURL=="string")try{o=new URL(e.baseURL),e.protocol===void 0&&(t.protocol=rr(o.protocol.substring(0,o.protocol.length-1),r)),!r&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&(t.username=rr(o.username,r)),!r&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&e.password===void 0&&(t.password=rr(o.password,r)),e.protocol===void 0&&e.hostname===void 0&&(t.hostname=rr(o.hostname,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&(t.port=rr(o.port,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&(t.pathname=rr(o.pathname,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&(t.search=rr(o.search.substring(1,o.search.length),r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&e.hash===void 0&&(t.hash=rr(o.hash.substring(1,o.hash.length),r))}catch{throw new TypeError(`invalid baseURL '${e.baseURL}'.`)}if(typeof e.protocol=="string"&&(t.protocol=VE(e.protocol,r)),typeof e.username=="string"&&(t.username=HE(e.username,r)),typeof e.password=="string"&&(t.password=FE(e.password,r)),typeof e.hostname=="string"&&(t.hostname=qE(e.hostname,r)),typeof e.port=="string"&&(t.port=GE(e.port,t.protocol,r)),typeof e.pathname=="string"){if(t.pathname=e.pathname,o&&!UE(t.pathname,r)){let n=o.pathname.lastIndexOf("/");n>=0&&(t.pathname=rr(o.pathname.substring(0,n+1),r)+t.pathname)}t.pathname=BE(t.pathname,t.protocol,r)}return typeof e.search=="string"&&(t.search=ZE(e.search,r)),typeof e.hash=="string"&&(t.hash=zE(e.hash,r)),t}s(Xo,"w");function ei(t){return t.replace(/([+*?:{}()\\])/g,"\\$1")}s(ei,"C");function tC(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}s(tC,"Oe");function rC(t,e){e.delimiter??="/#?",e.prefixes??="./",e.sensitive??=!1,e.strict??=!1,e.end??=!0,e.start??=!0,e.endsWith="";let r=".*",o=`[^${tC(e.delimiter)}]+?`,n=/[$_\u200C\u200D\p{ID_Continue}]/u,i="";for(let a=0;a<t.length;++a){let c=t[a];if(c.type===3){if(c.modifier===3){i+=ei(c.value);continue}i+=`{${ei(c.value)}}${wn(c.modifier)}`;continue}let u=c.hasCustomName(),l=!!c.suffix.length||!!c.prefix.length&&(c.prefix.length!==1||!e.prefixes.includes(c.prefix)),d=a>0?t[a-1]:null,p=a<t.length-1?t[a+1]:null;if(!l&&u&&c.type===1&&c.modifier===3&&p&&!p.prefix.length&&!p.suffix.length)if(p.type===3){let m=p.value.length>0?p.value[0]:"";l=n.test(m)}else l=!p.hasCustomName();if(!l&&!c.prefix.length&&d&&d.type===3){let m=d.value[d.value.length-1];l=e.prefixes.includes(m)}l&&(i+="{"),i+=ei(c.prefix),u&&(i+=`:${c.name}`),c.type===2?i+=`(${c.value})`:c.type===1?u||(i+=`(${o})`):c.type===0&&(!u&&(!d||d.type===3||d.modifier!==3||l||c.prefix!=="")?i+="*":i+=`(${r})`),c.type===1&&u&&c.suffix.length&&n.test(c.suffix[0])&&(i+="\\"),i+=ei(c.suffix),l&&(i+="}"),c.modifier!==3&&(i+=wn(c.modifier))}return i}s(rC,"ke");var ba=class{static{s(this,"me")}#e;#t={};#n={};#r={};#o={};#i=!1;constructor(t={},e,r){try{let o;if(typeof e=="string"?o=e:r=e,typeof t=="string"){let c=new eC(t);if(c.parse(),t=c.result,o===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=o}else{if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(o)throw new TypeError("parameter 1 is not of type 'string'.")}typeof r>"u"&&(r={ignoreCase:!1});let n={ignoreCase:r.ignoreCase===!0},i={pathname:fr,protocol:fr,username:fr,password:fr,hostname:fr,port:fr,search:fr,hash:fr};this.#e=Xo(i,t,!0),rx(this.#e.protocol)===this.#e.port&&(this.#e.port="");let a;for(a of Qm){if(!(a in this.#e))continue;let c={},u=this.#e[a];switch(this.#n[a]=[],a){case"protocol":Object.assign(c,gr),c.encodePart=Xm;break;case"username":Object.assign(c,gr),c.encodePart=JE;break;case"password":Object.assign(c,gr),c.encodePart=WE;break;case"hostname":Object.assign(c,ME),Xw(u)?c.encodePart=ox:c.encodePart=nx;break;case"port":Object.assign(c,gr),c.encodePart=ix;break;case"pathname":tx(this.#t.protocol)?(Object.assign(c,DE,n),c.encodePart=KE):(Object.assign(c,gr,n),c.encodePart=QE);break;case"search":Object.assign(c,gr,n),c.encodePart=YE;break;case"hash":Object.assign(c,gr,n),c.encodePart=XE;break}try{this.#o[a]=Kw(u,c),this.#t[a]=Qw(this.#o[a],this.#n[a],c),this.#r[a]=rC(this.#o[a],c),this.#i=this.#i||this.#o[a].some(l=>l.type===2)}catch{throw new TypeError(`invalid ${a} pattern '${this.#e[a]}'.`)}}}catch(o){throw new TypeError(`Failed to construct 'URLPattern': ${o.message}`)}}test(t={},e){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return!1;try{typeof t=="object"?r=Xo(r,t,!1):r=Xo(r,Jw(t,e),!1)}catch{return!1}let o;for(o of Qm)if(!this.#t[o].exec(r[o]))return!1;return!0}exec(t={},e){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?r=Xo(r,t,!1):r=Xo(r,Jw(t,e),!1)}catch{return null}let o={};e?o.inputs=[t,e]:o.inputs=[t];let n;for(n of Qm){let i=this.#t[n].exec(r[n]);if(!i)return null;let a={};for(let[c,u]of this.#n[n].entries())if(typeof u=="string"||typeof u=="number"){let l=i[c+1];a[u]=l}o[n]={input:r[n]??"",groups:a}}return o}static compareComponent(t,e,r){let o=s((c,u)=>{for(let l of["type","modifier","prefix","value","suffix"]){if(c[l]<u[l])return-1;if(c[l]!==u[l])return 1}return 0},"o"),n=new ti(3,"","","","",3),i=new ti(0,"","","","",3),a=s((c,u)=>{let l=0;for(;l<Math.min(c.length,u.length);++l){let d=o(c[l],u[l]);if(d)return d}return c.length===u.length?0:o(c[l]??n,u[l]??n)},"s");return!e.#r[t]&&!r.#r[t]?0:e.#r[t]&&!r.#r[t]?a(e.#o[t],[i]):!e.#r[t]&&r.#r[t]?a([i],r.#o[t]):a(e.#o[t],r.#o[t])}get protocol(){return this.#r.protocol}get username(){return this.#r.username}get password(){return this.#r.password}get hostname(){return this.#r.hostname}get port(){return this.#r.port}get pathname(){return this.#r.pathname}get search(){return this.#r.search}get hash(){return this.#r.hash}get hasRegExpGroups(){return this.#i}};var va=class{static{s(this,"UrlPatternBuilder")}pattern;pathParams={};searchParams=new URLSearchParams;expectedPathParams=new Set;seenPathParams=new Set;constructor(e){this.pattern=new ba({pathname:e});let r=/:(\w+)(\([^)]*\))?[*+?]?/g,o;for(;(o=r.exec(e))!==null;)this.expectedPathParams.add(o[1])}addParameter(e,r,o){let n=this.getParameterValue(e,r,o);if(n!=null)switch(e.in){case"path":if(!this.expectedPathParams.has(e.name))throw new R(`path parameter '${e.name}' missing from pattern '${this.pattern.pathname}'`);this.seenPathParams.add(e.name),this.addPathParameter(e.name,n);break;case"query":this.addQueryParameter(e.name,n);break;default:break}}getParameterValue(e,r,o){switch(e.in){case"path":return r?.[e.name];case"query":return o?.[e.name];default:return}}addPathParameter(e,r){this.pathParams[e]=String(r)}addQueryParameter(e,r){Array.isArray(r)?r.forEach(o=>{o!=null&&this.searchParams.append(e,String(o))}):typeof r=="object"&&r!==null?this.searchParams.append(e,JSON.stringify(r)):this.searchParams.append(e,String(r))}toString(){let e=[...this.expectedPathParams].filter(i=>!this.seenPathParams.has(i));if(e.length>0)throw new R(`missing path parameters in OpenAPI spec: ${e.join(", ")}`);let r=this.pattern.pathname.replace(/:(\w+)(\([^)]*\))?([*+?])?/g,(i,a)=>this.pathParams[a]?encodeURIComponent(this.pathParams[a]):i),o=this.cleanupUrlPatternSyntax(r),n=this.searchParams.toString();return n?`${o}?${n}`:o}cleanupUrlPatternSyntax(e){return e.replace(/\{\/\}\?/g,"").replace(/\{\/\}[*+]/g,"/").replace(/\{\/\}/g,"/").replace(/(\{[^}]*\})[?*+]/g,"$1").replace(/\\:/g,":")}};var wa=class{constructor(e){this.routeData=e}static{s(this,"McpUrlBuilder")}build(e,r){let o=this.routeData.pathPattern?this.routeData.pathPattern:this.routeData.path,n=this.routeData.raw()?.parameters||[],i=new va(o);for(let a of n)i.addParameter(a,e,r);return i.toString()}};je();je();je();var xa=class t{static{s(this,"ZodFormatSchemaRegistry")}static formatter=new Map([["email",()=>h.email()],["uri",()=>h.url()],["url",()=>h.url()],["date",()=>h.iso.date()],["date-time",()=>h.iso.datetime()],["time",()=>h.iso.time()],["ipv4",()=>h.ipv4()],["ipv6",()=>h.ipv6()],["uuid",()=>h.guid()],["int32",()=>h.int32()],["int64",()=>h.int64()],["float",()=>h.number()],["double",()=>h.number()]]);static get(e){return t.formatter.get(e)}static register(e,r){t.formatter.set(e,r)}},xn=class t{static{s(this,"OpenApiToZodTranspiler")}static typeTranspilers=new Map([["string",this.transpileString.bind(this)],["number",this.transpileNumber.bind(this)],["integer",this.transpileInteger.bind(this)],["boolean",this.transpileBoolean.bind(this)],["array",this.transpileArray.bind(this)],["object",this.transpileObject.bind(this)],["null",this.transpileNull.bind(this)]]);static run(e,r){let o={path:[],definitions:{},visitedRefs:new Set,...r};return t.transpileSchema(e,o)}static transpileSchema(e,r){if(!e)return h.unknown();try{if("$ref"in e)return t.resolveReference(e.$ref,r);if(e.allOf)return t.transpileAllOf(e.allOf,r);if(e.oneOf)return t.transpileOneOf(e.oneOf,r);if(e.anyOf)return t.transpileAnyOf(e.anyOf,r);if(e.not)return t.transpileNot(e.not,r);let o=t.transpileByType(e,r);return o=t.applyCommonModifiers(o,e),o}catch(o){let n=r.path.join(".");throw new Error(`Failed to transpile schema at path "${n}": ${o.message}`)}}static transpileByType(e,r){let o=e.type;!o&&e.properties&&(o="object");let n=t.typeTranspilers.get(o||"unknown");return n?n(e,r):h.unknown()}static transpileString(e,r){if(e.enum)return h.enum(e.enum);let o=e.format?xa.get(e.format):null,n=o?o():h.string();if(n instanceof h.ZodString){let i=n;return e.minLength!==void 0&&(i=i.min(e.minLength)),e.maxLength!==void 0&&(i=i.max(e.maxLength)),e.pattern&&(i=i.regex(new RegExp(e.pattern))),i}else e.minLength||e.maxLength||e.pattern;return n}static applyNumericConstraints(e,r,o){let n=e;if(r.minimum!==void 0&&(n=n.min(r.minimum)),r.maximum!==void 0&&(n=n.max(r.maximum)),r.exclusiveMinimum!==void 0){let i;if(typeof r.exclusiveMinimum=="number")i=r.exclusiveMinimum;else if(r.minimum!==void 0)i=r.minimum+Number.EPSILON;else throw new Error(`exclusiveMinimum requires minimum to be set at path "${o.path.join(".")}"`);n=n.gt(i)}if(r.exclusiveMaximum!==void 0){let i;if(typeof r.exclusiveMaximum=="number")i=r.exclusiveMaximum;else if(r.maximum!==void 0)i=r.maximum-Number.EPSILON;else throw new Error(`exclusiveMaximum requires maximum to be set at path "${o.path.join(".")}"`);n=n.lt(i)}return n}static transpileNumber(e,r){let o=h.number();return t.applyNumericConstraints(o,{...e,type:"number"},r)}static transpileInteger(e,r){let o=h.int();return t.applyNumericConstraints(o,{...e,type:"number"},r)}static transpileBoolean(e,r){return h.boolean()}static transpileArray(e,r){let o=e.items?t.transpileSchema(e.items,{...r,path:[...r.path,"items"]}):h.unknown(),n=h.array(o);return e.minItems!==void 0&&(n=n.min(e.minItems)),e.maxItems!==void 0&&(n=n.max(e.maxItems)),e.uniqueItems&&(n=n.refine(i=>new Set(i).size===i.length,{message:"Array must contain unique items"})),n}static transpileObject(e,r){let o;if(e.properties){let n={},i=new Set(e.required||[]);for(let[c,u]of Object.entries(e.properties)){let l={...r,path:[...r.path,c]},d=t.transpileSchema(u,l);i.has(c)||(d=d.optional()),n[c]=d}let a=h.object(n);e.additionalProperties===!1?a=a.strict():(e.additionalProperties,a=a.passthrough()),o=a}else if(e.additionalProperties===!1)o=h.object({}).strict();else if(typeof e.additionalProperties=="object"){let n=t.transpileSchema(e.additionalProperties,r);o=h.record(h.string(),n)}else o=h.unknown();return(e.minProperties!==void 0||e.maxProperties!==void 0)&&(o=o.refine(n=>{let i=Object.keys(n).length;return!(e.minProperties!==void 0&&i<e.minProperties||e.maxProperties!==void 0&&i>e.maxProperties)},{message:t.buildPropertyCountErrorMessage(e.minProperties,e.maxProperties)})),o}static buildPropertyCountErrorMessage(e,r){return e!==void 0&&r!==void 0?`Object must have between ${e} and ${r} properties`:e!==void 0?`Object must have at least ${e} properties`:`Object must have at most ${r} properties`}static transpileNull(e,r){return h.null()}static transpileAllOf(e,r){return e.map((n,i)=>t.transpileSchema(n,{...r,path:[...r.path,`allOf[${i}]`]})).reduce((n,i)=>n.and(i))}static transpileOneOf(e,r){let o=e.map((n,i)=>t.transpileSchema(n,{...r,path:[...r.path,`oneOf[${i}]`]}));return o.length===0?h.never():o.length===1?o[0]:h.union(o)}static transpileAnyOf(e,r){return t.transpileOneOf(e,r)}static transpileNot(e,r){let o=t.transpileSchema(e,{...r,path:[...r.path,"not"]});return h.unknown().refine(n=>!o.safeParse(n).success,{message:"Value must not match the schema"})}static resolveReference(e,r){if(r.visitedRefs?.has(e))return h.lazy(()=>t.resolveReference(e,r));r.visitedRefs?.add(e);let o=e.split("/");if(o[0]==="#"&&o[1]==="definitions"&&r.definitions){let n=r.definitions[o[2]];if(n)return t.transpileSchema(n,r)}throw new Error(`Unable to resolve reference: ${e}`)}static applyCommonModifiers(e,r){let o=e;return r.nullable&&(o=o.nullable()),r.default!==void 0&&(o=o.default(r.default)),r.description&&(o=o.describe(r.description)),r.examples&&r.examples.length>0&&(o=o.meta({examples:r.examples})),o}static registerTypeTranspiler(e,r){t.typeTranspilers.set(e,r)}static registerFormatSchema(e,r){xa.register(e,r)}};var Ra=class{constructor(e){this.schema=e}static{s(this,"JSONSchemaBuilder")}build(){return xn.run(this.schema)}},Ia=class{constructor(e,r){this.routeData=e;this.contentType=r}static{s(this,"RequestBodySchemaBuilder")}build(){let e=this.routeData.raw()?.requestBody;if(!e?.content?.[this.contentType])return null;let r=e.content[this.contentType].schema;return r?xn.run(r):null}},Pa=class{constructor(e){this.parameters=e}static{s(this,"ParameterSchemaBuilder")}build(){if(this.parameters.length===0)return null;let e={};for(let r of this.parameters)e[r.name]=this.buildParameterSchema(r);return h.object(e)}buildParameterSchema(e){let r;e.schema?r=xn.run(e.schema):r=h.string(),e.required||(r=r.optional()),e.description&&(r=r.describe(e.description));let o=[];if(e.schema?.example!==void 0&&o.push(e.schema.example),e.schema?.examples!==void 0&&Array.isArray(e.schema.examples)&&o.push(...e.schema.examples),e.examples&&(Array.isArray(e.examples)?o.push(...e.examples):typeof e.examples=="object"&&Object.values(e.examples).forEach(n=>{n?.value!==void 0&&o.push(n.value)})),e.example!==void 0&&o.push(e.example),o.length>0){let n=[...new Set(o.map(i=>JSON.stringify(i)))].map(i=>JSON.parse(i));r=r.meta({examples:n})}return r}};var Lr=class t{static{s(this,"UniversalValidatorBuilder")}root=null;components={};static withRoot(e){let r=new t;return r.root=e,r}withBody(e){return e&&(this.components.body=e),this}withQueryParams(e){return e&&(this.components.queryParams=e),this}withPathParams(e){return e&&(this.components.pathParams=e),this}withHeaders(e){return e&&(this.components.headers=e),this}build(){return this.root?this.buildFromSchema(this.root):Object.keys(this.components).length>0?this.buildFromComponents():this.buildEmptyValidator()}buildFromSchema(e){let r=h.toJSONSchema(e);return new mr(r,o=>{let n=e.safeParse(o);return n.success?{success:!0,data:n.data,errorData:null}:{success:!1,data:null,errorMessage:h.prettifyError(n.error),errorData:h.treeifyError(n.error)}})}buildFromComponents(){let e=h.object(this.components),r=h.toJSONSchema(e);return new mr(r,o=>{let n=e.safeParse(o);return n.success?{success:!0,data:n.data,errorData:null}:{success:!1,data:null,errorMessage:h.prettifyError(n.error),errorData:h.treeifyError(n.error)}})}buildEmptyValidator(){let e={type:"object",properties:{},required:[],additionalProperties:!1};return new mr(e,r=>({success:!0,data:r,errorData:null}))}},Rn=class t{static{s(this,"SchemaBuilderFactory")}static createJsonSchemaBuilder(e){return new Ra(e)}static createRequestBodyBuilder(e,r){return new Ia(e,r)}static createParameterBuilder(e,r){let o=r?e.filter(n=>n.in===r):e;return new Pa(o)}static createValidatorBuilder(e,r){let o=new Lr,n=e.raw()?.parameters||[];if(r){let u=t.createRequestBodyBuilder(e,r);o.withBody(u.build())}let i=t.createParameterBuilder(n,"query");o.withQueryParams(i.build());let a=t.createParameterBuilder(n,"path");o.withPathParams(a.build());let c=t.createParameterBuilder(n,"header");return o.withHeaders(c.build()),o}static createPromptValidatorBuilder(e){let r=new Lr,n=e.raw()?.requestBody;if(!n?.content||!n.content["application/json"])return r;let a=t.createRequestBodyBuilder(e,"application/json");return Lr.withRoot(a.build())}static createObjectValidatorBuilder(e){let r=new Lr;if(!e||Object.keys(e).length===0)return r;let o=t.createJsonSchemaBuilder(e);return Lr.withRoot(o.build())}};var Sa=class t{static{s(this,"ZuploMcpServer")}static instances=new Map;static async getInstance({opts:e,context:r,key:o}){let n=e.debugMode??!1,i=t.instances.get(o);if(i)n&&r.log.debug("MCP Server warm reuse",{routeKey:o});else{let a=Date.now();if(i=new t(e,r),i.registerFromOperations(i.opts.operations??[]),i.registerToolsFromFileSources(i.opts.files??[]),i.registerPromptsFromFileSources(i.opts.prompts??[]),i.registerResourcesFromFileSources(i.opts.resources??[]),await i.transport.connect(),i.server.withTransport(i.transport),t.instances.set(o,i),n){let c=i.server.getTools(),u=c?c.size:0,l=i.server.getPromptDefinitions(),d=l?l.length:0,p=i.server.getResourceDefinitions(),m=p?p.length:0,y=Date.now()-a;r.log.debug("MCP Server cold start",{routeKey:o,toolCount:u,promptCount:d,resourceCount:m,totalElapsedMs:y,debugMode:n,includeOutputSchema:i.includeOutputSchema,includeStructuredContent:i.includeStructuredContent})}}return i}transport;server;opts;context;serverName;serverDisplayName;registeredToolNames;registeredPromptNames;registeredResourceNames;includeOutputSchema;includeStructuredContent;debugMode;constructor(e,r){this.debugMode=e.debugMode??!1;let o;this.debugMode?o=r.log:o=new ao,this.context=r,this.opts=e,this.serverName=e.name,this.serverDisplayName=e.name??"Zuplo MCP Server",this.server=new ga({name:this.serverDisplayName,version:e.version??"0.0.0",logger:o}),this.transport=new ha({logger:o}),this.includeOutputSchema=e.includeOutputSchema??!1,this.includeStructuredContent=e.includeStructuredContent??!1,this.registeredToolNames=new Set,this.registeredPromptNames=new Set,this.registeredResourceNames=new Set}emitEvent(e,r){Hw(e,Bw(r,this.serverName))}async handleRequest(e,r){let o=Date.now(),n=e.headers.get("mcp-session-id")??e.headers.get("Mcp-Session-Id")??null;try{let i=await e.clone().json().catch(()=>({})),a=typeof i?.method=="string"?i.method:null;this.emitEvent(r,{eventType:ce.MCP_REQUEST_RECEIVED,outcome:"success",mcpMethod:a??void 0,httpMethod:e.method,transport:"http",sessionId:n??void 0,mcpSessionId:n??void 0});try{Je.getContextExtensions(r).addHandlerResponseHook(d=>{let p=Date.now()-o;this.emitEvent(r,{eventType:ce.MCP_REQUEST_COMPLETED,outcome:d.status>=400?"failure":"success",mcpMethod:a??void 0,httpMethod:e.method,httpStatusCode:d.status,transport:"http",sessionId:n??void 0,mcpSessionId:n??void 0,latencyMs:p})})}catch{}switch(this.debugMode&&r.log.debug("MCP Server request start",{method:i.method,requestId:i.id,routePath:r.route?.path}),i.method){case"tools/list":if(this.debugMode){let d=this.server.getTools(),p=d?Array.from(d.keys()):[];r.log.debug("MCP Server list tools request",{toolCount:p.length,toolNames:p})}break;case"tools/call":r.custom.mcpCallToolRequest=i;break;case"prompts/list":if(this.debugMode){let d=this.server.getPromptDefinitions(),p=d?d.map(m=>m.name):[];r.log.debug("MCP Server list prompts request",{promptCount:p.length,promptNames:p})}break;case"resources/list":if(this.debugMode){let d=this.server.getResourceDefinitions(),p=d?d.map(m=>m.name):[];r.log.debug("MCP Server list resources request",{resourceCount:p.length,resourceNames:p})}break}let c=await this.transport.handleRequest(e),u=Date.now()-o,l=c.status>=200&&c.status<300;switch(i.method){case"initialize":{let d=i?.params?.clientInfo,p=i?.params?.protocolVersion,m=typeof d?.name=="string"?d.name:void 0,y=typeof d?.title=="string"?d.title:void 0,g=typeof d?.version=="string"?d.version:void 0,w=typeof p=="string"?p:void 0;this.emitEvent(r,{eventType:ce.MCP_INITIALIZE_NEGOTIATED,outcome:l?"success":"failure",mcpMethod:"initialize",httpMethod:e.method,httpStatusCode:c.status,transport:"http",sessionId:n??void 0,mcpSessionId:n??void 0,clientName:m,clientTitle:y,clientVersion:g,mcpProtocolVersion:w,latencyMs:u}),l||this.emitEvent(r,{eventType:ce.MCP_CLIENT_UNSUPPORTED_BEHAVIOR,outcome:"failure",mcpMethod:"initialize",httpMethod:e.method,httpStatusCode:c.status,transport:"http",sessionId:n??void 0,mcpSessionId:n??void 0,clientName:m,clientVersion:g,mcpProtocolVersion:w,reasonClass:"client",reasonCode:"initialize_failed",attributes:{feature:"initialize"}});break}case"tools/list":this.emitEvent(r,{eventType:ce.MCP_CAPABILITY_LISTED,outcome:l?"success":"failure",capabilityType:"tool",mcpMethod:"tools/list",httpMethod:e.method,httpStatusCode:c.status,transport:"http",sessionId:n??void 0,mcpSessionId:n??void 0,latencyMs:u});break;case"resources/list":this.emitEvent(r,{eventType:ce.MCP_CAPABILITY_LISTED,outcome:l?"success":"failure",capabilityType:"resource",mcpMethod:"resources/list",httpMethod:e.method,httpStatusCode:c.status,transport:"http",sessionId:n??void 0,mcpSessionId:n??void 0,latencyMs:u});break;case"prompts/list":this.emitEvent(r,{eventType:ce.MCP_CAPABILITY_LISTED,outcome:l?"success":"failure",capabilityType:"prompt",mcpMethod:"prompts/list",httpMethod:e.method,httpStatusCode:c.status,transport:"http",sessionId:n??void 0,mcpSessionId:n??void 0,latencyMs:u});break}if(this.debugMode){let d=await c.clone().json().catch(()=>({}));r.log.debug("MCP Server response complete",{status:c.status,requestMethod:i.method,requestId:i.id,totalElapsedMs:u,respData:d})}return c}catch(i){let a=Date.now()-o;return r.log.error("MCP server internal error",{elapsedMs:a,err:i}),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}`}static getOperationsMetadataForFile(e){let{routes:r}=Pe.instance.routeData,o=r.filter(i=>i.metadata?.filepath===e);if(o.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 n=new Map;for(let i of o){let a=i?.raw().operationId;if(a){n.set(a,{routeConfig:i});let c=i?.raw(),u=c["x-zuplo-mcp-tool"],l=c["x-zuplo-mcp-prompt"],d=c["x-zuplo-mcp-graphql"],p=c["x-zuplo-mcp-resource"],m=c["x-zuplo-route"]?.mcp;(u||l||d||p||m)&&n.set(a,{routeConfig:i,toolExtension:u||void 0,promptExtension:l||void 0,graphqlExtension:d||void 0,resourceExtension:p||void 0,routeMcpExtension:m||void 0})}}return n}registerFromOperations(e){let r=new Map;for(let o of e){let n=r.get(o.file)??[];n.push(o.id),r.set(o.file,n)}for(let[o,n]of r.entries()){let i=t.getOperationsMetadataForFile(o);for(let a of n){let c=i.get(a);if(!c)throw new Error(`MCP configuration error: Could not find operation with ID "${a}" in file ${o}. Verify that the operation ID exists in your OpenAPI specification.`);let{routeConfig:u,routeMcpExtension:l}=c;switch(l?.type){case"tool":this.registerTool(u,a,l);break;case"prompt":this.registerPrompt(u,a,l);break;case"resource":this.registerResource(u,a,l);break;case"graphql":this.registerGraphQLTools(a,u,l);break;default:this.context.log.warn(`Could not find "x-zuplo-route.mcp" configuration for operation: "${a}". Creating tool with fallback name and description`),this.registerTool(u,a,l)}}}}registerPromptsFromFileSources(e){for(let r of e){let o=t.getOperationsMetadataForFile(r.path),n=new Set;for(let i of r.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP prompt with operation ID: "${i}" from file: "${r.path}" with: "options.prompts" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=o.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(n.has(l))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${l}". Prompt names must be unique across all configured prompts.`);n.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,o,n){try{if(o.handler?.export==="mcpServerHandler")return;let a=Rn.createPromptValidatorBuilder(o).build();this.server.addPrompt({name:e,description:r,validator:a,generator:s(async c=>{let u=vn(),l=Date.now();try{this.debugMode&&u.log.debug("MCP prompt invoked",{promptName:e,operationId:o.raw()?.operationId,path:o.path,args:c});let d=this.buildToolUrl(o,{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(),y=await u.invokeRoute(d,p),g=Date.now()-m,w=await y.json();if(!y.ok)throw new Error(`Route returned ${y.status}: ${w}`);let v;try{if(v=w.messages||w,!Array.isArray(v))throw new Error("Response must contain a 'messages' array or be an array of messages")}catch(I){throw new Error(`Invalid JSON response or missing messages array: ${I instanceof Error?I.message:String(I)}`)}let x=Date.now()-l;return this.debugMode&&u.log.debug("MCP prompt response complete",{promptName:e,operationId:o.raw()?.operationId,status:y.status,elapsedMs:x,downstreamElapsedMs:g,messageCount:v.length}),this.emitEvent(u,{eventType:ce.MCP_CAPABILITY_COMPLETED,outcome:"success",capabilityType:"prompt",capabilityName:e,mcpMethod:"prompts/get",transport:"http",toolPath:o.path,toolMethod:"POST",toolOperationId:o.raw()?.operationId,latencyMs:x}),v}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:o.raw()?.operationId,path:o.path,elapsedMs:p,err:d}),this.emitEvent(u,{eventType:ce.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"prompt",capabilityName:e,mcpMethod:"prompts/get",transport:"http",toolPath:o.path,toolMethod:"POST",toolOperationId:o.raw()?.operationId,latencyMs:p,reasonCode:"gateway_error",reasonClass:"upstream",errorType:d instanceof Error?d.name:"unknown"}),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:n,path:o.path})}catch(i){throw this.context.log.error("Failed to register MCP prompt",{promptName:e,operationId:n,error:i instanceof Error?i.message:String(i)}),new Error(`Failed to register prompt "${e}" for operation "${n}": ${i instanceof Error?i.message:String(i)}`)}}registerResourcesFromFileSources(e){let r=new Set;for(let o of e){let n=t.getOperationsMetadataForFile(o.path);for(let i of o.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP resource with operation ID: "${i}" from file: "${o.path}" with: "options.resources" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=n.get(i);if(!a)throw new Error(`MCP Resource configuration error: Could not find operation with ID "${i}" in file ${o.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}`,y=u?.uri?.trim()||`mcp://resources/${encodeURIComponent(p)}`,g=u?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(p,y,m,c,i,g)}}}registerResourceForOperation(e,r,o,n,i,a,c){try{if(n.handler?.export==="mcpServerHandler")return;this.server.addResource(e,r,{title:e,description:o,mimeType:a,...c&&{_meta:c}},async()=>{let u=vn(),l=Date.now();try{this.debugMode&&u.log.debug("MCP resource invoked",{resourceName:e,operationId:n.raw()?.operationId,path:n.path,uri:r});let d=this.buildToolUrl(n,{}),p=this.buildToolRequest("GET",null,{});this.debugMode&&u.log.debug("MCP resource downstream call",{resourceName:e,url:d,method:"GET"});let m=Date.now(),y=await u.invokeRoute(d,p),g=Date.now()-m,w=await y.text(),v=Date.now()-l;return this.debugMode&&u.log.debug("MCP resource response complete",{resourceName:e,operationId:n.raw()?.operationId,status:y.status,elapsedMs:v,downstreamElapsedMs:g,declaredMimeType:a,contentLength:w.length}),this.emitEvent(u,{eventType:y.ok?ce.MCP_CAPABILITY_COMPLETED:ce.MCP_CAPABILITY_FAILED,outcome:y.ok?"success":"failure",capabilityType:"resource",capabilityName:e,resourceUri:r,resourceMimeType:a,mcpMethod:"resources/read",transport:"http",toolPath:n.path,toolMethod:"GET",toolOperationId:n.raw()?.operationId,latencyMs:v,...y.ok?{}:{errorCode:y.status,reasonCode:"upstream_error",reasonClass:"upstream"}}),{contents:[{uri:r,mimeType:a,text:w,...c&&{_meta:c}}]}}catch(d){let p=Date.now()-l,m=d instanceof Error?`${d.name}: ${d.message}`:String(d);throw u.log.error("MCP resource invocation failed",{resourceName:e,operationId:n.raw()?.operationId,path:n.path,elapsedMs:p,err:d}),this.emitEvent(u,{eventType:ce.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"resource",capabilityName:e,resourceUri:r,resourceMimeType:a,mcpMethod:"resources/read",transport:"http",toolPath:n.path,toolMethod:"GET",toolOperationId:n.raw()?.operationId,latencyMs:p,reasonCode:"gateway_error",reasonClass:"upstream",errorType:d instanceof Error?d.name:"unknown"}),new Error(`MCP resource call failed for resource '${e}': ${m}`)}}),this.debugMode&&this.context.log.debug("MCP resource registered from file source",{resourceName:e,operationId:i,path:n.path,uri:r,mimeType:a||"auto-detected"})}catch(u){throw this.context.log.error("Failed to register MCP resource",{resourceName:e,operationId:i,error:u instanceof Error?u.message:String(u)}),new Error(`Failed to register resource "${e}" for operation "${i}": ${u instanceof Error?u.message:String(u)}`)}}registerTool(e,r,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP tool disabled by x-zuplo-route.mcp configuration",{operationId:r});return}let i=o?.name?.trim()||r;if(this.registeredToolNames.has(i))throw new Error(`MCP Tool configuration error: Tool name conflict detected for operation: "${r}". The tool name "${i}" is already in use. Provide a unique 'name' in the x-zuplo-route.mcp configuration for operation "${r}".`);this.registeredToolNames.add(i);let a=o?.description?.trim()||e.raw().description?.trim()||e.raw().summary?.trim()||`Executes tool: ${i}`,c=o?.includeOutputSchema??this.includeOutputSchema??!1,u=o?.includeStructuredContent??this.includeStructuredContent??!1;if(e.methods.length!=1)throw new Error(`MCP tool configuration error: multiple methods "${e.methods.join(", ")}" on operation "${r}" not permitted. Only tools with a singular method are permitted.`);this.registerToolsForMethod({routeData:e,method:e.methods[0],name:i,description:a,includeOutputSchema:c,includeStructuredContent:u,annotations:o?.annotations,_meta:o?._meta})}registerPrompt(e,r,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP prompt disabled by x-zuplo-route.mcp",{operationId:r});return}let i=o?.name?.trim()||r;if(this.registeredPromptNames.has(i))throw new Error(`MCP Prompt configuration error: Duplicate prompt name "${i}" for operation ID "${r}". Prompt names must be unique across all configured prompts.`);this.registeredPromptNames.add(i);let a=o?.description?.trim()||this.generatePromptDescriptionFromSpec(e);this.registerPromptForOperation(i,a,e,r)}registerResource(e,r,o){if(!(o?.enabled??!0)){this.debugMode&&this.context.log.debug("MCP resource disabled by x-zuplo-route.mcp",{operationId:r});return}if(!e.methods||e.methods.length===0)throw new Error(`MCP Resource configuration error: Operation "${r}" has no HTTP methods defined. Resources must use GET method.`);if(e.methods.length>1)throw new Error(`MCP Resource configuration error: Operation "${r}" has multiple HTTP methods (${e.methods.join(", ")}). Resources must use exactly one method and it must be GET.`);let i=e.methods[0].toUpperCase();if(i!=="GET")throw new Error(`MCP Resource configuration error: Operation "${r}" uses ${i} method. Resources are read-only and must use GET method only.`);let a=o?.name?.trim()||r;if(this.registeredResourceNames.has(a))throw new Error(`MCP Resource configuration error: Duplicate resource name "${a}". Resource names must be unique across all configured resources.`);this.registeredResourceNames.add(a);let c=o?.description?.trim()||e.raw()?.description?.trim()||e.raw()?.summary?.trim()||`Resource for ${a}`,u=o?.uri?.trim()||`mcp://resources/${encodeURIComponent(a)}`,l=o?.mimeType?.trim()||"text/plain";this.registerResourceForOperation(a,u,c,e,r,l,o?._meta)}registerToolsFromFileSources(e){let r=new Set;for(let o of e){let n=t.getOperationsMetadataForFile(o.path);this.debugMode&&this.context.log.debug("Processing file source",{path:o.path,operationIds:o.operationIds,availableOperationIds:Array.from(n.keys())});for(let i of o.operationIds){this.context.log.warn(`DEPRECATED: Registering MCP tool with operation ID: "${i}" from file: "${o.path}" with: "options.files" is deprecated and will soon be removed: migrate to using "options.operations". See docs at: https://zuplo.com/docs/handlers/mcp-server`);let a=n.get(i);if(!a)throw new Error(`MCP Tool configuration error: Operation ID "${i}" not found in OpenAPI spec at ${o.path}. Available operation IDs: ${Array.from(n.keys()).join(", ")}`);if(a.toolExtension?.enabled===!1){this.debugMode&&this.context.log.debug("Skipping disabled tool",{operationId:i,path:o.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 "${o.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,{type:"graphql",introspectionTool:{name:a.graphqlExtension.introspectionToolName??"",description:a.graphqlExtension.introspectionToolDescription??""},executeTool:{name:a.graphqlExtension.executeToolName??"",description:a.graphqlExtension.executeToolDescription??""}}):this.registerToolsForMethod({routeData:a.routeConfig,method:a.routeConfig.methods[0],name:c,description:u,includeOutputSchema:l,includeStructuredContent:d})}}}registerGraphQLTools(e,r,o){let n=o?.introspectionTool?.name?.trim()||`${e}_introspect`,i=o?.executeTool?.name?.trim()||`${e}_execute_query`;if(this.registeredToolNames.has(n))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The introspection tool name "${n}" is already in use. Provide a unique tool name.`);if(this.registeredToolNames.has(i))throw new Error(`MCP GraphQL tool configuration error: Tool name conflict detected. The execute tool name "${i}" is already in use. Provide a unique 'executeToolName' in the x-zuplo-graphql extension.`);this.registeredToolNames.add(n),this.registeredToolNames.add(i);let a=o?.introspectionTool?.description??`Get the GraphQL schema for ${e}`,c=o?.executeTool?.description??`Execute a GraphQL query on ${e}`,u=r.path,d=Rn.createObjectValidatorBuilder({}).build();this.server.addTool({name:n,description:a,validator:d,handler:s(async()=>{let m=vn(),y=Date.now();try{this.debugMode&&m.log.debug("MCP GraphQL introspection tool invoked",{toolName:n,operationId:e,path:u});let g=ya(),w=this.buildToolUrl(r,{}),v=this.buildToolRequest("POST","application/json",{body:{query:g}}),x=Date.now(),I=await m.invokeRoute(w,v),k=Date.now()-x,C=await I.text(),A=Date.now()-y;this.debugMode&&(I.ok?m.log.debug("MCP GraphQL introspection tool ok response",{toolName:n,operationId:e,status:I.status,elapsedMs:A,downstreamElapsedMs:k}):m.log.debug("MCP GraphQL introspection tool 'isError' response",{toolName:n,operationId:e,status:I.status,elapsedMs:A,downstreamElapsedMs:k,response:C}));let Z;try{Z=JSON.parse(C)}catch(V){this.debugMode&&m.log.debug("MCP GraphQL introspection structuredContent JSON parse failed",{toolName:n,body:C,parseErr:V})}return{content:[{type:"text",text:C}],...Z&&{structuredContent:Z},isError:!I.ok}}catch(g){let w=Date.now()-y,v=g instanceof Error?`${g.name}: ${g.message}`:String(g);throw m.log.error("MCP GraphQL introspection tool invocation failed",{toolName:n,operationId:e,path:u,elapsedMs:w,err:g}),new Error(`MCP GraphQL introspection tool call failed for '${n}': ${v}`)}},"handler")});let p={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:i,description:c,validator:new mr(p,m=>typeof m=="object"&&m!==null&&"query"in m&&typeof m?.query=="string"?{success:!0,data:m,errorData:null}:{success:!1,data:null,errorMessage:"Invalid input: query field is required and must be a string",errorData:null}),handler:s(async m=>{let y=vn(),g=Date.now();try{this.debugMode&&y.log.debug("MCP GraphQL execute tool invoked",{toolName:i,operationId:e,path:u,queryPreview:m.query.substring(0,100)});let w=this.buildToolUrl(r,{}),v={query:m.query};m.variables&&(v.variables=m.variables);let x=this.buildToolRequest("POST","application/json",{body:v}),I=Date.now(),k=await y.invokeRoute(w,x),C=Date.now()-I,A=await k.text(),Z=Date.now()-g;this.debugMode&&(k.ok?y.log.debug("MCP GraphQL execute tool ok response",{toolName:i,operationId:e,status:k.status,elapsedMs:Z,downstreamElapsedMs:C}):y.log.debug("MCP GraphQL execute tool 'isError' response",{toolName:i,operationId:e,status:k.status,elapsedMs:Z,downstreamElapsedMs:C,response:A}));let V;try{V=JSON.parse(A)}catch(Q){this.debugMode&&y.log.debug("MCP GraphQL execute structuredContent JSON parse failed",{toolName:i,body:A,parseErr:Q})}return{content:[{type:"text",text:A}],...V&&{structuredContent:V},isError:!k.ok}}catch(w){let v=Date.now()-g,x=w instanceof Error?`${w.name}: ${w.message}`:String(w);throw y.log.error("MCP GraphQL execute tool invocation failed",{toolName:i,operationId:e,path:u,elapsedMs:v,err:w}),new Error(`MCP GraphQL execute tool call failed for '${i}': ${x}`)}},"handler")}),this.debugMode&&this.context.log.debug("MCP GraphQL tools registered",{operationId:e,introspectionToolName:n,executeToolName:i,path:u})}registerToolsForMethod({routeData:e,method:r,name:o,description:n,includeOutputSchema:i,includeStructuredContent:a,annotations:c,_meta:u}){if(e.handler?.export!=="mcpServerHandler")if(e.raw().requestBody?.content)for(let l of Object.keys(e.raw().requestBody?.content)){let p=Object.keys(e.raw().requestBody?.content).length>1?`${o}_${l.replace(/[^\w]/g,"_")}`:o;this.registerGenericToolSpec({name:p,description:n,routeData:e,method:r,contentType:l,includeOutputSchema:i,includeStructuredContent:a,annotations:c,_meta:u})}else this.registerGenericToolSpec({name:o,description:n,routeData:e,method:r,contentType:null,includeOutputSchema:i,includeStructuredContent:a,annotations:c,_meta:u})}registerGenericToolSpec({name:e,description:r,routeData:o,method:n,contentType:i,includeOutputSchema:a,includeStructuredContent:c,annotations:u,_meta:l}){let d=this.buildUniversalValidator(o,i);if(!d)throw new Error(`MCP Tool registration error: Could not build parameter validator for ${n.toUpperCase()} ${o.path}. This may indicate an issue with the OpenAPI parameter definitions for this route.`);let p=a?this.extractOutputSchema(o):void 0;try{this.server.addTool({name:e,description:r,validator:d,...p&&{outputSchema:p},...u&&{annotations:u},...l&&{_meta:l},handler:s(async(m,y)=>{let g=vn(),w=Date.now();try{this.debugMode&&g.log.debug("MCP tool invoked",{toolName:e,operationId:o.raw()?.operationId,method:n,path:o.path,args:m});let v=this.buildToolUrl(o,m),x=this.buildToolRequest(n,i,m);this.debugMode&&g.log.debug("MCP tool downstream call",{toolName:e,url:v,method:n,headers:x.headers?Object.keys(x.headers).join(", "):"",bodyPreview:m.body});let I=Date.now(),k=await g.invokeRoute(v,x),C=Date.now()-I,A=await k.text(),Z;if(c)try{Z=JSON.parse(A)}catch(Q){this.debugMode&&g.log.debug("MCP tool structuredContent JSON parse failed",{toolName:e,body:A,parseErr:Q})}let V=Date.now()-w;return this.emitEvent(g,{eventType:k.ok?ce.MCP_CAPABILITY_COMPLETED:ce.MCP_CAPABILITY_FAILED,outcome:k.ok?"success":"failure",capabilityType:"tool",capabilityName:e,mcpMethod:"tools/call",transport:"http",toolPath:o.path,toolMethod:n,toolOperationId:o.raw()?.operationId??"unknown",latencyMs:V,...k.ok?{}:{errorCode:k.status,reasonCode:"upstream_error",reasonClass:"upstream"}}),this.debugMode&&(k.ok?g.log.debug("MCP tool ok response",{toolName:e,operationId:o.raw()?.operationId,status:k.status,elapsedMs:V,downstreamElapsedMs:C}):g.log.debug("MCP tool 'isError' response",{toolName:e,operationId:o.raw()?.operationId,status:k.status,elapsedMs:V,downstreamElapsedMs:C,response:A})),{content:[{type:"text",text:A}],...Z&&{structuredContent:Z},isError:!k.ok,_meta:g.custom.mcpCallToolResponse?._meta??{}}}catch(v){let x=Date.now()-w,I=v instanceof Error?`${v.name}: ${v.message}`:String(v);return g.log.error("MCP server tool invocation failed",{toolName:e,operationId:o.raw()?.operationId,method:n,path:o.path,elapsedMs:x,err:v}),this.emitEvent(g,{eventType:ce.MCP_CAPABILITY_FAILED,outcome:"failure",capabilityType:"tool",capabilityName:e,mcpMethod:"tools/call",transport:"http",toolPath:o.path,toolMethod:n,toolOperationId:o.raw()?.operationId??"unknown",latencyMs:x,reasonCode:"gateway_error",reasonClass:"upstream",errorType:v instanceof Error?v.name:"unknown"}),{content:[{type:"text",text:`MCP tool call failed for tool '${e}': ${I}`}],isError:!0}}},"handler")}),this.debugMode&&this.context.log.debug("MCP tool registered",{toolName:e,method:n.toUpperCase(),path:o.path,operationId:o.raw()?.operationId,contentType:i||"none",includeOutputSchema:a,includeStructuredContent:c,hasValidator:!!d,hasOutputSchema:!!p})}catch(m){throw new Error(`Failed to add tool ${n} ${o.path}`,m)}}buildToolUrl(e,r){return new wa(e).build(r.pathParams,r.queryParams)}buildToolRequest(e,r,o){let n=this.buildToolHeaders(e,r,o),i={method:e,headers:n};return this.shouldIncludeBody(e,r,o)&&(i.body=this.serializeBody(o.body,r)),i}buildToolHeaders(e,r,o){let n={...Km()};return delete n["content-type"],o.headers&&Object.entries(o.headers).forEach(([i,a])=>{n[i.toLowerCase()]=a}),r&&o.body!==void 0&&(n["content-type"]=r),this.isBodyMethod(e||"")&&o.body!==void 0&&!n["content-type"]&&(n["content-type"]="application/json"),n}shouldIncludeBody(e,r,o){return o.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 n=Rn.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}),n}catch(o){let n=o instanceof Error?o.message:String(o);throw this.context.log.warn("MCP validator build failed",{method:e.methods?.[0],path:e.path,contentType:r||"none",operationId:e.raw()?.operationId,error:n}),o}}extractOutputSchema(e){try{let r=e.raw(),o=r?.responses;if(!o){this.context.log.warn("No responses found in OpenAPI spec for outputSchema",{path:e.path,operationId:r?.operationId});return}for(let n of Object.keys(o))if(n.startsWith("2")){let a=o[n]?.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:n,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(o).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 nC(t,e){if(P("handler.mcp-server"),e.route.methods.some(a=>a.toUpperCase()!=="POST"))throw new R(`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 o=e.route?.handler?.options??{},n=e.route?.path??"unknown-route",i=await Sa.getInstance({opts:o,context:e,key:n});return Gw(r,e,()=>i.handleRequest(t,e))}s(nC,"mcpServerHandler");var oC=[502,503,504];async function In(t,e){if(oC.includes(t.status)){let r=B.getLogger(e),n=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:n,headers:i})}}s(In,"logBadGatewayResponses");var ef;function hr(t){if(ef===void 0){let r=T.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),ef=r}return t.log[ef]}s(hr,"getHandlerUserLogFunction");async function iC(t,e){P("handler.open-api");let r=T.instance.build.BUILD_ID,{buildAssetsUrl:o}=T.instance,n=e.route.handler.options,{openApiFilePath:i}=n;if(!i)throw new R("Open API Spec Handler must have 'openApiFilePath' specified");let a=sC(i);if(!a.isValid)throw new R(a.error);let c=`${o}/${r}${i.substring(1)}`,u=await D.fetch(c,{method:t.method,body:t.body,headers:t.headers});if(u.status!==200)return M.notFound(t,e,{detail:"OpenAPI file could not be found."});let l={"content-type":"application/json",vary:"Accept-Encoding"};T.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 In(d,e),d}s(iC,"openApiSpecHandler");var sC=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 aC(t,e){P("handler.redirect");let r=e.route.handler.options;if(!r.location)throw new R("Redirect Handler must have 'location' specified");let o=r.status??302;return new Response(null,{status:o,headers:{location:r.location}})}s(aC,"redirectHandler");async function cC(t){if(P("handler.zuplo-service-proxy"),Object.entries(t.params).length!==1)throw new R("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,T.instance.zuploEdgeApiUrl),r=new Headers(t.headers);return r.set("Authorization",`Bearer ${T.instance.authApiJWT}`),D.fetch(e,{method:t.method,headers:r,body:t.body})}s(cC,"zuploServiceProxy");function uC(t,e){let r=t.endsWith("/"),o=e.startsWith("/");return r&&o?`${t.substring(0,t.length-1)}${e}`:!r&&!o?`${t}/${e}`:`${t}${e}`}s(uC,"join");async function lC(t,e){P("handler.url-forward");let r=hr(e),o=e.route.handler.options,n=o.forwardSearch!==!1,i;if(T.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?i=o.followRedirects===!0?"follow":"manual":typeof o.followRedirects<"u"&&P("handler.url-forward.follow-redirects"),!o.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!o||typeof o.__rewriteFunction!="function")throw new R("Invalid options for this route");let a=yr(e),c=new URL(t.url),u=o.__rewriteFunction(t,a),l=uC(u,c.pathname),d=n?`${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(w){throw new Error(`Failed to buffer request body for redirect handling: ${w}`)}let y=await fetch(d,{method:t.method,body:m,headers:t.headers,redirect:i,zuplo:o.mtlsCertificate?{mtlsCertificate:o.mtlsCertificate}:void 0}),g=Date.now()-p;return r(`URL Forward received response ${y.status} - ${y.statusText} in ${g}ms`),In(y,e),y}s(lC,"urlForwardHandler");var dC=s((t,e)=>{let r=new URL(t),o=new URL(e);for(let[n,i]of o.searchParams.entries())r.searchParams.append(n,i);return r.toString()},"addQuery");async function pC(t,e){P("handler.url-rewrite");let r=hr(e),o=e.route.handler.options,n=o.forwardSearch!==!1,i=o.followRedirects??!1;if(!o||typeof o.__rewriteFunction!="function")throw new R("Invalid options for this route");let a=yr(e),c=o.__rewriteFunction(t,a),u=n?dC(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:o.mtlsCertificate?{mtlsCertificate:o.mtlsCertificate}:void 0}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),In(d,e),d}s(pC,"urlRewriteHandler");function mC(t,e,r){t.addEventListener("close",()=>{e.close()}),e.addEventListener("close",()=>{t.close()}),t.addEventListener("error",o=>{r.log.error(`Incoming WebSocket error: ${JSON.stringify(o)}`),e.send(JSON.stringify(o))}),e.addEventListener("error",o=>{r.log.error(`Outgoing WebSocket error: ${JSON.stringify(o)}`),t.send(JSON.stringify(o))}),t.addEventListener("message",o=>{e.send(o.data)}),e.addEventListener("message",o=>{t.send(o.data)})}s(mC,"wireUpPassthrough");async function fC(t,e){P("handler.websocket");let r=e.route.handler.options,o=hr(e);if(!r||!r.rewritePattern)throw new R("WebSocket Handler must have option 'rewritePattern' specified");let n=t.headers.get("Upgrade");if(!n||n!=="websocket")return M.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new R("Invalid options for this route");let i=yr(e),a=r.__rewriteFunction(t,i);if(o(`Attempting WebSocket connection to '${a}'`),T.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(),o("WebSocket connection established with upstream"),d()},"onOpen"),y=s(w=>{g(),o(`WebSocket connection error: ${w}`),p(new Error("Upstream open failed"))},"onErr"),g=s(()=>{c.removeEventListener("open",m),c.removeEventListener("error",y)},"cleanup");c.addEventListener("open",m),c.addEventListener("error",y)}).catch(d=>{throw new Error(`Failed to open outgoing socket: ${d.message}`)});let{socket:u,response:l}=globalThis.Deno.upgradeWebSocket(t.originalRequest);return mC(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 o(`WebSocket connected, received response ${c.status} - ${c.statusText}`),new Response(null,{status:101,webSocket:c.webSocket})}}s(fC,"webSocketHandler");var tf=s((t,e)=>t.map((o,n)=>{let i;if(typeof o.module=="object"&&(i=o.module[o.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${n+1}, export name: ${o.export}`;throw new R(`${a} - Websocket policy must be a valid function (${c})`)}return i}),"getWebSocketPolicyFunctions"),sx=s(async(t,e,r,o,n,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,o,n),a===void 0)return}}return a},"webSocketPolicyProcessor");async function gC(t,e,r){r(`Attempting WebSocket connection to '${e}'`);let o=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(()=>{o.removeEventListener("open",u),o.removeEventListener("error",l)},"cleanup");o.addEventListener("open",u),o.addEventListener("error",l)}).catch(a=>{throw new Error(`Failed to open outgoing socket: ${a.message}`)});let{socket:n,response:i}=globalThis.Deno.upgradeWebSocket(t);return{clientSocket:n,outgoingSocket:o,response:i}}s(gC,"getDenoClientAndServerSockets");function hC(t){return t>=400&&t<600}s(hC,"isUpstreamHttpErrorStatus");async function yC(t,e,r){r(`Attempting WebSocket connection to '${e}'`);let o=await fetch(e,{method:t.method,headers:t.headers,body:t.body});if(o.status!==101||!o.webSocket)return r(`WebSocket upgrade failed: ${o.status} ${o.statusText}`),{ok:!1,response:o};let n=new WebSocketPair,[i,a]=Object.values(n);r(`WebSocket connected, received response ${o.status} - ${o.statusText}`),o.webSocket.accept(),a.accept();let c=new Response(null,{status:101,webSocket:i});return{ok:!0,clientSocket:i,outgoingSocket:o.webSocket,serverSocket:a,response:c}}s(yC,"getCfClientAndServerSockets");function ax(t,e,r,o,n,i){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",a=>{o.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 sx(l,t,e,r,o,n);d!==void 0&&e.send(d)},"innerPipeline")(a).catch(o.log.error);o.waitUntil(u)}catch(c){o.log.error(c)}})}s(ax,"wireUpListeners");async function bC(t,e){P("handler.websocket-pipeline");let r=e.route.handler.options,o=hr(e);if(!r||!r.rewritePattern)throw new R("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let n=t.headers.get("Upgrade");if(!n||n!=="websocket")return M.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new R("Invalid options for this route");let i=yr(e),a=r.__rewriteFunction(t,i),c=r.policies?.inbound?tf(r.policies.inbound,"inbound"):[],u=r.policies?.outbound?tf(r.policies.outbound,"outbound"):[],l,d,p;if(T.instance.isDeno){if(!t.originalRequest)throw new Error("Original websocket request is not available");let m=await gC(t.originalRequest,a,o);l=m.clientSocket,d=m.outgoingSocket,p=m.response}else{a=a.replace(/^(ws)/,"http");let m=await yC(t,a,o);if(!m.ok){let y=m.response;if(hC(y.status))return y;let g=await y.text(),w=`WebSocket connection error - ${y.status}: ${y.statusText}, content: '${g}'`;return e.log.warn({outgoingUrl:a,status:y.status},w),M.badGateway(t,e,{detail:w})}l=m.serverSocket,d=m.outgoingSocket,p=m.response}return ax(l,d,t,e,c,"inbound"),ax(d,l,t,e,u,"outbound"),p}s(bC,"webSocketPipelineHandler");var rf=class extends Ne{constructor(r){super();this.options=r}static{s(this,"AWSLoggingPlugin")}getTransport(){return new nf(this.options)}},nf=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;environmentStage;logGroupName;logStreamName;region;fields;batcher=new ue("aws-log-transport",10,async e=>{if(e.length===0)return;let r=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let o=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:r,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}});o.ok||await me({level:"error",messages:[`Failed to send logs to AWS: ${o.status} - ${o.statusText}`]},o)}catch{await me({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:r,logGroupName:o,secretAccessKey:n,region:i,fields:a}){P("logging.aws"),this.awsClient=new tn({accessKeyId:e,secretAccessKey:n,service:"logs",region:i}),this.logGroupName=o,this.logStreamName=r,this.region=i,this.environmentType=T.instance.loggingEnvironmentType,this.environmentStage=T.instance.loggingEnvironmentStage,this.environment=T.instance.deploymentName,this.fields=a??{}}log(e,r){e.messages.forEach(o=>{let n={timestamp:Date.now(),message:JSON.stringify(Object.assign({data:ut(o),severity:e.level,source:e.logSource,environment:this.environment,atomicCounter:e.vectorClock,requestId:e.requestId,environmentType:this.environmentType,environmentStage:this.environmentStage,rayId:e.rayId===null?void 0:e.rayId},this.fields,r.properties??{}))};this.batcher.enqueue(n)}),r.waitUntil(this.batcher.waitUntilFlushed())}};var of=class extends Ne{constructor(r){super();this.options=r}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new sf(this.options)}},sf=class{static{s(this,"DynaTraceTransport")}constructor(e){P("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=T.instance.loggingEnvironmentType,this.#o=T.instance.loggingEnvironmentStage,this.#n=T.instance.deploymentName,this.#i=e.fields??{}}#e;#t;#n;#r;#o;#i;log(e,r){e.messages.forEach(o=>{let n=Object.assign({timestamp:new Date().toISOString(),message:ut(o),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.atomicCounter":e.vectorClock,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId},this.#i,r.properties??{});this.batcher.enqueue(n)}),r.waitUntil(this.batcher.waitUntilFlushed())}#s=s(async e=>{if(e.length!==0)try{let r=await D.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});r.ok||await me({level:"error",messages:[`Failed to send logs to Dynatrace: ${r.status} - ${r.statusText}`]},r)}catch{await me({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ue("dyna-trace-log-transport",10,this.#s)};var af=class extends Ne{constructor(r){super();this.options=r}static{s(this,"LokiLoggingPlugin")}getTransport(){return new uf(this.options)}},cf=class{static{s(this,"LokiStream")}constructor(e,r,o,n,i,a){this.level=e,this.environment=r,this.environmentType=o,this.environmentStage=n,this.requestId=a,this.job=i}job;level;environment;environmentType;environmentStage;requestId;equals=s(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function vC(t,e){return btoa(`${t}:${e}`)}s(vC,"createBasicDigest");var uf=class{static{s(this,"LokiTransport")}constructor(e){P("logging.loki"),this.#n=e.url,this.#r=vC(e.username,e.password),this.#i=T.instance.loggingEnvironmentType,this.#s=T.instance.loggingEnvironmentStage,this.#o=T.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo",this.#a=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;#a;log(e,r){let o=new cf(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(n=>{let i=Object.assign({stream:o,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:ut(n),nanoSecondEpoch:`${e.timestamp.getTime()}000000`},this.#a,r.properties??{});this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}#u=s(e=>{let r={streams:[]};return e.forEach(o=>{let n=r.streams.find(i=>i.stream.equals(o.stream));n||(n={stream:o.stream,values:[]},r.streams.push(n)),n.values.push(this.#e>1?[o.nanoSecondEpoch,o.message,{requestId:o.requestId,rayId:o.rayId,atomicCounter:JSON.stringify(o.atomicCounter)}]:[o.nanoSecondEpoch,o.message])}),r},"#convertToLokiStreamsBatch");#l=s(async e=>{if(e.length===0)return;let r=this.#u(e);try{let o=await D.fetch(this.#n,{method:"POST",body:JSON.stringify(r),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});o.ok||await me({level:"error",messages:[`Failed to send logs to Loki: ${o.status} - ${o.statusText}`]},o)}catch{await me({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ue("loki-log-transport",10,this.#l)};var lf=class extends Ne{constructor(r){super();this.options=r}static{s(this,"NewRelicLoggingPlugin")}getTransport(){return new df(this.options)}},df=class{static{s(this,"NewRelicTransport")}constructor(e){P("logging.newrelic"),this.#e=e.url??"https://log-api.newrelic.com/log/v1",this.#t=e.apiKey,this.#r=T.instance.loggingEnvironmentType,this.#o=T.instance.loggingEnvironmentStage,this.#n=T.instance.deploymentName,this.#i=e.fields??{},this.#s=e.service??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,r){e.messages.forEach(o=>{let n=Object.assign({message:ut(o),level:e.level,timestamp:Date.now(),service:this.#s,request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource},this.#i,r.properties??{});this.batcher.enqueue(n)}),r.waitUntil(this.batcher.waitUntilFlushed())}#a=s(async e=>{if(e.length!==0)try{let r=await D.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json","Api-Key":this.#t}});r.ok||await me({level:"error",messages:[`Failed to send logs to New Relic: ${r.status} - ${r.statusText}`]},r)}catch{await me({level:"error",messages:["Failed to connect to New Relic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ue("new-relic-log-transport",10,this.#a)};var pf=class extends Ne{constructor(r){super();this.options=r}static{s(this,"SplunkLoggingPlugin")}getTransport(){return new mf(this.options)}},mf=class{static{s(this,"SplunkTransport")}constructor(e){P("logging.splunk"),this.#e=e.url,this.#t=e.token,this.#r=T.instance.loggingEnvironmentType,this.#o=T.instance.loggingEnvironmentStage,this.#n=T.instance.deploymentName,this.#i=e.fields??{},this.#s=e.index??"main",this.#a=e.sourcetype??"json",this.#u=e.host??"zuplo-api",this.#l=e.channel}#e;#t;#n;#r;#o;#i;#s;#a;#u;#l;log(e,r){e.messages.forEach(o=>{let i={event:{message:ut(o),level:e.level,timestamp:new Date().toISOString(),request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource,...this.#i,...r.properties??{}},sourcetype:this.#a,host:this.#u,index:this.#s,time:Math.floor(Date.now()/1e3)};this.batcher.enqueue(i)}),r.waitUntil(this.batcher.waitUntilFlushed())}#c=s(async e=>{if(e.length!==0)try{for(let r of e){let o={"Content-Type":"application/json",Authorization:`Splunk ${this.#t}`};this.#l&&(o["X-Splunk-Request-Channel"]=this.#l);let n=await D.fetch(this.#e,{method:"POST",body:JSON.stringify(r),headers:o});if(!n.ok){let i=await n.text();await me({level:"error",messages:[`Failed to send logs to Splunk: ${n.status} - ${n.statusText}`,`Response: ${i}`]},n)}}}catch(r){await me({level:"error",messages:["Failed to connect to Splunk logging service. Check that the URL is correct.",`Error: ${r instanceof Error?r.message:String(r)}`]})}},"#dispatchFunction");batcher=new ue("splunk-log-transport",10,this.#c)};var ff=class extends Ne{constructor(r){super();this.options=r}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new gf(this.options)}},gf=class{static{s(this,"SumoLogicTransport")}constructor(e){P("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=T.instance.loggingEnvironmentType,this.#r=T.instance.loggingEnvironmentStage,this.#t=T.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;log(e,r){e.messages.forEach(o=>{let n=Object.assign({timestamp:new Date().toISOString(),message:ut(o),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId},this.#s,r.properties??{});this.batcher.enqueue(n)}),r.waitUntil(this.batcher.waitUntilFlushed())}#a=s(async e=>{if(e.length===0)return;let r=e.map(n=>JSON.stringify(n)).join(`
241
241
  `),o=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&o.set("X-Sumo-Name",this.#i),this.#o&&o.set("X-Sumo-Category",this.#o);try{let n=await D.fetch(this.#e,{method:"POST",body:r,headers:o});n.ok||await me({level:"error",messages:[`Failed to send logs to Sumologic: ${n.status} - ${n.statusText}`]},n)}catch{await me({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ue("sumo-logic-log-transport",10,this.#a)};var wC="d3a5b78f823648f5b1df4fe269d41172",hf=class extends Ne{constructor(r){super();this.options=r}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new yf(this.options)}},yf=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){P("logging.vmware-loginsight");let r;try{r=new URL(e.url),r.pathname==="/"&&(r.pathname=`/api/v1/events/ingest/${e.agentId??wC}`)}catch{throw new R(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=r.toString(),this.#r=T.instance.loggingEnvironmentType,this.#o=T.instance.loggingEnvironmentStage,this.#n=T.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([o,n])=>({name:o,content:n})))}#e;#t;#n;#r;#o;#i;#s;log(e,r){let o=this.buildEntry(e,r);this.batcher.enqueue(o),r.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,r){let o=ty(e.messages);this.#t?.forEach(i=>{o=o.replaceAll(i[0],i[1])});let n={timestamp:Date.now(),text:o,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&n.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&n.fields.push({name:"environment",content:this.#n}),this.#s&&n.fields.push(...this.#s),r.properties&&Object.entries(r.properties).forEach(([i,a])=>{let c=Oi(a);c&&n.fields.push({name:i,content:c})}),r.custom&&Object.entries(r.custom).forEach(([i,a])=>{let c=Oi(a);c&&n.fields.push({name:i,content:c})}),this.#i&&(n=this.#i(n)),n}#a=s(async e=>{if(e.length!==0)try{let r=await D.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});r.ok||await me({level:"error",messages:[`Failed to send logs to Log Insight: ${r.status} - ${r.statusText}`]},r)}catch{await me({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ue("vmware-log-insights-log-transport",10,this.#a)};var bf=class{static{s(this,"ZuploMcpSdk")}context;constructor(e){this.context=e}getRawCallToolRequest(){let e=null;return this.context.custom.mcpCallToolRequest&&(e=this.context.custom.mcpCallToolRequest),this.context.parentContext?.custom.mcpCallToolRequest&&(e=this.context.parentContext.custom.mcpCallToolRequest),e}setRawCallToolResult(e){if(this.context.parentContext?.custom.mcpCallToolRequest){this.context.parentContext.custom.mcpCallToolResponse=e;return}this.context.custom.mcpCallToolResponse=e}};var wf=new WeakMap,xC={tags:[]},cx="https://api.datadoghq.com",ka="/api/v2/series",Ta="/api/v1/distribution_points",RC=`${cx}${ka}`,IC=`${cx}${Ta}`,PC=".v2",SC="zuplo.request.latency",TC="zuplo.request.content_length",kC="zuplo.response.content_length",vf=s((t,e)=>e?`${t}${PC}`:t,"getMetricNameForMode"),EC=s((t,e)=>{try{let r=new URL(t);return r.pathname.replace(/\/+$/,"")===""?(r.pathname=e,r.search="",r.toString()):t}catch{return t}},"normalizeDatadogApiUrl"),CC=s(t=>{try{let e=new URL(t),r=e.pathname.replace(/\/+$/,"");if(r==="")return e.pathname=Ta,e.search="",e.toString();if(r.endsWith(ka)){let o=r.length-ka.length;return e.pathname=r.slice(0,o)+Ta,e.search="",e.toString()}return e.pathname=Ta,e.search="",e.toString()}catch{}return IC},"getDefaultDistributionUrl"),_C=s(t=>[...t].sort(),"normalizeTagsForGrouping"),xf=class extends vt{constructor(r){super();this.options=r;P("metrics.datadog")}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new Rf(this.options)}static setContext(r,o){let n=wf.get(r);n||(n=xC);let i=Object.assign({...n},o);wf.set(r,i)}},Rf=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i;#s;#a=void 0;#u=void 0;constructor(e){this.#e=e.apiKey,this.#t=EC(e.url??RC,ka),this.#n=CC(this.#t),this.#s=e.metricMode==="distributionMode",this.#r=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#i=e.include??{},this.#o=e.tags??[]}#l(e){return this.#a===void 0&&(this.#a=new ue("data-dog-metrics-transport",10,this.dispatchSeriesFunction,B.getLogger(e))),this.#a}#c(e){return this.#u===void 0&&(this.#u=new ue("data-dog-metrics-distribution-transport",10,this.dispatchDistributionFunction,B.getLogger(e))),this.#u}#f(e,r,o,n,i){this.#c(e).enqueue({metric:r,timestamp:o,value:n,tags:i})}pushMetrics(e,r){let o=Math.floor(e.timestamp.getTime()/1e3),n=vf(SC,this.#s),i=vf(TC,this.#s),a=vf(kC,this.#s),c=this.#o.concat(wf.get(r)?.tags??[]);if(this.#i.country&&c.push(`country:${e.country}`),this.#i.httpMethod&&c.push(`httpMethod:${e.method}`),this.#i.statusCode&&c.push(`statusCode:${e.statusCode}`),this.#i.path){let u=e.systemRouteName||e.routePath;c.push(`path:${u}`)}this.#r.latency&&(this.#s?this.#f(r,n,o,e.durationMs,c):this.#l(r).enqueue({metric:n,type:3,points:[{timestamp:o,value:e.durationMs}],tags:c})),this.#r.requestContentLength&&e.requestContentLength&&(this.#s?this.#f(r,i,o,e.requestContentLength,c):this.#l(r).enqueue({metric:i,type:3,points:[{timestamp:o,value:e.requestContentLength}],tags:c})),this.#r.responseContentLength&&e.responseContentLength&&(this.#s?this.#f(r,a,o,e.responseContentLength,c):this.#l(r).enqueue({metric:a,type:3,points:[{timestamp:o,value:e.responseContentLength}],tags:c})),this.#a&&r.waitUntil(this.#a.waitUntilFlushed()),this.#u&&r.waitUntil(this.#u.waitUntilFlushed())}dispatchSeriesFunction=s(async e=>{if(e.length!==0)try{let r=JSON.stringify({series:e}),o=await D.fetch(this.#t,{method:"POST",body:r,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});o.ok||await me({level:"error",messages:["Failed to send metrics to DataDog."]},o)}catch{await me({level:"error",messages:["Failed to connect to DataDog metrics service. Check that the URL is correct."]})}},"dispatchSeriesFunction");dispatchDistributionFunction=s(async e=>{if(e.length!==0)try{let r=new Map;e.forEach(i=>{let a=_C(i.tags),c=`${i.metric}:${i.timestamp}:${JSON.stringify(a)}`,u=r.get(c);if(u){u.points[0][1].push(i.value);return}r.set(c,{metric:i.metric,points:[[i.timestamp,[i.value]]],tags:a})});let o=JSON.stringify({series:[...r.values()]}),n=await D.fetch(this.#n,{method:"POST",body:o,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});n.ok||await me({level:"error",messages:["Failed to send latency distributions to DataDog."]},n)}catch{await me({level:"error",messages:["Failed to connect to DataDog metrics distribution service. Check that the URL is correct."]})}},"dispatchDistributionFunction")};var If=new WeakMap,OC={dimensions:[]},Pf=class extends vt{constructor(r){super();this.options=r;P("metrics.dynatrace")}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new Sf(this.options)}static setContext(r,o){let n=If.get(r);n||(n=OC);let i=Object.assign({...n},o);If.set(r,i)}},Sf=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,r){this.#r===void 0&&(this.#r=new ue("dynatrace-metrics-transport",10,this.dispatchFunction,B.getLogger(r)));let o=Math.floor(e.timestamp.getTime()),n=this.dimensions.concat(If.get(r)?.dimensions??[]);if(this.#n.country&&n.push(`country="${e.country}"`),this.#n.httpMethod&&n.push(`http_method="${e.method}"`),this.#n.statusCode&&n.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;n.push(`path="${a}"`)}let i=n.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${o}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${o}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${o}`),r.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let r=e.join(`
242
242
  `),o=await D.fetch(this.#e,{method:"POST",body:r,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});o.ok||await me({level:"error",messages:["Failed to send metrics to Dynatrace."]},o)}catch{await me({level:"error",messages:["Failed to connect to Dynatrace metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Tf=new WeakMap,AC={attributes:{}},kf=class extends vt{constructor(r){super();this.options=r;P("metrics.newrelic")}static{s(this,"NewRelicMetricsPlugin")}getTransport(){return new Ef(this.options)}static setContext(r,o){let n=Tf.get(r);n||(n=AC);let i=Object.assign({...n},o);Tf.set(r,i)}},Ef=class{static{s(this,"NewRelicMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://metric-api.newrelic.com/metric/v1",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.attributes??{service:"zuplo"}}pushMetrics(e,r){this.#i===void 0&&(this.#i=new ue("new-relic-metrics-transport",10,this.dispatchFunction,B.getLogger(r)));let o=Math.floor(e.timestamp.getTime()),n={...this.#r,...Tf.get(r)?.attributes};if(this.#o.country&&(n.country=e.country),this.#o.httpMethod&&(n.httpMethod=e.method),this.#o.statusCode&&(n.statusCode=e.statusCode.toString()),this.#o.path){let i=e.systemRouteName||e.routePath;n.path=i}this.#n.latency&&this.#i.enqueue({name:"zuplo.request.latency",type:"gauge",value:e.durationMs,timestamp:o,attributes:n}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({name:"zuplo.request.content_length",type:"gauge",value:e.requestContentLength,timestamp:o,attributes:n}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({name:"zuplo.response.content_length",type:"gauge",value:e.responseContentLength,timestamp:o,attributes:n}),r.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let r=JSON.stringify([{metrics:e}]),o=await qe({retries:3,retryDelayMs:300,logger:D.console},this.#t,{method:"POST",body:r,headers:{"Content-Type":"application/json","Api-Key":this.#e}});o.ok||await me({level:"error",messages:[`Failed to send metrics to New Relic. Status: ${o.status} ${o.statusText}`]},o)}catch(r){await me({level:"error",messages:["Failed to connect to New Relic metrics service. Check that the URL is correct.",`Error: ${r instanceof Error?r.message:String(r)}`]})}},"dispatchFunction")};var Cf=new WeakMap,$C={attributes:{}},_f=class extends vt{constructor(r){super();this.options=r;P("metrics.otel")}static{s(this,"OTelMetricsPlugin")}getTransport(){return new Of(this.options)}static setContext(r,o){let n=Cf.get(r);n||(n=$C);let i=Object.assign({...n},o);Cf.set(r,i)}};function LC(t){let e=[];for(let[r,o]of Object.entries(t))o!==void 0&&(typeof o=="string"?e.push({key:r,value:{stringValue:o}}):typeof o=="number"?Number.isInteger(o)?e.push({key:r,value:{intValue:o.toString()}}):e.push({key:r,value:{doubleValue:o}}):typeof o=="boolean"&&e.push({key:r,value:{boolValue:o}}));return e}s(LC,"attributesToOTLP");var Of=class{static{s(this,"OTelMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.url,this.#t=e.headers??{},this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.attributes??{}}pushMetrics(e,r){this.#i===void 0&&(this.#i=new ue("otel-metrics-transport",10,this.dispatchFunction,B.getLogger(r)));let o=(e.timestamp.getTime()*1e6).toString(),n={...this.#r},i=Cf.get(r)?.attributes??{};if(Object.assign(n,i),this.#o.country&&e.country&&(n["client.geo.country_iso_code"]=e.country),this.#o.httpMethod&&(n["http.request.method"]=e.method),this.#o.statusCode&&(n["http.response.status_code"]=e.statusCode),this.#o.path){let c=e.systemRouteName||e.routePath;n["http.route"]=c}let a=LC(n);this.#n.latency&&this.#i.enqueue({name:"http.server.request.duration",unit:"ms",value:e.durationMs,timeUnixNano:o,attributes:[...a]}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({name:"http.server.request.body.size",unit:"By",value:e.requestContentLength,timeUnixNano:o,attributes:[...a]}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({name:"http.server.response.body.size",unit:"By",value:e.responseContentLength,timeUnixNano:o,attributes:[...a]}),r.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let r=e.map(a=>({name:a.name,unit:a.unit,gauge:{dataPoints:[{timeUnixNano:a.timeUnixNano,asDouble:a.value,attributes:a.attributes}]}})),n=JSON.stringify({resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:"zuplo",version:"1.0.0"},metrics:r}]}]}),i=await D.fetch(this.#e,{method:"POST",body:n,headers:{"content-type":"application/json",...this.#t}});i.ok||await me({level:"error",messages:["Failed to send metrics to OpenTelemetry collector."]},i)}catch{await me({level:"error",messages:["Failed to connect to OpenTelemetry metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Af=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,P("audit-logs.datastax")}#e;writeLogBatch=s(async e=>{await Promise.allSettled(e.map(async r=>{await D.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(r)})}))},"writeLogBatch")};var $f=class extends Ue{static{s(this,"AuditLogPlugin")}constructor(e,r){super(),this.#e=e,this.#t=r,P("audit-logs")}#e;#t;async initialize(e){new Lf(e,this.#e,this.#t)}},ux=s(t=>{let e={};return t.forEach((r,o)=>{e[o]=r}),e},"serializableHeaders"),NC={requestFilter:s(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Lf=class{static{s(this,"AuditPluginImpl")}constructor(e,r,o){this.#t=r;let n={...NC};o?.requestFilter&&(n.requestFilter=o.requestFilter),o?.include?.request&&Object.assign(n,o.include.request),o?.include?.response&&Object.assign(n,o.include.response),this.#e=n,e.addRequestHook(this.#i),this.#n=new ue("audit-log",10,this.#r)}#e;#t;#n;#r=s(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#o=s(async(e,r,o,n,i,a)=>{try{let c={timestamp:n,durationMs:i,routePath:o.route.path,requestId:o.requestId,userSub:a,request:{url:r.url,method:r.method,headers:this.#e.include?.request?.headers?ux(r.headers):void 0,body:this.#e.include?.request?.body?await r.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?ux(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(c),o.waitUntil(this.#n.waitUntilFlushed())}catch(c){o.log.error(c)}},"#asyncPrepLogs");#i=s(async(e,r)=>{try{if(!await this.#e.requestFilter(e,r))return e;let n=new Date,i=Date.now(),a=e.clone();return r.addResponseSendingFinalHook(async(c,u)=>{let l=Date.now(),d=c.clone(),p=this.#o(d,a,r,n,l-i,u.user?.sub).catch(m=>{r.log.error(m)});r.waitUntil(p)}),e}catch(o){return r.log.error(o),e}},"#auditHook")};import{importJWK as MC,SignJWT as DC}from"jose";var lx="EdDSA",dx=["EdDSA","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"],px=!1,ri=class t extends Ue{static{s(this,"JwtServicePlugin")}#e;static#t=void 0;static#n=void 0;static#r=void 0;static#o=void 0;static#i=lx;static async signJwt({audience:e,subject:r,expiresIn:o=t.#r,...n}){if(!t.#n){let u=T.instance.authPrivateKey;if(!u)throw new R("JwtServicePlugin - Cannot sign JWT. Private key configured for this Zuplo project.");try{t.#n=await MC(JSON.parse(u),t.#i)}catch(l){throw new R(`JwtServicePlugin - Failed to import private key. Ensure it is a valid JWK format and matches the configured algorithm "${t.#i}".`,{cause:l})}}if(!t.#t)throw new R("JwtServicePlugin - Cannot sign JWT. The issuer URL is not configured. Ensure the plugin is initialized.");if(!t.#r)throw new R("JwtServicePlugin - Cannot sign JWT. The token expiration is not configured. Ensure the plugin is initialized.");let i=o??t.#r,a=typeof i=="number"?new Date(Date.now()+i*1e3):i,c=new DC(n).setProtectedHeader({alg:t.#i}).setIssuer(t.#t).setIssuedAt(new Date).setExpirationTime(a);return e&&c.setAudience(e),r&&c.setSubject(r),await c.sign(t.#n)}constructor(e){if(super(),px)throw new R("JwtServicePlugin - Only one instance of JwtServicePlugin can be created. Ensure you are not creating multiple instances in your code.");let r=e?.algorithm??lx;if(!dx.includes(r))throw new R(`JwtServicePlugin - Unsupported signing algorithm "${r}". Supported algorithms: ${dx.join(", ")}.`);P("plugin.jwt-service"),px=!0,this.#e=e?.basePath??"/__zuplo/issuer",t.#r=e?.expiresIn??"1h",t.#i=r,this.#e.endsWith("/")&&(this.#e=this.#e.slice(0,-1))}registerRoutes({runtimeSettings:e,router:r}){let o=e.api.urls?.defaultUrl;if(!o)throw new R("JwtServicePlugin - Cannot determine issuer URL. Ensure the API is properly configured.");let n=new URL(this.#e,o).toString();t.#t=n,r.addPluginRoute({methods:["GET"],path:`${this.#e}/.well-known/openid-configuration`,handler:s(async()=>{let i={issuer:n,jwks_uri:`${n}/.well-known/jwks.json`,id_token_signing_alg_values_supported:[t.#i],subject_types_supported:["public"]};return new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json","Cache-Control":"public, max-age=15, stale-while-revalidate=15, stale-if-error=86400"}})},"handler")}),r.addPluginRoute({methods:["GET"],path:`${this.#e}/.well-known/jwks.json`,handler:s(async()=>{if(!t.#o)try{let i=T.instance.authPublicKey;if(!i)throw new R("JwtServicePlugin - Public key is not configured for this Zuplo project");let a={keys:[JSON.parse(i)]};t.#o=JSON.stringify(a)}catch(i){throw new R("JwtServicePlugin - Failed to export public key as JWK.",{cause:i})}return new Response(t.#o,{headers:{"Content-Type":"application/json","Cache-Control":"public, max-age=15, stale-while-revalidate=15, stale-if-error=86400"}})},"handler")})}};var Pn=class extends Ue{static{s(this,"OAuthProtectedResourceBasePlugin")}createOauthProtectedResourceHandler(){return async(e,r)=>{let o=new URL(e.url),n=e.params.resourcePath,i=n?`${o.origin}/${n}`:o.origin,a;try{a=await this.getMetadataOptions(e,r)}catch(u){return r.log.warn({err:u},"Failed to get metadata options for OAuth protected resource"),new Response("Not Found",{status:404})}let c={resource:i,authorization_servers:a.authorizationServers,resource_name:a.resourceName};return new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})}}registerRoutes(e){let{router:r}=e;r.addPluginRoute({methods:["GET"],path:"/.well-known/oauth-protected-resource/:resourcePath*",handler:this.createOauthProtectedResourceHandler(),corsPolicy:"anything-goes",processors:[Wr]})}};var ni=class extends Pn{static{s(this,"McpGatewayOAuthProtectedResourcePlugin")}authServerBaseUrl;constructor(e){super(),this.authServerBaseUrl=e}async getMetadataOptions(e,r){let n=e.params.resourcePath.split("/").pop();if(!n)throw new Error("Failed to extract resource from path");return{authorizationServers:[`${this.authServerBaseUrl}/${n}`],resource:n,resourceName:"Zuplo MCP Gateway"}}};var oi=class extends Pn{static{s(this,"OAuthProtectedResourcePlugin")}options;constructor(e){super(),this.options=e}async getMetadataOptions(e,r){return{authorizationServers:this.options.authorizationServers,resourceName:this.options.resourceName}}};var Nf={None:0,JsonEscape:1},ii=class{constructor(e,r={}){this.stream=e;this.options=r;this.placeholder=`__STREAM_TOKEN_${crypto.randomUUID()}__`}static{s(this,"StreamToken")}placeholder;getRawStream(){return this.stream}getOptions(){return this.options}getSafeToken(){return this.placeholder}async getContent(){if(!this.stream)return this.options.useEmptyStringIfNull?"":null;let e=this.stream.getReader(),r=[];try{for(;;){let{done:c,value:u}=await e.read();if(c)break;r.push(u)}}finally{e.releaseLock()}let o=r.reduce((c,u)=>c+u.length,0),n=new Uint8Array(o),i=0;for(let c of r)n.set(c,i),i+=c.length;let a=new TextDecoder().decode(n);return this.options.base64Encode&&(a=btoa(a)),a}},Ea=class{static{s(this,"StreamBuilder")}template;tokens;flags;constructor(e){this.template=e.template,this.tokens=e.tokens,this.flags=e.flags}escapeJsonString(e){return e.replace(/[\\\"\n\r\t\f\b]/g,r=>{switch(r){case"\\":return"\\\\";case'"':return'\\"';case`
243
243
  `:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return r}})}async toString(){let r=this.getStream().getReader(),o=new TextDecoder,n="";for(;;){let{done:i,value:a}=await r.read();if(i)break;n+=o.decode(a,{stream:!0})}return n+=o.decode(),n}getStream(){let e=this.template,r=this.flags,o=new TextEncoder,n=new Map;for(let m of this.tokens)n.set(m.getSafeToken(),m);let i=/"(__STREAM_TOKEN_[^"]+__)"|(__STREAM_TOKEN_[^"]+__)/g,a=[],c=0,u;for(;(u=i.exec(e))!==null;){if(u.index>c&&a.push({type:"literal",value:e.substring(c,u.index)}),u[1]){let m=n.get(u[1]);m?a.push({type:"token",token:m,isQuoted:!0}):a.push({type:"literal",value:u[0]})}else if(u[2]){let m=n.get(u[2]);m?a.push({type:"token",token:m,isQuoted:!1}):a.push({type:"literal",value:u[0]})}c=i.lastIndex}c<e.length&&a.push({type:"literal",value:e.substring(c)});function l(){let m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",y=new Uint8Array(0);return new TransformStream({transform(g,w){let v=new Uint8Array(y.length+g.length);v.set(y),v.set(g,y.length);let x=v.length%3,I=v.length-x;if(I>0){let k=v.subarray(0,I),C="";for(let A=0;A<k.length;A+=3){let Z=k[A],V=k[A+1],Q=k[A+2],te=Z<<16|V<<8|Q;C+=m[te>>18&63],C+=m[te>>12&63],C+=m[te>>6&63],C+=m[te&63]}w.enqueue(C)}y=v.subarray(v.length-x)},flush(g){if(y.length>0){let w=y[0],v=y.length>1?y[1]:0,x=w<<16|v<<8,I="";I+=m[x>>18&63],I+=m[x>>12&63],I+=y.length===2?m[x>>6&63]:"=",I+="=",g.enqueue(I)}}})}s(l,"createBase64EncodeTransformStream");function d(){return new TransformStream({transform(m,y){let g=m.replace(/[\\\"\n\r\t\f\b]/g,w=>{switch(w){case"\\":return"\\\\";case'"':return'\\"';case`
@@ -314,5 +314,5 @@ Signature verification is impossible without access to the original signed mater
314
314
  `);let b=new g("!xml"),S=b,_="",$="";this.entityExpansionCount=0,this.currentExpandedLength=0;let O=new w(this.options.processEntities);for(let U=0;U<f.length;U++)if(f[U]==="<")if(f[U+1]==="/"){let q=yt(f,">",U,"Closing Tag is not closed."),j=f.substring(U+2,q).trim();if(this.options.removeNSPrefix){let et=j.indexOf(":");et!==-1&&(j=j.substr(et+1))}this.options.transformTagName&&(j=this.options.transformTagName(j)),S&&(_=this.saveTextToParentTag(_,S,$));let Ie=$.substring($.lastIndexOf(".")+1);if(j&&this.options.unpairedTags.indexOf(j)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${j}>`);let ae=0;Ie&&this.options.unpairedTags.indexOf(Ie)!==-1?(ae=$.lastIndexOf(".",$.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ae=$.lastIndexOf("."),$=$.substring(0,ae),S=this.tagsNodeStack.pop(),_="",U=q}else if(f[U+1]==="?"){let q=nr(f,U,!1,"?>");if(!q)throw new Error("Pi Tag is not closed.");if(_=this.saveTextToParentTag(_,S,$),!(this.options.ignoreDeclaration&&q.tagName==="?xml"||this.options.ignorePiTags)){let j=new g(q.tagName);j.add(this.options.textNodeName,""),q.tagName!==q.tagExp&&q.attrExpPresent&&(j[":@"]=this.buildAttributesMap(q.tagExp,$,q.tagName)),this.addChild(S,j,$,U)}U=q.closeIndex+1}else if(f.substr(U+1,3)==="!--"){let q=yt(f,"-->",U+4,"Comment is not closed.");if(this.options.commentPropName){let j=f.substring(U+4,q-2);_=this.saveTextToParentTag(_,S,$),S.add(this.options.commentPropName,[{[this.options.textNodeName]:j}])}U=q}else if(f.substr(U+1,2)==="!D"){let q=O.readDocType(f,U);this.docTypeEntities=q.entities,U=q.i}else if(f.substr(U+1,2)==="!["){let q=yt(f,"]]>",U,"CDATA is not closed.")-2,j=f.substring(U+9,q);_=this.saveTextToParentTag(_,S,$);let Ie=this.parseTextData(j,S.tagname,$,!0,!1,!0,!0);Ie==null&&(Ie=""),this.options.cdataPropName?S.add(this.options.cdataPropName,[{[this.options.textNodeName]:j}]):S.add(this.options.textNodeName,Ie),U=q+2}else{let q=nr(f,U,this.options.removeNSPrefix),j=q.tagName,Ie=q.rawTagName,ae=q.tagExp,et=q.attrExpPresent,oh=q.closeIndex;if(this.options.transformTagName){let tt=this.options.transformTagName(j);ae===j&&(ae=tt),j=tt}S&&_&&S.tagname!=="!xml"&&(_=this.saveTextToParentTag(_,S,$,!1));let ih=S;ih&&this.options.unpairedTags.indexOf(ih.tagname)!==-1&&(S=this.tagsNodeStack.pop(),$=$.substring(0,$.lastIndexOf("."))),j!==b.tagname&&($+=$?"."+j:j);let Wa=U;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,$,j)){let tt="";if(ae.length>0&&ae.lastIndexOf("/")===ae.length-1)j[j.length-1]==="/"?(j=j.substr(0,j.length-1),$=$.substr(0,$.length-1),ae=j):ae=ae.substr(0,ae.length-1),U=q.closeIndex;else if(this.options.unpairedTags.indexOf(j)!==-1)U=q.closeIndex;else{let Ka=this.readStopNodeData(f,Ie,oh+1);if(!Ka)throw new Error(`Unexpected end of ${Ie}`);U=Ka.i,tt=Ka.tagContent}let jr=new g(j);j!==ae&&et&&(jr[":@"]=this.buildAttributesMap(ae,$,j)),tt&&(tt=this.parseTextData(tt,j,$,!0,et,!0,!0)),$=$.substr(0,$.lastIndexOf(".")),jr.add(this.options.textNodeName,tt),this.addChild(S,jr,$,Wa)}else{if(ae.length>0&&ae.lastIndexOf("/")===ae.length-1){if(j[j.length-1]==="/"?(j=j.substr(0,j.length-1),$=$.substr(0,$.length-1),ae=j):ae=ae.substr(0,ae.length-1),this.options.transformTagName){let jr=this.options.transformTagName(j);ae===j&&(ae=jr),j=jr}let tt=new g(j);j!==ae&&et&&(tt[":@"]=this.buildAttributesMap(ae,$,j)),this.addChild(S,tt,$,Wa),$=$.substr(0,$.lastIndexOf("."))}else{let tt=new g(j);this.tagsNodeStack.push(S),j!==ae&&et&&(tt[":@"]=this.buildAttributesMap(ae,$,j)),this.addChild(S,tt,$,Wa),S=tt}_="",U=oh}}else _+=f[U];return b.child},"parseXml");function he(f,b,S,_){this.options.captureMetaData||(_=void 0);let $=this.options.updateTag(b.tagname,S,b[":@"]);$===!1||(typeof $=="string"&&(b.tagname=$),f.addChild(b,_))}s(he,"addChild"),r(he,"addChild");var Te=r(function(f,b,S){if(f.indexOf("&")===-1)return f;let _=this.options.processEntities;if(!_.enabled||_.allowedTags&&!_.allowedTags.includes(b)||_.tagFilter&&!_.tagFilter(b,S))return f;for(let $ in this.docTypeEntities){let O=this.docTypeEntities[$],U=f.match(O.regx);if(U){if(this.entityExpansionCount+=U.length,_.maxTotalExpansions&&this.entityExpansionCount>_.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${_.maxTotalExpansions}`);let oe=f.length;if(f=f.replace(O.regx,O.val),_.maxExpandedLength&&(this.currentExpandedLength+=f.length-oe,this.currentExpandedLength>_.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${_.maxExpandedLength}`)}}if(f.indexOf("&")===-1)return f;for(let $ in this.lastEntities){let O=this.lastEntities[$];f=f.replace(O.regex,O.val)}if(f.indexOf("&")===-1)return f;if(this.options.htmlEntities)for(let $ in this.htmlEntities){let O=this.htmlEntities[$];f=f.replace(O.regex,O.val)}return f=f.replace(this.ampEntity.regex,this.ampEntity.val),f},"replaceEntitiesValue");function ve(f,b,S,_){return f&&(_===void 0&&(_=b.child.length===0),f=this.parseTextData(f,b.tagname,S,!1,b[":@"]?Object.keys(b[":@"]).length!==0:!1,_),f!==void 0&&f!==""&&b.add(this.options.textNodeName,f),f=""),f}s(ve,"saveTextToParentTag"),r(ve,"saveTextToParentTag");function Ye(f,b,S,_){return!!(b&&b.has(_)||f&&f.has(S))}s(Ye,"isItStopNode"),r(Ye,"isItStopNode");function $t(f,b,S=">"){let _,$="";for(let O=b;O<f.length;O++){let U=f[O];if(_)U===_&&(_="");else if(U==='"'||U==="'")_=U;else if(U===S[0])if(S[1]){if(f[O+1]===S[1])return{data:$,index:O}}else return{data:$,index:O};else U===" "&&(U=" ");$+=U}}s($t,"tagExpWithClosingIndex"),r($t,"tagExpWithClosingIndex");function yt(f,b,S,_){let $=f.indexOf(b,S);if($===-1)throw new Error(_);return $+b.length-1}s(yt,"findClosingIndex"),r(yt,"findClosingIndex");function nr(f,b,S,_=">"){let $=$t(f,b+1,_);if(!$)return;let O=$.data,U=$.index,oe=O.search(/\s/),q=O,j=!0;oe!==-1&&(q=O.substring(0,oe),O=O.substring(oe+1).trimStart());let Ie=q;if(S){let ae=q.indexOf(":");ae!==-1&&(q=q.substr(ae+1),j=q!==$.data.substr(ae+1))}return{tagName:q,tagExp:O,closeIndex:U,attrExpPresent:j,rawTagName:Ie}}s(nr,"readTagExp"),r(nr,"readTagExp");function Dr(f,b,S){let _=S,$=1;for(;S<f.length;S++)if(f[S]==="<")if(f[S+1]==="/"){let O=yt(f,">",S,`${b} is not closed`);if(f.substring(S+2,O).trim()===b&&($--,$===0))return{tagContent:f.substring(_,S),i:O};S=O}else if(f[S+1]==="?")S=yt(f,"?>",S+1,"StopNode is not closed.");else if(f.substr(S+1,3)==="!--")S=yt(f,"-->",S+3,"StopNode is not closed.");else if(f.substr(S+1,2)==="![")S=yt(f,"]]>",S,"StopNode is not closed.")-2;else{let O=nr(f,S,">");O&&((O&&O.tagName)===b&&O.tagExp[O.tagExp.length-1]!=="/"&&$++,S=O.closeIndex)}}s(Dr,"readStopNodeData"),r(Dr,"readStopNodeData");function fi(f,b,S){if(b&&typeof f=="string"){let _=f.trim();return _==="true"?!0:_==="false"?!1:Z(f,S)}else return m(f)?f:""}s(fi,"parseValue"),r(fi,"parseValue");function qa(f,b,S){let _=Number.parseInt(f,b);return _>=0&&_<=1114111?String.fromCodePoint(_):S+f+";"}s(qa,"fromCodePoint"),r(qa,"fromCodePoint");var Fa=g.getMetaDataSymbol();function Wg(f,b){return Ha(f,b)}s(Wg,"prettify"),r(Wg,"prettify");function Ha(f,b,S){let _,$={};for(let O=0;O<f.length;O++){let U=f[O],oe=Kg(U),q="";if(S===void 0?q=oe:q=S+"."+oe,oe===b.textNodeName)_===void 0?_=U[oe]:_+=""+U[oe];else{if(oe===void 0)continue;if(U[oe]){let j=Ha(U[oe],b,q),Ie=Yg(j,b);U[Fa]!==void 0&&(j[Fa]=U[Fa]),U[":@"]?Qg(j,U[":@"],q,b):Object.keys(j).length===1&&j[b.textNodeName]!==void 0&&!b.alwaysCreateTextNode?j=j[b.textNodeName]:Object.keys(j).length===0&&(b.alwaysCreateTextNode?j[b.textNodeName]="":j=""),$[oe]!==void 0&&$.hasOwnProperty(oe)?(Array.isArray($[oe])||($[oe]=[$[oe]]),$[oe].push(j)):b.isArray(oe,q,Ie)?$[oe]=[j]:$[oe]=j}}}return typeof _=="string"?_.length>0&&($[b.textNodeName]=_):_!==void 0&&($[b.textNodeName]=_),$}s(Ha,"compress"),r(Ha,"compress");function Kg(f){let b=Object.keys(f);for(let S=0;S<b.length;S++){let _=b[S];if(_!==":@")return _}}s(Kg,"propName"),r(Kg,"propName");function Qg(f,b,S,_){if(b){let $=Object.keys(b),O=$.length;for(let U=0;U<O;U++){let oe=$[U];_.isArray(oe,S+"."+oe,!0,!0)?f[oe]=[b[oe]]:f[oe]=b[oe]}}}s(Qg,"assignAttributes"),r(Qg,"assignAttributes");function Yg(f,b){let{textNodeName:S}=b,_=Object.keys(f).length;return!!(_===0||_===1&&(f[S]||typeof f[S]=="boolean"||f[S]===0))}s(Yg,"isLeafTag"),r(Yg,"isLeafTag");var QR={allowBooleanAttributes:!1,unpairedTags:[]};function Xg(f,b){b=Object.assign({},QR,b);let S=[],_=!1,$=!1;f[0]==="\uFEFF"&&(f=f.substr(1));for(let O=0;O<f.length;O++)if(f[O]==="<"&&f[O+1]==="?"){if(O+=2,O=Ga(f,O),O.err)return O}else if(f[O]==="<"){let U=O;if(O++,f[O]==="!"){O=Va(f,O);continue}else{let oe=!1;f[O]==="/"&&(oe=!0,O++);let q="";for(;O<f.length&&f[O]!==">"&&f[O]!==" "&&f[O]!==" "&&f[O]!==`
315
315
  `&&f[O]!=="\r";O++)q+=f[O];if(q=q.trim(),q[q.length-1]==="/"&&(q=q.substring(0,q.length-1),O--),!L(q)){let ae;return q.trim().length===0?ae="Invalid space after '<'.":ae="Tag '"+q+"' is an invalid name.",De("InvalidTag",ae,Xe(f,O))}let j=eh(f,O);if(j===!1)return De("InvalidAttr","Attributes for '"+q+"' have open quote.",Xe(f,O));let Ie=j.value;if(O=j.index,Ie[Ie.length-1]==="/"){let ae=O-Ie.length;Ie=Ie.substring(0,Ie.length-1);let et=Ja(Ie,b);if(et===!0)_=!0;else return De(et.err.code,et.err.msg,Xe(f,ae+et.err.line))}else if(oe)if(j.tagClosed){if(Ie.trim().length>0)return De("InvalidTag","Closing tag '"+q+"' can't have attributes or invalid starting.",Xe(f,U));if(S.length===0)return De("InvalidTag","Closing tag '"+q+"' has not been opened.",Xe(f,U));{let ae=S.pop();if(q!==ae.tagName){let et=Xe(f,ae.tagStartPos);return De("InvalidTag","Expected closing tag '"+ae.tagName+"' (opened in line "+et.line+", col "+et.col+") instead of closing tag '"+q+"'.",Xe(f,U))}S.length==0&&($=!0)}}else return De("InvalidTag","Closing tag '"+q+"' doesn't have proper closing.",Xe(f,O));else{let ae=Ja(Ie,b);if(ae!==!0)return De(ae.err.code,ae.err.msg,Xe(f,O-Ie.length+ae.err.line));if($===!0)return De("InvalidXml","Multiple possible root nodes found.",Xe(f,O));b.unpairedTags.indexOf(q)!==-1||S.push({tagName:q,tagStartPos:U}),_=!0}for(O++;O<f.length;O++)if(f[O]==="<")if(f[O+1]==="!"){O++,O=Va(f,O);continue}else if(f[O+1]==="?"){if(O=Ga(f,++O),O.err)return O}else break;else if(f[O]==="&"){let ae=rh(f,O);if(ae==-1)return De("InvalidChar","char '&' is not expected.",Xe(f,O));O=ae}else if($===!0&&!Ba(f[O]))return De("InvalidXml","Extra text at the end",Xe(f,O));f[O]==="<"&&O--}}else{if(Ba(f[O]))continue;return De("InvalidChar","char '"+f[O]+"' is not expected.",Xe(f,O))}if(_){if(S.length==1)return De("InvalidTag","Unclosed tag '"+S[0].tagName+"'.",Xe(f,S[0].tagStartPos));if(S.length>0)return De("InvalidXml","Invalid '"+JSON.stringify(S.map(O=>O.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return De("InvalidXml","Start tag expected.",1);return!0}s(Xg,"validate"),r(Xg,"validate");function Ba(f){return f===" "||f===" "||f===`
316
316
  `||f==="\r"}s(Ba,"isWhiteSpace"),r(Ba,"isWhiteSpace");function Ga(f,b){let S=b;for(;b<f.length;b++)if(f[b]=="?"||f[b]==" "){let _=f.substr(S,b-S);if(b>5&&_==="xml")return De("InvalidXml","XML declaration allowed only at the start of the document.",Xe(f,b));if(f[b]=="?"&&f[b+1]==">"){b++;break}else continue}return b}s(Ga,"readPI"),r(Ga,"readPI");function Va(f,b){if(f.length>b+5&&f[b+1]==="-"&&f[b+2]==="-"){for(b+=3;b<f.length;b++)if(f[b]==="-"&&f[b+1]==="-"&&f[b+2]===">"){b+=2;break}}else if(f.length>b+8&&f[b+1]==="D"&&f[b+2]==="O"&&f[b+3]==="C"&&f[b+4]==="T"&&f[b+5]==="Y"&&f[b+6]==="P"&&f[b+7]==="E"){let S=1;for(b+=8;b<f.length;b++)if(f[b]==="<")S++;else if(f[b]===">"&&(S--,S===0))break}else if(f.length>b+9&&f[b+1]==="["&&f[b+2]==="C"&&f[b+3]==="D"&&f[b+4]==="A"&&f[b+5]==="T"&&f[b+6]==="A"&&f[b+7]==="["){for(b+=8;b<f.length;b++)if(f[b]==="]"&&f[b+1]==="]"&&f[b+2]===">"){b+=2;break}}return b}s(Va,"readCommentAndCDATA"),r(Va,"readCommentAndCDATA");var YR='"',XR="'";function eh(f,b){let S="",_="",$=!1;for(;b<f.length;b++){if(f[b]===YR||f[b]===XR)_===""?_=f[b]:_!==f[b]||(_="");else if(f[b]===">"&&_===""){$=!0;break}S+=f[b]}return _!==""?!1:{value:S,index:b,tagClosed:$}}s(eh,"readAttributeStr"),r(eh,"readAttributeStr");var eI=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function Ja(f,b){let S=d(f,eI),_={};for(let $=0;$<S.length;$++){if(S[$][1].length===0)return De("InvalidAttr","Attribute '"+S[$][2]+"' has no space in starting.",Ur(S[$]));if(S[$][3]!==void 0&&S[$][4]===void 0)return De("InvalidAttr","Attribute '"+S[$][2]+"' is without value.",Ur(S[$]));if(S[$][3]===void 0&&!b.allowBooleanAttributes)return De("InvalidAttr","boolean attribute '"+S[$][2]+"' is not allowed.",Ur(S[$]));let O=S[$][2];if(!nh(O))return De("InvalidAttr","Attribute '"+O+"' is an invalid name.",Ur(S[$]));if(!_.hasOwnProperty(O))_[O]=1;else return De("InvalidAttr","Attribute '"+O+"' is repeated.",Ur(S[$]))}return!0}s(Ja,"validateAttributeString"),r(Ja,"validateAttributeString");function th(f,b){let S=/\d/;for(f[b]==="x"&&(b++,S=/[\da-fA-F]/);b<f.length;b++){if(f[b]===";")return b;if(!f[b].match(S))break}return-1}s(th,"validateNumberAmpersand"),r(th,"validateNumberAmpersand");function rh(f,b){if(b++,f[b]===";")return-1;if(f[b]==="#")return b++,th(f,b);let S=0;for(;b<f.length;b++,S++)if(!(f[b].match(/\w/)&&S<20)){if(f[b]===";")break;return-1}return b}s(rh,"validateAmpersand"),r(rh,"validateAmpersand");function De(f,b,S){return{err:{code:f,msg:b,line:S.line||S,col:S.col}}}s(De,"getErrorObject"),r(De,"getErrorObject");function nh(f){return p(f)}s(nh,"validateAttrName"),r(nh,"validateAttrName");function L(f){return p(f)}s(L,"validateTagName"),r(L,"validateTagName");function Xe(f,b){let S=f.substring(0,b).split(/\r?\n/);return{line:S.length,col:S[S.length-1].length+1}}s(Xe,"getLineNumberForPosition"),r(Xe,"getLineNumberForPosition");function Ur(f){return f.startIndex+f[1].length}s(Ur,"getPositionFromMatch"),r(Ur,"getPositionFromMatch");var tI=class{static{s(this,"XMLParser")}static{r(this,"XMLParser")}constructor(f){this.externalEntities={},this.options=i(f)}parse(f,b){if(typeof f!="string"&&f.toString)f=f.toString();else if(typeof f!="string")throw new Error("XML data is accepted in String or Bytes[] form.");if(b){b===!0&&(b={});let $=Xg(f,b);if($!==!0)throw Error(`${$.err.msg}:${$.err.line}:${$.err.col}`)}let S=new Ee(this.options);S.addExternalEntities(this.externalEntities);let _=S.parseXml(f);return this.options.preserveOrder||_===void 0?_:Wg(_,this.options)}addEntity(f,b){if(b.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(f.indexOf("&")!==-1||f.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(b==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[f]=b}static getMetaDataSymbol(){return g.getMetaDataSymbol()}};return new tI(t)},"getXmlParser");var Gg=class extends ir{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,r){super(e,r),P("policy.outbound.xml-to-json"),ge(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?Dt(e.parseOnStatusCodes):void 0,this.parser=FR({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,r,o){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let n;try{let c=await e.text();n=this.parser.parse(c)}catch(c){let u=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw o.log.error(u,c),new z(u)}let i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:i})}};var Vg=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,r){if(this.services.get(e))throw new ye(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,r)}getService(e){return this.services.get(e)}};var Jg=class{static{s(this,"ApiKeyConsumerClient")}bucketId;cacheDurationSeconds;cacheNamePromise;constructor(e){this.bucketId=e?.bucketId,this.cacheDurationSeconds=e?.cacheDurationSeconds??60}getCacheName(e){return this.cacheNamePromise||(this.cacheNamePromise=Re("zuplo-get-consumer",void 0,{bucketId:e})),this.cacheNamePromise}async get(e){P("utility.get-consumer");let r=My(),o=this.bucketId??Ze.ZUPLO_SERVICE_BUCKET_ID;if(!o)throw new R("ApiKeyConsumerClient - no bucketId provided and no default bucket is configured for this environment. Pass `bucketId` explicitly (find it in the Zuplo portal under Settings > API Key Buckets).");if(!o.startsWith("bckt_"))throw new R(`ApiKeyConsumerClient - bucketId "${o}" is not a valid bucket id. Bucket ids start with "bckt_" (e.g. "bckt_2HaK3odRyJle6NJSu8mzNKBC30BYxllxL"); a bucket name (e.g. "zprj-...-working-copy") is not accepted here. Find the bucket id in the Zuplo portal under Settings > API Key Buckets.`);if(!e||e.trim()==="")throw new R("ApiKeyConsumerClient.get - consumerId is required and cannot be empty");let n=await this.getCacheName(o),i=new we(n,r);if(this.cacheDurationSeconds>0){let l=await i.get(e);if(l)return l}let a=`/v2/key-auth/${encodeURIComponent(o)}/consumers/${encodeURIComponent(e)}`,c=await Xa(a),u={id:c.id,name:c.name,createdOn:c.createdOn,updatedOn:c.updatedOn};return c.description!==void 0&&(u.description=c.description),c.metadata!==void 0&&(u.metadata=c.metadata),this.cacheDurationSeconds>0&&i.put(e,u,this.cacheDurationSeconds),u}};var HR=10,BR=3e4,si=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,r){if(typeof r=="number"){let o=r;this.#n=o*1e3,this.#o=BR,this.#r=HR}else{let o=r;this.#n=o.ttlSeconds*1e3,this.#o=o.loaderTimeoutSeconds?o.loaderTimeoutSeconds*1e3:BR,this.#r=HR}this.#t=e}#s(e){return e.expiry<=new Date}#a(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.#a(e))try{await n$(()=>this.#u(e)!==void 0||!this.#a(e),this.#o+this.#r+1,this.#r);let o=this.#u(e);if(o)return o}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let r=this.#c(e);ar().waitUntil(r)}}async#c(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 R(`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 n$(t,e,r){let o=Date.now();for(;!t();){let n=Date.now()-o;if(n>e)throw new R(`BackgroundLoader: Timeout waiting for an on-going loader after ${n} ms.`);await scheduler.wait(r)}}s(n$,"waitUntilTrue");import{SpanStatusCode as GR,trace as VR}from"@opentelemetry/api";var JR=s(async(t,e,r)=>{let o=Pe.instance.routeData.policies,n=Kr([t],o);if(n.length===0)throw new z(`Invalid 'invokeInboundPolicy call' - no policy '${t}' found.`);let i=n[0];return await VR.getTracer("pipeline").startActiveSpan(`policy:${i.policyName}`,async u=>{try{let l=await i.handler(e,r);if(l instanceof Request||l instanceof de||l instanceof Response)return l instanceof Response||l instanceof de?l:new de(l);{let d=new R(`Invalid state - invalid handler on policy '${i.policyName}' invoked via 'invokeInboundPolicy' on route '${r.route.path}'. The result of an inbound policy must be a Response or Request.`);throw u.setStatus({code:GR.ERROR}),u.recordException(d),d}}finally{u.end()}})},"invokeInboundPolicy"),WR=s(async(t,e,r,o)=>{let n=Pe.instance.routeData.policies,i=Wn([t],n);if(i.length===0)throw new z(`Invalid 'invokeOutboundPolicy call' - no policy '${t}' found.`);let a=i[0];return await VR.getTracer("pipeline").startActiveSpan(`policy:${a.policyName}`,async l=>{try{let d=await a.handler(e,r,o);if(d instanceof Response)return d;{let p=new R(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${o.route.path}. The result of an outbound policy must be a Response.`);throw l.setStatus({code:GR.ERROR}),l.recordException(p),p}}finally{l.end()}})},"invokeOutboundPolicy");function o$(t){let e={};if(!t)return e;try{let r=t.split(","),o={};return r.forEach(n=>{let[i,a]=n.split("=");i&&a&&(o[i.trim()]=a.trim())}),o.asnum&&(e[xi]=o.asnum),o.zip&&(e[Ri]=o.zip.split("+")[0]),o.dma&&(e[Ii]=o.dma),o.region_code&&(e[Pi]=o.region_code),o.timezone&&(e[Si]=o.timezone),o.city&&(e[hi]=o.city),o.continent&&(e[yi]=o.continent),o.country_code&&(e[bi]=o.country_code),o.long&&(e[vi]=o.long),o.lat&&(e[wi]=o.lat),e}catch{return{}}}s(o$,"parseEdgeScapeHeader");function KR(t,e){let r=o$(e);for(let[o,n]of Object.entries(r))t.has(o)||t.set(o,n)}s(KR,"setZpHeadersFromAkamaiEdgeScapeHeader");var Yi=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let r=e.get(Lh);if(r){let o=new Headers(e);KR(o,r),this.#e=o}}get asn(){try{let e=this.#e.get(xi);if(typeof e=="string")return parseInt(e,10)}catch{}}get asOrganization(){return this.#e.get(Ch)??void 0}get city(){return this.#e.get(dh)??this.#e.get(hi)??void 0}get continent(){return this.#e.get(ph)??this.#e.get(yi)??void 0}get country(){return this.#e.get(mh)??this.#e.get(bi)??void 0}get latitude(){return this.#e.get(gh)??this.#e.get(wi)??void 0}get longitude(){return this.#e.get(fh)??this.#e.get(vi)??void 0}get colo(){return this.#e.get(_h)??void 0}get postalCode(){return this.#e.get(vh)??this.#e.get(Ri)??void 0}get metroCode(){return this.#e.get(bh)??this.#e.get(Ii)??void 0}get region(){return this.#e.get(hh)??this.#e.get(Oh)??void 0}get regionCode(){return this.#e.get(yh)??this.#e.get(Pi)??void 0}get timezone(){return this.#e.get(wh)??this.#e.get(Si)??void 0}get httpProtocol(){return this.#e.get(Ah)??void 0}get clientCert(){return this.#e.get(xh)??void 0}get clientMtlsVerificationStatus(){return this.#e.get(Rh)??void 0}get clientMtlsVerificationReason(){return this.#e.get(Ih)??void 0}get clientCertFingerprintSha256(){return this.#e.get(Ph)??void 0}get clientCertNotBefore(){return this.#e.get(Sh)??void 0}get clientCertNotAfter(){return this.#e.get(Th)??void 0}get clientCertIssuerDn(){return this.#e.get(kh)??void 0}get clientCertSubjectDn(){return this.#e.get(Eh)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone,httpProtocol:this.httpProtocol,clientCert:this.clientCert,clientMtlsVerificationStatus:this.clientMtlsVerificationStatus,clientMtlsVerificationReason:this.clientMtlsVerificationReason,clientCertFingerprintSha256:this.clientCertFingerprintSha256,clientCertNotBefore:this.clientCertNotBefore,clientCertNotAfter:this.clientCertNotAfter,clientCertIssuerDn:this.clientCertIssuerDn,clientCertSubjectDn:this.clientCertSubjectDn}}};function yr(t){return{contextId:t.contextId,incomingRequestProperties:t.incomingRequestProperties,requestId:t.requestId,route:t.route,custom:t.custom,parentContext:t.parentContext,analyticsContext:t.analyticsContext}}s(yr,"createRewriteContext");var Vn=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,r){super("responseSending"),this.request=e,this.mutableResponse=r}request;mutableResponse},Jn=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,r){super("responseSent"),this.request=e,this.response=r}request;response},Je=class t{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,r){if(!t.#e.has(e)){let o=new t(r);return t.#e.set(e,o),o}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let r=t.#e.get(e);if(!r)throw new z(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return r}latestRequest;#t;#n;#r;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[],this.#r=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#r.push(e)}onResponseSendingFinal=s(async(e,r,o)=>{for(let n of this.#t)await n(e,r,o)},"onResponseSendingFinal");onResponseSending=s(async(e,r,o)=>{let n=e,i=T.instance.build.COMPATIBILITY_FLAGS.chainResponseSendingHooks;for(let a of this.#n)n=await a(i?n:e,r,o);return n},"onResponseSending");onHandlerResponse=s(async(e,r,o)=>{for(let n of this.#r)await n(e,r,o)},"onHandlerResponse")},Xi=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:r,requestId:o,event:n,custom:i,incomingRequestProperties:a,parentContext:c}){super(),this.log=Object.freeze(e),this.route=r,this.requestId=o,this.custom=i,this.incomingRequestProperties=a,this.parentContext=c,this.#e=n,this.invokeInboundPolicy=(u,l)=>JR(u,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,l,d)=>WR(u,l,d,this),this.invokeRoute=async(u,l)=>{let d=u;typeof u=="string"&&u.startsWith("/")&&(d=new URL(u,"http://localhost"));let p=new de(d,l);return Pe.instance.handleRequest(p,this,{parentContext:this})},this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{Je.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{Je.getContextExtensions(this).addResponseSendingFinalHook(u)},this.analyticsContext=new jh(o),Object.freeze(this)}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;analyticsContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,r,o){P("context.addEventListener");let n=s(i=>{try{typeof r=="function"?r(i):r.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,n,o)}removeEventListener(e,r,o){P("context.removeEventListener"),super.removeEventListener(e,r,o)}};export{P as a,Le as b,Xa as c,jn as d,we as e,nc as f,zn as g,Zn as h,vr as i,M as j,Ue as k,wr as l,de as m,ic as n,sc as o,ue as p,lt as q,Bt as r,ke as s,ir as t,mc as u,bc as v,Br as w,My as x,Vn as y,Jn as z,Je as A,fe as B,Hc as C,ot as D,wP as E,OP as F,AP as G,ub as H,zP as I,Xc as J,Xs as K,im as L,$T as M,Sv as N,Tv as O,_v as P,ik as Q,na as R,Tm as S,uk as T,dk as U,la as V,pk as W,Uv as X,zv as Y,Fv as Z,Bv as _,oa as $,Pk as aa,Ek as ba,Ck as ca,Lm as da,h as ea,je as fa,_E as ga,nC as ha,iC as ia,aC as ja,cC as ka,lC as la,pC as ma,fC as na,bC as oa,rf as pa,of as qa,af as ra,lf as sa,pf as ta,ff as ua,hf as va,bf as wa,xf as xa,Pf as ya,kf as za,_f as Aa,Af as Ba,$f as Ca,ri as Da,ni as Ea,oi as Fa,Uf as Ga,ai as Ha,Zf as Ia,qf as Ja,XC as Ka,Ff as La,Hf as Ma,r_ as Na,o_ as Oa,s_ as Pa,u_ as Qa,l_ as Ra,d_ as Sa,p_ as Ta,R_ as Ua,P_ as Va,Xf as Wa,S_ as Xa,eg as Ya,E_ as Za,it as _a,M_ as $a,ig as ab,sg as bb,U_ as cb,ug as db,W_ as eb,K_ as fb,Q_ as gb,Y_ as hb,X_ as ib,eO as jb,aO as kb,yg as lb,hO as mb,yO as nb,bO as ob,wO as pb,xO as qb,PO as rb,SO as sb,kO as tb,EO as ub,CO as vb,$O as wb,MO as xb,Ig as yb,FO as zb,Sg as Ab,WO as Bb,Tg as Cb,Eg as Db,KO as Eb,YO as Fb,XO as Gb,Og as Hb,RR as Ib,iA as Jb,sA as Kb,aA as Lb,cA as Mb,uA as Nb,lA as Ob,_R as Pb,dA as Qb,pA as Rb,fA as Sb,wA as Tb,xA as Ub,RA as Vb,IA as Wb,PA as Xb,SA as Yb,TA as Zb,EA as _b,Dg as $b,UA as ac,jA as bc,ZA as cc,HA as dc,mi as ec,zg as fc,BA as gc,VA as hc,Hg as ic,JA as jc,r$ as kc,Gg as lc,Vg as mc,Jg as nc,si as oc};
317
- /*! For license information please see chunk-YTQ3TTI6.js.LEGAL.txt */
318
- //# sourceMappingURL=chunk-YTQ3TTI6.js.map
317
+ /*! For license information please see chunk-2GVPMQ7M.js.LEGAL.txt */
318
+ //# sourceMappingURL=chunk-2GVPMQ7M.js.map