xmcp 1.11.0 → 1.12.0

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.
@@ -1,4 +1,4 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var a in r)("object"==typeof exports?exports:e)[a]=r[a]}}(this,()=>(()=>{"use strict";var e={6982(e){e.exports=require("crypto")},9896(e){e.exports=require("fs")},6928(e){e.exports=require("path")}},t={};function r(a){var i=t[a];if(void 0!==i)return i.exports;var n=t[a]={exports:{}};return e[a](n,n.exports,r),n.exports}r.d=(e,t,a)=>{var i=(t,a)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,[a]:t[i]})};i(t,"get"),i(a,"value")},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var a={};return(()=>{let e,t,i,n,o,s,l,c,u,d,p,m,h,f,g,y,v,_,b,S,$,w,R;r.r(a),r.d(a,{xmcpHandler:()=>gq});let k=require("node:crypto");var x,P,E,T,j,O,C,I,N,q,A,z,M,L,Z,D,U=Object.create,V=Object.defineProperty,F=Object.getOwnPropertyDescriptor,H=Object.getOwnPropertyNames,J=Object.getPrototypeOf,B=Object.prototype.hasOwnProperty,K=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),G=(e,t,r)=>(r=null!=e?U(J(e)):{},((e,t,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(var a,i=H(t),n=0,o=i.length;n<o;n++)a=i[n],B.call(e,a)||void 0===a||V(e,a,{get:(e=>t[e]).bind(null,a),enumerable:!(r=F(t,a))||r.enumerable});return e})(!t&&e&&e.__esModule?r:V(r,"default",{value:e,enumerable:!0}),e));let W=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),Y=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),X=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),Q=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function ee(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function et(e,t="|"){return e.map(e=>ew(e)).join(t)}function er(e,t){return"bigint"==typeof t?t.toString():t}class ea{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return void 0!==e&&(this._value=e(),this._getter=void 0),this._value}}function ei(e){return new ea(e)}function en(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}let eo=Symbol("evaluating");function es(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function el(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function ec(e){return el(e._zod.def)??e._zod.def.shape}function eu(e,t,r){Object.defineProperty(e,t,{get(){let e=r();return es(this,t,e),e},enumerable:!0,configurable:!0})}function ed(e,t,r){t in e?es(e,t,r):e[t]=r}function ep(e,t,r,a){let i=ec(t);for(let n of r){let r=Object.getOwnPropertyDescriptor(i,n);r.enumerable&&(r.get?eu(e,n,()=>{let e=t._zod.def.shape[n];return a?a(e,n):e}):ed(e,n,a?a(r.value,n):r.value))}}function em(...e){let t={};for(let r of e)Object.assign(t,Object.getOwnPropertyDescriptors(r));return Object.defineProperties({},t)}let eh="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ef(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let eg=ei(()=>{if(eW.jitless||"u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function ey(e){if(!1===ef(e))return!1;let t=e.constructor;if(void 0===t||"function"!=typeof t)return!0;let r=t.prototype;return!1!==ef(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function ev(e){return ey(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let e_=new Set(["string","number","symbol"]);function eb(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function eS(e,t,r){let a=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(a._zod.parent=e),a}function e$(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function ew(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}let eR={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ek={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ex(e,t){let r=ec(e),a=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&a.push(e)}return a}function eP(e,t){let r={};ep(r,e,Reflect.ownKeys(ec(e)));for(let e of Reflect.ownKeys(t)){let a=Object.getOwnPropertyDescriptor(t,e);a.enumerable&&(a.get?eu(r,e,()=>t[e]):ed(r,e,a.value))}return r}function eE(e,t,r,a="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${a}() cannot be used on object schemas containing refinements`);let n=r?new Set(ex(t,r)):void 0,o={};return ep(o,t,Reflect.ownKeys(ec(t)),e&&((t,r)=>n&&!n.has(r)?t:new e({type:"optional",innerType:t}))),eS(t,em(t._zod.def,{shape:o,checks:[]}))}function eT(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ej(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function eO(e){return"string"==typeof e?e:e?.message}function eC(e){let t=[];for(let r of e??[]){let e=r._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let a=e.maximum??e.length??e.size;a>=0&&t.push([a,r])}return t}function eI(e,t,r){var a;for(let i=t;i<e.length;i++)(a=e[i]).schema??(a.schema=r)}function eN(e,t,r){let a=e.inst?._zod?.traits;a?.has("$ZodType")&&(a.has("$ZodCheck")?e.schema??(e.schema=e.inst):e.schema=e.inst);let i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,n=e.message?e.message:eO(e.inst?._zod.def?.error?.(e))??eO(i?.(e))??eO(t?.error?.(e))??eO(r.customError?.(e))??eO(r.localeError?.(e))??"Invalid input",o={};for(let t of Object.keys(e))"inst"!==t&&"schema"!==t&&"continue"!==t&&"input"!==t&&"__proto__"!==t&&(o[t]=e[t]);return o.path??(o.path=[]),o.message=n,t?.reportInput&&(o.input=e.input),o}let eq=/[\uD800-\uDBFF]/;function eA(e){let t=e.length;if(!eq.test(e))return t;let r=t;for(let a=0;a<t-1;a++)(64512&e.charCodeAt(a))==55296&&(64512&e.charCodeAt(a+1))==56320&&(r--,a++);return r}function ez(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function eM(...e){let[t,r,a]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:a}:{...t}}function eL(e,t,r,a=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:a,value:r}),r}function eZ(e,t){for(let r in e){let a=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return eL(this,r,a(this))},set(e){eL(this,r,e)}})}return t}let eD=!1,eU={configurable:!0,get(){eD=!0}};function eV(t,r,a){let i=Object.getPrototypeOf(t._zod);if(r in i&&e!==t._zod){e=void 0;return}e=t._zod,Object.defineProperty(i,r,{configurable:!0,get(){Object.defineProperty(this,r,eU);let e=eD;eD=!1;try{let t=a(this);return eD?delete this[r]:Object.defineProperty(this,r,{configurable:!0,writable:!0,value:t}),eD=eD||e,t}catch(t){throw delete this[r],eD=eD||e,t}},set(e){Object.defineProperty(this,r,{configurable:!0,writable:!0,value:e})}})}let eF=Object.freeze({status:"aborted"}),eH={value:void 0,enumerable:!1},eJ="captureStackTrace"in Error?Error:null;function eB(e,t,r,a){function i(e){this.def=e,this.constr=c,this.traits=new Set}i.prototype={};let n=r&&new WeakSet;function o(a,o){if(a._zod){if(a._zod.traits.has(e))return}else{eH.value=new i(o);try{Object.defineProperty(a,"_zod",eH)}finally{eH.value=void 0}}if(a._zod.traits.add(e),t(a,o),n){let e=Object.getPrototypeOf(a),t=a._zod.constr.prototype,i=e;for(;i&&i!==t;)i=Object.getPrototypeOf(i);let o=i??e;if(!n.has(o)){n.add(o);for(let e in r){let t=Object.getOwnPropertyDescriptor(r,e);t.get?Object.defineProperty(o,e,{...t,enumerable:!1}):function(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:eL(this,t,r.bind(this))},set(e){eL(this,t,e)}})}(o,e,t.value)}}}let s=c.prototype;for(let e in s)Object.prototype.hasOwnProperty.call(s,e)&&(e in a||(a[e]=s[e].bind(a)))}let s=a?.Parent??Object;class l extends s{}function c(e){let t=a?.Parent?function(e){let t=eJ;if(t){let r=t.stackTraceLimit;if("number"==typeof r){try{t.stackTraceLimit=0}catch{return eJ=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}(l):this;o(t,e);let r=t._zod.deferred;if(r){for(let e of r)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(l,"name",{value:e}),Object.defineProperty(c,"init",{value:o}),Object.defineProperty(c,Symbol.hasInstance,{value:t=>!!a?.Parent&&t instanceof a.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(c,"name",{value:e}),c}class eK extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class eG extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(q=globalThis).__zod_globalConfig??(q.__zod_globalConfig={});let eW=globalThis.__zod_globalConfig;function eY(e){return e&&Object.assign(eW,e),eW}class eX extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}let eQ="~memo",e0=[];function e1(e){return null!==e&&"object"==typeof e}function e2(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}let e9=new WeakMap,e4=[],e3={alloc(e,r,a){let i=t;if(!i)return a;t=void 0;let n={value:a,issues:null};return i.set(r.value,n),e4.push(n),a},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,r=(e,r)=>{var a,i;let n;if("backward"!==r.direction&&(a=r,i=e.value,void 0!==(n=a[eQ]?.backEdges)&&e1(i)&&n.has(i)))throw new eX;return t(e,r)};e._zod.parse=r,e._zod.run===t&&(e._zod.run=r)})},attach(e){var r;let a,i,n,o=!1;(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred.push(()=>{let r=e._zod.parse,s=(l,c)=>{let u;if(void 0===a){let t=function e(t,r,a){var i,n;let o=e9.get(t);if(void 0!==o)return 2*!!o;if(r.has(t))return 2;r.add(t);let s=0,l=t=>{if(2!==s&&t?._zod){let i=e(t,r,a);i>s&&(s=i)}},c=e=>{e>s&&(s=e)},u=t._zod.def;switch(u.type){case"object":{let t=el(u);c(t?((t,i)=>{let n=0;for(let o of Reflect.ownKeys(t)){let s=Object.getOwnPropertyDescriptor(t,o);if(i&&!s.enumerable)continue;let l=s.get?1:s.value?._zod?e(s.value,r,a):0;l>n&&(n=l)}return n})(t,!0):1),l(u.catchall);break}case"array":l(u.element);break;case"tuple":for(let e of u.items)l(e);l(u.rest);break;case"record":case"map":l(u.keyType),l(u.valueType);break;case"set":l(u.valueType);break;case"union":for(let e of u.options)l(e);break;case"intersection":l(u.left),l(u.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":l(u.innerType);break;case"pipe":l(u.in),l(u.out);break;case"function":l(u.input),l(u.output);break;case"lazy":{let i=u._cachedInner??(a?t._zod.innerType:void 0);c(i?e(i,r,!1):1);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let e in u){let t=Object.getOwnPropertyDescriptor(u,e);if(!t||t.get)continue;let r=t.value;if(r&&"object"==typeof r){if(r._zod)l(r);else if(Array.isArray(r))for(let e of r)l(e)}}}return r.delete(t),i=t,1!==(n=s)&&e9.set(i,2===n),n}(e,new Set,!1);if(0===t)return e._zod.parse=r,e._zod.run===s&&(e._zod.run=r),r(l,c);2===t||o?a=!0:o=!0}let d=l.value;if(!e1(d))return r(l,c);let p=c[eQ];if(p||(p={buckets:new WeakMap,backEdges:void 0},c[eQ]=p),i===c)u=n;else{var m;let t;(t=(m=p).buckets.get(e))||(t=new WeakMap,m.buckets.set(e,t)),u=t,i=c,n=u}let h=u.get(d);if(h)return l.value=h.value,h.issues?h.issues.length&&l.issues.push(...e2(h.issues)):(l.memo=!0,p.backEdges??(p.backEdges=new WeakSet),p.backEdges.add(h.value)),l;t=u;let f=e4.length,g=r(l,c);t=void 0;let y=e4.length>f?e4.pop():void 0;return g instanceof Promise?g.then(e=>(y&&(y.issues=e.issues.length?e2(e.issues):e0),e)):(y&&(y.issues=g.issues.length?e2(g.issues):e0),g)};e._zod.parse=s,e._zod.run===r&&(e._zod.run=s)})}},e5=/^[cC][0-9a-z]{6,}$/,e6=/^[0-9a-z]+$/,e8=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,e7=/^[0-9a-vA-V]{20}$/,te=/^[A-Za-z0-9]{27}$/,tt=/^[a-zA-Z0-9_-]{21}$/,tr=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ta=/^([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})$/,ti=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,tn=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,to=/^(?:(?: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])$/,ts=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,tl=/^((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])$/,tc=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,tu=/^https?$/,td=/^\+[1-9]\d{6,14}$/,tp="(?:(?:\\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])))",tm=RegExp(`^${tp}$`);function th(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}let tf=/^[\s\S]{0,}$/,tg=/^-?\d+$/,ty=/^-?\d+(?:\.\d+)?$/,tv=/^(?:true|false)$/i,t_=/^null$/i,tb=/^[^A-Z]*$/,tS=/^[^a-z]*$/,t$=eB("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),tw=e=>{let t=e.value;return null!=t&&void 0!==t.length},tR={number:"number",bigint:"bigint",object:"date"},tk=eB("$ZodCheckLessThan",(e,t)=>{t$.init(e,t);let r=tR[typeof t.value];e._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:tR[typeof a.value]??r,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),tx=eB("$ZodCheckGreaterThan",(e,t)=>{t$.init(e,t);let r=tR[typeof t.value];e._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:tR[typeof a.value]??r,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),tP=eB("$ZodCheckMultipleOf",(e,t)=>{t$.init(e,t),e._zod.check=r=>{let a,i,n;if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):0==(i=Math.round(a=r.value/t.value),n=4*Number.EPSILON*Math.max(Math.abs(a),1),Math.abs(a-i)<n?0:a-i))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),tE=eB("$ZodCheckNumberFormat",(e,t)=>{t$.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),a=r?"int":"number",[i,n]=eR[t.format];e._zod.check=o=>{let s=o.value;if(r){if(!Number.isInteger(s))return void o.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?o.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}))}s<i&&o.issues.push({origin:"number",input:s,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>n&&o.issues.push({origin:"number",input:s,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),tT=eB("$ZodCheckMaxLength",(e,t)=>{var r;t$.init(e,t),(r=e._zod.def).when??(r.when=tw),e._zod.check=r=>{let a=r.value,i=a.length;if(("string"==typeof a&&i>t.maximum?eA(a):i)<=t.maximum)return;let n=ez(a);r.issues.push({origin:n,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),tj=eB("$ZodCheckMinLength",(e,t)=>{var r;t$.init(e,t),(r=e._zod.def).when??(r.when=tw),e._zod.check=r=>{let a=r.value,i=a.length;if(("string"==typeof a&&i>=t.minimum&&i<2*t.minimum?eA(a):i)>=t.minimum)return;let n=ez(a);r.issues.push({origin:n,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),tO=eB("$ZodCheckLengthEquals",(e,t)=>{var r;t$.init(e,t),(r=e._zod.def).when??(r.when=tw),e._zod.check=r=>{let a=r.value,i=a.length,n="string"==typeof a&&i>=t.length&&i<=2*t.length?eA(a):i;if(n===t.length)return;let o=ez(a),s=n>t.length;r.issues.push({origin:o,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),tC=eB("$ZodCheckStringFormat",(e,t)=>{var r,a;t$.init(e,t),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),tI=eB("$ZodCheckRegex",(e,t)=>{tC.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),tN=eB("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=tb),tC.init(e,t)}),tq=eB("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=tS),tC.init(e,t)}),tA=eB("$ZodCheckIncludes",(e,t)=>{t$.init(e,t);let r=eb(t.includes),a=new RegExp("number"==typeof t.position?`^.{${t.position},}${r}`:r);t.pattern=a,e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),tz=eB("$ZodCheckStartsWith",(e,t)=>{t$.init(e,t);let r=RegExp(`^${eb(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),tM=eB("$ZodCheckEndsWith",(e,t)=>{t$.init(e,t);let r=RegExp(`.*${eb(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),tL=eB("$ZodCheckOverwrite",(e,t)=>{t$.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class tZ{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
1
+ !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var a in r)("object"==typeof exports?exports:e)[a]=r[a]}}(this,()=>(()=>{"use strict";var e={6982(e){e.exports=require("crypto")},9896(e){e.exports=require("fs")},6928(e){e.exports=require("path")}},t={};function r(a){var i=t[a];if(void 0!==i)return i.exports;var n=t[a]={exports:{}};return e[a](n,n.exports,r),n.exports}r.d=(e,t,a)=>{var i=(t,a)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,[a]:t[i]})};i(t,"get"),i(a,"value")},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var a={};return(()=>{let e,t,i,n,o,s,l,c,u,d,p,m,h,f,g,y,v,_,b,S,$,w,R;r.r(a),r.d(a,{xmcpHandler:()=>gZ});let k=require("node:crypto");var x,P,E,T,j,O,C,I,N,q,A,z,M,L,Z,D,U=Object.create,V=Object.defineProperty,F=Object.getOwnPropertyDescriptor,H=Object.getOwnPropertyNames,J=Object.getPrototypeOf,B=Object.prototype.hasOwnProperty,K=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),G=(e,t,r)=>(r=null!=e?U(J(e)):{},((e,t,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(var a,i=H(t),n=0,o=i.length;n<o;n++)a=i[n],B.call(e,a)||void 0===a||V(e,a,{get:(e=>t[e]).bind(null,a),enumerable:!(r=F(t,a))||r.enumerable});return e})(!t&&e&&e.__esModule?r:V(r,"default",{value:e,enumerable:!0}),e));let W=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),Y=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),X=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),Q=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function ee(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function et(e,t="|"){return e.map(e=>ew(e)).join(t)}function er(e,t){return"bigint"==typeof t?t.toString():t}class ea{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return void 0!==e&&(this._value=e(),this._getter=void 0),this._value}}function ei(e){return new ea(e)}function en(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}let eo=Symbol("evaluating");function es(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function el(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function ec(e){return el(e._zod.def)??e._zod.def.shape}function eu(e,t,r){Object.defineProperty(e,t,{get(){let e=r();return es(this,t,e),e},enumerable:!0,configurable:!0})}function ed(e,t,r){t in e?es(e,t,r):e[t]=r}function ep(e,t,r,a){let i=ec(t);for(let n of r){let r=Object.getOwnPropertyDescriptor(i,n);r.enumerable&&(r.get?eu(e,n,()=>{let e=t._zod.def.shape[n];return a?a(e,n):e}):ed(e,n,a?a(r.value,n):r.value))}}function em(...e){let t={};for(let r of e)Object.assign(t,Object.getOwnPropertyDescriptors(r));return Object.defineProperties({},t)}let eh="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ef(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let eg=ei(()=>{if(eW.jitless||"u">typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function ey(e){if(!1===ef(e))return!1;let t=e.constructor;if(void 0===t||"function"!=typeof t)return!0;let r=t.prototype;return!1!==ef(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function ev(e){return ey(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let e_=new Set(["string","number","symbol"]);function eb(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function eS(e,t,r){let a=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(a._zod.parent=e),a}function e$(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}function ew(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}let eR={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-0x80000000,0x7fffffff],uint32:[0,0xffffffff],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ek={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function ex(e,t){let r=ec(e),a=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&a.push(e)}return a}function eP(e,t){let r={};ep(r,e,Reflect.ownKeys(ec(e)));for(let e of Reflect.ownKeys(t)){let a=Object.getOwnPropertyDescriptor(t,e);a.enumerable&&(a.get?eu(r,e,()=>t[e]):ed(r,e,a.value))}return r}function eE(e,t,r,a="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${a}() cannot be used on object schemas containing refinements`);let n=r?new Set(ex(t,r)):void 0,o={};return ep(o,t,Reflect.ownKeys(ec(t)),e&&((t,r)=>n&&!n.has(r)?t:new e({type:"optional",innerType:t}))),eS(t,em(t._zod.def,{shape:o,checks:[]}))}function eT(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ej(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function eO(e){return"string"==typeof e?e:e?.message}function eC(e){let t=[];for(let r of e??[]){let e=r._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let a=e.maximum??e.length??e.size;a>=0&&t.push([a,r])}return t}function eI(e,t,r){var a;for(let i=t;i<e.length;i++)(a=e[i]).schema??(a.schema=r)}function eN(e,t,r){let a=e.inst?._zod?.traits;a?.has("$ZodType")&&(a.has("$ZodCheck")?e.schema??(e.schema=e.inst):e.schema=e.inst);let i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,n=e.message?e.message:eO(e.inst?._zod.def?.error?.(e))??eO(i?.(e))??eO(t?.error?.(e))??eO(r.customError?.(e))??eO(r.localeError?.(e))??"Invalid input",o={};for(let t of Object.keys(e))"inst"!==t&&"schema"!==t&&"continue"!==t&&"input"!==t&&"__proto__"!==t&&(o[t]=e[t]);return o.path??(o.path=[]),o.message=n,t?.reportInput&&(o.input=e.input),o}let eq=/[\uD800-\uDBFF]/;function eA(e){let t=e.length;if(!eq.test(e))return t;let r=t;for(let a=0;a<t-1;a++)(64512&e.charCodeAt(a))==55296&&(64512&e.charCodeAt(a+1))==56320&&(r--,a++);return r}function ez(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function eM(...e){let[t,r,a]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:a}:{...t}}function eL(e,t,r,a=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:a,value:r}),r}function eZ(e,t){for(let r in e){let a=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return eL(this,r,a(this))},set(e){eL(this,r,e)}})}return t}let eD=!1,eU={configurable:!0,get(){eD=!0}};function eV(t,r,a){let i=Object.getPrototypeOf(t._zod);if(r in i&&e!==t._zod){e=void 0;return}e=t._zod,Object.defineProperty(i,r,{configurable:!0,get(){Object.defineProperty(this,r,eU);let e=eD;eD=!1;try{let t=a(this);return eD?delete this[r]:Object.defineProperty(this,r,{configurable:!0,writable:!0,value:t}),eD=eD||e,t}catch(t){throw delete this[r],eD=eD||e,t}},set(e){Object.defineProperty(this,r,{configurable:!0,writable:!0,value:e})}})}let eF=Object.freeze({status:"aborted"}),eH={value:void 0,enumerable:!1},eJ="captureStackTrace"in Error?Error:null;function eB(e,t,r,a){function i(e){this.def=e,this.constr=c,this.traits=new Set}i.prototype={};let n=r&&new WeakSet;function o(a,o){if(a._zod){if(a._zod.traits.has(e))return}else{eH.value=new i(o);try{Object.defineProperty(a,"_zod",eH)}finally{eH.value=void 0}}if(a._zod.traits.add(e),t(a,o),n){let e=Object.getPrototypeOf(a),t=a._zod.constr.prototype,i=e;for(;i&&i!==t;)i=Object.getPrototypeOf(i);let o=i??e;if(!n.has(o)){n.add(o);for(let e in r){let t=Object.getOwnPropertyDescriptor(r,e);t.get?Object.defineProperty(o,e,{...t,enumerable:!1}):function(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:eL(this,t,r.bind(this))},set(e){eL(this,t,e)}})}(o,e,t.value)}}}let s=c.prototype;for(let e in s)Object.prototype.hasOwnProperty.call(s,e)&&(e in a||(a[e]=s[e].bind(a)))}let s=a?.Parent??Object;class l extends s{}function c(e){let t=a?.Parent?function(e){let t=eJ;if(t){let r=t.stackTraceLimit;if("number"==typeof r){try{t.stackTraceLimit=0}catch{return eJ=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}(l):this;o(t,e);let r=t._zod.deferred;if(r){for(let e of r)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(l,"name",{value:e}),Object.defineProperty(c,"init",{value:o}),Object.defineProperty(c,Symbol.hasInstance,{value:t=>!!a?.Parent&&t instanceof a.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(c,"name",{value:e}),c}class eK extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class eG extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(q=globalThis).__zod_globalConfig??(q.__zod_globalConfig={});let eW=globalThis.__zod_globalConfig;function eY(e){return e&&Object.assign(eW,e),eW}class eX extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}let eQ="~memo",e0=[];function e1(e){return null!==e&&"object"==typeof e}function e2(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}let e9=new WeakMap,e4=[],e3={alloc(e,r,a){let i=t;if(!i)return a;t=void 0;let n={value:a,issues:null};return i.set(r.value,n),e4.push(n),a},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,r=(e,r)=>{var a,i;let n;if("backward"!==r.direction&&(a=r,i=e.value,void 0!==(n=a[eQ]?.backEdges)&&e1(i)&&n.has(i)))throw new eX;return t(e,r)};e._zod.parse=r,e._zod.run===t&&(e._zod.run=r)})},attach(e){var r;let a,i,n,o=!1;(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred.push(()=>{let r=e._zod.parse,s=(l,c)=>{let u;if(void 0===a){let t=function e(t,r,a){var i,n;let o=e9.get(t);if(void 0!==o)return 2*!!o;if(r.has(t))return 2;r.add(t);let s=0,l=t=>{if(2!==s&&t?._zod){let i=e(t,r,a);i>s&&(s=i)}},c=e=>{e>s&&(s=e)},u=t._zod.def;switch(u.type){case"object":{let t=el(u);c(t?((t,i)=>{let n=0;for(let o of Reflect.ownKeys(t)){let s=Object.getOwnPropertyDescriptor(t,o);if(i&&!s.enumerable)continue;let l=s.get?1:s.value?._zod?e(s.value,r,a):0;l>n&&(n=l)}return n})(t,!0):1),l(u.catchall);break}case"array":l(u.element);break;case"tuple":for(let e of u.items)l(e);l(u.rest);break;case"record":case"map":l(u.keyType),l(u.valueType);break;case"set":l(u.valueType);break;case"union":for(let e of u.options)l(e);break;case"intersection":l(u.left),l(u.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":l(u.innerType);break;case"pipe":l(u.in),l(u.out);break;case"function":l(u.input),l(u.output);break;case"lazy":{let i=u._cachedInner??(a?t._zod.innerType:void 0);c(i?e(i,r,!1):1);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let e in u){let t=Object.getOwnPropertyDescriptor(u,e);if(!t||t.get)continue;let r=t.value;if(r&&"object"==typeof r){if(r._zod)l(r);else if(Array.isArray(r))for(let e of r)l(e)}}}return r.delete(t),i=t,1!==(n=s)&&e9.set(i,2===n),n}(e,new Set,!1);if(0===t)return e._zod.parse=r,e._zod.run===s&&(e._zod.run=r),r(l,c);2===t||o?a=!0:o=!0}let d=l.value;if(!e1(d))return r(l,c);let p=c[eQ];if(p||(p={buckets:new WeakMap,backEdges:void 0},c[eQ]=p),i===c)u=n;else{var m;let t;(t=(m=p).buckets.get(e))||(t=new WeakMap,m.buckets.set(e,t)),u=t,i=c,n=u}let h=u.get(d);if(h)return l.value=h.value,h.issues?h.issues.length&&l.issues.push(...e2(h.issues)):(l.memo=!0,p.backEdges??(p.backEdges=new WeakSet),p.backEdges.add(h.value)),l;t=u;let f=e4.length,g=r(l,c);t=void 0;let y=e4.length>f?e4.pop():void 0;return g instanceof Promise?g.then(e=>(y&&(y.issues=e.issues.length?e2(e.issues):e0),e)):(y&&(y.issues=g.issues.length?e2(g.issues):e0),g)};e._zod.parse=s,e._zod.run===r&&(e._zod.run=s)})}},e5=/^[cC][0-9a-z]{6,}$/,e6=/^[0-9a-z]+$/,e8=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,e7=/^[0-9a-vA-V]{20}$/,te=/^[A-Za-z0-9]{27}$/,tt=/^[a-zA-Z0-9_-]{21}$/,tr=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ta=/^([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})$/,ti=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,tn=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,to=/^(?:(?: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])$/,ts=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,tl=/^((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])$/,tc=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,tu=/^https?$/,td=/^\+[1-9]\d{6,14}$/,tp="(?:(?:\\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])))",tm=RegExp(`^${tp}$`);function th(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}let tf=/^[\s\S]{0,}$/,tg=/^-?\d+$/,ty=/^-?\d+(?:\.\d+)?$/,tv=/^(?:true|false)$/i,t_=/^null$/i,tb=/^[^A-Z]*$/,tS=/^[^a-z]*$/,t$=eB("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),tw=e=>{let t=e.value;return null!=t&&void 0!==t.length},tR={number:"number",bigint:"bigint",object:"date"},tk=eB("$ZodCheckLessThan",(e,t)=>{t$.init(e,t);let r=tR[typeof t.value];e._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:tR[typeof a.value]??r,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),tx=eB("$ZodCheckGreaterThan",(e,t)=>{t$.init(e,t);let r=tR[typeof t.value];e._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:tR[typeof a.value]??r,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),tP=eB("$ZodCheckMultipleOf",(e,t)=>{t$.init(e,t),e._zod.check=r=>{let a,i,n;if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):0==(i=Math.round(a=r.value/t.value),n=4*Number.EPSILON*Math.max(Math.abs(a),1),Math.abs(a-i)<n?0:a-i))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),tE=eB("$ZodCheckNumberFormat",(e,t)=>{t$.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),a=r?"int":"number",[i,n]=eR[t.format];e._zod.check=o=>{let s=o.value;if(r){if(!Number.isInteger(s))return void o.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?o.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}))}s<i&&o.issues.push({origin:"number",input:s,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>n&&o.issues.push({origin:"number",input:s,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),tT=eB("$ZodCheckMaxLength",(e,t)=>{var r;t$.init(e,t),(r=e._zod.def).when??(r.when=tw),e._zod.check=r=>{let a=r.value,i=a.length;if(("string"==typeof a&&i>t.maximum?eA(a):i)<=t.maximum)return;let n=ez(a);r.issues.push({origin:n,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),tj=eB("$ZodCheckMinLength",(e,t)=>{var r;t$.init(e,t),(r=e._zod.def).when??(r.when=tw),e._zod.check=r=>{let a=r.value,i=a.length;if(("string"==typeof a&&i>=t.minimum&&i<2*t.minimum?eA(a):i)>=t.minimum)return;let n=ez(a);r.issues.push({origin:n,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),tO=eB("$ZodCheckLengthEquals",(e,t)=>{var r;t$.init(e,t),(r=e._zod.def).when??(r.when=tw),e._zod.check=r=>{let a=r.value,i=a.length,n="string"==typeof a&&i>=t.length&&i<=2*t.length?eA(a):i;if(n===t.length)return;let o=ez(a),s=n>t.length;r.issues.push({origin:o,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),tC=eB("$ZodCheckStringFormat",(e,t)=>{var r,a;t$.init(e,t),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),tI=eB("$ZodCheckRegex",(e,t)=>{tC.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),tN=eB("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=tb),tC.init(e,t)}),tq=eB("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=tS),tC.init(e,t)}),tA=eB("$ZodCheckIncludes",(e,t)=>{t$.init(e,t);let r=eb(t.includes),a=new RegExp("number"==typeof t.position?`^.{${t.position},}${r}`:r);t.pattern=a,e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),tz=eB("$ZodCheckStartsWith",(e,t)=>{t$.init(e,t);let r=RegExp(`^${eb(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),tM=eB("$ZodCheckEndsWith",(e,t)=>{t$.init(e,t);let r=RegExp(`.*${eb(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),tL=eB("$ZodCheckOverwrite",(e,t)=>{t$.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class tZ{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
2
2
  ${t.join("\n")}
3
3
  };`)(...Object.values(this.closed))}}let tD={major:4,minor:6,patch:7},tU=eB("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=tD;let a=e._zod.def.checks,i=e._zod.traits.has("$ZodCheck")?[e,...a??[]]:a?.length?[...a]:[];for(let t of i)for(let r of t._zod.onattach)r(e);if(0===i.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,r,a)=>{let i;if(t.memo)return t;let n=eT(t);for(let o of r){if(o._zod.def.when){if(function(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}(t)||!o._zod.def.when(t))continue}else if(n)continue;let r=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&a?.async===!1)throw new eK;if(i||s instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await s,t.issues.length!==r&&(eI(t.issues,r,e),n||(n=eT(t,r)))});else{if(t.issues.length===r)continue;eI(t.issues,r,e),n||(n=eT(t,r))}}return i?i.then(()=>t):t},r=(r,a,n)=>{if(eT(r))return r.aborted=!0,r;let o=t(a,i,n);if(o instanceof Promise){if(!1===n.async)throw new eK;return o.then(t=>e._zod.parse(t,n))}return e._zod.parse(o,n)};e._zod.run=(a,n)=>{if(n.skipChecks)return e._zod.parse(a,n);if("backward"===n.direction){let t=e._zod.parse({value:a.value,issues:[]},{...n,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,a,n)):r(t,a,n)}let o=e._zod.parse(a,n);if(o instanceof Promise){if(!1===n.async)throw new eK;return o.then(e=>t(e,i,n))}return t(o,i,n)}}},{get"~standard"(){return eL(this,"~standard",tF(this),!1)},set"~standard"(e){eL(this,"~standard",e)}}),tV=(e,t)=>e.issues.length?{issues:e.issues.map(e=>eN(e,t,eY()))}:{value:e.value};function tF(e){return{validate:t=>{let r={async:!1};try{let a=e._zod.run({value:t,issues:[]},r);if(!(a instanceof Promise))return tV(a,r)}catch(e){}return async function(e,t){let r={async:!0};return tV(await e._zod.run({value:t,issues:[]},r),r)}(e,t)},vendor:"zod",version:1}}let tH=eB("$ZodString",(e,t)=>{tU.init(e,t),e._zod.pattern=t.pattern??tf,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=String(r.value)}catch(e){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),tJ=eB("$ZodStringFormat",(e,t)=>{tC.init(e,t),tH.init(e,t)}),tB=eB("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ta),tJ.init(e,t)}),tK=eB("$ZodUUID",(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ti(e))}else t.pattern??(t.pattern=ti());tJ.init(e,t)}),tG=eB("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=tn),tJ.init(e,t)});function tW(e){try{if("u">typeof URL&&"function"==typeof URL.canParse)return URL.canParse(e);return new URL(e),!0}catch{return!1}}let tY=/[\t\n\r]/g;function tX(e){return e.replace(tY,"")}let tQ=eB("$ZodURL",(e,t)=>{tJ.init(e,t),e._zod.check=r=>{try{var a,i;let n=r.value.trim(),o="normalize"in t||"hostname"in t||"protocol"in t?function(e,t){if(!t.normalize&&t.protocol?.source===tu.source&&!/^https?:\/\//i.test(e))return 1;try{if("u">typeof URL){let t=URL;if("function"==typeof t.parse)return t.parse(e)??2}return new URL(e)}catch{return 2}}(n,t):tW(n)||2;if(1===o)return void r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});if(2===o)return void r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort});if(!0===o){r.value=tX(n);return}t.hostname&&((a=t.hostname).lastIndex=0,!a.test(o.hostname))&&r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort}),t.protocol&&((i=t.protocol).lastIndex=0,!i.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol))&&r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort}),r.value=t.normalize?o.href:tX(n);return}catch(a){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),t0=eB("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=RegExp("^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$","u")),tJ.init(e,t)}),t1=eB("$ZodNanoID",(e,t)=>{var r;if(void 0!==t.length&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=void 0===t.length?tt:(r=t.length,RegExp(`^[a-zA-Z0-9_-]{${r}}$`))),tJ.init(e,t)}),t2=eB("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=e5),tJ.init(e,t)}),t9=eB("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=e6),tJ.init(e,t)}),t4=eB("$ZodULID",(e,t)=>{t.pattern??(t.pattern=e8),tJ.init(e,t)}),t3=eB("$ZodXID",(e,t)=>{t.pattern??(t.pattern=e7),tJ.init(e,t)}),t5=eB("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=te),tJ.init(e,t)}),t6=eB("$ZodISODateTime",(e,t)=>{let r,a,i;t.pattern??(r=["Z"],t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)"),a=`${th({precision:t.precision,seconds:!0})}(?:${r.join("|")})`,i=t.local?`${a}|${th({precision:t.precision})}`:a,t.pattern=RegExp(`^${tp}T(?:${i})$`)),tJ.init(e,t)}),t8=eB("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=tm),tJ.init(e,t)}),t7=eB("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=RegExp(`^${th(t)}$`)),tJ.init(e,t)}),re=eB("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=tr),tJ.init(e,t)}),rt=eB("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=to),tJ.init(e,t)}),rr=/^[0-9a-fA-F:.]+$/;function ra(e){return!!rr.test(e)&&tW(`http://[${e}]`)}let ri=eB("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ts),tJ.init(e,t),e._zod.check=r=>{ra(r.value)||r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}),rn=eB("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=tl),tJ.init(e,t)}),ro=eB("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=tc),tJ.init(e,t),e._zod.check=r=>{!function(e){let t=e.split("/");if(2!==t.length)return!1;let[r,a]=t;if(!a)return!1;let i=Number(a);return`${i}`===a&&!(i<0)&&!(i>128)&&ra(r)}(r.value)&&r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}});function rs(e){if(""===e)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let rl=/^[0-9a-zA-Z+/]*={0,2}$/,rc=eB("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=rl),tJ.init(e,t),e._zod.check=r=>{rs(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),ru=/^[A-Za-z0-9_-]*$/,rd=eB("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ru),tJ.init(e,t),e._zod.check=r=>{!function(e){if(!ru.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return rs(t.padEnd(4*Math.ceil(t.length/4),"="))}(r.value)&&r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),rp=eB("$ZodE164",(e,t)=>{t.pattern??(t.pattern=td),tJ.init(e,t)}),rm=eB("$ZodJWT",(e,t)=>{tJ.init(e,t),e._zod.check=r=>{!function(e,t=null){try{let r=e.split(".");if(3!==r.length)return!1;let[a]=r;if(!a)return!1;let i=JSON.parse(atob(a));if("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))return!1;return!0}catch{return!1}}(r.value,t.alg)&&r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),rh=eB("$ZodNumber",(e,t)=>{tU.init(e,t),e._zod.pattern=ty,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}let i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;let n="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:String(i):void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...n?{received:n}:{}}),r}}),rf=eB("$ZodNumberFormat",(e,t)=>{tE.init(e,t),rh.init(e,t)}),rg=eB("$ZodBoolean",(e,t)=>{tU.init(e,t),e._zod.pattern=tv,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=!!r.value}catch(e){}let i=r.value;return"boolean"==typeof i||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),ry=eB("$ZodNull",(e,t)=>{tU.init(e,t),e._zod.pattern=t_,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{let a=t.value;return null===a||t.issues.push({expected:"null",code:"invalid_type",input:a,inst:e}),t}}),rv=eB("$ZodAny",(e,t)=>{tU.init(e,t),e._zod.parse=e=>e}),r_=eB("$ZodUnknown",(e,t)=>{tU.init(e,t),e._zod.parse=e=>e}),rb=eB("$ZodNever",(e,t)=>{tU.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),rS=e=>Array.isArray(e)?e.length:-1;function r$(e,t,r){e.issues.length&&t.issues.push(...ej(r,e.issues)),t.value[r]=e.value}let rw=eB("$ZodArray",(e,t)=>{tU.init(e,t);let r=eW.memoizer;r?.attach(e),e._zod.parse=(a,i)=>{let n=a.value;if(!Array.isArray(n))return a.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),a;a.value=r?r.alloc(e,a,Array(n.length),i):Array(n.length);let o=[],s=i?.abortEarly;for(let e=0;e<n.length;e++){let r=n[e],l=t.element._zod.run({value:r,issues:[]},i);if(l instanceof Promise)o.push(l.then(t=>r$(t,a,e)));else if(r$(l,a,e),s&&0!==l.issues.length&&eT(l))break}return o.length?Promise.all(o).then(()=>a):a},function(e,t){let r=eC(e._zod.def.checks);if(!r.length)return;let a=Math.min(...r.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(r,n)=>{let o=t(r.value);if(o>a&&!n?.skipChecks&&n?.direction!=="backward"){for(let[t,a]of eC(e._zod.def.checks))if(o>t&&a._zod.def.when(r)){let t=r.issues.length;return a._zod.check(r),r.issues[t].continue=!1,eI(r.issues,t,e),r}}return i(r,n)}}(e,rS)});function rR(e,t,r,a,i,n){let o=r in a,s="optional"===n;if(o||!s||"optional"!==i){if(e.issues.length){if(void 0!==i&&s&&!o)return;t.issues.push(...ej(r,e.issues))}if(!o&&void 0===i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}void 0===e.value?(o||"defaulted"===i&&!s)&&(t.value[r]=void 0):t.value[r]=e.value}}let rk=[];function rx(e){var t;let r=Object.keys(e.shape),a=Object.getOwnPropertySymbols(e.shape),i=a.length?a:rk,n=i.length?[...r,...i]:r;for(let t of n)if(!e.shape?.[t]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let o=Object.keys(t=e.shape).filter(e=>void 0!==t[e]._zod.optin&&"optional"===t[e]._zod.optout);return{...e,allKeys:n,symbolKeys:i,keySet:new Set(r),numKeys:r.length,optionalKeys:new Set(o)}}function rP(e,t,r,a,i,n,o){let s=[],l=i.keySet,c=i.catchall._zod,u=c.def.type,d=c.optin,p=c.optout,m=0;for(let i in t){if(o&&r.issues.length!==m){if(eT(r,m))break;m=r.issues.length}if(l.has(i))continue;if("__proto__"===i){"never"===u&&s.push(i);continue}if("never"===u){s.push(i);continue}let n=c.run({value:t[i],issues:[]},a);n instanceof Promise?e.push(n.then(e=>rR(e,r,i,t,d,p))):rR(n,r,i,t,d,p)}return(s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:n,continue:!0}),e.length)?Promise.all(e).then(()=>r):r}let rE=eB("$ZodObject",(e,t)=>{let r;tU.init(e,t);let a=Object.getOwnPropertyDescriptor(t,"shape"),i=a?.get?a.get.raw:t.shape??{};if(i){let e=()=>{let r={...i};return Object.defineProperty(t,"shape",{value:r}),e.raw=r,r};e.raw=i,Object.defineProperty(t,"shape",{get:e})}let n=ei(()=>rx(t));eV(e,"propValues",e=>{let t=e.def.shape,r={};for(let e in t){let a=t[e]._zod;if(a.values){for(let t of(Object.prototype.hasOwnProperty.call(r,e)||es(r,e,new Set),a.values))r[e].add(t);void 0!==a.optin&&r[e].add(void 0)}}return r});let o=t.catchall,s=eW.memoizer;s?.attach(e),e._zod.parse=(t,a)=>{r??(r=n.value);let i=t.value;if(!ef(i))return t.issues.push({expected:"object",code:"invalid_type",input:i,inst:e}),t;t.value=s?s.alloc(e,t,{},a):{};let l=[],c=r.shape,u=a?.abortEarly,d=t.issues.length;for(let e of r.allKeys){if(u&&t.issues.length!==d){if(eT(t,d))break;d=t.issues.length}if("__proto__"===e)continue;let r=c[e],n=r._zod.optin,o=r._zod.optout,s=r._zod.run({value:i[e],issues:[]},a);s instanceof Promise?l.push(s.then(r=>rR(r,t,e,i,n,o))):rR(s,t,e,i,n,o)}return o?rP(l,i,t,a,n.value,e,!0===u):l.length?Promise.all(l).then(()=>t):t}}),rT=eB("$ZodObjectJIT",(e,t)=>{let r,a;rE.init(e,t);let i=e._zod.parse,n=ei(()=>rx(t)),o=eW.memoizer,s=!eW.jitless,l=s&&eg.value,c=t.catchall;e._zod.parse=(u,d)=>{a??(a=n.value);let p=u.value;return ef(p)?s&&l&&d?.async===!1&&!0!==d.jitless?(r||(r=(t=>{let r=n.value,a=r.symbolKeys,i=new tZ(["payload","ctx"],{shape:t,inst:e,memo:o,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,l=(e,t)=>`
4
4
  let ${e}_ab = false;
@@ -74,23 +74,23 @@ data:
74
74
  `;return a&&(i+=`id: ${a}
75
75
  `),i+=`data: ${JSON.stringify(r)}
76
76
 
77
- `,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error("Method not allowed.")),Response.json({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null},{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,t){try{let r,a,i,n,o,s=e.headers.get("accept");if(!s?.includes("application/json")||!s.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");if(!uL(e.headers.get("content-type")))return this.onerror?.(Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");if(t?.parsedBody===void 0)try{let t=await p1(e,this._maxRequestBodySize);if(t.tooLarge){let e=pQ(this._maxRequestBodySize);return this.onerror?.(Error(e)),this.createJsonErrorResponse(413,-32e3,e)}r=JSON.parse(t.text)}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else r=t.parsedBody;if(Array.isArray(r)&&r.length>100)return this.onerror?.(Error("Invalid Request: Batch must not exceed 100 messages")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Batch must not exceed 100 messages");try{a=Array.isArray(r)?r.map(e=>ou.parse(e)):[ou.parse(r)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let l=a.some(e=>ok.safeParse(e).success);if(l){if(this._initialized&&void 0!==this.sessionId)return this.onerror?.(Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(a.length>1)return this.onerror?.(Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!l){let t=this.validateSession(e);if(t)return t;let r=this.validateProtocolVersion(e);if(r)return r}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");try{i=await this._checkScopeChallenge(a,t?.authInfo)}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32603,"Internal server error")}if(i)return i;if(!a.some(e=>cW(e))){for(let r of a)this.onmessage?.(r,{authInfo:t?.authInfo,request:e});return new Response(null,{status:202})}let c=crypto.randomUUID(),u=a.find(e=>ok.safeParse(e).success),d=u?u.params.protocolVersion:e.headers.get("mcp-protocol-version")??"2025-03-26";if(this._enableJsonResponse)return new Promise(r=>{for(let e of(this._streamMapping.set(c,{resolveJson:r,cleanup:()=>{this._streamMapping.delete(c)}}),a))cW(e)&&this._requestToStreamMapping.set(e.id,c);for(let r of a)this.onmessage?.(r,{authInfo:t?.authInfo,request:e})});let p=new TextEncoder,m=new ReadableStream({start:e=>{n=e},cancel:()=>{void 0!==o&&clearInterval(o),this._streamMapping.get(c)?.controller===n&&this._streamMapping.delete(c)}}),h={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};for(let e of(void 0!==this.sessionId&&(h["mcp-session-id"]=this.sessionId),a))cW(e)&&(this._streamMapping.set(c,{controller:n,encoder:p,cleanup:()=>{void 0!==o&&clearInterval(o),this._streamMapping.delete(c);try{n.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));for(let r of(await this.writePrimingEvent(n,p,c,d),a)){let a,i;cW(r)&&this._eventStore&&this.supportsEmptySSEData(d)&&(a=()=>{this.closeSSEStream(r.id)},i=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(r,{authInfo:t?.authInfo,request:e,closeSSEStream:a,closeStandaloneSSEStream:i})}return this._streamMapping.get(c)?.controller===n&&(o=this.startKeepAlive(n,p)),new Response(m,{status:200,headers:h})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(e)})}}async handleDeleteRequest(e){let t=this.validateSession(e);if(t)return t;let r=this.validateProtocolVersion(e);if(r)return r;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(void 0===this.sessionIdGenerator)return;if(!this._initialized)return this.onerror?.(Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let t=e.headers.get("mcp-session-id");return t?t!==this.sessionId?(this.onerror?.(Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")):void 0:(this.onerror?.(Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required"))}validateProtocolVersion(e){let t=e.headers.get("mcp-protocol-version");if(null!==t&&!this._supportedProtocolVersions.includes(t)){let e=`Bad Request: Unsupported protocol version: ${t} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(400,-32e3,e)}}async close(){if(!this._closed){for(let{cleanup:e}of(this._closed=!0,this._streamMapping.values()))e();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let r=this._streamMapping.get(t);r&&r.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let r=t?.relatedRequestId;if((cX(e)||cQ(e))&&(r=e.id),void 0===r){let t;if(cX(e)||cQ(e))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let r=this._streamMapping.get(this._standaloneSseStreamId);if(void 0===r)return;r.controller&&r.encoder&&(void 0===t||!r.replayedEventIds?.has(t))&&this.writeSSEEvent(r.controller,r.encoder,e,t);return}let a=this._requestToStreamMapping.get(r);if(!a)throw Error(`No connection established for request ID: ${String(r)}`);let i=this._streamMapping.get(a);if(!this._enableJsonResponse){let t;this._eventStore&&(t=await this._eventStore.storeEvent(a,e),i=this._streamMapping.get(a)),i?.controller&&i?.encoder&&(void 0===t||!i.replayedEventIds?.has(t))&&this.writeSSEEvent(i.controller,i.encoder,e,t)}if(cX(e)||cQ(e)){this._requestResponseMap.set(r,e);let t=[...this._requestToStreamMapping.entries()].filter(([e,t])=>t===a).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(r)}`);if(!this._eventStore){for(let e of(this.onerror?.(Error(`Response for request ID ${String(r)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)),t))this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":"application/json"};void 0!==this.sessionId&&(e["mcp-session-id"]=this.sessionId);let r=t.map(e=>this._requestResponseMap.get(e));1===r.length?i.resolveJson(Response.json(r[0],{status:200,headers:e})):i.resolveJson(Response.json(r,{status:200,headers:e})),i.cleanup()}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}};function p9(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let{method:t,id:r}=e;return"string"!=typeof t?null:"string"==typeof r||"number"==typeof r?r:null}function p4(e,t,r,a,i=null){return Response.json({jsonrpc:"2.0",error:{code:t,message:r,...void 0!==a&&{data:a}},id:i},{status:e,...405===e&&{headers:{Allow:"POST"}}})}function p3(e,t=null){return p4(e.httpStatus,e.code,e.message,e.data,t)}function p5(e){return e instanceof Error?e:Error(String(e))}function p6(e=null){return p4(500,-32603,"Internal server error",void 0,e)}function p8(e){if(void 0!==e.transport)throw Error("The factory returned an instance that is still serving another request. Return a new instance for each request.")}function p7(e){return{protocolVersionHeader:e.headers.get("mcp-protocol-version")??void 0,mcpMethodHeader:e.headers.get("mcp-method")??void 0,mcpNameHeader:e.headers.get("mcp-name")??void 0}}require("node:http");let me=require("node:http2"),mt=require("node:stream"),mr=new Set(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","server","user-agent"]),ma=/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/,mi=e=>9===e||10===e||13===e||32===e,mn=e=>{if(!mi(e.charCodeAt(0))&&!mi(e.charCodeAt(e.length-1)))return e;let t=0,r=e.length;for(;t<r&&mi(e.charCodeAt(t));)t++;for(;r>t&&mi(e.charCodeAt(r-1));)r--;return e.slice(t,r)},mo=/[\0\r\n]/,ms=globalThis.Headers,ml=(e,t=ms)=>{let r=new t;for(let t=0;t<e.length;t+=2){let a=e[t];a.startsWith(":")||r.append(a,e[t+1])}return r};var mc=class{#e;#t;#r;#a;constructor(e){this.#e=e,e instanceof me.Http2ServerRequest&&(this.#t=e.rawHeaders.slice())}get #i(){return this.#t??=this.#e.rawHeaders.slice()}get #n(){return this.#r||(this.#r=ml(this.#i),this.#t=void 0),this.#r}#o(e){if("string"==typeof e){if(!ma.test(e))throw TypeError(`Invalid header name: ${e}`);return e.toLowerCase()}}#s(e){let t=this.#e instanceof me.Http2ServerRequest?void 0:this.#e.headers;if(!t||mr.has(e)||"set-cookie"===e||"__proto__"===e)return;if(!Object.hasOwn(t,e))return null;let r=t[e];if("string"==typeof r){let e=mn(r);return mo.test(e)?void 0:e}}#l(e,t){let r="cookie"===t?"; ":", ",a=null;for(let i=0;i<e.length;i+=2){let n=e[i];if(n.length===t.length&&n.toLowerCase()===t){let t=mn(e[i+1]);if(mo.test(t)){this.#a=!0;return}a=null===a?t:a+r+t}}return a}append(e,t){this.#n.append(e,t)}delete(e){this.#n.delete(e)}get(e){let t=this.#o(e);if(t&&!this.#r&&!this.#a){let e=this.#s(t);if(void 0!==e)return e;let r=this.#l(this.#i,t);if(void 0!==r)return r}return this.#n.get(e)}has(e){let t=this.#o(e);if(t&&!this.#r&&!this.#a){let e=this.#s(t);if(void 0!==e)return null!==e;let r=this.#l(this.#i,t);if(void 0!==r)return null!==r}return this.#n.has(e)}set(e,t){this.#n.set(e,t)}getSetCookie(){return this.#n.getSetCookie()}keys(){return this.#n.keys()}values(){return this.#n.values()}entries(){return this.#n.entries()}forEach(e,t){this.#n.forEach((r,a)=>{e.call(t,r,a,this)})}[Symbol.iterator](){return this.entries()}};Object.defineProperty(mc.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){return`Headers (lightweight) ${r(Object.fromEntries(this),{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(mc.prototype,ms.prototype);let mu=e=>globalThis.Headers===ms?new mc(e):ml(e.rawHeaders,globalThis.Headers),md=global.Request;var mp=class extends md{constructor(e,t){if("object"==typeof e&&mS in e){let r=void 0!==t&&"body"in t&&null!=t.body;if(e[mC]&&!r)throw TypeError("Cannot construct a Request with a Request object that has already been used.");e=e[mS]()}void 0!==t?.body?.getReader&&(t.duplex??="half"),super(e,t)}};let mm=Symbol("wrapBodyStream"),mh=new Set(["latin1","binary","hex","base64","base64url"]),mf=Symbol("bodyBufferedBeforeDisconnect"),mg=Symbol("bodyBufferedLengthBeforeDisconnect"),my=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??"utf8"),mv=e=>{let t;return!(e instanceof me.Http2ServerRequest)&&!!e.complete&&!!e.readableAborted&&"function"==typeof e.read&&(null===(t=e.readableEncoding)||mh.has(t))},m_=(e,t)=>{let r;if(e.readableDidRead&&!t||!mv(e))return;if(void 0!==e[mf])return e[mf];let a=e.errored;if(a&&"ECONNRESET"!==a.code)r=a;else if(void 0!==e[mg]&&e.readableLength!==e[mg])r=mq();else{let a=t??[],i=e.read();null!==i&&a.push(my(i,e.readableEncoding));let n=1===a.length?a[0]:Buffer.concat(a);r=n;let o=e.headers["content-length"];if("string"==typeof o&&/^\d+$/.test(o)){let e=Number(o);Number.isSafeInteger(e)&&n.length!==e&&(r=mq())}}return e[mf]=r,r},mb=(e,t)=>{t instanceof Error?e.error(t):(t.length>0&&e.enqueue(t),e.close())},mS=Symbol("getRequestCache"),m$=Symbol("requestCache"),mw=Symbol("incomingKey"),mR=Symbol("urlKey"),mk=Symbol("methodKey"),mx=Symbol("headersKey"),mP=Symbol("abortControllerKey"),mE=Symbol("getAbortController"),mT=Symbol("abortRequest"),mj=Symbol("bodyBuffer"),mO=Symbol("bodyReadPromise"),mC=Symbol("bodyConsumedDirectly"),mI=Symbol("bodyLockReader"),mN=Symbol("abortReason"),mq=()=>TypeError("Body is unusable"),mA=new TextDecoder,mz=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,mM=(e,t,r)=>{if(e[mC])return Promise.reject(mq());let a=e.method;if("GET"===a||"HEAD"===a)return e[mS]()[t]();let i=(e=>{if(!mz.test(e))return TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if("CONNECT"===t||"TRACK"===t||"TRACE"===t&&"TRACE"!==e)return TypeError(`'${e}' HTTP method is unsupported.`)})(a);if(i)return Promise.reject(i);if(e[m$]&&"TRACE"!==a)return e[m$][t]();let n=(e=>{if(e[mC])return Promise.reject(mq());e[mC]=!0})(e);if(n)return n;let o=mL(e);if(o){let t=Promise.resolve(r(o,e));return e[mj]=void 0,t}return mD(e).then(t=>{let a=r(t,e);return e[mj]=void 0,a})},mL=e=>{let t=e[mw];if("rawBody"in t&&t.rawBody instanceof Buffer)return t.rawBody},mZ=(e,t)=>{if(t.errored)return t.errored;let r=e[mN];return void 0!==r?r instanceof Error?r:Error(String(r)):Error("Client connection prematurely closed.")},mD=e=>{if(e[mj])return Promise.resolve(e[mj]);if(e[mO])return e[mO];let t=e[mw];if(t.readableDidRead)return Promise.reject(mq());let r=m_(t);if(void 0!==r)return r instanceof Error?Promise.reject(r):(e[mj]=r,Promise.resolve(r));let a=new Promise((r,a)=>{let i=[],n=!1,o=e=>{n||(n=!0,p(),e())},s=n=>{let s=t.errored??n;return!!mv(t)&&(!s||"ECONNRESET"===s.code)&&(o(()=>{let o=m_(t,i);o instanceof Error?a(o):void 0===o?a(n??mZ(e,t)):(e[mj]=o,r(o))}),!0)},l=e=>{i.push(my(e,t.readableEncoding))},c=()=>{o(()=>{let t=1===i.length?i[0]:Buffer.concat(i);e[mj]=t,r(t)})},u=e=>{s(e)||o(()=>{a(e)})},d=()=>{t.readableEnded?c():s()||o(()=>{a(mZ(e,t))})},p=()=>{t.off("data",l),t.off("end",c),t.off("error",u),t.off("close",d),e[mO]=void 0};t.on("data",l),t.on("end",c),t.on("error",u),t.on("close",d),queueMicrotask(()=>{!n&&(t.readableEnded?c():t.errored?u(t.errored):t.destroyed&&d())})});return e[mO]=a,a},mU={get method(){return this[mk]},get url(){return this[mR]},get headers(){return this[mx]||=mu(this[mw])},[mT](e){void 0===this[mN]&&(this[mN]=e);let t=this[mP];t&&!t.signal.aborted&&t.abort(e)},[mE](){return this[mP]||=new AbortController,void 0===this[mN]||this[mP].signal.aborted||this[mP].abort(this[mN]),this[mP]},[mS](){let e=this[mE]();if(this[m$])return this[m$];let t=this.method;if(this[mC]&&"GET"!==t&&"HEAD"!==t){this[mj]=void 0;let r={method:"TRACE"===t?"GET":t,headers:this.headers,signal:e.signal};"TRACE"!==t&&(r.body=new ReadableStream({start(e){e.close()}}),r.duplex="half");let a=new mp(this[mR],r);return"TRACE"===t&&Object.defineProperty(a,"method",{get:()=>"TRACE"}),this[m$]=a}return this[m$]=((e,t,r,a,i)=>{let n={method:e,headers:r,signal:i.signal};if("TRACE"===e){n.method="GET";let e=new mp(t,n);return Object.defineProperty(e,"method",{get:()=>"TRACE"}),e}if("GET"!==e&&"HEAD"!==e)if("rawBody"in a&&a.rawBody instanceof Buffer)n.body=new ReadableStream({start(e){e.enqueue(a.rawBody),e.close()}});else if(a[mm]){let e;n.body=new ReadableStream({async pull(t){try{if(!e){let e=m_(a);if(void 0!==e)return void mb(t,e)}e||=mt.Readable.toWeb(a).getReader();let{done:r,value:i}=await e.read();r?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else{let e=m_(a);void 0!==e?n.body=new ReadableStream({start(t){mb(t,e)}}):n.body=mt.Readable.toWeb(a)}return new mp(t,n)})(this.method,this[mR],this.headers,this[mw],e)},get body(){if(!this[mC])return this[mS]().body;let e=this[mS]();return!this[mI]&&e.body&&(this[mI]=e.body.getReader()),e.body},get bodyUsed(){return!!this[mC]||!!this[m$]&&this[m$].bodyUsed}};Object.defineProperty(mU,"signal",{get(){return this[mE]().signal}}),["cache","credentials","destination","duplex","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(e=>{Object.defineProperty(mU,e,{get(){return this[mS]()[e]}})}),["clone","formData"].forEach(e=>{Object.defineProperty(mU,e,{value:function(){if(this[mC]){if("clone"===e)throw mq();return Promise.reject(mq())}return this[mS]()[e]()}})}),Object.defineProperty(mU,"text",{value:function(){return mM(this,"text",e=>mA.decode(e))}}),Object.defineProperty(mU,"arrayBuffer",{value:function(){return mM(this,"arrayBuffer",e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))}}),Object.defineProperty(mU,"blob",{value:function(){return mM(this,"blob",(e,t)=>{let r=(t[mx]||=mu(t[mw])).get("content-type")||"";return new Response(e,r?{headers:{"content-type":r}}:void 0).blob()})}}),Object.defineProperty(mU,"json",{value:function(){return this[mC]?Promise.reject(mq()):this.text().then(JSON.parse)}}),Object.defineProperty(mU,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){return`Request (lightweight) ${r({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[m$]},{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(mU,mp.prototype);let mV=Symbol("responseCache"),mF=Symbol("getResponseCache"),mH=Symbol("cache"),mJ=global.Response;var mB=class e{#c;#u;[mF](){let e=this[mH],t=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[mH],this[mV]||=new mJ(this.#c,t?{status:this.#u?.status,statusText:this.#u?.statusText,headers:t}:this.#u)}constructor(t,r){let a;if(this.#c=t,r instanceof mJ){let t=r[mV];if(t){this.#u=t,this[mF]();return}this.#u=r instanceof e?r.#u:r,a=new Headers(r.headers)}else this.#u=r;(null==t||"string"==typeof t||void 0!==t?.getReader||t instanceof Blob||t instanceof Uint8Array)&&(this[mH]=[r?.status||200,t??null,a||r?.headers])}get headers(){let e=this[mH];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(null===e[1]?void 0:{"content-type":"text/plain; charset=UTF-8"}))),e[2]):this[mF]().headers}get status(){return this[mH]?.[0]??this[mF]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(mB.prototype,e,{get(){return this[mF]()[e]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(mB.prototype,e,{value:function(){return this[mF]()[e]()}})}),Object.defineProperty(mB.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){return`Response (lightweight) ${r({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[mV]},{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(mB,mJ),Object.setPrototypeOf(mB.prototype,mJ.prototype);let mK=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,mG=new Set([301,302,303,307,308]);Object.defineProperty(mB,"redirect",{value:function(e,t=302){if(!mG.has(t))throw RangeError("Invalid status code");return new mB(null,{status:t,headers:{location:e instanceof URL?e.href:mK.test(e)?e:new URL(e).href}})},writable:!0,configurable:!0}),Object.defineProperty(mB,"json",{value:function(e,t){let r,a=JSON.stringify(e);if(void 0===a)throw TypeError("The data is not JSON serializable");let i=t?.headers;return i?(r=new Headers(i)).has("content-type")||r.set("content-type","application/json"):r={"content-type":"application/json"},new mB(a,{status:t?.status??200,statusText:t?.statusText,headers:r})},writable:!0,configurable:!0}),Symbol("outgoingEnded"),Symbol("incomingDraining"),globalThis.CloseEvent??Event,globalThis.ErrorEvent??Event,Symbol("CONNECTION_SYMBOL_KEY"),Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");var mW=class extends Error{status=413;constructor(e){super(`Payload Too Large: Request body must not exceed ${e} bytes`),this.name="RequestBodyTooLargeError"}};function mY(e){if(void 0===e)return 4194304;if("number"!=typeof e||!Number.isFinite(e)||e<=0)throw RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(e)}`);return e}function mX(e){return Array.isArray(e)?e[0]:e}let mQ=require("async_hooks"),m0=(e,t)=>{globalThis[e]=t},m1=e=>globalThis[e];function m2({name:e,fallback:t=!0}){let r=Symbol.for(`xmcp-context-${e}`),a=Symbol.for(`xmcp-context-${e}-fallback-store`);if(m1(r))return m1(r);let i=new mQ.AsyncLocalStorage,n=globalThis[a]??{current:null};m0(a,n);let o={provider:(e,r)=>(t&&(n.current=e),i.run(e,r)),getContext:()=>{let r=i.getStore();if(r)return r;if(t&&n.current)return n.current;throw Error(`getContext() can only be used within the ${e} context.`)},setContext:r=>{let a=i.getStore()??(t?n.current:null);if(!a)throw Error(`setContext() can only be used within the ${e} context.`);Object.assign(a,r)}};return m0(r,o),o}let m9=m2({name:"http-request-context"});m9.setContext;let m4=m9.getContext,m3=m9.provider,m5=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),m6=e=>{if(!m5(e)||"string"!=typeof e.name||"string"!=typeof e.version)return;let t={name:e.name,version:e.version};return"string"==typeof e.title&&(t.title=e.title),"string"==typeof e.websiteUrl&&(t.websiteUrl=e.websiteUrl),"string"==typeof e.description&&(t.description=e.description),t},m8=e=>{if(e&&"initialize"===e.method&&m5(e.params))return m6(e.params.clientInfo)},m7=(e,t)=>{let r=t.toLowerCase();for(let[t,a]of Object.entries(e)){if(t.toLowerCase()!==r)continue;let e=Array.isArray(a)?a[0]:a;if("string"!=typeof e)break;let i=e.trim();return i.length>0?i:void 0}};function he(e){let{tags:t,enabled:r,...a}=e;return{...a,_meta:void 0===t?a._meta:{...a._meta,"xmcp/tags":t}}}let ht=new class{add(e,t){this.resources.set(e,t)}getAll(){return this.resources}clear(){this.resources.clear()}has(e){return this.resources.has(e)}constructor(){var e,t;e="resources",t=new Map,e in this?Object.defineProperty(this,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):this[e]=t}},hr=m2({name:"request-context",fallback:!1});function ha(){try{return hr.getContext().value}catch{throw Error("getRequestContext() can only be used while handling an MCP request.")}}function hi(e,t,r,a=!1){let i;if(a){let t;try{t=hr.getContext()}catch{}if(t?.request===e.mcpReq)return r()}let n=new Map;if(e.http){let e=m4(),t=Object.fromEntries(Object.entries(e.headers).map(([e,t])=>[e,Array.isArray(t)?Object.freeze([...t]):t]));i=Object.freeze({id:e.id,headers:Object.freeze(t)})}let o=Object.freeze({clientInfo:t?Object.freeze({...t}):void 0,http:i,authInfo:e.http?.authInfo,signal:e.mcpReq.signal,set(e,t){n.set(e,t)},get:e=>n.get(e),async progress(t,r){let a=e.mcpReq._meta?.progressToken;void 0!==a&&await e.mcpReq.notify({method:"notifications/progress",params:{progressToken:a,progress:t,...void 0===r?{}:{total:r}}})},log:(t,r)=>e.mcpReq.log(t,r)});return hr.provider({request:e.mcpReq,value:o},r)}function hn(e){let t=e?.["xmcp/tags"];return Array.isArray(t)?t:void 0}function ho(e,t,r=!1){let a;try{a=new URL(t).toString()}catch{return}for(let i of r?[t,a]:[a]){let t=e.uiOwners.get(i)??e.resources.get(i);if(t)return t}for(let{component:t,template:r}of e.templates.values())if(r.uriTemplate.match(a))return t}let hs=m2({name:"client-info-context"});hs.setContext;let hl=hs.getContext;hs.provider;let hc=new Set(["message","mode","requestedSchema"]),hu=new Set(["elicitationId","message","mode","url"]),hd=new Set(["properties","required","type"]),hp=new Set(["default","description","format","maxLength","minLength","title","type"]),hm=new Set(["default","description","enum","enumNames","title","type"]),hh=new Set(["default","description","title","type"]),hf=new Set(["default","description","maximum","minimum","title","type"]),hg=new Set(["date","date-time","email","uri"]);function hy(e,t,r){let a=Object.keys(e).filter(e=>!t.has(e));if(0!==a.length)throw Error(`${r} includes unsupported key(s): ${a.join(", ")}.`)}function hv(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}function h_(e,t){if("string"!=typeof e)throw Error(t)}function hb(e,t){if("string"!=typeof e||0===e.trim().length)throw Error(t)}function hS(e,t){if(void 0!==e&&"string"!=typeof e)throw Error(t)}function h$(e,t){if(void 0!==e&&"number"!=typeof e)throw Error(t)}function hw(e,t){if(!Array.isArray(e)||e.some(e=>"string"!=typeof e))throw Error(t)}let hR=new Set(["_meta","includeContext","maxTokens","messages","metadata","modelPreferences","stopSequences","systemPrompt","temperature"]),hk=new Set(["task","toolChoice","tools"]),hx=new Set(["text","image","audio"]);function hP(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}let hE={text:e=>"string"!=typeof e.text?{valid:!1,error:'Text content must have a "text" property of type string'}:{valid:!0},image:e=>"string"!=typeof e.data?{valid:!1,error:'Image content must have a "data" property of type string (base64-encoded image)'}:"string"!=typeof e.mimeType?{valid:!1,error:'Image content must have a "mimeType" property of type string'}:{valid:!0},audio:e=>"string"!=typeof e.data?{valid:!1,error:'Audio content must have a "data" property of type string (base64-encoded audio)'}:"string"!=typeof e.mimeType?{valid:!1,error:'Audio content must have a "mimeType" property of type string'}:{valid:!0},resource_link:e=>"string"!=typeof e.name?{valid:!1,error:'Resource link content must have a "name" property of type string'}:"string"!=typeof e.uri?{valid:!1,error:'Resource link content must have a "uri" property of type string'}:void 0!==e.title&&"string"!=typeof e.title?{valid:!1,error:'Resource link "title" property must be a string if provided'}:void 0!==e.description&&"string"!=typeof e.description?{valid:!1,error:'Resource link "description" property must be a string if provided'}:void 0!==e.mimeType&&"string"!=typeof e.mimeType?{valid:!1,error:'Resource link "mimeType" property must be a string if provided'}:{valid:!0}};function hT(e){if(!e||"object"!=typeof e)return{valid:!1,error:"Content must be an object"};if("string"!=typeof e.type)return{valid:!1,error:'Content must have a "type" property of type string'};if(void 0!==e._meta&&(null===e._meta||"object"!=typeof e._meta))return{valid:!1,error:'Content "_meta" property must be an object if provided'};let t=hE[e.type];return t?t(e):{valid:!0}}function hj(e,t,r,a){if(null===e||"object"!=typeof e||Array.isArray(e))throw Error(`Tool "${r}" ${a}: expected a plain object.`);let i=new Set(Object.keys(t)),n=Object.keys(e).filter(e=>!i.has(e));if(n.length>0)throw Error(`Tool "${r}" ${a}: unrecognized key(s): ${n.join(", ")}`);for(let[i,n]of Object.entries(t))try{n.parse(e[i])}catch(e){throw Error(`Tool "${r}" ${a}: ${e?.message??`invalid field "${i}"`}`)}}function hO(e){return!!(e&&"object"==typeof e&&Object.keys(e).some(e=>e.startsWith("ui/")))}function hC(e){let t=e.mcpReq.envelope,r=m6(t?.[nG]);if(!r)try{let e,t=m4();r=t.clientInfo??(e=t.headers,m6({name:m7(e,"x-mcp-client-name"),version:m7(e,"x-mcp-client-version"),title:m7(e,"x-mcp-client-title"),websiteUrl:m7(e,"x-mcp-client-website-url"),description:m7(e,"x-mcp-client-description")}))}catch{}if(!r)try{r=hl().clientInfo}catch{}return r}function hI(e,t=!1){let r=[...e];return(e,a,i)=>hi(a,hC(a),async()=>{if(0===r.length)return i();let t=Object.freeze({...ha(),...e,params:Object.freeze({...e.params})}),a=-1,n=async e=>{if(e<=a)throw Error("MCP middleware next() can only be called once");a=e;let o=r[e];return o?o(t,()=>n(e+1)):i()};return n(0)},t)}function hN(e,t=new WeakMap){if(null===e||"object"!=typeof e)return e;let r=Object.getPrototypeOf(e);if(!Array.isArray(e)&&r!==Object.prototype&&null!==r)return e;if(t.has(e))return t.get(e);let a=Array.isArray(e)?[]:Object.create(r);for(let[r,i]of(t.set(e,a),Object.entries(e)))Object.defineProperty(a,r,{value:hN(i,t),enumerable:!0,configurable:!0,writable:!0});return Object.freeze(a)}let hq=new Set(["tools/list","prompts/get","prompts/list","resources/read","resources/list","resources/templates/list","completion/complete"]);function hA(e){return e.endsWith(".tsx")}let hz=Symbol("Let zodToJsonSchema decide on which parser to use"),hM={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"};(j=M||(M={})).assertEqual=e=>{},j.assertIs=function(e){},j.assertNever=function(e){throw Error()},j.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},j.getValidEnumValues=e=>{let t=j.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(let a of t)r[a]=e[a];return j.objectValues(r)},j.objectValues=e=>j.objectKeys(e).map(function(t){return e[t]}),j.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},j.find=(e,t)=>{for(let r of e)if(t(r))return r},j.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,j.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},j.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(L||(L={})).mergeShapes=(e,t)=>({...e,...t});let hL=M.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),hZ=e=>{switch(typeof e){case"undefined":return hL.undefined;case"string":return hL.string;case"number":return Number.isNaN(e)?hL.nan:hL.number;case"boolean":return hL.boolean;case"function":return hL.function;case"bigint":return hL.bigint;case"symbol":return hL.symbol;case"object":if(Array.isArray(e))return hL.array;if(null===e)return hL.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return hL.promise;if("u">typeof Map&&e instanceof Map)return hL.map;if("u">typeof Set&&e instanceof Set)return hL.set;if("u">typeof Date&&e instanceof Date)return hL.date;return hL.object;default:return hL.unknown}},hD=M.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class hU extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(let i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(a);else if("invalid_return_type"===i.code)a(i.returnTypeError);else if("invalid_arguments"===i.code)a(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,a=0;for(;a<i.path.length;){let r=i.path[a],n=a===i.path.length-1;if("_errors"===r){n&&e._errors.push(t(i)),a++;continue}Object.prototype.hasOwnProperty.call(e,r)||("__proto__"===r?Object.defineProperty(e,r,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):e[r]={_errors:[]}),e=e[r],n&&e._errors.push(t(i)),a++}}};return a(this),r}static assert(e){if(!(e instanceof hU))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,M.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){let t=Object.create(null),r=[];for(let a of this.issues)if(a.path.length>0){let r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}hU.create=e=>new hU(e);let hV=(e,t)=>{let r;switch(e.code){case hD.invalid_type:r=e.received===hL.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case hD.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,M.jsonStringifyReplacer)}`;break;case hD.unrecognized_keys:r=`Unrecognized key(s) in object: ${M.joinValues(e.keys,", ")}`;break;case hD.invalid_union:r="Invalid input";break;case hD.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${M.joinValues(e.options)}`;break;case hD.invalid_enum_value:r=`Invalid enum value. Expected ${M.joinValues(e.options)}, received '${e.received}'`;break;case hD.invalid_arguments:r="Invalid function arguments";break;case hD.invalid_return_type:r="Invalid function return type";break;case hD.invalid_date:r="Invalid date";break;case hD.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:M.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case hD.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case hD.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case hD.custom:r="Invalid input";break;case hD.invalid_intersection_types:r="Intersection results could not be merged";break;case hD.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case hD.not_finite:r="Number must be finite";break;default:r=t.defaultError,M.assertNever(e)}return{message:r}};(O=Z||(Z={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},O.toString=e=>"string"==typeof e?e:e?.message;function hF(e,t){let r=(e=>{let{data:t,path:r,errorMaps:a,issueData:i}=e,n=[...r,...i.path||[]],o={...i,path:n};if(void 0!==i.message)return{...i,path:n,message:i.message};let s="";for(let e of a.filter(e=>!!e).slice().reverse())s=e(o,{data:t,defaultError:s}).message;return{...i,path:n,message:s}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,hV,void 0].filter(e=>!!e)});e.common.issues.push(r)}class hH{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let a of t){if("aborted"===a.status)return hJ;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t){let t=await e.key,a=await e.value;r.push({key:t,value:a})}return hH.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let a of t){let{key:t,value:i}=a;if("aborted"===t.status||"aborted"===i.status)return hJ;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==i.value||a.alwaysSet)&&(r[t.value]=i.value)}return{status:e.value,value:r}}}let hJ=Object.freeze({status:"aborted"}),hB=e=>({status:"dirty",value:e}),hK=e=>({status:"valid",value:e}),hG=e=>"u">typeof Promise&&e instanceof Promise;class hW{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}let hY=(e,t)=>{if("valid"===t.status)return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new hU(e.common.issues);return this._error=t,this._error}}};function hX(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:a,description:i}=e;if(t&&(r||a))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:n}=e;return"invalid_enum_value"===t.code?{message:n??i.defaultError}:void 0===i.data?{message:n??a??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:n??r??i.defaultError}},description:i}}class hQ{get description(){return this._def.description}_getType(e){return hZ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:hZ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new hH,ctx:{common:e.parent.common,data:e.data,parsedType:hZ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(hG(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hZ(e)},a=this._parseSync({data:e,path:r.path,parent:r});return hY(r,a)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hZ(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return"valid"===r.status?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>"valid"===e.status?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hZ(e)},a=this._parse({data:e,path:r.path,parent:r});return hY(r,await (hG(a)?a:Promise.resolve(a)))}refine(e,t){return this._refinement((r,a)=>{let i=e(r),n=()=>a.addIssue({code:hD.custom,..."string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(r):t});return"u">typeof Promise&&i instanceof Promise?i.then(e=>!!e||(n(),!1)):!!i||(n(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new fC({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return fI.create(this,this._def)}nullable(){return fN.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return f_.create(this)}promise(){return fO.create(this,this._def)}or(e){return fS.create([this,e],this._def)}and(e){return f$.create(this,e,this._def)}transform(e){return new fC({...hX(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new fq({...hX(this._def),innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:D.ZodDefault})}brand(){return new fM({typeName:D.ZodBranded,type:this,...hX(this._def)})}catch(e){return new fA({...hX(this._def),innerType:this,catchValue:"function"==typeof e?e:()=>e,typeName:D.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return fL.create(this,e)}readonly(){return fZ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let h0=/^c[^\s-]{8,}$/i,h1=/^[0-9a-z]+$/,h2=/^[0-9A-HJKMNP-TV-Z]{26}$/i,h9=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,h4=/^[a-z0-9_-]{21}$/i,h3=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,h5=/^[-+]?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)?)??$/,h6=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,h8=/^(?:(?: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])$/,h7=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,fe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ft=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,fr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fa=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,fi="((\\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])))",fn=RegExp(`^${fi}$`);function fo(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}class fs extends hQ{_parse(e){var t,r,a,i;let n;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==hL.string){let t=this._getOrReturnCtx(e);return hF(t,{code:hD.invalid_type,expected:hL.string,received:t.parsedType}),hJ}let o=new hH;for(let s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(hF(n=this._getOrReturnCtx(e,n),{code:hD.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),o.dirty());else if("max"===s.kind)e.data.length>s.value&&(hF(n=this._getOrReturnCtx(e,n),{code:hD.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),o.dirty());else if("length"===s.kind){let t=e.data.length>s.value,r=e.data.length<s.value;(t||r)&&(n=this._getOrReturnCtx(e,n),t?hF(n,{code:hD.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):r&&hF(n,{code:hD.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),o.dirty())}else if("email"===s.kind)h6.test(e.data)||(hF(n=this._getOrReturnCtx(e,n),{validation:"email",code:hD.invalid_string,message:s.message}),o.dirty());else if("emoji"===s.kind)h||(h=RegExp("^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$","u")),h.test(e.data)||(hF(n=this._getOrReturnCtx(e,n),{validation:"emoji",code:hD.invalid_string,message:s.message}),o.dirty());else if("uuid"===s.kind)h9.test(e.data)||(hF(n=this._getOrReturnCtx(e,n),{validation:"uuid",code:hD.invalid_string,message:s.message}),o.dirty());else if("nanoid"===s.kind)h4.test(e.data)||(hF(n=this._getOrReturnCtx(e,n),{validation:"nanoid",code:hD.invalid_string,message:s.message}),o.dirty());else if("cuid"===s.kind)h0.test(e.data)||(hF(n=this._getOrReturnCtx(e,n),{validation:"cuid",code:hD.invalid_string,message:s.message}),o.dirty());else if("cuid2"===s.kind)h1.test(e.data)||(hF(n=this._getOrReturnCtx(e,n),{validation:"cuid2",code:hD.invalid_string,message:s.message}),o.dirty());else if("ulid"===s.kind)h2.test(e.data)||(hF(n=this._getOrReturnCtx(e,n),{validation:"ulid",code:hD.invalid_string,message:s.message}),o.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{hF(n=this._getOrReturnCtx(e,n),{validation:"url",code:hD.invalid_string,message:s.message}),o.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(e.data)||(hF(n=this._getOrReturnCtx(e,n),{validation:"regex",code:hD.invalid_string,message:s.message}),o.dirty())):"trim"===s.kind?e.data=e.data.trim():"includes"===s.kind?e.data.includes(s.value,s.position)||(hF(n=this._getOrReturnCtx(e,n),{code:hD.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),o.dirty()):"toLowerCase"===s.kind?e.data=e.data.toLowerCase():"toUpperCase"===s.kind?e.data=e.data.toUpperCase():"startsWith"===s.kind?e.data.startsWith(s.value)||(hF(n=this._getOrReturnCtx(e,n),{code:hD.invalid_string,validation:{startsWith:s.value},message:s.message}),o.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(hF(n=this._getOrReturnCtx(e,n),{code:hD.invalid_string,validation:{endsWith:s.value},message:s.message}),o.dirty()):"datetime"===s.kind?(function(e){let t=`${fi}T${fo(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,RegExp(`^${t}$`)})(s).test(e.data)||(hF(n=this._getOrReturnCtx(e,n),{code:hD.invalid_string,validation:"datetime",message:s.message}),o.dirty()):"date"===s.kind?fn.test(e.data)||(hF(n=this._getOrReturnCtx(e,n),{code:hD.invalid_string,validation:"date",message:s.message}),o.dirty()):"time"===s.kind?RegExp(`^${fo(s)}$`).test(e.data)||(hF(n=this._getOrReturnCtx(e,n),{code:hD.invalid_string,validation:"time",message:s.message}),o.dirty()):"duration"===s.kind?h5.test(e.data)||(hF(n=this._getOrReturnCtx(e,n),{validation:"duration",code:hD.invalid_string,message:s.message}),o.dirty()):"ip"===s.kind?(t=e.data,!(("v4"===(r=s.version)||!r)&&h8.test(t)||("v6"===r||!r)&&fe.test(t))&&1&&(hF(n=this._getOrReturnCtx(e,n),{validation:"ip",code:hD.invalid_string,message:s.message}),o.dirty())):"jwt"===s.kind?!function(e,t){if(!h3.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(a));if("object"!=typeof i||null===i||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)return!1;return!0}catch{return!1}}(e.data,s.alg)&&(hF(n=this._getOrReturnCtx(e,n),{validation:"jwt",code:hD.invalid_string,message:s.message}),o.dirty()):"cidr"===s.kind?(a=e.data,!(("v4"===(i=s.version)||!i)&&h7.test(a)||("v6"===i||!i)&&ft.test(a))&&1&&(hF(n=this._getOrReturnCtx(e,n),{validation:"cidr",code:hD.invalid_string,message:s.message}),o.dirty())):"base64"===s.kind?fr.test(e.data)||(hF(n=this._getOrReturnCtx(e,n),{validation:"base64",code:hD.invalid_string,message:s.message}),o.dirty()):"base64url"===s.kind?fa.test(e.data)||(hF(n=this._getOrReturnCtx(e,n),{validation:"base64url",code:hD.invalid_string,message:s.message}),o.dirty()):M.assertNever(s);return{status:o.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:hD.invalid_string,...Z.errToObj(r)})}_addCheck(e){return new fs({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Z.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Z.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...Z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Z.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Z.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Z.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Z.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Z.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Z.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Z.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Z.errToObj(t)})}nonempty(e){return this.min(1,Z.errToObj(e))}trim(){return new fs({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new fs({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new fs({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}fs.create=e=>new fs({checks:[],typeName:D.ZodString,coerce:e?.coerce??!1,...hX(e)});class fl extends hQ{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let t;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==hL.number){let t=this._getOrReturnCtx(e);return hF(t,{code:hD.invalid_type,expected:hL.number,received:t.parsedType}),hJ}let r=new hH;for(let a of this._def.checks)"int"===a.kind?M.isInteger(e.data)||(hF(t=this._getOrReturnCtx(e,t),{code:hD.invalid_type,expected:"integer",received:"float",message:a.message}),r.dirty()):"min"===a.kind?(a.inclusive?e.data<a.value:e.data<=a.value)&&(hF(t=this._getOrReturnCtx(e,t),{code:hD.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):"max"===a.kind?(a.inclusive?e.data>a.value:e.data>=a.value)&&(hF(t=this._getOrReturnCtx(e,t),{code:hD.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):"multipleOf"===a.kind?0!==function(e,t){let r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,i=r>a?r:a;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}(e.data,a.value)&&(hF(t=this._getOrReturnCtx(e,t),{code:hD.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(hF(t=this._getOrReturnCtx(e,t),{code:hD.not_finite,message:a.message}),r.dirty()):M.assertNever(a);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Z.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Z.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Z.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Z.toString(t))}setLimit(e,t,r,a){return new fl({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Z.toString(a)}]})}_addCheck(e){return new fl({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Z.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Z.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Z.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&M.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;else"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value);return Number.isFinite(t)&&Number.isFinite(e)}}fl.create=e=>new fl({checks:[],typeName:D.ZodNumber,coerce:e?.coerce||!1,...hX(e)});class fc extends hQ{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let t;if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==hL.bigint)return this._getInvalidInput(e);let r=new hH;for(let a of this._def.checks)"min"===a.kind?(a.inclusive?e.data<a.value:e.data<=a.value)&&(hF(t=this._getOrReturnCtx(e,t),{code:hD.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):"max"===a.kind?(a.inclusive?e.data>a.value:e.data>=a.value)&&(hF(t=this._getOrReturnCtx(e,t),{code:hD.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):"multipleOf"===a.kind?e.data%a.value!==BigInt(0)&&(hF(t=this._getOrReturnCtx(e,t),{code:hD.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):M.assertNever(a);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return hF(t,{code:hD.invalid_type,expected:hL.bigint,received:t.parsedType}),hJ}gte(e,t){return this.setLimit("min",e,!0,Z.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Z.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Z.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Z.toString(t))}setLimit(e,t,r,a){return new fc({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Z.toString(a)}]})}_addCheck(e){return new fc({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Z.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Z.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}fc.create=e=>new fc({checks:[],typeName:D.ZodBigInt,coerce:e?.coerce??!1,...hX(e)});class fu extends hQ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==hL.boolean){let t=this._getOrReturnCtx(e);return hF(t,{code:hD.invalid_type,expected:hL.boolean,received:t.parsedType}),hJ}return hK(e.data)}}fu.create=e=>new fu({typeName:D.ZodBoolean,coerce:e?.coerce||!1,...hX(e)});class fd extends hQ{_parse(e){let t;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==hL.date){let t=this._getOrReturnCtx(e);return hF(t,{code:hD.invalid_type,expected:hL.date,received:t.parsedType}),hJ}if(Number.isNaN(e.data.getTime()))return hF(this._getOrReturnCtx(e),{code:hD.invalid_date}),hJ;let r=new hH;for(let a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(hF(t=this._getOrReturnCtx(e,t),{code:hD.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):"max"===a.kind?e.data.getTime()>a.value&&(hF(t=this._getOrReturnCtx(e,t),{code:hD.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):M.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new fd({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Z.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Z.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}fd.create=e=>new fd({checks:[],coerce:e?.coerce||!1,typeName:D.ZodDate,...hX(e)});class fp extends hQ{_parse(e){if(this._getType(e)!==hL.symbol){let t=this._getOrReturnCtx(e);return hF(t,{code:hD.invalid_type,expected:hL.symbol,received:t.parsedType}),hJ}return hK(e.data)}}fp.create=e=>new fp({typeName:D.ZodSymbol,...hX(e)});class fm extends hQ{_parse(e){if(this._getType(e)!==hL.undefined){let t=this._getOrReturnCtx(e);return hF(t,{code:hD.invalid_type,expected:hL.undefined,received:t.parsedType}),hJ}return hK(e.data)}}fm.create=e=>new fm({typeName:D.ZodUndefined,...hX(e)});class fh extends hQ{_parse(e){if(this._getType(e)!==hL.null){let t=this._getOrReturnCtx(e);return hF(t,{code:hD.invalid_type,expected:hL.null,received:t.parsedType}),hJ}return hK(e.data)}}fh.create=e=>new fh({typeName:D.ZodNull,...hX(e)});class ff extends hQ{constructor(){super(...arguments),this._any=!0}_parse(e){return hK(e.data)}}ff.create=e=>new ff({typeName:D.ZodAny,...hX(e)});class fg extends hQ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return hK(e.data)}}fg.create=e=>new fg({typeName:D.ZodUnknown,...hX(e)});class fy extends hQ{_parse(e){let t=this._getOrReturnCtx(e);return hF(t,{code:hD.invalid_type,expected:hL.never,received:t.parsedType}),hJ}}fy.create=e=>new fy({typeName:D.ZodNever,...hX(e)});class fv extends hQ{_parse(e){if(this._getType(e)!==hL.undefined){let t=this._getOrReturnCtx(e);return hF(t,{code:hD.invalid_type,expected:hL.void,received:t.parsedType}),hJ}return hK(e.data)}}fv.create=e=>new fv({typeName:D.ZodVoid,...hX(e)});class f_ extends hQ{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==hL.array)return hF(t,{code:hD.invalid_type,expected:hL.array,received:t.parsedType}),hJ;if(null!==a.exactLength){let e=t.data.length>a.exactLength.value,i=t.data.length<a.exactLength.value;(e||i)&&(hF(t,{code:e?hD.too_big:hD.too_small,minimum:i?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(hF(t,{code:hD.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(hF(t,{code:hD.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>a.type._parseAsync(new hW(t,e,t.path,r)))).then(e=>hH.mergeArray(r,e));let i=[...t.data].map((e,r)=>a.type._parseSync(new hW(t,e,t.path,r)));return hH.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new f_({...this._def,minLength:{value:e,message:Z.toString(t)}})}max(e,t){return new f_({...this._def,maxLength:{value:e,message:Z.toString(t)}})}length(e,t){return new f_({...this._def,exactLength:{value:e,message:Z.toString(t)}})}nonempty(e){return this.min(1,e)}}f_.create=(e,t)=>new f_({type:e,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...hX(t)});class fb extends hQ{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=M.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==hL.object){let t=this._getOrReturnCtx(e);return hF(t,{code:hD.invalid_type,expected:hL.object,received:t.parsedType}),hJ}let{status:t,ctx:r}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),n=[];if(!(this._def.catchall instanceof fy&&"strip"===this._def.unknownKeys))for(let e in r.data)i.includes(e)||n.push(e);let o=[];for(let e of i){let t=a[e],i=r.data[e];o.push({key:{status:"valid",value:e},value:t._parse(new hW(r,i,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof fy){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of n)o.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)n.length>0&&(hF(r,{code:hD.unrecognized_keys,keys:n}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of n){let a=r.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new hW(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e}).then(e=>hH.mergeObjectSync(t,e)):hH.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return Z.errToObj,new fb({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{let a=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:Z.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new fb({...this._def,unknownKeys:"strip"})}passthrough(){return new fb({...this._def,unknownKeys:"passthrough"})}extend(e){return new fb({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new fb({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new fb({...this._def,catchall:e})}pick(e){let t={};for(let r of M.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new fb({...this._def,shape:()=>t})}omit(e){let t={};for(let r of M.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new fb({...this._def,shape:()=>t})}deepPartial(){return function e(t){if(t instanceof fb){let r={};for(let a in t.shape){let i=t.shape[a];r[a]=fI.create(e(i))}return new fb({...t._def,shape:()=>r})}if(t instanceof f_)return new f_({...t._def,type:e(t.element)});if(t instanceof fI)return fI.create(e(t.unwrap()));if(t instanceof fN)return fN.create(e(t.unwrap()));if(t instanceof fw)return fw.create(t.items.map(t=>e(t)));else return t}(this)}partial(e){let t={};for(let r of M.objectKeys(this.shape)){let a=this.shape[r];e&&!e[r]?t[r]=a:t[r]=a.optional()}return new fb({...this._def,shape:()=>t})}required(e){let t={};for(let r of M.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof fI;)e=e._def.innerType;t[r]=e}return new fb({...this._def,shape:()=>t})}keyof(){return fE(M.objectKeys(this.shape))}}fb.create=(e,t)=>new fb({shape:()=>e,unknownKeys:"strip",catchall:fy.create(),typeName:D.ZodObject,...hX(t)}),fb.strictCreate=(e,t)=>new fb({shape:()=>e,unknownKeys:"strict",catchall:fy.create(),typeName:D.ZodObject,...hX(t)}),fb.lazycreate=(e,t)=>new fb({shape:e,unknownKeys:"strip",catchall:fy.create(),typeName:D.ZodObject,...hX(t)});class fS extends hQ{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new hU(e.ctx.common.issues));return hF(t,{code:hD.invalid_union,unionErrors:r}),hJ});{let e,a=[];for(let i of r){let r={...t,common:{...t.common,issues:[]},parent:null},n=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=a.map(e=>new hU(e));return hF(t,{code:hD.invalid_union,unionErrors:i}),hJ}}get options(){return this._def.options}}fS.create=(e,t)=>new fS({options:e,typeName:D.ZodUnion,...hX(t)});class f$ extends hQ{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),a=(e,a)=>{if("aborted"===e.status||"aborted"===a.status)return hJ;let i=function e(t,r){let a=hZ(t),i=hZ(r);if(t===r)return{valid:!0,data:t};if(a===hL.object&&i===hL.object){let a=M.objectKeys(r),i=M.objectKeys(t).filter(e=>-1!==a.indexOf(e)),n={...t,...r};for(let a of(Object.prototype.hasOwnProperty.call(n,"__proto__")&&delete n.__proto__,i)){if("__proto__"===a)continue;let i=e(t[a],r[a]);if(!i.valid)return{valid:!1};n[a]=i.data}return{valid:!0,data:n}}if(a===hL.array&&i===hL.array){if(t.length!==r.length)return{valid:!1};let a=[];for(let i=0;i<t.length;i++){let n=e(t[i],r[i]);if(!n.valid)return{valid:!1};a.push(n.data)}return{valid:!0,data:a}}if(a===hL.date&&i===hL.date&&+t==+r)return{valid:!0,data:t};return{valid:!1}}(e.value,a.value);return i.valid?(("dirty"===e.status||"dirty"===a.status)&&t.dirty(),{status:t.value,value:i.data}):(hF(r,{code:hD.invalid_intersection_types}),hJ)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>a(e,t)):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}f$.create=(e,t,r)=>new f$({left:e,right:t,typeName:D.ZodIntersection,...hX(r)});class fw extends hQ{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==hL.array)return hF(r,{code:hD.invalid_type,expected:hL.array,received:r.parsedType}),hJ;if(r.data.length<this._def.items.length)return hF(r,{code:hD.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),hJ;!this._def.rest&&r.data.length>this._def.items.length&&(hF(r,{code:hD.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...r.data].map((e,t)=>{let a=this._def.items[t]||this._def.rest;return a?a._parse(new hW(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>hH.mergeArray(t,e)):hH.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new fw({...this._def,rest:e})}}fw.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new fw({items:e,typeName:D.ZodTuple,rest:null,...hX(t)})};class fR extends hQ{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==hL.map)return hF(r,{code:hD.invalid_type,expected:hL.map,received:r.parsedType}),hJ;let a=this._def.keyType,i=this._def.valueType,n=[...r.data.entries()].map(([e,t],n)=>({key:a._parse(new hW(r,e,r.path,[n,"key"])),value:i._parse(new hW(r,t,r.path,[n,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of n){let a=await r.key,i=await r.value;if("aborted"===a.status||"aborted"===i.status)return hJ;("dirty"===a.status||"dirty"===i.status)&&t.dirty(),e.set(a.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of n){let a=r.key,i=r.value;if("aborted"===a.status||"aborted"===i.status)return hJ;("dirty"===a.status||"dirty"===i.status)&&t.dirty(),e.set(a.value,i.value)}return{status:t.value,value:e}}}}fR.create=(e,t,r)=>new fR({valueType:t,keyType:e,typeName:D.ZodMap,...hX(r)});class fk extends hQ{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==hL.set)return hF(r,{code:hD.invalid_type,expected:hL.set,received:r.parsedType}),hJ;let a=this._def;null!==a.minSize&&r.data.size<a.minSize.value&&(hF(r,{code:hD.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&r.data.size>a.maxSize.value&&(hF(r,{code:hD.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());let i=this._def.valueType;function n(e){let r=new Set;for(let a of e){if("aborted"===a.status)return hJ;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}let o=[...r.data.values()].map((e,t)=>i._parse(new hW(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>n(e)):n(o)}min(e,t){return new fk({...this._def,minSize:{value:e,message:Z.toString(t)}})}max(e,t){return new fk({...this._def,maxSize:{value:e,message:Z.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}fk.create=(e,t)=>new fk({valueType:e,minSize:null,maxSize:null,typeName:D.ZodSet,...hX(t)});class fx extends hQ{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}fx.create=(e,t)=>new fx({getter:e,typeName:D.ZodLazy,...hX(t)});class fP extends hQ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return hF(t,{received:t.data,code:hD.invalid_literal,expected:this._def.value}),hJ}return{status:"valid",value:e.data}}get value(){return this._def.value}}function fE(e,t){return new fT({values:e,typeName:D.ZodEnum,...hX(t)})}fP.create=(e,t)=>new fP({value:e,typeName:D.ZodLiteral,...hX(t)});class fT extends hQ{_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return hF(t,{expected:M.joinValues(r),received:t.parsedType,code:hD.invalid_type}),hJ}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return hF(t,{received:t.data,code:hD.invalid_enum_value,options:r}),hJ}return hK(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return fT.create(e,{...this._def,...t})}exclude(e,t=this._def){return fT.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}fT.create=fE;class fj extends hQ{_parse(e){let t=M.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==hL.string&&r.parsedType!==hL.number){let e=M.objectValues(t);return hF(r,{expected:M.joinValues(e),received:r.parsedType,code:hD.invalid_type}),hJ}if(this._cache||(this._cache=new Set(M.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let e=M.objectValues(t);return hF(r,{received:r.data,code:hD.invalid_enum_value,options:e}),hJ}return hK(e.data)}get enum(){return this._def.values}}fj.create=(e,t)=>new fj({values:e,typeName:D.ZodNativeEnum,...hX(t)});class fO extends hQ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==hL.promise&&!1===t.common.async?(hF(t,{code:hD.invalid_type,expected:hL.promise,received:t.parsedType}),hJ):hK((t.parsedType===hL.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}fO.create=(e,t)=>new fO({type:e,typeName:D.ZodPromise,...hX(t)});class fC extends hQ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),a=this._def.effect||null,i={addIssue:e=>{hF(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===a.type){let e=a.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return hJ;let a=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===a.status?hJ:"dirty"===a.status||"dirty"===t.value?hB(a.value):a});{if("aborted"===t.value)return hJ;let a=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===a.status?hJ:"dirty"===a.status||"dirty"===t.value?hB(a.value):a}}if("refinement"===a.type){let e=e=>{let t=a.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?hJ:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))));{let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===a.status?hJ:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}}if("transform"===a.type)if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>"valid"!==e.status?hJ:Promise.resolve(a.transform(e.value,i)).then(e=>({status:t.value,value:e})));else{let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if("valid"!==e.status)return hJ;let n=a.transform(e.value,i);if(n instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}M.assertNever(a)}}fC.create=(e,t,r)=>new fC({schema:e,typeName:D.ZodEffects,effect:t,...hX(r)}),fC.createWithPreprocess=(e,t,r)=>new fC({schema:t,effect:{type:"preprocess",transform:e},typeName:D.ZodEffects,...hX(r)});class fI extends hQ{_parse(e){return this._getType(e)===hL.undefined?hK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}fI.create=(e,t)=>new fI({innerType:e,typeName:D.ZodOptional,...hX(t)});class fN extends hQ{_parse(e){return this._getType(e)===hL.null?hK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}fN.create=(e,t)=>new fN({innerType:e,typeName:D.ZodNullable,...hX(t)});class fq extends hQ{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===hL.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}fq.create=(e,t)=>new fq({innerType:e,typeName:D.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...hX(t)});class fA extends hQ{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return hG(a)?a.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new hU(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new hU(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}fA.create=(e,t)=>new fA({innerType:e,typeName:D.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...hX(t)});class fz extends hQ{_parse(e){if(this._getType(e)!==hL.nan){let t=this._getOrReturnCtx(e);return hF(t,{code:hD.invalid_type,expected:hL.nan,received:t.parsedType}),hJ}return{status:"valid",value:e.data}}}fz.create=e=>new fz({typeName:D.ZodNaN,...hX(e)}),Symbol("zod_brand");class fM extends hQ{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class fL extends hQ{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?hJ:"dirty"===e.status?(t.dirty(),hB(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?hJ:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new fL({in:e,out:t,typeName:D.ZodPipeline})}}class fZ extends hQ{_parse(e){let t=this._def.innerType._parse(e),r=e=>("valid"===e.status&&(e.value=Object.freeze(e.value)),e);return hG(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}fZ.create=(e,t)=>new fZ({innerType:e,typeName:D.ZodReadonly,...hX(t)}),fb.lazycreate,(C=D||(D={})).ZodString="ZodString",C.ZodNumber="ZodNumber",C.ZodNaN="ZodNaN",C.ZodBigInt="ZodBigInt",C.ZodBoolean="ZodBoolean",C.ZodDate="ZodDate",C.ZodSymbol="ZodSymbol",C.ZodUndefined="ZodUndefined",C.ZodNull="ZodNull",C.ZodAny="ZodAny",C.ZodUnknown="ZodUnknown",C.ZodNever="ZodNever",C.ZodVoid="ZodVoid",C.ZodArray="ZodArray",C.ZodObject="ZodObject",C.ZodUnion="ZodUnion",C.ZodDiscriminatedUnion="ZodDiscriminatedUnion",C.ZodIntersection="ZodIntersection",C.ZodTuple="ZodTuple",C.ZodRecord="ZodRecord",C.ZodMap="ZodMap",C.ZodSet="ZodSet",C.ZodFunction="ZodFunction",C.ZodLazy="ZodLazy",C.ZodLiteral="ZodLiteral",C.ZodEnum="ZodEnum",C.ZodEffects="ZodEffects",C.ZodNativeEnum="ZodNativeEnum",C.ZodOptional="ZodOptional",C.ZodNullable="ZodNullable",C.ZodDefault="ZodDefault",C.ZodCatch="ZodCatch",C.ZodPromise="ZodPromise",C.ZodBranded="ZodBranded",C.ZodPipeline="ZodPipeline",C.ZodReadonly="ZodReadonly";let fD=fs.create;fl.create,fz.create,fc.create,fu.create,fd.create,fp.create,fm.create,fh.create,ff.create,fg.create,fy.create,fv.create,f_.create;let fU=fb.create;fb.strictCreate,fS.create,f$.create,fw.create,fR.create,fk.create,fx.create,fP.create,fT.create,fj.create,fO.create,fC.create,fI.create,fN.create,fC.createWithPreprocess,fL.create;let fV=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function fF(e){if("openAi"!==e.target)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?fV(t,e.currentPath):t.join("/")}}function fH(e,t,r,a){a?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function fJ(e,t,r,a,i){e[t]=r,fH(e,t,a,i)}function fB(e,t){return gi(e.type._def,t)}let fK=/^[cC][^\s-]{8,}$/,fG=/^[0-9a-z]+$/,fW=/^[0-9A-HJKMNP-TV-Z]{26}$/,fY=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,fX=()=>(void 0===w&&(w=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),w),fQ=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,f0=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,f1=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,f2=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,f9=/^[a-zA-Z0-9_-]{21}$/,f4=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function f3(e,t){let r={type:"string"};if(e.checks)for(let a of e.checks)switch(a.kind){case"min":fJ(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t);break;case"max":fJ(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"email":switch(t.emailStrategy){case"format:email":f8(r,"email",a.message,t);break;case"format:idn-email":f8(r,"idn-email",a.message,t);break;case"pattern:zod":f7(r,fY,a.message,t)}break;case"url":f8(r,"uri",a.message,t);break;case"uuid":f8(r,"uuid",a.message,t);break;case"regex":f7(r,a.regex,a.message,t);break;case"cuid":f7(r,fK,a.message,t);break;case"cuid2":f7(r,fG,a.message,t);break;case"startsWith":f7(r,RegExp(`^${f5(a.value,t)}`),a.message,t);break;case"endsWith":f7(r,RegExp(`${f5(a.value,t)}$`),a.message,t);break;case"datetime":f8(r,"date-time",a.message,t);break;case"date":f8(r,"date",a.message,t);break;case"time":f8(r,"time",a.message,t);break;case"duration":f8(r,"duration",a.message,t);break;case"length":fJ(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t),fJ(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"includes":f7(r,RegExp(f5(a.value,t)),a.message,t);break;case"ip":"v6"!==a.version&&f8(r,"ipv4",a.message,t),"v4"!==a.version&&f8(r,"ipv6",a.message,t);break;case"base64url":f7(r,f2,a.message,t);break;case"jwt":f7(r,f4,a.message,t);break;case"cidr":"v6"!==a.version&&f7(r,fQ,a.message,t),"v4"!==a.version&&f7(r,f0,a.message,t);break;case"emoji":f7(r,fX(),a.message,t);break;case"ulid":f7(r,fW,a.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":f8(r,"binary",a.message,t);break;case"contentEncoding:base64":fJ(r,"contentEncoding","base64",a.message,t);break;case"pattern:zod":f7(r,f1,a.message,t)}break;case"nanoid":f7(r,f9,a.message,t)}return r}function f5(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)f6.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}let f6=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function f8(e,t,r,a){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&a.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&a.errorMessages&&{errorMessage:{format:r}}})):fJ(e,"format",t,r,a)}function f7(e,t,r,a){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&a.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:ge(t,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):fJ(e,"pattern",ge(t,a),r,a)}function ge(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},a=r.i?e.source.toLowerCase():e.source,i="",n=!1,o=!1,s=!1;for(let e=0;e<a.length;e++){if(n){i+=a[e],n=!1;continue}if(r.i){if(o){if(a[e].match(/[a-z]/)){s?(i+=a[e],i+=`${a[e-2]}-${a[e]}`.toUpperCase(),s=!1):"-"===a[e+1]&&a[e+2]?.match(/[a-z]/)?(i+=a[e],s=!0):i+=`${a[e]}${a[e].toUpperCase()}`;continue}}else if(a[e].match(/[a-z]/)){i+=`[${a[e]}${a[e].toUpperCase()}]`;continue}}if(r.m){if("^"===a[e]){i+=`(^|(?<=[\r
77
+ `,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error("Method not allowed.")),Response.json({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null},{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,t){try{let r,a,i,n,o,s=e.headers.get("accept");if(!s?.includes("application/json")||!s.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");if(!uL(e.headers.get("content-type")))return this.onerror?.(Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");if(t?.parsedBody===void 0)try{let t=await p1(e,this._maxRequestBodySize);if(t.tooLarge){let e=pQ(this._maxRequestBodySize);return this.onerror?.(Error(e)),this.createJsonErrorResponse(413,-32e3,e)}r=JSON.parse(t.text)}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else r=t.parsedBody;if(Array.isArray(r)&&r.length>100)return this.onerror?.(Error("Invalid Request: Batch must not exceed 100 messages")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Batch must not exceed 100 messages");try{a=Array.isArray(r)?r.map(e=>ou.parse(e)):[ou.parse(r)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let l=a.some(e=>ok.safeParse(e).success);if(l){if(this._initialized&&void 0!==this.sessionId)return this.onerror?.(Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(a.length>1)return this.onerror?.(Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!l){let t=this.validateSession(e);if(t)return t;let r=this.validateProtocolVersion(e);if(r)return r}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");try{i=await this._checkScopeChallenge(a,t?.authInfo)}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32603,"Internal server error")}if(i)return i;if(!a.some(e=>cW(e))){for(let r of a)this.onmessage?.(r,{authInfo:t?.authInfo,request:e});return new Response(null,{status:202})}let c=crypto.randomUUID(),u=a.find(e=>ok.safeParse(e).success),d=u?u.params.protocolVersion:e.headers.get("mcp-protocol-version")??"2025-03-26";if(this._enableJsonResponse)return new Promise(r=>{for(let e of(this._streamMapping.set(c,{resolveJson:r,cleanup:()=>{this._streamMapping.delete(c)}}),a))cW(e)&&this._requestToStreamMapping.set(e.id,c);for(let r of a)this.onmessage?.(r,{authInfo:t?.authInfo,request:e})});let p=new TextEncoder,m=new ReadableStream({start:e=>{n=e},cancel:()=>{void 0!==o&&clearInterval(o),this._streamMapping.get(c)?.controller===n&&this._streamMapping.delete(c)}}),h={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};for(let e of(void 0!==this.sessionId&&(h["mcp-session-id"]=this.sessionId),a))cW(e)&&(this._streamMapping.set(c,{controller:n,encoder:p,cleanup:()=>{void 0!==o&&clearInterval(o),this._streamMapping.delete(c);try{n.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));for(let r of(await this.writePrimingEvent(n,p,c,d),a)){let a,i;cW(r)&&this._eventStore&&this.supportsEmptySSEData(d)&&(a=()=>{this.closeSSEStream(r.id)},i=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(r,{authInfo:t?.authInfo,request:e,closeSSEStream:a,closeStandaloneSSEStream:i})}return this._streamMapping.get(c)?.controller===n&&(o=this.startKeepAlive(n,p)),new Response(m,{status:200,headers:h})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(e)})}}async handleDeleteRequest(e){let t=this.validateSession(e);if(t)return t;let r=this.validateProtocolVersion(e);if(r)return r;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(void 0===this.sessionIdGenerator)return;if(!this._initialized)return this.onerror?.(Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let t=e.headers.get("mcp-session-id");return t?t!==this.sessionId?(this.onerror?.(Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")):void 0:(this.onerror?.(Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required"))}validateProtocolVersion(e){let t=e.headers.get("mcp-protocol-version");if(null!==t&&!this._supportedProtocolVersions.includes(t)){let e=`Bad Request: Unsupported protocol version: ${t} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(400,-32e3,e)}}async close(){if(!this._closed){for(let{cleanup:e}of(this._closed=!0,this._streamMapping.values()))e();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let r=this._streamMapping.get(t);r&&r.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let r=t?.relatedRequestId;if((cX(e)||cQ(e))&&(r=e.id),void 0===r){let t;if(cX(e)||cQ(e))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let r=this._streamMapping.get(this._standaloneSseStreamId);if(void 0===r)return;r.controller&&r.encoder&&(void 0===t||!r.replayedEventIds?.has(t))&&this.writeSSEEvent(r.controller,r.encoder,e,t);return}let a=this._requestToStreamMapping.get(r);if(!a)throw Error(`No connection established for request ID: ${String(r)}`);let i=this._streamMapping.get(a);if(!this._enableJsonResponse){let t;this._eventStore&&(t=await this._eventStore.storeEvent(a,e),i=this._streamMapping.get(a)),i?.controller&&i?.encoder&&(void 0===t||!i.replayedEventIds?.has(t))&&this.writeSSEEvent(i.controller,i.encoder,e,t)}if(cX(e)||cQ(e)){this._requestResponseMap.set(r,e);let t=[...this._requestToStreamMapping.entries()].filter(([e,t])=>t===a).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(r)}`);if(!this._eventStore){for(let e of(this.onerror?.(Error(`Response for request ID ${String(r)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)),t))this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e);return}if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":"application/json"};void 0!==this.sessionId&&(e["mcp-session-id"]=this.sessionId);let r=t.map(e=>this._requestResponseMap.get(e));1===r.length?i.resolveJson(Response.json(r[0],{status:200,headers:e})):i.resolveJson(Response.json(r,{status:200,headers:e})),i.cleanup()}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}};function p9(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let{method:t,id:r}=e;return"string"!=typeof t?null:"string"==typeof r||"number"==typeof r?r:null}function p4(e,t,r,a,i=null){return Response.json({jsonrpc:"2.0",error:{code:t,message:r,...void 0!==a&&{data:a}},id:i},{status:e,...405===e&&{headers:{Allow:"POST"}}})}function p3(e,t=null){return p4(e.httpStatus,e.code,e.message,e.data,t)}function p5(e){return e instanceof Error?e:Error(String(e))}function p6(e=null){return p4(500,-32603,"Internal server error",void 0,e)}function p8(e){if(void 0!==e.transport)throw Error("The factory returned an instance that is still serving another request. Return a new instance for each request.")}function p7(e){return{protocolVersionHeader:e.headers.get("mcp-protocol-version")??void 0,mcpMethodHeader:e.headers.get("mcp-method")??void 0,mcpNameHeader:e.headers.get("mcp-name")??void 0}}require("node:http");let me=require("node:http2"),mt=require("node:stream"),mr=new Set(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","server","user-agent"]),ma=/^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/,mi=e=>9===e||10===e||13===e||32===e,mn=e=>{if(!mi(e.charCodeAt(0))&&!mi(e.charCodeAt(e.length-1)))return e;let t=0,r=e.length;for(;t<r&&mi(e.charCodeAt(t));)t++;for(;r>t&&mi(e.charCodeAt(r-1));)r--;return e.slice(t,r)},mo=/[\0\r\n]/,ms=globalThis.Headers,ml=(e,t=ms)=>{let r=new t;for(let t=0;t<e.length;t+=2){let a=e[t];a.startsWith(":")||r.append(a,e[t+1])}return r};var mc=class{#e;#t;#r;#a;constructor(e){this.#e=e,e instanceof me.Http2ServerRequest&&(this.#t=e.rawHeaders.slice())}get #i(){return this.#t??=this.#e.rawHeaders.slice()}get #n(){return this.#r||(this.#r=ml(this.#i),this.#t=void 0),this.#r}#o(e){if("string"==typeof e){if(!ma.test(e))throw TypeError(`Invalid header name: ${e}`);return e.toLowerCase()}}#s(e){let t=this.#e instanceof me.Http2ServerRequest?void 0:this.#e.headers;if(!t||mr.has(e)||"set-cookie"===e||"__proto__"===e)return;if(!Object.hasOwn(t,e))return null;let r=t[e];if("string"==typeof r){let e=mn(r);return mo.test(e)?void 0:e}}#l(e,t){let r="cookie"===t?"; ":", ",a=null;for(let i=0;i<e.length;i+=2){let n=e[i];if(n.length===t.length&&n.toLowerCase()===t){let t=mn(e[i+1]);if(mo.test(t)){this.#a=!0;return}a=null===a?t:a+r+t}}return a}append(e,t){this.#n.append(e,t)}delete(e){this.#n.delete(e)}get(e){let t=this.#o(e);if(t&&!this.#r&&!this.#a){let e=this.#s(t);if(void 0!==e)return e;let r=this.#l(this.#i,t);if(void 0!==r)return r}return this.#n.get(e)}has(e){let t=this.#o(e);if(t&&!this.#r&&!this.#a){let e=this.#s(t);if(void 0!==e)return null!==e;let r=this.#l(this.#i,t);if(void 0!==r)return null!==r}return this.#n.has(e)}set(e,t){this.#n.set(e,t)}getSetCookie(){return this.#n.getSetCookie()}keys(){return this.#n.keys()}values(){return this.#n.values()}entries(){return this.#n.entries()}forEach(e,t){this.#n.forEach((r,a)=>{e.call(t,r,a,this)})}[Symbol.iterator](){return this.entries()}};Object.defineProperty(mc.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){return`Headers (lightweight) ${r(Object.fromEntries(this),{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(mc.prototype,ms.prototype);let mu=e=>globalThis.Headers===ms?new mc(e):ml(e.rawHeaders,globalThis.Headers),md=global.Request;var mp=class extends md{constructor(e,t){if("object"==typeof e&&mS in e){let r=void 0!==t&&"body"in t&&null!=t.body;if(e[mC]&&!r)throw TypeError("Cannot construct a Request with a Request object that has already been used.");e=e[mS]()}void 0!==t?.body?.getReader&&(t.duplex??="half"),super(e,t)}};let mm=Symbol("wrapBodyStream"),mh=new Set(["latin1","binary","hex","base64","base64url"]),mf=Symbol("bodyBufferedBeforeDisconnect"),mg=Symbol("bodyBufferedLengthBeforeDisconnect"),my=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??"utf8"),mv=e=>{let t;return!(e instanceof me.Http2ServerRequest)&&!!e.complete&&!!e.readableAborted&&"function"==typeof e.read&&(null===(t=e.readableEncoding)||mh.has(t))},m_=(e,t)=>{let r;if(e.readableDidRead&&!t||!mv(e))return;if(void 0!==e[mf])return e[mf];let a=e.errored;if(a&&"ECONNRESET"!==a.code)r=a;else if(void 0!==e[mg]&&e.readableLength!==e[mg])r=mq();else{let a=t??[],i=e.read();null!==i&&a.push(my(i,e.readableEncoding));let n=1===a.length?a[0]:Buffer.concat(a);r=n;let o=e.headers["content-length"];if("string"==typeof o&&/^\d+$/.test(o)){let e=Number(o);Number.isSafeInteger(e)&&n.length!==e&&(r=mq())}}return e[mf]=r,r},mb=(e,t)=>{t instanceof Error?e.error(t):(t.length>0&&e.enqueue(t),e.close())},mS=Symbol("getRequestCache"),m$=Symbol("requestCache"),mw=Symbol("incomingKey"),mR=Symbol("urlKey"),mk=Symbol("methodKey"),mx=Symbol("headersKey"),mP=Symbol("abortControllerKey"),mE=Symbol("getAbortController"),mT=Symbol("abortRequest"),mj=Symbol("bodyBuffer"),mO=Symbol("bodyReadPromise"),mC=Symbol("bodyConsumedDirectly"),mI=Symbol("bodyLockReader"),mN=Symbol("abortReason"),mq=()=>TypeError("Body is unusable"),mA=new TextDecoder,mz=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,mM=(e,t,r)=>{if(e[mC])return Promise.reject(mq());let a=e.method;if("GET"===a||"HEAD"===a)return e[mS]()[t]();let i=(e=>{if(!mz.test(e))return TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if("CONNECT"===t||"TRACK"===t||"TRACE"===t&&"TRACE"!==e)return TypeError(`'${e}' HTTP method is unsupported.`)})(a);if(i)return Promise.reject(i);if(e[m$]&&"TRACE"!==a)return e[m$][t]();let n=(e=>{if(e[mC])return Promise.reject(mq());e[mC]=!0})(e);if(n)return n;let o=mL(e);if(o){let t=Promise.resolve(r(o,e));return e[mj]=void 0,t}return mD(e).then(t=>{let a=r(t,e);return e[mj]=void 0,a})},mL=e=>{let t=e[mw];if("rawBody"in t&&t.rawBody instanceof Buffer)return t.rawBody},mZ=(e,t)=>{if(t.errored)return t.errored;let r=e[mN];return void 0!==r?r instanceof Error?r:Error(String(r)):Error("Client connection prematurely closed.")},mD=e=>{if(e[mj])return Promise.resolve(e[mj]);if(e[mO])return e[mO];let t=e[mw];if(t.readableDidRead)return Promise.reject(mq());let r=m_(t);if(void 0!==r)return r instanceof Error?Promise.reject(r):(e[mj]=r,Promise.resolve(r));let a=new Promise((r,a)=>{let i=[],n=!1,o=e=>{n||(n=!0,p(),e())},s=n=>{let s=t.errored??n;return!!mv(t)&&(!s||"ECONNRESET"===s.code)&&(o(()=>{let o=m_(t,i);o instanceof Error?a(o):void 0===o?a(n??mZ(e,t)):(e[mj]=o,r(o))}),!0)},l=e=>{i.push(my(e,t.readableEncoding))},c=()=>{o(()=>{let t=1===i.length?i[0]:Buffer.concat(i);e[mj]=t,r(t)})},u=e=>{s(e)||o(()=>{a(e)})},d=()=>{t.readableEnded?c():s()||o(()=>{a(mZ(e,t))})},p=()=>{t.off("data",l),t.off("end",c),t.off("error",u),t.off("close",d),e[mO]=void 0};t.on("data",l),t.on("end",c),t.on("error",u),t.on("close",d),queueMicrotask(()=>{!n&&(t.readableEnded?c():t.errored?u(t.errored):t.destroyed&&d())})});return e[mO]=a,a},mU={get method(){return this[mk]},get url(){return this[mR]},get headers(){return this[mx]||=mu(this[mw])},[mT](e){void 0===this[mN]&&(this[mN]=e);let t=this[mP];t&&!t.signal.aborted&&t.abort(e)},[mE](){return this[mP]||=new AbortController,void 0===this[mN]||this[mP].signal.aborted||this[mP].abort(this[mN]),this[mP]},[mS](){let e=this[mE]();if(this[m$])return this[m$];let t=this.method;if(this[mC]&&"GET"!==t&&"HEAD"!==t){this[mj]=void 0;let r={method:"TRACE"===t?"GET":t,headers:this.headers,signal:e.signal};"TRACE"!==t&&(r.body=new ReadableStream({start(e){e.close()}}),r.duplex="half");let a=new mp(this[mR],r);return"TRACE"===t&&Object.defineProperty(a,"method",{get:()=>"TRACE"}),this[m$]=a}return this[m$]=((e,t,r,a,i)=>{let n={method:e,headers:r,signal:i.signal};if("TRACE"===e){n.method="GET";let e=new mp(t,n);return Object.defineProperty(e,"method",{get:()=>"TRACE"}),e}if("GET"!==e&&"HEAD"!==e)if("rawBody"in a&&a.rawBody instanceof Buffer)n.body=new ReadableStream({start(e){e.enqueue(a.rawBody),e.close()}});else if(a[mm]){let e;n.body=new ReadableStream({async pull(t){try{if(!e){let e=m_(a);if(void 0!==e)return void mb(t,e)}e||=mt.Readable.toWeb(a).getReader();let{done:r,value:i}=await e.read();r?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else{let e=m_(a);void 0!==e?n.body=new ReadableStream({start(t){mb(t,e)}}):n.body=mt.Readable.toWeb(a)}return new mp(t,n)})(this.method,this[mR],this.headers,this[mw],e)},get body(){if(!this[mC])return this[mS]().body;let e=this[mS]();return!this[mI]&&e.body&&(this[mI]=e.body.getReader()),e.body},get bodyUsed(){return!!this[mC]||!!this[m$]&&this[m$].bodyUsed}};Object.defineProperty(mU,"signal",{get(){return this[mE]().signal}}),["cache","credentials","destination","duplex","integrity","mode","redirect","referrer","referrerPolicy","keepalive"].forEach(e=>{Object.defineProperty(mU,e,{get(){return this[mS]()[e]}})}),["clone","formData"].forEach(e=>{Object.defineProperty(mU,e,{value:function(){if(this[mC]){if("clone"===e)throw mq();return Promise.reject(mq())}return this[mS]()[e]()}})}),Object.defineProperty(mU,"text",{value:function(){return mM(this,"text",e=>mA.decode(e))}}),Object.defineProperty(mU,"arrayBuffer",{value:function(){return mM(this,"arrayBuffer",e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength))}}),Object.defineProperty(mU,"blob",{value:function(){return mM(this,"blob",(e,t)=>{let r=(t[mx]||=mu(t[mw])).get("content-type")||"";return new Response(e,r?{headers:{"content-type":r}}:void 0).blob()})}}),Object.defineProperty(mU,"json",{value:function(){return this[mC]?Promise.reject(mq()):this.text().then(JSON.parse)}}),Object.defineProperty(mU,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){return`Request (lightweight) ${r({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[m$]},{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(mU,mp.prototype);let mV=Symbol("responseCache"),mF=Symbol("getResponseCache"),mH=Symbol("cache"),mJ=global.Response;var mB=class e{#c;#u;[mF](){let e=this[mH],t=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[mH],this[mV]||=new mJ(this.#c,t?{status:this.#u?.status,statusText:this.#u?.statusText,headers:t}:this.#u)}constructor(t,r){let a;if(this.#c=t,r instanceof mJ){let t=r[mV];if(t){this.#u=t,this[mF]();return}this.#u=r instanceof e?r.#u:r,a=new Headers(r.headers)}else this.#u=r;(null==t||"string"==typeof t||void 0!==t?.getReader||t instanceof Blob||t instanceof Uint8Array)&&(this[mH]=[r?.status||200,t??null,a||r?.headers])}get headers(){let e=this[mH];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(null===e[1]?void 0:{"content-type":"text/plain; charset=UTF-8"}))),e[2]):this[mF]().headers}get status(){return this[mH]?.[0]??this[mF]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(mB.prototype,e,{get(){return this[mF]()[e]}})}),["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(mB.prototype,e,{value:function(){return this[mF]()[e]()}})}),Object.defineProperty(mB.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){return`Response (lightweight) ${r({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[mV]},{...t,depth:null==e?null:e-1})}`}}),Object.setPrototypeOf(mB,mJ),Object.setPrototypeOf(mB.prototype,mJ.prototype);let mK=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,mG=new Set([301,302,303,307,308]);Object.defineProperty(mB,"redirect",{value:function(e,t=302){if(!mG.has(t))throw RangeError("Invalid status code");return new mB(null,{status:t,headers:{location:e instanceof URL?e.href:mK.test(e)?e:new URL(e).href}})},writable:!0,configurable:!0}),Object.defineProperty(mB,"json",{value:function(e,t){let r,a=JSON.stringify(e);if(void 0===a)throw TypeError("The data is not JSON serializable");let i=t?.headers;return i?(r=new Headers(i)).has("content-type")||r.set("content-type","application/json"):r={"content-type":"application/json"},new mB(a,{status:t?.status??200,statusText:t?.statusText,headers:r})},writable:!0,configurable:!0}),Symbol("outgoingEnded"),Symbol("incomingDraining"),globalThis.CloseEvent??Event,globalThis.ErrorEvent??Event,Symbol("CONNECTION_SYMBOL_KEY"),Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");var mW=class extends Error{status=413;constructor(e){super(`Payload Too Large: Request body must not exceed ${e} bytes`),this.name="RequestBodyTooLargeError"}};function mY(e){if(void 0===e)return 4194304;if("number"!=typeof e||!Number.isFinite(e)||e<=0)throw RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(e)}`);return e}function mX(e){return Array.isArray(e)?e[0]:e}let mQ=require("async_hooks"),m0=(e,t)=>{globalThis[e]=t},m1=e=>globalThis[e];function m2({name:e,fallback:t=!0}){let r=Symbol.for(`xmcp-context-${e}`),a=Symbol.for(`xmcp-context-${e}-fallback-store`);if(m1(r))return m1(r);let i=new mQ.AsyncLocalStorage,n=globalThis[a]??{current:null};m0(a,n);let o={provider:(e,r)=>(t&&(n.current=e),i.run(e,r)),getContext:()=>{let r=i.getStore();if(r)return r;if(t&&n.current)return n.current;throw Error(`getContext() can only be used within the ${e} context.`)},setContext:r=>{let a=i.getStore()??(t?n.current:null);if(!a)throw Error(`setContext() can only be used within the ${e} context.`);Object.assign(a,r)}};return m0(r,o),o}let m9=m2({name:"http-request-context"});m9.setContext;let m4=m9.getContext,m3=m9.provider,m5=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),m6=e=>{if(!m5(e)||"string"!=typeof e.name||"string"!=typeof e.version)return;let t={name:e.name,version:e.version};return"string"==typeof e.title&&(t.title=e.title),"string"==typeof e.websiteUrl&&(t.websiteUrl=e.websiteUrl),"string"==typeof e.description&&(t.description=e.description),t},m8=e=>{if(e&&"initialize"===e.method&&m5(e.params))return m6(e.params.clientInfo)},m7=(e,t)=>{let r=t.toLowerCase();for(let[t,a]of Object.entries(e)){if(t.toLowerCase()!==r)continue;let e=Array.isArray(a)?a[0]:a;if("string"!=typeof e)break;let i=e.trim();return i.length>0?i:void 0}};function he(e){let{tags:t,enabled:r,...a}=e;return{...a,_meta:void 0===t?a._meta:{...a._meta,"xmcp/tags":t}}}let ht=new class{add(e,t){this.resources.set(e,t)}getAll(){return this.resources}clear(){this.resources.clear()}has(e){return this.resources.has(e)}constructor(){var e,t;e="resources",t=new Map,e in this?Object.defineProperty(this,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):this[e]=t}},hr=m2({name:"request-context",fallback:!1});function ha(){try{return hr.getContext().value}catch{throw Error("getRequestContext() can only be used while handling an MCP request.")}}function hi(e,t,r,a=!1){let i;if(a){let t;try{t=hr.getContext()}catch{}if(t?.request===e.mcpReq)return r()}let n=new Map;if(e.http){let e=m4(),t=Object.fromEntries(Object.entries(e.headers).map(([e,t])=>[e,Array.isArray(t)?Object.freeze([...t]):t]));i=Object.freeze({id:e.id,headers:Object.freeze(t)})}let o=Object.freeze({clientInfo:t?Object.freeze({...t}):void 0,http:i,authInfo:e.http?.authInfo,_meta:e.mcpReq._meta?Object.freeze({...e.mcpReq._meta}):void 0,signal:e.mcpReq.signal,set(e,t){n.set(e,t)},get:e=>n.get(e),async progress(t,r){let a=e.mcpReq._meta?.progressToken;void 0!==a&&await e.mcpReq.notify({method:"notifications/progress",params:{progressToken:a,progress:t,...void 0===r?{}:{total:r}}})},log:(t,r)=>e.mcpReq.log(t,r)});return hr.provider({request:e.mcpReq,value:o},r)}function hn(e){let t=e?.["xmcp/tags"];return Array.isArray(t)?t:void 0}function ho(e,t,r=!1){let a;try{a=new URL(t).toString()}catch{return}for(let i of r?[t,a]:[a]){let t=e.uiOwners.get(i)??e.resources.get(i);if(t)return t}for(let{component:t,template:r}of e.templates.values())if(r.uriTemplate.match(a))return t}let hs=m2({name:"client-info-context"});hs.setContext;let hl=hs.getContext;hs.provider;let hc=new Set(["message","mode","requestedSchema"]),hu=new Set(["elicitationId","message","mode","url"]),hd=new Set(["properties","required","type"]),hp=new Set(["default","description","format","maxLength","minLength","title","type"]),hm=new Set(["default","description","enum","enumNames","title","type"]),hh=new Set(["default","description","title","type"]),hf=new Set(["default","description","maximum","minimum","title","type"]),hg=new Set(["date","date-time","email","uri"]);function hy(e,t,r){let a=Object.keys(e).filter(e=>!t.has(e));if(0!==a.length)throw Error(`${r} includes unsupported key(s): ${a.join(", ")}.`)}function hv(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}function h_(e,t){if("string"!=typeof e)throw Error(t)}function hb(e,t){if("string"!=typeof e||0===e.trim().length)throw Error(t)}function hS(e,t){if(void 0!==e&&"string"!=typeof e)throw Error(t)}function h$(e,t){if(void 0!==e&&"number"!=typeof e)throw Error(t)}function hw(e,t){if(!Array.isArray(e)||e.some(e=>"string"!=typeof e))throw Error(t)}let hR=new Set(["_meta","includeContext","maxTokens","messages","metadata","modelPreferences","stopSequences","systemPrompt","temperature"]),hk=new Set(["task","toolChoice","tools"]),hx=new Set(["text","image","audio"]);function hP(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}let hE={text:e=>"string"!=typeof e.text?{valid:!1,error:'Text content must have a "text" property of type string'}:{valid:!0},image:e=>"string"!=typeof e.data?{valid:!1,error:'Image content must have a "data" property of type string (base64-encoded image)'}:"string"!=typeof e.mimeType?{valid:!1,error:'Image content must have a "mimeType" property of type string'}:{valid:!0},audio:e=>"string"!=typeof e.data?{valid:!1,error:'Audio content must have a "data" property of type string (base64-encoded audio)'}:"string"!=typeof e.mimeType?{valid:!1,error:'Audio content must have a "mimeType" property of type string'}:{valid:!0},resource_link:e=>"string"!=typeof e.name?{valid:!1,error:'Resource link content must have a "name" property of type string'}:"string"!=typeof e.uri?{valid:!1,error:'Resource link content must have a "uri" property of type string'}:void 0!==e.title&&"string"!=typeof e.title?{valid:!1,error:'Resource link "title" property must be a string if provided'}:void 0!==e.description&&"string"!=typeof e.description?{valid:!1,error:'Resource link "description" property must be a string if provided'}:void 0!==e.mimeType&&"string"!=typeof e.mimeType?{valid:!1,error:'Resource link "mimeType" property must be a string if provided'}:{valid:!0}};function hT(e){if(!e||"object"!=typeof e)return{valid:!1,error:"Content must be an object"};if("string"!=typeof e.type)return{valid:!1,error:'Content must have a "type" property of type string'};if(void 0!==e._meta&&(null===e._meta||"object"!=typeof e._meta))return{valid:!1,error:'Content "_meta" property must be an object if provided'};let t=hE[e.type];return t?t(e):{valid:!0}}let hj=Symbol("Let zodToJsonSchema decide on which parser to use"),hO={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"};(j=M||(M={})).assertEqual=e=>{},j.assertIs=function(e){},j.assertNever=function(e){throw Error()},j.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},j.getValidEnumValues=e=>{let t=j.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),r={};for(let a of t)r[a]=e[a];return j.objectValues(r)},j.objectValues=e=>j.objectKeys(e).map(function(t){return e[t]}),j.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},j.find=(e,t)=>{for(let r of e)if(t(r))return r},j.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,j.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},j.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(L||(L={})).mergeShapes=(e,t)=>({...e,...t});let hC=M.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),hI=e=>{switch(typeof e){case"undefined":return hC.undefined;case"string":return hC.string;case"number":return Number.isNaN(e)?hC.nan:hC.number;case"boolean":return hC.boolean;case"function":return hC.function;case"bigint":return hC.bigint;case"symbol":return hC.symbol;case"object":if(Array.isArray(e))return hC.array;if(null===e)return hC.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return hC.promise;if("u">typeof Map&&e instanceof Map)return hC.map;if("u">typeof Set&&e instanceof Set)return hC.set;if("u">typeof Date&&e instanceof Date)return hC.date;return hC.object;default:return hC.unknown}},hN=M.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class hq extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},a=e=>{for(let i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(a);else if("invalid_return_type"===i.code)a(i.returnTypeError);else if("invalid_arguments"===i.code)a(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,a=0;for(;a<i.path.length;){let r=i.path[a],n=a===i.path.length-1;if("_errors"===r){n&&e._errors.push(t(i)),a++;continue}Object.prototype.hasOwnProperty.call(e,r)||("__proto__"===r?Object.defineProperty(e,r,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):e[r]={_errors:[]}),e=e[r],n&&e._errors.push(t(i)),a++}}};return a(this),r}static assert(e){if(!(e instanceof hq))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,M.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){let t=Object.create(null),r=[];for(let a of this.issues)if(a.path.length>0){let r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}hq.create=e=>new hq(e);let hA=(e,t)=>{let r;switch(e.code){case hN.invalid_type:r=e.received===hC.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case hN.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,M.jsonStringifyReplacer)}`;break;case hN.unrecognized_keys:r=`Unrecognized key(s) in object: ${M.joinValues(e.keys,", ")}`;break;case hN.invalid_union:r="Invalid input";break;case hN.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${M.joinValues(e.options)}`;break;case hN.invalid_enum_value:r=`Invalid enum value. Expected ${M.joinValues(e.options)}, received '${e.received}'`;break;case hN.invalid_arguments:r="Invalid function arguments";break;case hN.invalid_return_type:r="Invalid function return type";break;case hN.invalid_date:r="Invalid date";break;case hN.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:M.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case hN.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case hN.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case hN.custom:r="Invalid input";break;case hN.invalid_intersection_types:r="Intersection results could not be merged";break;case hN.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case hN.not_finite:r="Number must be finite";break;default:r=t.defaultError,M.assertNever(e)}return{message:r}};(O=Z||(Z={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},O.toString=e=>"string"==typeof e?e:e?.message;function hz(e,t){let r=(e=>{let{data:t,path:r,errorMaps:a,issueData:i}=e,n=[...r,...i.path||[]],o={...i,path:n};if(void 0!==i.message)return{...i,path:n,message:i.message};let s="";for(let e of a.filter(e=>!!e).slice().reverse())s=e(o,{data:t,defaultError:s}).message;return{...i,path:n,message:s}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,hA,void 0].filter(e=>!!e)});e.common.issues.push(r)}class hM{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let a of t){if("aborted"===a.status)return hL;"dirty"===a.status&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t){let t=await e.key,a=await e.value;r.push({key:t,value:a})}return hM.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let a of t){let{key:t,value:i}=a;if("aborted"===t.status||"aborted"===i.status)return hL;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==i.value||a.alwaysSet)&&(r[t.value]=i.value)}return{status:e.value,value:r}}}let hL=Object.freeze({status:"aborted"}),hZ=e=>({status:"dirty",value:e}),hD=e=>({status:"valid",value:e}),hU=e=>"u">typeof Promise&&e instanceof Promise;class hV{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}let hF=(e,t)=>{if("valid"===t.status)return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new hq(e.common.issues);return this._error=t,this._error}}};function hH(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:a,description:i}=e;if(t&&(r||a))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:n}=e;return"invalid_enum_value"===t.code?{message:n??i.defaultError}:void 0===i.data?{message:n??a??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:n??r??i.defaultError}},description:i}}class hJ{get description(){return this._def.description}_getType(e){return hI(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:hI(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new hM,ctx:{common:e.parent.common,data:e.data,parsedType:hI(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(hU(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hI(e)},a=this._parseSync({data:e,path:r.path,parent:r});return hF(r,a)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hI(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return"valid"===r.status?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>"valid"===e.status?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hI(e)},a=this._parse({data:e,path:r.path,parent:r});return hF(r,await (hU(a)?a:Promise.resolve(a)))}refine(e,t){return this._refinement((r,a)=>{let i=e(r),n=()=>a.addIssue({code:hN.custom,..."string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(r):t});return"u">typeof Promise&&i instanceof Promise?i.then(e=>!!e||(n(),!1)):!!i||(n(),!1)})}refinement(e,t){return this._refinement((r,a)=>!!e(r)||(a.addIssue("function"==typeof t?t(r,a):t),!1))}_refinement(e){return new fk({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return fx.create(this,this._def)}nullable(){return fP.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fp.create(this)}promise(){return fR.create(this,this._def)}or(e){return fh.create([this,e],this._def)}and(e){return ff.create(this,e,this._def)}transform(e){return new fk({...hH(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new fE({...hH(this._def),innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:D.ZodDefault})}brand(){return new fO({typeName:D.ZodBranded,type:this,...hH(this._def)})}catch(e){return new fT({...hH(this._def),innerType:this,catchValue:"function"==typeof e?e:()=>e,typeName:D.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return fC.create(this,e)}readonly(){return fI.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let hB=/^c[^\s-]{8,}$/i,hK=/^[0-9a-z]+$/,hG=/^[0-9A-HJKMNP-TV-Z]{26}$/i,hW=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,hY=/^[a-z0-9_-]{21}$/i,hX=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,hQ=/^[-+]?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)?)??$/,h0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,h1=/^(?:(?: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])$/,h2=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,h9=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,h4=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,h3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,h5=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,h6="((\\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])))",h8=RegExp(`^${h6}$`);function h7(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}class fe extends hJ{_parse(e){var t,r,a,i;let n;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==hC.string){let t=this._getOrReturnCtx(e);return hz(t,{code:hN.invalid_type,expected:hC.string,received:t.parsedType}),hL}let o=new hM;for(let s of this._def.checks)if("min"===s.kind)e.data.length<s.value&&(hz(n=this._getOrReturnCtx(e,n),{code:hN.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),o.dirty());else if("max"===s.kind)e.data.length>s.value&&(hz(n=this._getOrReturnCtx(e,n),{code:hN.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),o.dirty());else if("length"===s.kind){let t=e.data.length>s.value,r=e.data.length<s.value;(t||r)&&(n=this._getOrReturnCtx(e,n),t?hz(n,{code:hN.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):r&&hz(n,{code:hN.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),o.dirty())}else if("email"===s.kind)h0.test(e.data)||(hz(n=this._getOrReturnCtx(e,n),{validation:"email",code:hN.invalid_string,message:s.message}),o.dirty());else if("emoji"===s.kind)h||(h=RegExp("^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$","u")),h.test(e.data)||(hz(n=this._getOrReturnCtx(e,n),{validation:"emoji",code:hN.invalid_string,message:s.message}),o.dirty());else if("uuid"===s.kind)hW.test(e.data)||(hz(n=this._getOrReturnCtx(e,n),{validation:"uuid",code:hN.invalid_string,message:s.message}),o.dirty());else if("nanoid"===s.kind)hY.test(e.data)||(hz(n=this._getOrReturnCtx(e,n),{validation:"nanoid",code:hN.invalid_string,message:s.message}),o.dirty());else if("cuid"===s.kind)hB.test(e.data)||(hz(n=this._getOrReturnCtx(e,n),{validation:"cuid",code:hN.invalid_string,message:s.message}),o.dirty());else if("cuid2"===s.kind)hK.test(e.data)||(hz(n=this._getOrReturnCtx(e,n),{validation:"cuid2",code:hN.invalid_string,message:s.message}),o.dirty());else if("ulid"===s.kind)hG.test(e.data)||(hz(n=this._getOrReturnCtx(e,n),{validation:"ulid",code:hN.invalid_string,message:s.message}),o.dirty());else if("url"===s.kind)try{new URL(e.data)}catch{hz(n=this._getOrReturnCtx(e,n),{validation:"url",code:hN.invalid_string,message:s.message}),o.dirty()}else"regex"===s.kind?(s.regex.lastIndex=0,s.regex.test(e.data)||(hz(n=this._getOrReturnCtx(e,n),{validation:"regex",code:hN.invalid_string,message:s.message}),o.dirty())):"trim"===s.kind?e.data=e.data.trim():"includes"===s.kind?e.data.includes(s.value,s.position)||(hz(n=this._getOrReturnCtx(e,n),{code:hN.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),o.dirty()):"toLowerCase"===s.kind?e.data=e.data.toLowerCase():"toUpperCase"===s.kind?e.data=e.data.toUpperCase():"startsWith"===s.kind?e.data.startsWith(s.value)||(hz(n=this._getOrReturnCtx(e,n),{code:hN.invalid_string,validation:{startsWith:s.value},message:s.message}),o.dirty()):"endsWith"===s.kind?e.data.endsWith(s.value)||(hz(n=this._getOrReturnCtx(e,n),{code:hN.invalid_string,validation:{endsWith:s.value},message:s.message}),o.dirty()):"datetime"===s.kind?(function(e){let t=`${h6}T${h7(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,RegExp(`^${t}$`)})(s).test(e.data)||(hz(n=this._getOrReturnCtx(e,n),{code:hN.invalid_string,validation:"datetime",message:s.message}),o.dirty()):"date"===s.kind?h8.test(e.data)||(hz(n=this._getOrReturnCtx(e,n),{code:hN.invalid_string,validation:"date",message:s.message}),o.dirty()):"time"===s.kind?RegExp(`^${h7(s)}$`).test(e.data)||(hz(n=this._getOrReturnCtx(e,n),{code:hN.invalid_string,validation:"time",message:s.message}),o.dirty()):"duration"===s.kind?hQ.test(e.data)||(hz(n=this._getOrReturnCtx(e,n),{validation:"duration",code:hN.invalid_string,message:s.message}),o.dirty()):"ip"===s.kind?(t=e.data,!(("v4"===(r=s.version)||!r)&&h1.test(t)||("v6"===r||!r)&&h9.test(t))&&1&&(hz(n=this._getOrReturnCtx(e,n),{validation:"ip",code:hN.invalid_string,message:s.message}),o.dirty())):"jwt"===s.kind?!function(e,t){if(!hX.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(a));if("object"!=typeof i||null===i||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)return!1;return!0}catch{return!1}}(e.data,s.alg)&&(hz(n=this._getOrReturnCtx(e,n),{validation:"jwt",code:hN.invalid_string,message:s.message}),o.dirty()):"cidr"===s.kind?(a=e.data,!(("v4"===(i=s.version)||!i)&&h2.test(a)||("v6"===i||!i)&&h4.test(a))&&1&&(hz(n=this._getOrReturnCtx(e,n),{validation:"cidr",code:hN.invalid_string,message:s.message}),o.dirty())):"base64"===s.kind?h3.test(e.data)||(hz(n=this._getOrReturnCtx(e,n),{validation:"base64",code:hN.invalid_string,message:s.message}),o.dirty()):"base64url"===s.kind?h5.test(e.data)||(hz(n=this._getOrReturnCtx(e,n),{validation:"base64url",code:hN.invalid_string,message:s.message}),o.dirty()):M.assertNever(s);return{status:o.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:hN.invalid_string,...Z.errToObj(r)})}_addCheck(e){return new fe({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Z.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Z.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...Z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Z.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Z.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...Z.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Z.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Z.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Z.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Z.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Z.errToObj(t)})}nonempty(e){return this.min(1,Z.errToObj(e))}trim(){return new fe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new fe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new fe({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}fe.create=e=>new fe({checks:[],typeName:D.ZodString,coerce:e?.coerce??!1,...hH(e)});class ft extends hJ{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let t;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==hC.number){let t=this._getOrReturnCtx(e);return hz(t,{code:hN.invalid_type,expected:hC.number,received:t.parsedType}),hL}let r=new hM;for(let a of this._def.checks)"int"===a.kind?M.isInteger(e.data)||(hz(t=this._getOrReturnCtx(e,t),{code:hN.invalid_type,expected:"integer",received:"float",message:a.message}),r.dirty()):"min"===a.kind?(a.inclusive?e.data<a.value:e.data<=a.value)&&(hz(t=this._getOrReturnCtx(e,t),{code:hN.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):"max"===a.kind?(a.inclusive?e.data>a.value:e.data>=a.value)&&(hz(t=this._getOrReturnCtx(e,t),{code:hN.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):"multipleOf"===a.kind?0!==function(e,t){let r=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,i=r>a?r:a;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}(e.data,a.value)&&(hz(t=this._getOrReturnCtx(e,t),{code:hN.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(hz(t=this._getOrReturnCtx(e,t),{code:hN.not_finite,message:a.message}),r.dirty()):M.assertNever(a);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Z.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Z.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Z.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Z.toString(t))}setLimit(e,t,r,a){return new ft({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Z.toString(a)}]})}_addCheck(e){return new ft({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Z.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Z.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Z.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&M.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;else"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value);return Number.isFinite(t)&&Number.isFinite(e)}}ft.create=e=>new ft({checks:[],typeName:D.ZodNumber,coerce:e?.coerce||!1,...hH(e)});class fr extends hJ{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let t;if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==hC.bigint)return this._getInvalidInput(e);let r=new hM;for(let a of this._def.checks)"min"===a.kind?(a.inclusive?e.data<a.value:e.data<=a.value)&&(hz(t=this._getOrReturnCtx(e,t),{code:hN.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):"max"===a.kind?(a.inclusive?e.data>a.value:e.data>=a.value)&&(hz(t=this._getOrReturnCtx(e,t),{code:hN.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):"multipleOf"===a.kind?e.data%a.value!==BigInt(0)&&(hz(t=this._getOrReturnCtx(e,t),{code:hN.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):M.assertNever(a);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return hz(t,{code:hN.invalid_type,expected:hC.bigint,received:t.parsedType}),hL}gte(e,t){return this.setLimit("min",e,!0,Z.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Z.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Z.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Z.toString(t))}setLimit(e,t,r,a){return new fr({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Z.toString(a)}]})}_addCheck(e){return new fr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Z.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Z.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}fr.create=e=>new fr({checks:[],typeName:D.ZodBigInt,coerce:e?.coerce??!1,...hH(e)});class fa extends hJ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==hC.boolean){let t=this._getOrReturnCtx(e);return hz(t,{code:hN.invalid_type,expected:hC.boolean,received:t.parsedType}),hL}return hD(e.data)}}fa.create=e=>new fa({typeName:D.ZodBoolean,coerce:e?.coerce||!1,...hH(e)});class fi extends hJ{_parse(e){let t;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==hC.date){let t=this._getOrReturnCtx(e);return hz(t,{code:hN.invalid_type,expected:hC.date,received:t.parsedType}),hL}if(Number.isNaN(e.data.getTime()))return hz(this._getOrReturnCtx(e),{code:hN.invalid_date}),hL;let r=new hM;for(let a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(hz(t=this._getOrReturnCtx(e,t),{code:hN.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):"max"===a.kind?e.data.getTime()>a.value&&(hz(t=this._getOrReturnCtx(e,t),{code:hN.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):M.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new fi({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Z.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Z.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}fi.create=e=>new fi({checks:[],coerce:e?.coerce||!1,typeName:D.ZodDate,...hH(e)});class fn extends hJ{_parse(e){if(this._getType(e)!==hC.symbol){let t=this._getOrReturnCtx(e);return hz(t,{code:hN.invalid_type,expected:hC.symbol,received:t.parsedType}),hL}return hD(e.data)}}fn.create=e=>new fn({typeName:D.ZodSymbol,...hH(e)});class fo extends hJ{_parse(e){if(this._getType(e)!==hC.undefined){let t=this._getOrReturnCtx(e);return hz(t,{code:hN.invalid_type,expected:hC.undefined,received:t.parsedType}),hL}return hD(e.data)}}fo.create=e=>new fo({typeName:D.ZodUndefined,...hH(e)});class fs extends hJ{_parse(e){if(this._getType(e)!==hC.null){let t=this._getOrReturnCtx(e);return hz(t,{code:hN.invalid_type,expected:hC.null,received:t.parsedType}),hL}return hD(e.data)}}fs.create=e=>new fs({typeName:D.ZodNull,...hH(e)});class fl extends hJ{constructor(){super(...arguments),this._any=!0}_parse(e){return hD(e.data)}}fl.create=e=>new fl({typeName:D.ZodAny,...hH(e)});class fc extends hJ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return hD(e.data)}}fc.create=e=>new fc({typeName:D.ZodUnknown,...hH(e)});class fu extends hJ{_parse(e){let t=this._getOrReturnCtx(e);return hz(t,{code:hN.invalid_type,expected:hC.never,received:t.parsedType}),hL}}fu.create=e=>new fu({typeName:D.ZodNever,...hH(e)});class fd extends hJ{_parse(e){if(this._getType(e)!==hC.undefined){let t=this._getOrReturnCtx(e);return hz(t,{code:hN.invalid_type,expected:hC.void,received:t.parsedType}),hL}return hD(e.data)}}fd.create=e=>new fd({typeName:D.ZodVoid,...hH(e)});class fp extends hJ{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==hC.array)return hz(t,{code:hN.invalid_type,expected:hC.array,received:t.parsedType}),hL;if(null!==a.exactLength){let e=t.data.length>a.exactLength.value,i=t.data.length<a.exactLength.value;(e||i)&&(hz(t,{code:e?hN.too_big:hN.too_small,minimum:i?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),r.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(hz(t,{code:hN.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),r.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(hz(t,{code:hN.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>a.type._parseAsync(new hV(t,e,t.path,r)))).then(e=>hM.mergeArray(r,e));let i=[...t.data].map((e,r)=>a.type._parseSync(new hV(t,e,t.path,r)));return hM.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new fp({...this._def,minLength:{value:e,message:Z.toString(t)}})}max(e,t){return new fp({...this._def,maxLength:{value:e,message:Z.toString(t)}})}length(e,t){return new fp({...this._def,exactLength:{value:e,message:Z.toString(t)}})}nonempty(e){return this.min(1,e)}}fp.create=(e,t)=>new fp({type:e,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...hH(t)});class fm extends hJ{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=M.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==hC.object){let t=this._getOrReturnCtx(e);return hz(t,{code:hN.invalid_type,expected:hC.object,received:t.parsedType}),hL}let{status:t,ctx:r}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),n=[];if(!(this._def.catchall instanceof fu&&"strip"===this._def.unknownKeys))for(let e in r.data)i.includes(e)||n.push(e);let o=[];for(let e of i){let t=a[e],i=r.data[e];o.push({key:{status:"valid",value:e},value:t._parse(new hV(r,i,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof fu){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of n)o.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)n.length>0&&(hz(r,{code:hN.unrecognized_keys,keys:n}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of n){let a=r.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new hV(r,a,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let r=await t.key,a=await t.value;e.push({key:r,value:a,alwaysSet:t.alwaysSet})}return e}).then(e=>hM.mergeObjectSync(t,e)):hM.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return Z.errToObj,new fm({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{let a=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:Z.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new fm({...this._def,unknownKeys:"strip"})}passthrough(){return new fm({...this._def,unknownKeys:"passthrough"})}extend(e){return new fm({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new fm({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new fm({...this._def,catchall:e})}pick(e){let t={};for(let r of M.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new fm({...this._def,shape:()=>t})}omit(e){let t={};for(let r of M.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new fm({...this._def,shape:()=>t})}deepPartial(){return function e(t){if(t instanceof fm){let r={};for(let a in t.shape){let i=t.shape[a];r[a]=fx.create(e(i))}return new fm({...t._def,shape:()=>r})}if(t instanceof fp)return new fp({...t._def,type:e(t.element)});if(t instanceof fx)return fx.create(e(t.unwrap()));if(t instanceof fP)return fP.create(e(t.unwrap()));if(t instanceof fg)return fg.create(t.items.map(t=>e(t)));else return t}(this)}partial(e){let t={};for(let r of M.objectKeys(this.shape)){let a=this.shape[r];e&&!e[r]?t[r]=a:t[r]=a.optional()}return new fm({...this._def,shape:()=>t})}required(e){let t={};for(let r of M.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof fx;)e=e._def.innerType;t[r]=e}return new fm({...this._def,shape:()=>t})}keyof(){return fS(M.objectKeys(this.shape))}}fm.create=(e,t)=>new fm({shape:()=>e,unknownKeys:"strip",catchall:fu.create(),typeName:D.ZodObject,...hH(t)}),fm.strictCreate=(e,t)=>new fm({shape:()=>e,unknownKeys:"strict",catchall:fu.create(),typeName:D.ZodObject,...hH(t)}),fm.lazycreate=(e,t)=>new fm({shape:e,unknownKeys:"strip",catchall:fu.create(),typeName:D.ZodObject,...hH(t)});class fh extends hJ{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new hq(e.ctx.common.issues));return hz(t,{code:hN.invalid_union,unionErrors:r}),hL});{let e,a=[];for(let i of r){let r={...t,common:{...t.common,issues:[]},parent:null},n=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:r}),r.common.issues.length&&a.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=a.map(e=>new hq(e));return hz(t,{code:hN.invalid_union,unionErrors:i}),hL}}get options(){return this._def.options}}fh.create=(e,t)=>new fh({options:e,typeName:D.ZodUnion,...hH(t)});class ff extends hJ{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),a=(e,a)=>{if("aborted"===e.status||"aborted"===a.status)return hL;let i=function e(t,r){let a=hI(t),i=hI(r);if(t===r)return{valid:!0,data:t};if(a===hC.object&&i===hC.object){let a=M.objectKeys(r),i=M.objectKeys(t).filter(e=>-1!==a.indexOf(e)),n={...t,...r};for(let a of(Object.prototype.hasOwnProperty.call(n,"__proto__")&&delete n.__proto__,i)){if("__proto__"===a)continue;let i=e(t[a],r[a]);if(!i.valid)return{valid:!1};n[a]=i.data}return{valid:!0,data:n}}if(a===hC.array&&i===hC.array){if(t.length!==r.length)return{valid:!1};let a=[];for(let i=0;i<t.length;i++){let n=e(t[i],r[i]);if(!n.valid)return{valid:!1};a.push(n.data)}return{valid:!0,data:a}}if(a===hC.date&&i===hC.date&&+t==+r)return{valid:!0,data:t};return{valid:!1}}(e.value,a.value);return i.valid?(("dirty"===e.status||"dirty"===a.status)&&t.dirty(),{status:t.value,value:i.data}):(hz(r,{code:hN.invalid_intersection_types}),hL)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>a(e,t)):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ff.create=(e,t,r)=>new ff({left:e,right:t,typeName:D.ZodIntersection,...hH(r)});class fg extends hJ{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==hC.array)return hz(r,{code:hN.invalid_type,expected:hC.array,received:r.parsedType}),hL;if(r.data.length<this._def.items.length)return hz(r,{code:hN.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),hL;!this._def.rest&&r.data.length>this._def.items.length&&(hz(r,{code:hN.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...r.data].map((e,t)=>{let a=this._def.items[t]||this._def.rest;return a?a._parse(new hV(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(a).then(e=>hM.mergeArray(t,e)):hM.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new fg({...this._def,rest:e})}}fg.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new fg({items:e,typeName:D.ZodTuple,rest:null,...hH(t)})};class fy extends hJ{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==hC.map)return hz(r,{code:hN.invalid_type,expected:hC.map,received:r.parsedType}),hL;let a=this._def.keyType,i=this._def.valueType,n=[...r.data.entries()].map(([e,t],n)=>({key:a._parse(new hV(r,e,r.path,[n,"key"])),value:i._parse(new hV(r,t,r.path,[n,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of n){let a=await r.key,i=await r.value;if("aborted"===a.status||"aborted"===i.status)return hL;("dirty"===a.status||"dirty"===i.status)&&t.dirty(),e.set(a.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of n){let a=r.key,i=r.value;if("aborted"===a.status||"aborted"===i.status)return hL;("dirty"===a.status||"dirty"===i.status)&&t.dirty(),e.set(a.value,i.value)}return{status:t.value,value:e}}}}fy.create=(e,t,r)=>new fy({valueType:t,keyType:e,typeName:D.ZodMap,...hH(r)});class fv extends hJ{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==hC.set)return hz(r,{code:hN.invalid_type,expected:hC.set,received:r.parsedType}),hL;let a=this._def;null!==a.minSize&&r.data.size<a.minSize.value&&(hz(r,{code:hN.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&r.data.size>a.maxSize.value&&(hz(r,{code:hN.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());let i=this._def.valueType;function n(e){let r=new Set;for(let a of e){if("aborted"===a.status)return hL;"dirty"===a.status&&t.dirty(),r.add(a.value)}return{status:t.value,value:r}}let o=[...r.data.values()].map((e,t)=>i._parse(new hV(r,e,r.path,t)));return r.common.async?Promise.all(o).then(e=>n(e)):n(o)}min(e,t){return new fv({...this._def,minSize:{value:e,message:Z.toString(t)}})}max(e,t){return new fv({...this._def,maxSize:{value:e,message:Z.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}fv.create=(e,t)=>new fv({valueType:e,minSize:null,maxSize:null,typeName:D.ZodSet,...hH(t)});class f_ extends hJ{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}f_.create=(e,t)=>new f_({getter:e,typeName:D.ZodLazy,...hH(t)});class fb extends hJ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return hz(t,{received:t.data,code:hN.invalid_literal,expected:this._def.value}),hL}return{status:"valid",value:e.data}}get value(){return this._def.value}}function fS(e,t){return new f$({values:e,typeName:D.ZodEnum,...hH(t)})}fb.create=(e,t)=>new fb({value:e,typeName:D.ZodLiteral,...hH(t)});class f$ extends hJ{_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return hz(t,{expected:M.joinValues(r),received:t.parsedType,code:hN.invalid_type}),hL}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return hz(t,{received:t.data,code:hN.invalid_enum_value,options:r}),hL}return hD(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return f$.create(e,{...this._def,...t})}exclude(e,t=this._def){return f$.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}f$.create=fS;class fw extends hJ{_parse(e){let t=M.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==hC.string&&r.parsedType!==hC.number){let e=M.objectValues(t);return hz(r,{expected:M.joinValues(e),received:r.parsedType,code:hN.invalid_type}),hL}if(this._cache||(this._cache=new Set(M.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let e=M.objectValues(t);return hz(r,{received:r.data,code:hN.invalid_enum_value,options:e}),hL}return hD(e.data)}get enum(){return this._def.values}}fw.create=(e,t)=>new fw({values:e,typeName:D.ZodNativeEnum,...hH(t)});class fR extends hJ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==hC.promise&&!1===t.common.async?(hz(t,{code:hN.invalid_type,expected:hC.promise,received:t.parsedType}),hL):hD((t.parsedType===hC.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}fR.create=(e,t)=>new fR({type:e,typeName:D.ZodPromise,...hH(t)});class fk extends hJ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),a=this._def.effect||null,i={addIssue:e=>{hz(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===a.type){let e=a.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return hL;let a=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===a.status?hL:"dirty"===a.status||"dirty"===t.value?hZ(a.value):a});{if("aborted"===t.value)return hL;let a=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===a.status?hL:"dirty"===a.status||"dirty"===t.value?hZ(a.value):a}}if("refinement"===a.type){let e=e=>{let t=a.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?hL:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))));{let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===a.status?hL:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}}if("transform"===a.type)if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>"valid"!==e.status?hL:Promise.resolve(a.transform(e.value,i)).then(e=>({status:t.value,value:e})));else{let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if("valid"!==e.status)return hL;let n=a.transform(e.value,i);if(n instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}M.assertNever(a)}}fk.create=(e,t,r)=>new fk({schema:e,typeName:D.ZodEffects,effect:t,...hH(r)}),fk.createWithPreprocess=(e,t,r)=>new fk({schema:t,effect:{type:"preprocess",transform:e},typeName:D.ZodEffects,...hH(r)});class fx extends hJ{_parse(e){return this._getType(e)===hC.undefined?hD(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}fx.create=(e,t)=>new fx({innerType:e,typeName:D.ZodOptional,...hH(t)});class fP extends hJ{_parse(e){return this._getType(e)===hC.null?hD(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}fP.create=(e,t)=>new fP({innerType:e,typeName:D.ZodNullable,...hH(t)});class fE extends hJ{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===hC.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}fE.create=(e,t)=>new fE({innerType:e,typeName:D.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...hH(t)});class fT extends hJ{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return hU(a)?a.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new hq(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new hq(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}fT.create=(e,t)=>new fT({innerType:e,typeName:D.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...hH(t)});class fj extends hJ{_parse(e){if(this._getType(e)!==hC.nan){let t=this._getOrReturnCtx(e);return hz(t,{code:hN.invalid_type,expected:hC.nan,received:t.parsedType}),hL}return{status:"valid",value:e.data}}}fj.create=e=>new fj({typeName:D.ZodNaN,...hH(e)}),Symbol("zod_brand");class fO extends hJ{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class fC extends hJ{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?hL:"dirty"===e.status?(t.dirty(),hZ(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?hL:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new fC({in:e,out:t,typeName:D.ZodPipeline})}}class fI extends hJ{_parse(e){let t=this._def.innerType._parse(e),r=e=>("valid"===e.status&&(e.value=Object.freeze(e.value)),e);return hU(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}fI.create=(e,t)=>new fI({innerType:e,typeName:D.ZodReadonly,...hH(t)}),fm.lazycreate,(C=D||(D={})).ZodString="ZodString",C.ZodNumber="ZodNumber",C.ZodNaN="ZodNaN",C.ZodBigInt="ZodBigInt",C.ZodBoolean="ZodBoolean",C.ZodDate="ZodDate",C.ZodSymbol="ZodSymbol",C.ZodUndefined="ZodUndefined",C.ZodNull="ZodNull",C.ZodAny="ZodAny",C.ZodUnknown="ZodUnknown",C.ZodNever="ZodNever",C.ZodVoid="ZodVoid",C.ZodArray="ZodArray",C.ZodObject="ZodObject",C.ZodUnion="ZodUnion",C.ZodDiscriminatedUnion="ZodDiscriminatedUnion",C.ZodIntersection="ZodIntersection",C.ZodTuple="ZodTuple",C.ZodRecord="ZodRecord",C.ZodMap="ZodMap",C.ZodSet="ZodSet",C.ZodFunction="ZodFunction",C.ZodLazy="ZodLazy",C.ZodLiteral="ZodLiteral",C.ZodEnum="ZodEnum",C.ZodEffects="ZodEffects",C.ZodNativeEnum="ZodNativeEnum",C.ZodOptional="ZodOptional",C.ZodNullable="ZodNullable",C.ZodDefault="ZodDefault",C.ZodCatch="ZodCatch",C.ZodPromise="ZodPromise",C.ZodBranded="ZodBranded",C.ZodPipeline="ZodPipeline",C.ZodReadonly="ZodReadonly";let fN=fe.create;ft.create,fj.create,fr.create,fa.create,fi.create,fn.create,fo.create,fs.create,fl.create,fc.create,fu.create,fd.create,fp.create;let fq=fm.create;fm.strictCreate,fh.create,ff.create,fg.create,fy.create,fv.create,f_.create,fb.create,f$.create,fw.create,fR.create,fk.create,fx.create,fP.create,fk.createWithPreprocess,fC.create;let fA=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function fz(e){if("openAi"!==e.target)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?fA(t,e.currentPath):t.join("/")}}function fM(e,t,r,a){a?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function fL(e,t,r,a,i){e[t]=r,fM(e,t,a,i)}function fZ(e,t){return f6(e.type._def,t)}let fD=/^[cC][^\s-]{8,}$/,fU=/^[0-9a-z]+$/,fV=/^[0-9A-HJKMNP-TV-Z]{26}$/,fF=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,fH=()=>(void 0===w&&(w=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),w),fJ=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,fB=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,fK=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fG=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,fW=/^[a-zA-Z0-9_-]{21}$/,fY=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function fX(e,t){let r={type:"string"};if(e.checks)for(let a of e.checks)switch(a.kind){case"min":fL(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t);break;case"max":fL(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"email":switch(t.emailStrategy){case"format:email":f1(r,"email",a.message,t);break;case"format:idn-email":f1(r,"idn-email",a.message,t);break;case"pattern:zod":f2(r,fF,a.message,t)}break;case"url":f1(r,"uri",a.message,t);break;case"uuid":f1(r,"uuid",a.message,t);break;case"regex":f2(r,a.regex,a.message,t);break;case"cuid":f2(r,fD,a.message,t);break;case"cuid2":f2(r,fU,a.message,t);break;case"startsWith":f2(r,RegExp(`^${fQ(a.value,t)}`),a.message,t);break;case"endsWith":f2(r,RegExp(`${fQ(a.value,t)}$`),a.message,t);break;case"datetime":f1(r,"date-time",a.message,t);break;case"date":f1(r,"date",a.message,t);break;case"time":f1(r,"time",a.message,t);break;case"duration":f1(r,"duration",a.message,t);break;case"length":fL(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,a.value):a.value,a.message,t),fL(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,a.value):a.value,a.message,t);break;case"includes":f2(r,RegExp(fQ(a.value,t)),a.message,t);break;case"ip":"v6"!==a.version&&f1(r,"ipv4",a.message,t),"v4"!==a.version&&f1(r,"ipv6",a.message,t);break;case"base64url":f2(r,fG,a.message,t);break;case"jwt":f2(r,fY,a.message,t);break;case"cidr":"v6"!==a.version&&f2(r,fJ,a.message,t),"v4"!==a.version&&f2(r,fB,a.message,t);break;case"emoji":f2(r,fH(),a.message,t);break;case"ulid":f2(r,fV,a.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":f1(r,"binary",a.message,t);break;case"contentEncoding:base64":fL(r,"contentEncoding","base64",a.message,t);break;case"pattern:zod":f2(r,fK,a.message,t)}break;case"nanoid":f2(r,fW,a.message,t)}return r}function fQ(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)f0.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}let f0=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function f1(e,t,r,a){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&a.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&a.errorMessages&&{errorMessage:{format:r}}})):fL(e,"format",t,r,a)}function f2(e,t,r,a){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&a.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:f9(t,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):fL(e,"pattern",f9(t,a),r,a)}function f9(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},a=r.i?e.source.toLowerCase():e.source,i="",n=!1,o=!1,s=!1;for(let e=0;e<a.length;e++){if(n){i+=a[e],n=!1;continue}if(r.i){if(o){if(a[e].match(/[a-z]/)){s?(i+=a[e],i+=`${a[e-2]}-${a[e]}`.toUpperCase(),s=!1):"-"===a[e+1]&&a[e+2]?.match(/[a-z]/)?(i+=a[e],s=!0):i+=`${a[e]}${a[e].toUpperCase()}`;continue}}else if(a[e].match(/[a-z]/)){i+=`[${a[e]}${a[e].toUpperCase()}]`;continue}}if(r.m){if("^"===a[e]){i+=`(^|(?<=[\r
78
78
  ]))`;continue}else if("$"===a[e]){i+=`($|(?=[\r
79
79
  ]))`;continue}}if(r.s&&"."===a[e]){i+=o?`${a[e]}\r
80
80
  `:`[${a[e]}\r
81
- ]`;continue}i+=a[e],"\\"===a[e]?n=!0:o&&"]"===a[e]?o=!1:o||"["!==a[e]||(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function gt(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,a)=>({...r,[a]:gi(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??fF(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:gi(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===D.ZodString&&e.keyType._def.checks?.length){let{type:a,...i}=f3(e.keyType._def,t);return{...r,propertyNames:i}}if(e.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===D.ZodBranded&&e.keyType._def.type._def.typeName===D.ZodString&&e.keyType._def.type._def.checks?.length){let{type:a,...i}=fB(e.keyType._def,t);return{...r,propertyNames:i}}return r}let gr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},ga=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>gi(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function gi(e,t,r=!1){let a=t.seen.get(e);if(t.override){let i=t.override?.(e,t,a,r);if(i!==hz)return i}if(a&&!r){let e=gn(a,t);if(void 0!==e)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let n=((e,t,r)=>{switch(t){case D.ZodString:return f3(e,r);case D.ZodNumber:let a={type:"number"};if(!e.checks)return a;for(let t of e.checks)switch(t.kind){case"int":a.type="integer",fH(a,"type",t.message,r);break;case"min":"jsonSchema7"===r.target?t.inclusive?fJ(a,"minimum",t.value,t.message,r):fJ(a,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(a.exclusiveMinimum=!0),fJ(a,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?fJ(a,"maximum",t.value,t.message,r):fJ(a,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(a.exclusiveMaximum=!0),fJ(a,"maximum",t.value,t.message,r));break;case"multipleOf":fJ(a,"multipleOf",t.value,t.message,r)}return a;case D.ZodObject:return function(e,t){let r="openAi"===t.target,a={type:"object",properties:{}},i=[],n=e.shape();for(let e in n){let o=n[e];if(void 0===o||void 0===o._def)continue;let s=function(e){try{return e.isOptional()}catch{return!0}}(o);s&&r&&("ZodOptional"===o._def.typeName&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let l=gi(o._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==l&&(a.properties[e]=l,s||i.push(e))}i.length&&(a.required=i);let o=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return gi(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==o&&(a.additionalProperties=o),a}(e,r);case D.ZodBigInt:let i={type:"integer",format:"int64"};if(!e.checks)return i;for(let t of e.checks)switch(t.kind){case"min":"jsonSchema7"===r.target?t.inclusive?fJ(i,"minimum",t.value,t.message,r):fJ(i,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(i.exclusiveMinimum=!0),fJ(i,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?fJ(i,"maximum",t.value,t.message,r):fJ(i,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(i.exclusiveMaximum=!0),fJ(i,"maximum",t.value,t.message,r));break;case"multipleOf":fJ(i,"multipleOf",t.value,t.message,r)}return i;case D.ZodBoolean:return{type:"boolean"};case D.ZodDate:return function e(t,r,a){let i=a??r.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((a,i)=>e(t,r,a))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var n=t,o=r;let s={type:"integer",format:"unix-time"};if("openApi3"===o.target)return s;for(let e of n.checks)switch(e.kind){case"min":fJ(s,"minimum",e.value,e.message,o);break;case"max":fJ(s,"maximum",e.value,e.message,o)}return s}}(e,r);case D.ZodUndefined:return{not:fF(r)};case D.ZodNull:return"openApi3"===r.target?{enum:["null"],nullable:!0}:{type:"null"};case D.ZodArray:let n;return n={type:"array"},e.type?._def&&e.type?._def?.typeName!==D.ZodAny&&(n.items=gi(e.type._def,{...r,currentPath:[...r.currentPath,"items"]})),e.minLength&&fJ(n,"minItems",e.minLength.value,e.minLength.message,r),e.maxLength&&fJ(n,"maxItems",e.maxLength.value,e.maxLength.message,r),e.exactLength&&(fJ(n,"minItems",e.exactLength.value,e.exactLength.message,r),fJ(n,"maxItems",e.exactLength.value,e.exactLength.message,r)),n;case D.ZodUnion:case D.ZodDiscriminatedUnion:if("openApi3"===r.target)return ga(e,r);let o=e.options instanceof Map?Array.from(e.options.values()):e.options;if(o.every(e=>e._def.typeName in gr&&(!e._def.checks||!e._def.checks.length))){let e=o.reduce((e,t)=>{let r=gr[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(o.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=o.reduce((e,t)=>{let r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===o.length){let t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:o.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(o.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:o.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return ga(e,r);case D.ZodIntersection:let s,l,c;return s=[gi(e.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),gi(e.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(e=>!!e),l="jsonSchema2019-09"===r.target?{unevaluatedProperties:!1}:void 0,c=[],s.forEach(e=>{if((!("type"in e)||"string"!==e.type)&&"allOf"in e)c.push(...e.allOf),void 0===e.unevaluatedProperties&&(l=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...a}=e;t=a}else l=void 0;c.push(t)}}),c.length?{allOf:c,...l}:void 0;case D.ZodTuple:return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,t)=>gi(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:gi(e.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,t)=>gi(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])};case D.ZodRecord:return gt(e,r);case D.ZodLiteral:let u;return"bigint"!=(u=typeof e.value)&&"number"!==u&&"boolean"!==u&&"string"!==u?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===r.target?{type:"bigint"===u?"integer":u,enum:[e.value]}:{type:"bigint"===u?"integer":u,const:e.value};case D.ZodEnum:return{type:"string",enum:Array.from(e.values)};case D.ZodNativeEnum:let d,p,m;return d=e.values,{type:1===(m=Array.from(new Set((p=Object.keys(e.values).filter(e=>"number"!=typeof d[d[e]]).map(e=>d[e])).map(e=>typeof e)))).length?"string"===m[0]?"string":"number":["string","number"],enum:p};case D.ZodNullable:if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===r.target?{type:gr[e.innerType._def.typeName],nullable:!0}:{type:[gr[e.innerType._def.typeName],"null"]};if("openApi3"===r.target){let t=gi(e.innerType._def,{...r,currentPath:[...r.currentPath]});return t&&"$ref"in t?{allOf:[t],nullable:!0}:t&&{...t,nullable:!0}}let h=gi(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return h&&{anyOf:[h,{type:"null"}]};case D.ZodOptional:if(r.currentPath.toString()===r.propertyPath?.toString())return gi(e.innerType._def,r);let f=gi(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return f?{anyOf:[{not:fF(r)},f]}:fF(r);case D.ZodMap:if("record"===r.mapStrategy)return gt(e,r);return{type:"array",maxItems:125,items:{type:"array",items:[gi(e.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||fF(r),gi(e.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||fF(r)],minItems:2,maxItems:2}};case D.ZodSet:let g;return g={type:"array",uniqueItems:!0,items:gi(e.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})},e.minSize&&fJ(g,"minItems",e.minSize.value,e.minSize.message,r),e.maxSize&&fJ(g,"maxItems",e.maxSize.value,e.maxSize.message,r),g;case D.ZodLazy:return()=>e.getter()._def;case D.ZodPromise:return gi(e.type._def,r);case D.ZodNaN:case D.ZodNever:return"openAi"===r.target?void 0:{not:fF({...r,currentPath:[...r.currentPath,"not"]})};case D.ZodEffects:return"input"===r.effectStrategy?gi(e.schema._def,r):fF(r);case D.ZodAny:case D.ZodUnknown:return fF(r);case D.ZodDefault:return{...gi(e.innerType._def,r),default:e.defaultValue()};case D.ZodBranded:return fB(e,r);case D.ZodReadonly:case D.ZodCatch:return gi(e.innerType._def,r);case D.ZodPipeline:if("input"===r.pipeStrategy)return gi(e.in._def,r);if("output"===r.pipeStrategy)return gi(e.out._def,r);let y=gi(e.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),v=gi(e.out._def,{...r,currentPath:[...r.currentPath,"allOf",y?"1":"0"]});return{allOf:[y,v].filter(e=>void 0!==e)};case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:default:return}})(e,e.typeName,t),o="function"==typeof n?gi(n(),t):n;if(o&&go(e,t,o),t.postProcess){let r=t.postProcess(o,e,t);return i.jsonSchema=o,r}return i.jsonSchema=o,o}let gn=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:fV(t.currentPath,e.path)};case"none":case"seen":if(e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),fF(t);return"seen"===t.$refStrategy?fF(t):void 0}},go=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);function gs(e,t={}){let{strict:r=!1}=t,a=Object.entries(e),i=e=>({target:t})=>{let i={},n=[];for(let[r,o]of a)i[r]=function(e,t,r){let a=e["~standard"];if(a.jsonSchema)return a.jsonSchema[r]({target:t});if("zod"===e["~standard"].vendor&&!("_zod"in e)&&"_def"in e){let r=((e,t)=>{let r,a,i=(a=void 0!==(r="string"==typeof t?{...hM,name:t}:{...hM,...t}).name?[...r.basePath,r.definitionPath,r.name]:r.basePath,{...r,flags:{hasReferencedOpenAiAnyType:!1},currentPath:a,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([e,t])=>[t._def,{def:t._def,path:[...r.basePath,r.definitionPath,e],jsonSchema:void 0}]))}),n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:gi(r._def,{...i,currentPath:[...i.basePath,i.definitionPath,t]},!0)??fF(i)}),{}):void 0,o="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,s=gi(e._def,void 0===o?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1)??fF(i),l="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==l&&(s.title=l),i.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[i.openAiAnyTypeName]||(n[i.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===i.$refStrategy?"1":[...i.basePath,i.definitionPath,i.openAiAnyTypeName].join("/")}}));let c=void 0===o?n?{...s,[i.definitionPath]:n}:s:{$ref:[..."relative"===i.$refStrategy?[]:i.basePath,i.definitionPath,o].join("/"),[i.definitionPath]:{...n,[o]:s}};return"jsonSchema7"===i.target?c.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===i.target||"openAi"===i.target)&&(c.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===i.target&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c})(e,{$refStrategy:"none",target:"openapi-3.0"===t?"openApi3":"jsonSchema7"});return delete r.$schema,r}if("zod"===a.vendor&&"_zod"in e)try{let t=ir(e);return delete t.$schema,t}catch(e){throw Error(`Failed to convert a zod schema to JSON Schema (zod v4 without "~standard.jsonSchema"). Upgrade to zod >= 4.2.0. Original error: ${e instanceof Error?e.message:String(e)}`)}throw Error(`Schema library "${a.vendor}" cannot be converted to JSON Schema. Use zod v3 (>= 3.25.76), zod >= 4.2.0, or a Standard Schema library implementing "~standard.jsonSchema".`)}(o,t,e),!function(e,t){if("function"!=typeof e.safeParse)return!1;try{let r=e.safeParse(void 0);return r.success&&("input"===t||void 0===r.data)}catch{return!1}}(o,e)&&n.push(r);let o={type:"object",properties:i};return n.length>0&&(o.required=n),r&&(o.additionalProperties=!1),o};return{shape:e,"~standard":{version:1,vendor:"xmcp",validate:async t=>{if("object"!=typeof t||null===t||Array.isArray(t))return{issues:[{message:"Expected an object."}]};let i={},n=[];for(let[e,r]of a){let a=await r["~standard"].validate(t[e]);if(a.issues)for(let t of a.issues)n.push({message:t.message,path:[e,...t.path??[]]});else(e in t||void 0!==a.value)&&(i[e]=a.value)}if(r)for(let r of Object.keys(t))r in e||n.push({message:`Unrecognized key: "${r}"`,path:[r]});return n.length>0?{issues:n}:{value:i}},jsonSchema:{input:i("input"),output:i("output")}}}}function gl(e){let t={};return!function e(r,a=""){if(r&&"object"==typeof r)for(let[i,n]of Object.entries(r)){let r=a?`${a}/${i}`:i;!n||"object"!=typeof n||Array.isArray(n)||n instanceof Date||n instanceof RegExp?t[r]=n:e(n,r)}}(e),t}let gc=["ui/resourceUri","resourceUri","visibility"],gu=["prefersBorder","domain","csp","permissions","connectDomains","resourceDomains","frameDomains","baseUriDomains"];function gd(e){return"object"==typeof e&&null!==e&&Object.entries(e).every(([e,t])=>"string"==typeof e&&"object"==typeof t&&null!==t&&"parse"in t&&"function"==typeof t.parse)}function gp(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}function gm(e,t,r){return e.names?.includes(t)===!0||e.tags?.some(e=>r.includes(e))===!0}function gh(e,t){return t?new Map([...e].filter(([e,{metadata:r}])=>{if(r?.enabled===!1)return!1;let a=r?.name??gp(e),i=r?.tags??[];return(!t.include||gm(t.include,a,i))&&(!t.exclude||!gm(t.exclude,a,i))})):e}function gf(e){return Error(`[xmcp] Invalid prompt file: ${e}
82
- -> Default export must be a prompt handler function.`)}let gg=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load prompt file: ${t}
83
- -> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} prompt${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function gy(e){return Error(`[xmcp] Invalid resource file: ${e}
84
- -> Default export must be a resource handler function.`)}let gv=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load resource file: ${t}
85
- -> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} resource${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function g_(e){let t=e.replace(/\\/g,"/");if(!t)throw Error("Invalid tool path: path is empty");let r=t.replace(/\.[^/.]+$/,"").replace(/\//g,"_");return{normalizedPath:t,baseName:r}}function gb(e){let t=e.split("/").filter(e=>""!==e),r=t.findIndex(e=>e.match(/^\(.+\)$/));if(-1===r)return null;let a=t[t.length-1];if(a&&a.match(/^\[.+\]\.ts$/))return null;let i=t[r].slice(1,-1),n=t.slice(r+1),o=n[n.length-1];if(o&&o.includes(".")){let e=o.split(".")[0];"index"!==e?n[n.length-1]=e:n.pop()}let s=[],l=[],c=n.map(e=>{if(!e.match(/^\[.+\]$/))return l.push(e),e;{let t=e.slice(1,-1);return s.push(t),`{${t}}`}}),u=`${i}://${c.join("/")}`,d=s.length>0?"template":"direct";return{filePath:e,uriTemplate:u,scheme:i,parameters:s,pathSegments:l,type:d}}let gS={ttlMs:0,cacheScope:"private"},g$=fU({cursor:fD().optional()}).passthrough().optional(),gw=fU({uri:fD()}).passthrough();function gR({uri:e,frontmatter:t,files:r}){return{uri:e,frontmatter:t,resources:r.map(({uri:e,digest:t,size:r})=>({uri:e,digest:t,size:r}))}}function gk(e){return Error(`[xmcp] Invalid tool file: ${e}
86
- -> Default export must be a tool handler function.`)}let gx=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load tool file: ${t}
87
- -> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} tool${1===i?"":"s"} skipped due to empty files or missing default exports`)}}(),gP=INJECTED_TOOLS,gE=INJECTED_PROMPTS,gT=INJECTED_RESOURCES,gj="u"<typeof INJECTED_SKILLS?[]:INJECTED_SKILLS??[],gO=SERVER_INFO,gC=HTTP_CONFIG,gI=HTTP_CORS_CONFIG,gN=(I=function(e,t={}){var r;let{legacy:a,onerror:i,responseMode:n}=t,o=p0(t.maxRequestBodySize);if("function"==typeof a)throw TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.");let s=new Set,l=!1,u=e=>{try{i?.(e)}catch{}},h=t.bus??new pW(u),f={toolsChanged:()=>h.publish({kind:"tools_list_changed"}),promptsChanged:()=>h.publish({kind:"prompts_list_changed"}),resourcesChanged:()=>h.publish({kind:"resources_list_changed"}),resourceUpdated:e=>h.publish({kind:"resource_updated",uri:e})},g=function(e){let{bus:t,onerror:r}=e,a=e.maxSubscriptions??1024,i=e.keepAliveMs??15e3,n=new Set;return{serve:function(e,o,s,l){let c,u,d,p,m,h,f;if(n.size>=a)return r?.(Error(`subscriptions/listen refused: subscription limit reached (${a})`)),pY(e.id,-32603,"Subscription limit reached");let g=(m=cM(cz).validateRequest("subscriptions/listen",e)).ok?m.value.params?.notifications:void 0;if(void 0===g)return pY(e.id,-32602,"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter");let y=(h={},f=e=>void 0===s||!0===e,!0===g.toolsListChanged&&f(s?.tools?.listChanged)&&(h.toolsListChanged=!0),!0===g.promptsListChanged&&f(s?.prompts?.listChanged)&&(h.promptsListChanged=!0),!0===g.resourcesListChanged&&f(s?.resources?.listChanged)&&(h.resourcesListChanged=!0),void 0!==g.resourceSubscriptions&&g.resourceSubscriptions.length>0&&f(s?.resources?.subscribe)&&(h.resourceSubscriptions=[...g.resourceSubscriptions]),h),v=e.id,_=new TextEncoder,b=!1,S=e=>{if(!b)try{c.enqueue(_.encode(e))}catch(e){r?.(e instanceof Error?e:Error(String(e)))}},$=(e,t)=>{S(`event: message
81
+ ]`;continue}i+=a[e],"\\"===a[e]?n=!0:o&&"]"===a[e]?o=!1:o||"["!==a[e]||(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function f4(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,a)=>({...r,[a]:f6(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??fz(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:f6(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===D.ZodString&&e.keyType._def.checks?.length){let{type:a,...i}=fX(e.keyType._def,t);return{...r,propertyNames:i}}if(e.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===D.ZodBranded&&e.keyType._def.type._def.typeName===D.ZodString&&e.keyType._def.type._def.checks?.length){let{type:a,...i}=fZ(e.keyType._def,t);return{...r,propertyNames:i}}return r}let f3={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},f5=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>f6(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function f6(e,t,r=!1){let a=t.seen.get(e);if(t.override){let i=t.override?.(e,t,a,r);if(i!==hj)return i}if(a&&!r){let e=f8(a,t);if(void 0!==e)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let n=((e,t,r)=>{switch(t){case D.ZodString:return fX(e,r);case D.ZodNumber:let a={type:"number"};if(!e.checks)return a;for(let t of e.checks)switch(t.kind){case"int":a.type="integer",fM(a,"type",t.message,r);break;case"min":"jsonSchema7"===r.target?t.inclusive?fL(a,"minimum",t.value,t.message,r):fL(a,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(a.exclusiveMinimum=!0),fL(a,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?fL(a,"maximum",t.value,t.message,r):fL(a,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(a.exclusiveMaximum=!0),fL(a,"maximum",t.value,t.message,r));break;case"multipleOf":fL(a,"multipleOf",t.value,t.message,r)}return a;case D.ZodObject:return function(e,t){let r="openAi"===t.target,a={type:"object",properties:{}},i=[],n=e.shape();for(let e in n){let o=n[e];if(void 0===o||void 0===o._def)continue;let s=function(e){try{return e.isOptional()}catch{return!0}}(o);s&&r&&("ZodOptional"===o._def.typeName&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let l=f6(o._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==l&&(a.properties[e]=l,s||i.push(e))}i.length&&(a.required=i);let o=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return f6(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==o&&(a.additionalProperties=o),a}(e,r);case D.ZodBigInt:let i={type:"integer",format:"int64"};if(!e.checks)return i;for(let t of e.checks)switch(t.kind){case"min":"jsonSchema7"===r.target?t.inclusive?fL(i,"minimum",t.value,t.message,r):fL(i,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(i.exclusiveMinimum=!0),fL(i,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?fL(i,"maximum",t.value,t.message,r):fL(i,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(i.exclusiveMaximum=!0),fL(i,"maximum",t.value,t.message,r));break;case"multipleOf":fL(i,"multipleOf",t.value,t.message,r)}return i;case D.ZodBoolean:return{type:"boolean"};case D.ZodDate:return function e(t,r,a){let i=a??r.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((a,i)=>e(t,r,a))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var n=t,o=r;let s={type:"integer",format:"unix-time"};if("openApi3"===o.target)return s;for(let e of n.checks)switch(e.kind){case"min":fL(s,"minimum",e.value,e.message,o);break;case"max":fL(s,"maximum",e.value,e.message,o)}return s}}(e,r);case D.ZodUndefined:return{not:fz(r)};case D.ZodNull:return"openApi3"===r.target?{enum:["null"],nullable:!0}:{type:"null"};case D.ZodArray:let n;return n={type:"array"},e.type?._def&&e.type?._def?.typeName!==D.ZodAny&&(n.items=f6(e.type._def,{...r,currentPath:[...r.currentPath,"items"]})),e.minLength&&fL(n,"minItems",e.minLength.value,e.minLength.message,r),e.maxLength&&fL(n,"maxItems",e.maxLength.value,e.maxLength.message,r),e.exactLength&&(fL(n,"minItems",e.exactLength.value,e.exactLength.message,r),fL(n,"maxItems",e.exactLength.value,e.exactLength.message,r)),n;case D.ZodUnion:case D.ZodDiscriminatedUnion:if("openApi3"===r.target)return f5(e,r);let o=e.options instanceof Map?Array.from(e.options.values()):e.options;if(o.every(e=>e._def.typeName in f3&&(!e._def.checks||!e._def.checks.length))){let e=o.reduce((e,t)=>{let r=f3[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(o.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=o.reduce((e,t)=>{let r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===o.length){let t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:o.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(o.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:o.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return f5(e,r);case D.ZodIntersection:let s,l,c;return s=[f6(e.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),f6(e.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(e=>!!e),l="jsonSchema2019-09"===r.target?{unevaluatedProperties:!1}:void 0,c=[],s.forEach(e=>{if((!("type"in e)||"string"!==e.type)&&"allOf"in e)c.push(...e.allOf),void 0===e.unevaluatedProperties&&(l=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...a}=e;t=a}else l=void 0;c.push(t)}}),c.length?{allOf:c,...l}:void 0;case D.ZodTuple:return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,t)=>f6(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:f6(e.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,t)=>f6(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])};case D.ZodRecord:return f4(e,r);case D.ZodLiteral:let u;return"bigint"!=(u=typeof e.value)&&"number"!==u&&"boolean"!==u&&"string"!==u?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===r.target?{type:"bigint"===u?"integer":u,enum:[e.value]}:{type:"bigint"===u?"integer":u,const:e.value};case D.ZodEnum:return{type:"string",enum:Array.from(e.values)};case D.ZodNativeEnum:let d,p,m;return d=e.values,{type:1===(m=Array.from(new Set((p=Object.keys(e.values).filter(e=>"number"!=typeof d[d[e]]).map(e=>d[e])).map(e=>typeof e)))).length?"string"===m[0]?"string":"number":["string","number"],enum:p};case D.ZodNullable:if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===r.target?{type:f3[e.innerType._def.typeName],nullable:!0}:{type:[f3[e.innerType._def.typeName],"null"]};if("openApi3"===r.target){let t=f6(e.innerType._def,{...r,currentPath:[...r.currentPath]});return t&&"$ref"in t?{allOf:[t],nullable:!0}:t&&{...t,nullable:!0}}let h=f6(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return h&&{anyOf:[h,{type:"null"}]};case D.ZodOptional:if(r.currentPath.toString()===r.propertyPath?.toString())return f6(e.innerType._def,r);let f=f6(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return f?{anyOf:[{not:fz(r)},f]}:fz(r);case D.ZodMap:if("record"===r.mapStrategy)return f4(e,r);return{type:"array",maxItems:125,items:{type:"array",items:[f6(e.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||fz(r),f6(e.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||fz(r)],minItems:2,maxItems:2}};case D.ZodSet:let g;return g={type:"array",uniqueItems:!0,items:f6(e.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})},e.minSize&&fL(g,"minItems",e.minSize.value,e.minSize.message,r),e.maxSize&&fL(g,"maxItems",e.maxSize.value,e.maxSize.message,r),g;case D.ZodLazy:return()=>e.getter()._def;case D.ZodPromise:return f6(e.type._def,r);case D.ZodNaN:case D.ZodNever:return"openAi"===r.target?void 0:{not:fz({...r,currentPath:[...r.currentPath,"not"]})};case D.ZodEffects:return"input"===r.effectStrategy?f6(e.schema._def,r):fz(r);case D.ZodAny:case D.ZodUnknown:return fz(r);case D.ZodDefault:return{...f6(e.innerType._def,r),default:e.defaultValue()};case D.ZodBranded:return fZ(e,r);case D.ZodReadonly:case D.ZodCatch:return f6(e.innerType._def,r);case D.ZodPipeline:if("input"===r.pipeStrategy)return f6(e.in._def,r);if("output"===r.pipeStrategy)return f6(e.out._def,r);let y=f6(e.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),v=f6(e.out._def,{...r,currentPath:[...r.currentPath,"allOf",y?"1":"0"]});return{allOf:[y,v].filter(e=>void 0!==e)};case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:default:return}})(e,e.typeName,t),o="function"==typeof n?f6(n(),t):n;if(o&&f7(e,t,o),t.postProcess){let r=t.postProcess(o,e,t);return i.jsonSchema=o,r}return i.jsonSchema=o,o}let f8=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:fA(t.currentPath,e.path)};case"none":case"seen":if(e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),fz(t);return"seen"===t.$refStrategy?fz(t):void 0}},f7=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);function ge(e){if("object"!=typeof e||null===e)return!1;let t=e["~standard"];return"object"==typeof t&&null!==t&&"function"==typeof t.validate}function gt(e,t,r){let a=e["~standard"];if(a.jsonSchema)return a.jsonSchema[r]({target:t});if("zod"===e["~standard"].vendor&&!("_zod"in e)&&"_def"in e){let r=((e,t)=>{let r,a,i=(a=void 0!==(r="string"==typeof t?{...hO,name:t}:{...hO,...t}).name?[...r.basePath,r.definitionPath,r.name]:r.basePath,{...r,flags:{hasReferencedOpenAiAnyType:!1},currentPath:a,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([e,t])=>[t._def,{def:t._def,path:[...r.basePath,r.definitionPath,e],jsonSchema:void 0}]))}),n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:f6(r._def,{...i,currentPath:[...i.basePath,i.definitionPath,t]},!0)??fz(i)}),{}):void 0,o="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,s=f6(e._def,void 0===o?i:{...i,currentPath:[...i.basePath,i.definitionPath,o]},!1)??fz(i),l="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==l&&(s.title=l),i.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[i.openAiAnyTypeName]||(n[i.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===i.$refStrategy?"1":[...i.basePath,i.definitionPath,i.openAiAnyTypeName].join("/")}}));let c=void 0===o?n?{...s,[i.definitionPath]:n}:s:{$ref:[..."relative"===i.$refStrategy?[]:i.basePath,i.definitionPath,o].join("/"),[i.definitionPath]:{...n,[o]:s}};return"jsonSchema7"===i.target?c.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===i.target||"openAi"===i.target)&&(c.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===i.target&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c})(e,{$refStrategy:"none",target:"openapi-3.0"===t?"openApi3":"jsonSchema7"});return delete r.$schema,r}if("zod"===a.vendor&&"_zod"in e)try{let t=ir(e);return delete t.$schema,t}catch(e){throw Error(`Failed to convert a zod schema to JSON Schema (zod v4 without "~standard.jsonSchema"). Upgrade to zod >= 4.2.0. Original error: ${e instanceof Error?e.message:String(e)}`)}throw Error(`Schema library "${a.vendor}" cannot be converted to JSON Schema. Use zod v3 (>= 3.25.76), zod >= 4.2.0, or a Standard Schema library implementing "~standard.jsonSchema".`)}function gr(e,t={}){let{strict:r=!1}=t,a=Object.entries(e),i=e=>({target:t})=>{let i={},n=[];for(let[r,o]of a)i[r]=gt(o,t,e),!function(e,t){if("function"!=typeof e.safeParse)return!1;try{let r=e.safeParse(void 0);return r.success&&("input"===t||void 0===r.data)}catch{return!1}}(o,e)&&n.push(r);let o={type:"object",properties:i};return n.length>0&&(o.required=n),r&&(o.additionalProperties=!1),o};return{shape:e,"~standard":{version:1,vendor:"xmcp",validate:async t=>{if("object"!=typeof t||null===t||Array.isArray(t))return{issues:[{message:"Expected an object."}]};let i={},n=[];for(let[e,r]of a){let a=await r["~standard"].validate(t[e]);if(a.issues)for(let t of a.issues)n.push({message:t.message,path:[e,...t.path??[]]});else(e in t||void 0!==a.value)&&(i[e]=a.value)}if(r)for(let r of Object.keys(t))r in e||n.push({message:`Unrecognized key: "${r}"`,path:[r]});return n.length>0?{issues:n}:{value:i}},jsonSchema:{input:i("input"),output:i("output")}}}}function ga(e,t={}){let r;return ge(e)?{..."object"==typeof(r=e.shape)&&null!==r&&Object.values(r).every(ge)?{shape:r}:{},"~standard":{version:1,vendor:"xmcp",validate:t=>e["~standard"].validate(t),jsonSchema:{input:({target:t})=>gt(e,t,"input"),output:({target:t})=>gt(e,t,"output")}}}:gr(e,t)}async function gi(e,t,r,a){if(ge(t)){let i=await t["~standard"].validate(e);if(i.issues){let e=i.issues.map(e=>{let t=(e.path??[]).map(e=>"object"==typeof e&&null!==e&&"key"in e?String(e.key):String(e)).join(".");return t?`${t}: ${e.message}`:e.message}).join("; ");throw Error(`Tool "${r}" ${a}: ${e}`)}return}if(null===e||"object"!=typeof e||Array.isArray(e))throw Error(`Tool "${r}" ${a}: expected a plain object.`);let i=new Set(Object.keys(t)),n=Object.keys(e).filter(e=>!i.has(e));if(n.length>0)throw Error(`Tool "${r}" ${a}: unrecognized key(s): ${n.join(", ")}`);for(let[i,n]of Object.entries(t))try{n.parse(e[i])}catch(e){throw Error(`Tool "${r}" ${a}: ${e?.message??`invalid field "${i}"`}`)}}function gn(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&("structuredContent"in e||"content"in e&&Array.isArray(e.content)||"_meta"in e||"isError"in e)}function go(e){return!!(e&&"object"==typeof e&&Object.keys(e).some(e=>e.startsWith("ui/")))}function gs(e){let t=e.mcpReq.envelope,r=m6(t?.[nG]);if(!r)try{let e,t=m4();r=t.clientInfo??(e=t.headers,m6({name:m7(e,"x-mcp-client-name"),version:m7(e,"x-mcp-client-version"),title:m7(e,"x-mcp-client-title"),websiteUrl:m7(e,"x-mcp-client-website-url"),description:m7(e,"x-mcp-client-description")}))}catch{}if(!r)try{r=hl().clientInfo}catch{}return r}function gl(e,t=!1){let r=[...e];return(e,a,i)=>hi(a,gs(a),async()=>{if(0===r.length)return i();let t=Object.freeze({...ha(),...e,params:Object.freeze({...e.params})}),a=-1,n=async e=>{if(e<=a)throw Error("MCP middleware next() can only be called once");a=e;let o=r[e];return o?o(t,()=>n(e+1)):i()};return n(0)},t)}function gc(e,t=new WeakMap){if(null===e||"object"!=typeof e)return e;let r=Object.getPrototypeOf(e);if(!Array.isArray(e)&&r!==Object.prototype&&null!==r)return e;if(t.has(e))return t.get(e);let a=Array.isArray(e)?[]:Object.create(r);for(let[r,i]of(t.set(e,a),Object.entries(e)))Object.defineProperty(a,r,{value:gc(i,t),enumerable:!0,configurable:!0,writable:!0});return Object.freeze(a)}let gu=new Set(["tools/list","prompts/get","prompts/list","resources/read","resources/list","resources/templates/list","completion/complete"]);function gd(e){return e.endsWith(".tsx")}function gp(e){let t={};return!function e(r,a=""){if(r&&"object"==typeof r)for(let[i,n]of Object.entries(r)){let r=a?`${a}/${i}`:i;!n||"object"!=typeof n||Array.isArray(n)||n instanceof Date||n instanceof RegExp?t[r]=n:e(n,r)}}(e),t}let gm=["ui/resourceUri","resourceUri","visibility"],gh=["prefersBorder","domain","csp","permissions","connectDomains","resourceDomains","frameDomains","baseUriDomains"];function gf(e){return"object"==typeof e&&null!==e&&Object.entries(e).every(([e,t])=>"string"==typeof e&&"object"==typeof t&&null!==t&&"parse"in t&&"function"==typeof t.parse)}function gg(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}function gy(e,t,r){return e.names?.includes(t)===!0||e.tags?.some(e=>r.includes(e))===!0}function gv(e,t){return t?new Map([...e].filter(([e,{metadata:r}])=>{if(r?.enabled===!1)return!1;let a=r?.name??gg(e),i=r?.tags??[];return(!t.include||gy(t.include,a,i))&&(!t.exclude||!gy(t.exclude,a,i))})):e}function g_(e){if("string"!=typeof e)return;let t=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/.exec(e);if(!(!t||"ff"===t[1]||/^0+$/.test(t[2])||/^0+$/.test(t[3]))&&("00"!==t[1]||void 0===t[5]))return{trace:{id:t[2]},parent:{id:t[3]}}}function gb(e){return Error(`[xmcp] Invalid prompt file: ${e}
82
+ -> Default export must be a prompt handler function.`)}let gS=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load prompt file: ${t}
83
+ -> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} prompt${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function g$(e){return Error(`[xmcp] Invalid resource file: ${e}
84
+ -> Default export must be a resource handler function.`)}let gw=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load resource file: ${t}
85
+ -> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} resource${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function gR(e){let t=e.replace(/\\/g,"/");if(!t)throw Error("Invalid tool path: path is empty");let r=t.replace(/\.[^/.]+$/,"").replace(/\//g,"_");return{normalizedPath:t,baseName:r}}function gk(e){let t=e.split("/").filter(e=>""!==e),r=t.findIndex(e=>e.match(/^\(.+\)$/));if(-1===r)return null;let a=t[t.length-1];if(a&&a.match(/^\[.+\]\.ts$/))return null;let i=t[r].slice(1,-1),n=t.slice(r+1),o=n[n.length-1];if(o&&o.includes(".")){let e=o.split(".")[0];"index"!==e?n[n.length-1]=e:n.pop()}let s=[],l=[],c=n.map(e=>{if(!e.match(/^\[.+\]$/))return l.push(e),e;{let t=e.slice(1,-1);return s.push(t),`{${t}}`}}),u=`${i}://${c.join("/")}`,d=s.length>0?"template":"direct";return{filePath:e,uriTemplate:u,scheme:i,parameters:s,pathSegments:l,type:d}}let gx={ttlMs:0,cacheScope:"private"},gP=fq({cursor:fN().optional()}).passthrough().optional(),gE=fq({uri:fN()}).passthrough();function gT({uri:e,frontmatter:t,files:r}){return{uri:e,frontmatter:t,resources:r.map(({uri:e,digest:t,size:r})=>({uri:e,digest:t,size:r}))}}function gj(e){return Error(`[xmcp] Invalid tool file: ${e}
86
+ -> Default export must be a tool handler function.`)}let gO=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load tool file: ${t}
87
+ -> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} tool${1===i?"":"s"} skipped due to empty files or missing default exports`)}}(),gC=INJECTED_TOOLS,gI=INJECTED_PROMPTS,gN=INJECTED_RESOURCES,gq="u"<typeof INJECTED_SKILLS?[]:INJECTED_SKILLS??[],gA=SERVER_INFO,gz=HTTP_CONFIG,gM=HTTP_CORS_CONFIG,gL=(I=function(e,t={}){var r;let{legacy:a,onerror:i,responseMode:n}=t,o=p0(t.maxRequestBodySize);if("function"==typeof a)throw TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.");let s=new Set,l=!1,u=e=>{try{i?.(e)}catch{}},h=t.bus??new pW(u),f={toolsChanged:()=>h.publish({kind:"tools_list_changed"}),promptsChanged:()=>h.publish({kind:"prompts_list_changed"}),resourcesChanged:()=>h.publish({kind:"resources_list_changed"}),resourceUpdated:e=>h.publish({kind:"resource_updated",uri:e})},g=function(e){let{bus:t,onerror:r}=e,a=e.maxSubscriptions??1024,i=e.keepAliveMs??15e3,n=new Set;return{serve:function(e,o,s,l){let c,u,d,p,m,h,f;if(n.size>=a)return r?.(Error(`subscriptions/listen refused: subscription limit reached (${a})`)),pY(e.id,-32603,"Subscription limit reached");let g=(m=cM(cz).validateRequest("subscriptions/listen",e)).ok?m.value.params?.notifications:void 0;if(void 0===g)return pY(e.id,-32602,"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter");let y=(h={},f=e=>void 0===s||!0===e,!0===g.toolsListChanged&&f(s?.tools?.listChanged)&&(h.toolsListChanged=!0),!0===g.promptsListChanged&&f(s?.prompts?.listChanged)&&(h.promptsListChanged=!0),!0===g.resourcesListChanged&&f(s?.resources?.listChanged)&&(h.resourcesListChanged=!0),void 0!==g.resourceSubscriptions&&g.resourceSubscriptions.length>0&&f(s?.resources?.subscribe)&&(h.resourceSubscriptions=[...g.resourceSubscriptions]),h),v=e.id,_=new TextEncoder,b=!1,S=e=>{if(!b)try{c.enqueue(_.encode(e))}catch(e){r?.(e instanceof Error?e:Error(String(e)))}},$=(e,t)=>{S(`event: message
88
88
  data: ${JSON.stringify({jsonrpc:"2.0",method:e,params:t})}
89
89
 
90
90
  `)},w=e=>{if(!b){e&&S(`event: message
91
91
  data: ${JSON.stringify({jsonrpc:"2.0",id:v,result:{resultType:"complete",_meta:{[nX]:v,[nW]:l}}})}
92
92
 
93
- `),b=!0;try{u?.()}catch(e){r?.(e instanceof Error?e:Error(String(e)))}void 0!==d&&clearInterval(d),p?.(),n.delete(w);try{c.close()}catch{}}},R=new ReadableStream({start(e){c=e;let r=pX({method:"notifications/subscriptions/acknowledged",params:{notifications:y}},v);($(r.method,r.params),0===Object.keys(y).length)?w(!0):(u=t.subscribe(e=>{if(b||!function(e,t){switch(t.kind){case"tools_list_changed":return!0===e.toolsListChanged;case"prompts_list_changed":return!0===e.promptsListChanged;case"resources_list_changed":return!0===e.resourcesListChanged;case"resource_updated":return void 0!==e.resourceSubscriptions&&e.resourceSubscriptions.includes(t.uri)}}(y,e))return;let t=pX(function(e){switch(e.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed",...void 0!==e.params&&{params:e.params}};case"prompts_list_changed":return{method:"notifications/prompts/list_changed",...void 0!==e.params&&{params:e.params}};case"resources_list_changed":return{method:"notifications/resources/list_changed",...void 0!==e.params&&{params:e.params}};case"resource_updated":return{method:"notifications/resources/updated",params:{...e.params,uri:e.uri}}}}(e),v);$(t.method,t.params)}),d=pE(i,()=>S(": keepalive\n\n")),n.add(w))},cancel(){w(!1)}});if(void 0!==o)if(o.aborted)w(!1);else{let e=()=>w(!1);o.addEventListener("abort",e,{once:!0}),p=()=>o.removeEventListener("abort",e)}return new Response(R,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let e of n)e(!0)},get openCount(){return n.size}}}({bus:h,maxSubscriptions:t.maxSubscriptions??1024,keepAliveMs:t.keepAliveMs??15e3,onerror:u});"json"===n&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let y="reject"===a?void 0:(r=t.keepAliveMs,async(t,a)=>{if("POST"!==t.method.toUpperCase())return p4(405,-32e3,"Method not allowed.");try{let i=await e({era:"legacy",...a?.authInfo!==void 0&&{authInfo:a.authInfo},requestInfo:t}),n=new p2({sessionIdGenerator:void 0,...void 0!==r&&{keepAliveMs:r},...void 0!==o&&{maxRequestBodySize:o}});await i.connect(n);let s=()=>{n.close().catch(()=>{}),i.close().catch(()=>{})};t.signal?.addEventListener("abort",s,{once:!0});let l=await n.handleRequest(t,{...a?.authInfo!==void 0&&{authInfo:a.authInfo},...a?.parsedBody!==void 0&&{parsedBody:a.parsedBody}});if(null===l.body||"text/event-stream"!==uM(l.headers.get("content-type")))return s(),l;let c=l.body.getReader(),u=!1,d=()=>{u||(u=!0,s())},p=new ReadableStream({pull:async e=>{try{let{done:t,value:r}=await c.read();if(t){d(),e.close();return}void 0!==r&&e.enqueue(r)}catch(t){d(),e.error(t)}},cancel:e=>(d(),c.cancel(e).catch(()=>{}))});return new Response(p,{status:l.status,statusText:l.statusText,headers:l.headers})}catch(e){try{u?.(p5(e))}catch{}return p6(p9(a?.parsedBody))}});return{fetch:async(r,a)=>{if(l)throw Error("This MCP handler has been closed");try{return await async function(r,a){let i=a?.authInfo;if("POST"===r.method.toUpperCase()&&!uL(r.headers.get("content-type")))return u(Error("Unsupported Media Type: Content-Type must be application/json")),p4(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let l=await async function(e,t,r=!0,a=4194304){let i,n=e.method.toUpperCase(),o=t,s=e,l=!1;if("POST"===n){if(void 0===o){let t;r&&(s=e.clone());try{let r=await p1(e,a);if(r.tooLarge)return{step:"body-too-large"};t=r.text}catch{return{step:"unreadable-body"}}try{i=0===t.length?void 0:JSON.parse(t)}catch{l=!0}l||void 0===i||(o=i)}else i=o;if(l||void 0===i)return{step:"no-json-body",forwardRequest:s}}return{step:"classified",outcome:function(e){if("POST"!==(e={...e,...void 0!==e.protocolVersionHeader&&{protocolVersionHeader:us(e.protocolVersionHeader)},...void 0!==e.mcpMethodHeader&&{mcpMethodHeader:us(e.mcpMethodHeader)},...void 0!==e.mcpNameHeader&&{mcpNameHeader:us(e.mcpNameHeader)}}).httpMethod.toUpperCase())return{kind:"legacy",reason:"http-method"};let t=e.body;if(Array.isArray(t)){if(0===t.length)return ui("jsonrpc-shape","empty-batch",400,new cv(cy.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let e of t){if(cJ(ul(e)?e.params:void 0))return ui("jsonrpc-shape","batch-with-modern-element",400,new cv(cy.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(cW(e)||cY(e)||cX(e)||cQ(e)))return ui("jsonrpc-shape","batch-with-invalid-element",400,new cv(cy.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}return cX(t)||cQ(t)?{kind:"legacy",reason:"response"}:ul(t)&&cW(t)?function(e,t){let r=t.params,a=t.method,i=e.protocolVersionHeader,n=void 0!==i&&i>=lX;if("initialize"===a&&!function(e){if(!cJ(e))return!1;let t=cB(e);if(void 0===t||!(t>=lX))return!1;let r=cH(e);return void 0!==r&&0===cK(r).length}(r)){if(n)return un("initialize-with-modern-header",i,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let e=ul(r)&&"string"==typeof r.protocolVersion?r.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...void 0!==e&&{requestedVersion:e}}}if(cJ(r)){let n=cH(r),o=(void 0===n?[]:cK(n))[0];if(void 0!==o)return ui("envelope","envelope-invalid",400,new cv(cy.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${o.key}: ${o.problem}`,{envelope:o}),!0);let s=cB(r);return void 0!==i&&void 0!==s&&i!==s?un("header-body-version-mismatch",i,`the body envelope names protocol version ${s} but the MCP-Protocol-Version header names ${i}`):void 0!==e.mcpMethodHeader&&e.mcpMethodHeader!==a?un("method-header-mismatch",e.mcpMethodHeader,`the body names method ${a} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:t,classification:uc(s)}}if(n){let e=cH(r),t=cK(e??{}).filter(e=>"missing"===e.problem).map(e=>e.key),a=void 0===e?["_meta"]:t.length>0?t:[nK];return ui("envelope","modern-header-without-claim",400,new cv(cy.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${i}, but the request is missing the required per-request envelope key(s): ${a.join(", ")}`,{envelope:{missing:a}}),!0)}return{kind:"legacy",reason:"no-claim",...void 0!==i&&{requestedVersion:i}}}(e,t):ul(t)&&cY(t)?function(e,t){let r=t.params,a=t.method,i=e.protocolVersionHeader,n=void 0!==i&&i>=lX;if(cJ(r)){let n=cB(r);if(void 0===n){let e=cH(r),t=(void 0===e?[]:cK(e)).find(e=>e.key===nK)??{key:nK,problem:"expected a protocol version string"};return ui("envelope","notification-envelope-invalid",400,new cv(cy.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${t.key}: ${t.problem}`,{envelope:t}),!0)}if(void 0!==i&&i!==n)return un("notification-header-body-version-mismatch",i,`the notification envelope names protocol version ${n} but the MCP-Protocol-Version header names ${i}`);let o=uc(n);return"modern"===o.era&&void 0!==e.mcpMethodHeader&&e.mcpMethodHeader!==a?un("notification-method-header-mismatch",e.mcpMethodHeader,`the notification body names method ${a} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:t,classification:o}}return n?void 0!==e.mcpMethodHeader&&e.mcpMethodHeader!==a?un("notification-method-header-mismatch",e.mcpMethodHeader,`the notification body names method ${a} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:t,classification:{era:"modern",revision:i}}:{kind:"legacy",reason:"notification",...void 0!==i&&{requestedVersion:i}}}(e,t):ui("jsonrpc-shape","invalid-json-rpc-body",400,new cv(cy.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}({httpMethod:n,...p7(e),...void 0!==i&&{body:i}}),body:i,parsedBody:o,forwardRequest:s}}(r,a?.parsedBody,!0,o);if("unreadable-body"===l.step)return p4(400,-32700,"Parse error: the request body could not be read");if("body-too-large"===l.step)return p4(413,-32e3,pQ(o));if("no-json-body"===l.step)return void 0!==y?y(l.forwardRequest,{...void 0!==i&&{authInfo:i}}):p4(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:h,body:f,parsedBody:v,forwardRequest:_}=l;try{switch(h.kind){case"reject":return u(Error(`Rejected inbound request (${h.cell}): ${h.message}`)),p3(h,p9(f));case"modern":return await async function(r,a,i){var o,l;let h=r.classification.revision;if(void 0===h||!lQ.includes(h)){let e=new cS({supported:[...lQ],requested:h??"unknown"});return u(e),p4(400,e.code,e.message,e.data,p9(r.message))}let f=function(e,t){if("request"!==t.messageKind)return;let r=t.message.method;if(void 0===e.protocolVersionHeader){let e=t.classification.revision;return un("version-header-missing","(missing)",void 0===e?"the body carries a modern per-request envelope but the required MCP-Protocol-Version header is absent":`the body envelope names protocol version ${e} but the required MCP-Protocol-Version header is absent`,"standard-header-validation")}if(void 0===e.mcpMethodHeader)return un("method-header-missing","(missing)",`the body names method ${r} but the required Mcp-Method header is absent`,"standard-header-validation");let a=function(e,t){let r=Object.hasOwn(uo,e)?uo[e]:void 0;if(void 0===r)return;let a=ul(t)?t[r]:void 0;return{field:r,value:"string"==typeof a?a:void 0}}(r,t.message.params);if(void 0===a)return;let{field:i,value:n}=a;if(void 0===e.mcpNameHeader){if(void 0===n)return;return un("name-header-missing","(missing)",`the body carries params.${i}="${n}" but the required Mcp-Name header is absent`,"standard-header-validation")}let o=us(e.mcpNameHeader),s=ue(o);return void 0===s?un("name-header-invalid-encoding",o,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==n&&s!==n?un("name-header-mismatch",o,`the body carries params.${i}="${n}" but the Mcp-Name header names "${s}"`,"standard-header-validation"):void 0}({httpMethod:a.method,...p7(a)},r);if(void 0!==f)return u(Error(`Rejected inbound request (${f.cell}): ${f.message}`)),p3(f,p9(r.message));let y="request"===r.messageKind?cH(r.message.params):void 0,v=y?.[nY];if("request"===r.messageKind){let e=Object.hasOwn(lG,o=r.message.method)?lG[o]:void 0;if(void 0!==e){let t=lY(e,v);if(void 0!==t){let e=new c$({requiredCapabilities:t});return u(e),p4(ua[e.code]??400,e.code,e.message,e.data,r.message.id)}}}let _=await e({era:"modern",...void 0!==i&&{authInfo:i},requestInfo:a}),b=_ instanceof pZ?_.server:_;if(p8(b),"request"===r.messageKind&&"subscriptions/listen"===r.message.method){let e=b.getCapabilities(),t=m(b);return _.close().catch(u),g.serve(r.message,a.signal,e,t)}if("request"===r.messageKind&&"tools/call"===r.message.method&&_ instanceof pZ){let e=r.message.params,t="string"==typeof e?.name?e.name:void 0,i=void 0===t?void 0:_.toolInputSchemaJson(t);if(void 0!==i){let t=c4(i);if(void 0!==t.declarations&&t.declarations.length>0){let i=function(e,t,r){for(let a of e){let e=`Mcp-Param-${a.headerName}`,i=r.get(e),n=function(e,t){let r=e;for(let e of t){if(null===r||"object"!=typeof r)return;r=r[e]}return r}(t,a.path);if(null==n)continue;let o=function(e){if("string"==typeof e)return e;if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}(n);if(void 0===o)continue;if(null===i)return ut("param-header-missing",e,`the body carries ${c6(a.path)}=${JSON.stringify(n)} but the ${e} header is absent`);let s=ue(i);if(void 0===s)return ut("param-header-invalid-encoding",e,`the ${e} header carries an invalid Base64 sentinel value`);if(!(("integer"===a.type||"number"===a.type)&&c7.test(s)&&"number"==typeof n?Number(s)===n:s===o))return ut("param-header-mismatch",e,`the ${e} header decodes to ${JSON.stringify(s)} but the body carries ${c6(a.path)}=${JSON.stringify(n)}`)}}(t.declarations,e?.arguments,a.headers);if(void 0!==i)return _.close().catch(u),u(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),p3(i,r.message.id)}}}if("request"===r.messageKind&&_ instanceof pZ)try{let e=await pC([r.message],i,e=>_.resolveScopeChallenge(e));if(void 0!==e)return _.close().catch(u),pN(e,pI(i))}catch(e){return _.close().catch(u),u(p5(e)),p6(r.message.id)}p8(b),c(b,h),p(b,lQ),void 0!==y&&(l={clientInfo:y[nG],clientCapabilities:v},d(b,l));let S=b.onclose;s.add(b);let $=()=>{s.delete(b),b.onclose===$&&(b.onclose=S),S?.()};b.onclose=$;try{let e=await async function(e,t,r){let a=new pT({classification:r.classification,...void 0!==r.responseMode&&{responseMode:r.responseMode},...void 0!==r.keepAliveMs&&{keepAliveMs:r.keepAliveMs}});return await e.connect(a),a.handleMessage(t,{...void 0!==r.request&&{request:r.request},...void 0!==r.authInfo&&{authInfo:r.authInfo}})}(_,r.message,{classification:r.classification,request:a,...void 0!==i&&{authInfo:i},...void 0!==n&&{responseMode:n},...void 0!==t.keepAliveMs&&{keepAliveMs:t.keepAliveMs}});return"notification"===r.messageKind&&queueMicrotask(()=>void b.close().catch(()=>{})),e}catch(e){if(e instanceof lK&&e.code===lB.ConnectionClosed)return new Response(null,{status:499});return await b.close().catch(()=>{}),s.delete(b),u(p5(e)),p6(p9(r.message))}}(h,r,i);case"legacy":return await async function(e,t,r,a){if(void 0!==y)return y(t,{...void 0!==r&&{authInfo:r},...void 0!==a&&{parsedBody:a}});let i=function(e,t){switch(e.reason){case"http-method":return ui("http-method","modern-only-method-not-allowed",405,new cv(-32e3,"Method not allowed."),!0);case"batch":return ui("jsonrpc-shape","modern-only-batch-not-supported",400,new cv(cy.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return ui("jsonrpc-shape","modern-only-response-post",400,new cv(cy.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let r=e.requestedVersion;return ui("era-classification","modern-only-missing-envelope",400,void 0===r?new cv(cy.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...t]}):new cS({supported:[...t],requested:r}),!0)}}}(e,lQ);return void 0===i?new Response(null,{status:202}):(u(Error(`Rejected 2025-era request on a modern-only endpoint (${i.cell}): ${i.message}`)),p3(i,p9(a)))}(h,_,i,v)}}catch(e){return u(p5(e)),p6(p9(f))}}(r,a)}catch(e){return u(p5(e)),p6(p9(a?.parsedBody))}},notify:f,bus:h,close:async()=>{l=!0,g.closeAll();let e=[...s].map(e=>e.close().catch(()=>{}));s.clear(),await Promise.all(e)}}}(async function(){let{instructions:e,...t}=gO,a=new pZ(t,{instructions:e}),i=async function(){let{toolModules:e,skippedTools:t}=await async function(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw gk(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw gk(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default tool handler."}}:{skipped:!1,path:e,toolModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.toolModule)}return{toolModules:t,skippedTools:r}}(gP);return gx(t),e}(),n=async function(){let{promptModules:e,skippedPrompts:t}=await async function(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw gf(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw gf(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default prompt handler."}}:{skipped:!1,path:e,promptModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.promptModule)}return{promptModules:t,skippedPrompts:r}}(gE);return gg(t),e}(),o=async function(){let{resourceModules:e,skippedResources:t}=await async function(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw gy(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw gy(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default resource handler."}}:{skipped:!1,path:e,resourceModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.resourceModule)}return{resourceModules:t,skippedResources:r}}(gT);return gv(t),e}(),[s,l,c]=await Promise.all([i,n,o]);return async function(e,t,a,i){let n=await INJECTED_MIDDLEWARE?.(),o=function(e){if(void 0===e)return[];let t=Array.isArray(e)?[...e]:[e];if(!t.every(e=>"function"==typeof e))throw Error("src/middleware.ts must export mcp as a function or an array of functions");return t}(n?.mcp),s=function(e){if(void 0!==e){if("function"!=typeof e)throw Error("src/middleware.ts must export authorize as a function");return e}}(n?.authorize),l="u">typeof OBSERVABILITY_CONFIG&&OBSERVABILITY_CONFIG.enabled?function(e=e=>console.error(e)){let t=new Map,r=[];function a(t){try{e(JSON.stringify({"@timestamp":new Date().toISOString(),...t}))}catch{}}return{middleware:async(e,i)=>{let n,o,s;if("tools/call"!==e.method&&"prompts/get"!==e.method&&"resources/read"!==e.method)return i();try{o=performance.now(),n={log:{level:"info"},...function(e){let t=e.http?.headers.traceparent;if("string"!=typeof t)return{};let r=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/.exec(t);return!r||"ff"===r[1]||/^0+$/.test(r[2])||/^0+$/.test(r[3])||"00"===r[1]&&void 0!==r[5]?{}:{trace:{id:r[2]},parent:{id:r[3]}}}(e),transaction:{id:crypto.randomUUID()},...e.http?{http:{request:{id:e.http.id}}}:{},xmcp:{method:e.method,component:"resources/read"===e.method?function(e){try{let a=new URL(e).href;return t.get(a)??r.find(({template:e})=>e.uriTemplate.match(a))?.name??"unknown"}catch{return"unknown"}}(e.params.uri):e.params.name}}}catch{return i()}a({...n,event:{kind:"event",category:["api"],type:["start"],action:"execution.start"}});let l="unknown";try{let t=await i();try{l=e.signal.aborted?"cancelled":c0(t)?"input_required":"isError"in t&&!0===t.isError?"failure":"success","failure"===l&&(s={message:"Operation returned an error result"})}catch{}return t}catch(t){throw s={message:"cancelled"==(l=e.signal.aborted?"cancelled":"failure")?"Operation cancelled":"Operation threw an exception"},t}finally{try{a({...n,log:{level:"failure"===l?"error":"info"},event:{kind:"event",category:["api"],type:["end"],action:"execution.end",duration:Math.round((performance.now()-o)*1e6),outcome:"success"===l?"success":"failure"===l?"failure":"unknown"},xmcp:{...n.xmcp,status:l},...s?{error:s}:{}})}catch{}}},registerResource(e,a){try{"string"==typeof a?t.set(new URL(a).href,e):r.push({name:e,template:a})}catch{}}}}():void 0;l&&o.unshift(l.middleware),ht.clear();let c="u"<typeof COMPONENTS_CONFIG?void 0:COMPONENTS_CONFIG;return!function(e,t,r,a){let i=e.server,n=i.setRequestHandler,o=a?{tools:new Map,prompts:new Map,resources:new Map,templates:new Map,uiOwners:new Map}:void 0,s=a&&o?function(e,t){let r=async(t,r,a)=>!r||await e(t,r,a)===!0;async function a(e,t,a){if(!Array.isArray(t))return t;let i=await Promise.all(t.map(t=>r(e,a(t),"list")));return t.filter((e,t)=>i[t])}return async(e,i)=>{switch(e.method){case"tools/call":{let{name:a}=e.params;if(!await r(e,t.tools.get(a),"call"))throw new cv(cy.InvalidParams,`Tool ${a} not found`);return i()}case"prompts/get":{let{name:a}=e.params;if(!await r(e,t.prompts.get(a),"get"))throw new cv(cy.InvalidParams,`Prompt ${a} not found`);return i()}case"resources/read":{let{uri:a}=e.params;if(!await r(e,ho(t,a),"read"))throw new c_(a);return i()}case"completion/complete":{let{ref:a}=e.params,n="ref/prompt"===a.type?t.prompts.get(a.name):[...t.templates.values()].find(({component:e})=>e.uriTemplate===a.uri)?.component??t.uiOwners.get(a.uri)??t.resources.get(a.uri);if(!await r(e,n,"complete"))throw new cv(cy.InvalidParams,"ref/prompt"===a.type?`Prompt ${a.name} not found`:`Resource template ${a.uri} not found`);return i()}case"tools/list":{let r=await i();return{...r,tools:await a(e,r.tools,e=>t.tools.get(e.name))}}case"prompts/list":{let r=await i();return{...r,prompts:await a(e,r.prompts,e=>t.prompts.get(e.name))}}case"resources/list":{let r=await i();return{...r,resources:await a(e,r.resources,e=>ho(t,e.uri,!0))}}case"resources/templates/list":{let r=await i();return{...r,resourceTemplates:await a(e,r.resourceTemplates,e=>t.templates.get(e.name)?.component)}}default:return i()}}}(a,o):void 0,l=hI(s?[s,...t]:t),c=s?hI([s]):void 0;i.setRequestHandler=(e,...t)=>{if(1===t.length&&"function"==typeof t[0]){let r=t[0];hq.has(e)?t[0]=(e,t)=>l({method:e.method,params:e.params??{}},t,()=>r(e,t)):"tools/call"===e&&c&&o&&(t[0]=(e,t)=>{let a=o.tools.get(e.params.name);return a?c({method:"tools/call",params:{name:e.params.name,arguments:e.params.arguments??{}},tool:{metadata:a.metadata}},t,()=>r(e,t)):r(e,t)})}Reflect.apply(n,i,[e,...t])};try{if(o){let t=async(e,t,r)=>{let i=o.resources.get(t);return!i||await a(e,i,r)===!0},i={registerTool:e.registerTool,registerPrompt:e.registerPrompt,registerResource:e.registerResource};e.registerTool=(t,r,...a)=>{let n=hN({name:t,description:r.description??"",annotations:r.annotations,icons:r.icons,tags:hn(r._meta),_meta:r._meta});return o.tools.set(t,Object.freeze({type:"tool",name:t,metadata:n})),Reflect.apply(i.registerTool,e,[t,r,...a])},e.registerPrompt=(t,r,...a)=>{let n=hN({name:t,title:r.title,description:r.description,icons:r.icons,tags:hn(r._meta),_meta:r._meta});return o.prompts.set(t,Object.freeze({type:"prompt",name:t,metadata:n})),Reflect.apply(i.registerPrompt,e,[t,r,...a])},e.registerResource=(t,r,a,...n)=>{let s=hN({name:t,title:a.title,description:a.description,icons:a.icons,mimeType:a.mimeType,tags:hn(a._meta),_meta:a._meta});if("string"==typeof r)o.resources.set(r,Object.freeze({type:"resource",name:t,uri:r,metadata:s}));else{let e=r.uriTemplate.toString();o.templates.set(t,{component:Object.freeze({type:"resourceTemplate",name:t,uriTemplate:e,metadata:s}),template:r})}return Reflect.apply(i.registerResource,e,[t,r,a,...n])};try{r(t)}finally{Object.assign(e,i)}for(let[e,t]of ht.getAll()){let r=o.tools.get(e);r&&o.uiOwners.set(t.uri,r)}}else r()}finally{i.setRequestHandler=n}}(e,o,n=>{var s,u;!function(e,t,r=[]){t.forEach((t,a)=>{var i,n;let o,s,l,c,u={name:gp(a),description:"No description provided"},{default:d,metadata:p,schema:m,outputSchema:h}=t;if("object"==typeof p&&null!==p&&Object.assign(u,p),!1===u.enabled)return;if("function"==typeof d&&"__x402"in d){let e=global.__XMCP_X402_REGISTRY;e&&e.set(u.name,d.__x402)}let f={};if(gd(m)?f=m:null!=m&&console.warn(`Invalid schema for tool "${u.name}" at ${a}. Expected Record<string, z.ZodType>`),null!=h)if(gd(h))o=h;else throw Error(`Invalid outputSchema for tool "${u.name}" at ${a}. Expected Record<string, z.ZodType>`);u.annotations={...u.annotations??{}},void 0===u.annotations.title&&(u.annotations.title=u.name),u._meta={...he(u)._meta};let g=hA(a),y=!!(i=u._meta)&&"object"==typeof i&&"ui"in i&&"object"==typeof i.ui||g,v=u._meta;if(y){let e=`ui://app/${u.name}.html`;u._meta.ui||(u._meta.ui={}),u._meta.ui.resourceUri||(u._meta.ui.resourceUri=e);let t=function(e){let t={},r={};if(e.ui&&"object"==typeof e.ui){let a=e.ui,i={},n={};for(let[e,t]of Object.entries(a))gc.includes(e)?i[e]=t:gu.includes(e)?n[e]=t:i[e]=t;Object.keys(i).length>0&&(t.ui=i),Object.keys(n).length>0&&(r.ui=n)}for(let[r,a]of Object.entries(e))"ui"!==r&&(t[r]=a);return{toolMeta:t,resourceMeta:r}}(v);v=t.toolMeta;let r=t.resourceMeta;r.ui=r.ui||{},r.ui.csp=r.ui.csp||{},r.ui.csp.resourceDomains=r.ui.csp.resourceDomains||[],r.ui.csp.resourceDomains.includes("https://esm.sh")||r.ui.csp.resourceDomains.push("https://esm.sh"),ht.add(u.name,{name:u.name,uri:e,handler:d,mimeType:"text/html;profile=mcp-app",_meta:r,toolPath:g?a:void 0})}let _=gl(v),b=y?_:void 0;s=hA(a)&&y?async(e,t)=>({content:[{type:"text",text:""}],_meta:b,structuredContent:{args:e}}):function(e,t,r,a="unknown-tool"){return async(i,n)=>{let o,s,l=e(i,(o=hC(n),s=function(e){if(!e)return;let t={};return e.headers.forEach((e,r)=>{t[r]=e}),t}(n.http?.req),{signal:n.mcpReq.signal,authInfo:n.http?.authInfo,sessionId:n.sessionId,_meta:n.mcpReq._meta,requestId:n.mcpReq.id,requestInfo:s?{headers:s}:void 0,clientInfo:o,sendNotification:e=>n.mcpReq.notify(e),sendRequest:(e,t,r)=>n.mcpReq.send(e,t,r),elicit:(e,t)=>(async function(e,t,r){let a=function(e){let t=e.mode??"form";if("url"===t)return function(e){let t;hv(e,"Elicitation request must be a plain object."),hy(e,hu,"URL elicitation"),h_(e.message,"URL elicitation requires a string message."),hb(e.elicitationId,"URL elicitation requires a non-empty elicitationId."),hb(e.url,"URL elicitation requires a non-empty URL.");try{t=new URL(e.url)}catch{throw Error("URL elicitation requires a valid http or https URL.")}if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error("URL elicitation requires a valid http or https URL.")}(e),e;if("form"!==t)throw Error(`Unsupported elicitation mode "${String(e.mode)}". Expected "form" or "url".`);return function(e){hv(e,"Elicitation request must be a plain object."),hy(e,hc,"Form elicitation"),h_(e.message,"Form elicitation requires a string message.");let t=e.requestedSchema;if(hv(t,"Form elicitation requires a flat object schema."),hy(t,hd,"Form elicitation schema"),"object"!==t.type)throw Error('Form elicitation schema must use type "object".');for(let[e,r]of(hv(t.properties,"Form elicitation schema requires a properties object."),Object.entries(t.properties)))!function(e,t){if(hv(t,`Form elicitation field "${e}" must be a plain object.`),hS(t.title,`Form elicitation field "${e}" title must be a string.`),hS(t.description,`Form elicitation field "${e}" description must be a string.`),"string"===t.type&&"enum"in t){var r,a;if(hy(t,hm,`Form elicitation field "${e}"`),hw(t.enum,`Form elicitation field "${e}" enum values must be strings.`),r=t.enumNames,a=`Form elicitation field "${e}" enumNames must be strings.`,void 0!==r&&hw(r,a),void 0!==t.enumNames&&t.enumNames.length!==t.enum.length)throw Error(`Form elicitation field "${e}" enumNames length must match enum length.`);if(hS(t.default,`Form elicitation field "${e}" default must be a string.`),void 0!==t.default&&!t.enum.includes(t.default))throw Error(`Form elicitation field "${e}" default must be one of its enum values.`);return}if("string"===t.type&&!("enum"in t)){hy(t,hp,`Form elicitation field "${e}"`),h$(t.minLength,`Form elicitation field "${e}" minLength must be a number.`),h$(t.maxLength,`Form elicitation field "${e}" maxLength must be a number.`),hS(t.default,`Form elicitation field "${e}" default must be a string.`);let r=t.format;if(hS(r,`Form elicitation field "${e}" format must be a string.`),void 0!==r&&!hg.has(r))throw Error(`Form elicitation field "${e}" format must be one of: ${Array.from(hg).join(", ")}.`);return}if("boolean"===t.type){if(hy(t,hh,`Form elicitation field "${e}"`),void 0!==t.default&&"boolean"!=typeof t.default)throw Error(`Form elicitation field "${e}" default must be a boolean.`);return}if("number"===t.type||"integer"===t.type){hy(t,hf,`Form elicitation field "${e}"`),h$(t.minimum,`Form elicitation field "${e}" minimum must be a number.`),h$(t.maximum,`Form elicitation field "${e}" maximum must be a number.`),h$(t.default,`Form elicitation field "${e}" default must be a number.`);return}throw Error(`Form elicitation field "${e}" uses unsupported type "${String(t.type)}". Supported types are string, boolean, number, integer, and string enums.`)}(e,r);if(void 0!==t.required){if(!Array.isArray(t.required)||t.required.some(e=>"string"!=typeof e))throw Error("Form elicitation schema required fields must be a string array.");for(let e of t.required)if(!(e in t.properties))throw Error(`Form elicitation schema required field "${e}" is not defined in properties.`)}}(e),{...e,mode:"form"}}(t);try{let t=await e.mcpReq.elicitInput(a,r);return{...t,content:t.content??void 0}}catch(e){if(e instanceof lK&&e.code===lB.MethodNotSupportedByProtocolVersion)throw Error("extra.elicit() is not available on protocol revision 2026-07-28: server-initiated elicitation was replaced by multi round-trip requests. Return inputRequired({ ... }) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw e}})(n,e,t),sample:(e,t)=>(async function(e,t,r){let a=function(e){hP(e,"Sampling request must be a plain object.");let t=Object.keys(e),r=t.filter(e=>hk.has(e));if(r.length>0)throw Error(`Sampling request key(s) not supported by xmcp yet: ${r.join(", ")}.`);let a=t.filter(e=>!hR.has(e));if(a.length>0)throw Error(`Sampling request includes unsupported key(s): ${a.join(", ")}.`);if(!Array.isArray(e.messages)||0===e.messages.length)throw Error("Sampling requires at least one message.");for(let[t,r]of e.messages.entries())!function(e,t){if(hP(t,`Sampling message at index ${e} must be a plain object.`),"user"!==t.role&&"assistant"!==t.role)throw Error(`Sampling message at index ${e} requires role "user" or "assistant".`);let r=t.content;hP(r,`Sampling message at index ${e} requires a content object.`);let a=r.type;if("string"!=typeof a||!hx.has(a))throw Error(`Sampling message at index ${e} uses unsupported content type "${String(a)}". Supported types are text, image, and audio.`);if("text"===a&&"string"!=typeof r.text)throw Error(`Sampling message at index ${e} requires string text content.`);if(("image"===a||"audio"===a)&&("string"!=typeof r.data||"string"!=typeof r.mimeType))throw Error(`Sampling message at index ${e} requires base64 data and a mimeType.`)}(t,r);if("number"!=typeof e.maxTokens)throw Error("Sampling requires a numeric maxTokens.");return e}(t);try{return await e.mcpReq.requestSampling(a,r)}catch(e){if(e instanceof lK&&e.code===lB.MethodNotSupportedByProtocolVersion)throw Error("extra.sample() is not available on protocol revision 2026-07-28: server-initiated sampling was replaced by multi round-trip requests. Return inputRequired({ ... }) with inputRequired.createMessage(...) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw e}})(n,e,t),inputResponses:n.mcpReq.inputResponses,requestState:n.mcpReq.requestState}));if(l instanceof Promise&&(l=await l),c0(l))return l;if("string"==typeof l||"number"==typeof l){if(r){let e=Object.entries(r);if(1===e.length){let[t,r]=e[0];try{return r.parse(l),{content:[{type:"text",text:"number"==typeof l?`${l}`:l}],structuredContent:{[t]:l}}}catch{}}}return hO(t)?{content:[{type:"text",text:""}],structuredContent:{args:i},_meta:t}:{content:[{type:"text",text:"number"==typeof l?`${l}`:l}]}}if(!r||!l||"object"!=typeof l||Array.isArray(l)||"structuredContent"in l||"content"in l&&Array.isArray(l.content)||"_meta"in l||"isError"in l||(hj(l,r,a,"returned data that does not match outputSchema"),l={structuredContent:l}),l&&"object"==typeof l&&"_meta"in l&&!("content"in l)&&!("structuredContent"in l)){let e=l._meta;if(hO(e))return{content:[{type:"text",text:""}],_meta:e}}if(!l||"object"!=typeof l){let e=null===l?"null":typeof l,t=void 0===l?"undefined":null===l?"null":"object"==typeof l?JSON.stringify(l,null,2):String(l);throw Error(`Tool handler must return a CallToolResult, string, or number. Got ${e}: ${t}
93
+ `),b=!0;try{u?.()}catch(e){r?.(e instanceof Error?e:Error(String(e)))}void 0!==d&&clearInterval(d),p?.(),n.delete(w);try{c.close()}catch{}}},R=new ReadableStream({start(e){c=e;let r=pX({method:"notifications/subscriptions/acknowledged",params:{notifications:y}},v);($(r.method,r.params),0===Object.keys(y).length)?w(!0):(u=t.subscribe(e=>{if(b||!function(e,t){switch(t.kind){case"tools_list_changed":return!0===e.toolsListChanged;case"prompts_list_changed":return!0===e.promptsListChanged;case"resources_list_changed":return!0===e.resourcesListChanged;case"resource_updated":return void 0!==e.resourceSubscriptions&&e.resourceSubscriptions.includes(t.uri)}}(y,e))return;let t=pX(function(e){switch(e.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed",...void 0!==e.params&&{params:e.params}};case"prompts_list_changed":return{method:"notifications/prompts/list_changed",...void 0!==e.params&&{params:e.params}};case"resources_list_changed":return{method:"notifications/resources/list_changed",...void 0!==e.params&&{params:e.params}};case"resource_updated":return{method:"notifications/resources/updated",params:{...e.params,uri:e.uri}}}}(e),v);$(t.method,t.params)}),d=pE(i,()=>S(": keepalive\n\n")),n.add(w))},cancel(){w(!1)}});if(void 0!==o)if(o.aborted)w(!1);else{let e=()=>w(!1);o.addEventListener("abort",e,{once:!0}),p=()=>o.removeEventListener("abort",e)}return new Response(R,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let e of n)e(!0)},get openCount(){return n.size}}}({bus:h,maxSubscriptions:t.maxSubscriptions??1024,keepAliveMs:t.keepAliveMs??15e3,onerror:u});"json"===n&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let y="reject"===a?void 0:(r=t.keepAliveMs,async(t,a)=>{if("POST"!==t.method.toUpperCase())return p4(405,-32e3,"Method not allowed.");try{let i=await e({era:"legacy",...a?.authInfo!==void 0&&{authInfo:a.authInfo},requestInfo:t}),n=new p2({sessionIdGenerator:void 0,...void 0!==r&&{keepAliveMs:r},...void 0!==o&&{maxRequestBodySize:o}});await i.connect(n);let s=()=>{n.close().catch(()=>{}),i.close().catch(()=>{})};t.signal?.addEventListener("abort",s,{once:!0});let l=await n.handleRequest(t,{...a?.authInfo!==void 0&&{authInfo:a.authInfo},...a?.parsedBody!==void 0&&{parsedBody:a.parsedBody}});if(null===l.body||"text/event-stream"!==uM(l.headers.get("content-type")))return s(),l;let c=l.body.getReader(),u=!1,d=()=>{u||(u=!0,s())},p=new ReadableStream({pull:async e=>{try{let{done:t,value:r}=await c.read();if(t){d(),e.close();return}void 0!==r&&e.enqueue(r)}catch(t){d(),e.error(t)}},cancel:e=>(d(),c.cancel(e).catch(()=>{}))});return new Response(p,{status:l.status,statusText:l.statusText,headers:l.headers})}catch(e){try{u?.(p5(e))}catch{}return p6(p9(a?.parsedBody))}});return{fetch:async(r,a)=>{if(l)throw Error("This MCP handler has been closed");try{return await async function(r,a){let i=a?.authInfo;if("POST"===r.method.toUpperCase()&&!uL(r.headers.get("content-type")))return u(Error("Unsupported Media Type: Content-Type must be application/json")),p4(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let l=await async function(e,t,r=!0,a=4194304){let i,n=e.method.toUpperCase(),o=t,s=e,l=!1;if("POST"===n){if(void 0===o){let t;r&&(s=e.clone());try{let r=await p1(e,a);if(r.tooLarge)return{step:"body-too-large"};t=r.text}catch{return{step:"unreadable-body"}}try{i=0===t.length?void 0:JSON.parse(t)}catch{l=!0}l||void 0===i||(o=i)}else i=o;if(l||void 0===i)return{step:"no-json-body",forwardRequest:s}}return{step:"classified",outcome:function(e){if("POST"!==(e={...e,...void 0!==e.protocolVersionHeader&&{protocolVersionHeader:us(e.protocolVersionHeader)},...void 0!==e.mcpMethodHeader&&{mcpMethodHeader:us(e.mcpMethodHeader)},...void 0!==e.mcpNameHeader&&{mcpNameHeader:us(e.mcpNameHeader)}}).httpMethod.toUpperCase())return{kind:"legacy",reason:"http-method"};let t=e.body;if(Array.isArray(t)){if(0===t.length)return ui("jsonrpc-shape","empty-batch",400,new cv(cy.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let e of t){if(cJ(ul(e)?e.params:void 0))return ui("jsonrpc-shape","batch-with-modern-element",400,new cv(cy.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(cW(e)||cY(e)||cX(e)||cQ(e)))return ui("jsonrpc-shape","batch-with-invalid-element",400,new cv(cy.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}return cX(t)||cQ(t)?{kind:"legacy",reason:"response"}:ul(t)&&cW(t)?function(e,t){let r=t.params,a=t.method,i=e.protocolVersionHeader,n=void 0!==i&&i>=lX;if("initialize"===a&&!function(e){if(!cJ(e))return!1;let t=cB(e);if(void 0===t||!(t>=lX))return!1;let r=cH(e);return void 0!==r&&0===cK(r).length}(r)){if(n)return un("initialize-with-modern-header",i,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let e=ul(r)&&"string"==typeof r.protocolVersion?r.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...void 0!==e&&{requestedVersion:e}}}if(cJ(r)){let n=cH(r),o=(void 0===n?[]:cK(n))[0];if(void 0!==o)return ui("envelope","envelope-invalid",400,new cv(cy.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${o.key}: ${o.problem}`,{envelope:o}),!0);let s=cB(r);return void 0!==i&&void 0!==s&&i!==s?un("header-body-version-mismatch",i,`the body envelope names protocol version ${s} but the MCP-Protocol-Version header names ${i}`):void 0!==e.mcpMethodHeader&&e.mcpMethodHeader!==a?un("method-header-mismatch",e.mcpMethodHeader,`the body names method ${a} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:t,classification:uc(s)}}if(n){let e=cH(r),t=cK(e??{}).filter(e=>"missing"===e.problem).map(e=>e.key),a=void 0===e?["_meta"]:t.length>0?t:[nK];return ui("envelope","modern-header-without-claim",400,new cv(cy.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${i}, but the request is missing the required per-request envelope key(s): ${a.join(", ")}`,{envelope:{missing:a}}),!0)}return{kind:"legacy",reason:"no-claim",...void 0!==i&&{requestedVersion:i}}}(e,t):ul(t)&&cY(t)?function(e,t){let r=t.params,a=t.method,i=e.protocolVersionHeader,n=void 0!==i&&i>=lX;if(cJ(r)){let n=cB(r);if(void 0===n){let e=cH(r),t=(void 0===e?[]:cK(e)).find(e=>e.key===nK)??{key:nK,problem:"expected a protocol version string"};return ui("envelope","notification-envelope-invalid",400,new cv(cy.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${t.key}: ${t.problem}`,{envelope:t}),!0)}if(void 0!==i&&i!==n)return un("notification-header-body-version-mismatch",i,`the notification envelope names protocol version ${n} but the MCP-Protocol-Version header names ${i}`);let o=uc(n);return"modern"===o.era&&void 0!==e.mcpMethodHeader&&e.mcpMethodHeader!==a?un("notification-method-header-mismatch",e.mcpMethodHeader,`the notification body names method ${a} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:t,classification:o}}return n?void 0!==e.mcpMethodHeader&&e.mcpMethodHeader!==a?un("notification-method-header-mismatch",e.mcpMethodHeader,`the notification body names method ${a} but the Mcp-Method header names ${e.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:t,classification:{era:"modern",revision:i}}:{kind:"legacy",reason:"notification",...void 0!==i&&{requestedVersion:i}}}(e,t):ui("jsonrpc-shape","invalid-json-rpc-body",400,new cv(cy.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}({httpMethod:n,...p7(e),...void 0!==i&&{body:i}}),body:i,parsedBody:o,forwardRequest:s}}(r,a?.parsedBody,!0,o);if("unreadable-body"===l.step)return p4(400,-32700,"Parse error: the request body could not be read");if("body-too-large"===l.step)return p4(413,-32e3,pQ(o));if("no-json-body"===l.step)return void 0!==y?y(l.forwardRequest,{...void 0!==i&&{authInfo:i}}):p4(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:h,body:f,parsedBody:v,forwardRequest:_}=l;try{switch(h.kind){case"reject":return u(Error(`Rejected inbound request (${h.cell}): ${h.message}`)),p3(h,p9(f));case"modern":return await async function(r,a,i){var o,l;let h=r.classification.revision;if(void 0===h||!lQ.includes(h)){let e=new cS({supported:[...lQ],requested:h??"unknown"});return u(e),p4(400,e.code,e.message,e.data,p9(r.message))}let f=function(e,t){if("request"!==t.messageKind)return;let r=t.message.method;if(void 0===e.protocolVersionHeader){let e=t.classification.revision;return un("version-header-missing","(missing)",void 0===e?"the body carries a modern per-request envelope but the required MCP-Protocol-Version header is absent":`the body envelope names protocol version ${e} but the required MCP-Protocol-Version header is absent`,"standard-header-validation")}if(void 0===e.mcpMethodHeader)return un("method-header-missing","(missing)",`the body names method ${r} but the required Mcp-Method header is absent`,"standard-header-validation");let a=function(e,t){let r=Object.hasOwn(uo,e)?uo[e]:void 0;if(void 0===r)return;let a=ul(t)?t[r]:void 0;return{field:r,value:"string"==typeof a?a:void 0}}(r,t.message.params);if(void 0===a)return;let{field:i,value:n}=a;if(void 0===e.mcpNameHeader){if(void 0===n)return;return un("name-header-missing","(missing)",`the body carries params.${i}="${n}" but the required Mcp-Name header is absent`,"standard-header-validation")}let o=us(e.mcpNameHeader),s=ue(o);return void 0===s?un("name-header-invalid-encoding",o,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==n&&s!==n?un("name-header-mismatch",o,`the body carries params.${i}="${n}" but the Mcp-Name header names "${s}"`,"standard-header-validation"):void 0}({httpMethod:a.method,...p7(a)},r);if(void 0!==f)return u(Error(`Rejected inbound request (${f.cell}): ${f.message}`)),p3(f,p9(r.message));let y="request"===r.messageKind?cH(r.message.params):void 0,v=y?.[nY];if("request"===r.messageKind){let e=Object.hasOwn(lG,o=r.message.method)?lG[o]:void 0;if(void 0!==e){let t=lY(e,v);if(void 0!==t){let e=new c$({requiredCapabilities:t});return u(e),p4(ua[e.code]??400,e.code,e.message,e.data,r.message.id)}}}let _=await e({era:"modern",...void 0!==i&&{authInfo:i},requestInfo:a}),b=_ instanceof pZ?_.server:_;if(p8(b),"request"===r.messageKind&&"subscriptions/listen"===r.message.method){let e=b.getCapabilities(),t=m(b);return _.close().catch(u),g.serve(r.message,a.signal,e,t)}if("request"===r.messageKind&&"tools/call"===r.message.method&&_ instanceof pZ){let e=r.message.params,t="string"==typeof e?.name?e.name:void 0,i=void 0===t?void 0:_.toolInputSchemaJson(t);if(void 0!==i){let t=c4(i);if(void 0!==t.declarations&&t.declarations.length>0){let i=function(e,t,r){for(let a of e){let e=`Mcp-Param-${a.headerName}`,i=r.get(e),n=function(e,t){let r=e;for(let e of t){if(null===r||"object"!=typeof r)return;r=r[e]}return r}(t,a.path);if(null==n)continue;let o=function(e){if("string"==typeof e)return e;if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}(n);if(void 0===o)continue;if(null===i)return ut("param-header-missing",e,`the body carries ${c6(a.path)}=${JSON.stringify(n)} but the ${e} header is absent`);let s=ue(i);if(void 0===s)return ut("param-header-invalid-encoding",e,`the ${e} header carries an invalid Base64 sentinel value`);if(!(("integer"===a.type||"number"===a.type)&&c7.test(s)&&"number"==typeof n?Number(s)===n:s===o))return ut("param-header-mismatch",e,`the ${e} header decodes to ${JSON.stringify(s)} but the body carries ${c6(a.path)}=${JSON.stringify(n)}`)}}(t.declarations,e?.arguments,a.headers);if(void 0!==i)return _.close().catch(u),u(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),p3(i,r.message.id)}}}if("request"===r.messageKind&&_ instanceof pZ)try{let e=await pC([r.message],i,e=>_.resolveScopeChallenge(e));if(void 0!==e)return _.close().catch(u),pN(e,pI(i))}catch(e){return _.close().catch(u),u(p5(e)),p6(r.message.id)}p8(b),c(b,h),p(b,lQ),void 0!==y&&(l={clientInfo:y[nG],clientCapabilities:v},d(b,l));let S=b.onclose;s.add(b);let $=()=>{s.delete(b),b.onclose===$&&(b.onclose=S),S?.()};b.onclose=$;try{let e=await async function(e,t,r){let a=new pT({classification:r.classification,...void 0!==r.responseMode&&{responseMode:r.responseMode},...void 0!==r.keepAliveMs&&{keepAliveMs:r.keepAliveMs}});return await e.connect(a),a.handleMessage(t,{...void 0!==r.request&&{request:r.request},...void 0!==r.authInfo&&{authInfo:r.authInfo}})}(_,r.message,{classification:r.classification,request:a,...void 0!==i&&{authInfo:i},...void 0!==n&&{responseMode:n},...void 0!==t.keepAliveMs&&{keepAliveMs:t.keepAliveMs}});return"notification"===r.messageKind&&queueMicrotask(()=>void b.close().catch(()=>{})),e}catch(e){if(e instanceof lK&&e.code===lB.ConnectionClosed)return new Response(null,{status:499});return await b.close().catch(()=>{}),s.delete(b),u(p5(e)),p6(p9(r.message))}}(h,r,i);case"legacy":return await async function(e,t,r,a){if(void 0!==y)return y(t,{...void 0!==r&&{authInfo:r},...void 0!==a&&{parsedBody:a}});let i=function(e,t){switch(e.reason){case"http-method":return ui("http-method","modern-only-method-not-allowed",405,new cv(-32e3,"Method not allowed."),!0);case"batch":return ui("jsonrpc-shape","modern-only-batch-not-supported",400,new cv(cy.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return ui("jsonrpc-shape","modern-only-response-post",400,new cv(cy.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let r=e.requestedVersion;return ui("era-classification","modern-only-missing-envelope",400,void 0===r?new cv(cy.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...t]}):new cS({supported:[...t],requested:r}),!0)}}}(e,lQ);return void 0===i?new Response(null,{status:202}):(u(Error(`Rejected 2025-era request on a modern-only endpoint (${i.cell}): ${i.message}`)),p3(i,p9(a)))}(h,_,i,v)}}catch(e){return u(p5(e)),p6(p9(f))}}(r,a)}catch(e){return u(p5(e)),p6(p9(a?.parsedBody))}},notify:f,bus:h,close:async()=>{l=!0,g.closeAll();let e=[...s].map(e=>e.close().catch(()=>{}));s.clear(),await Promise.all(e)}}}(async function(){let e=function(){let{instructions:e,...t}=gA;return new pZ(t,{instructions:e,cacheHints:"u"<typeof CACHE_HINTS_CONFIG?void 0:CACHE_HINTS_CONFIG})}(),t=async function(){let{toolModules:e,skippedTools:t}=await async function(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw gj(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw gj(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default tool handler."}}:{skipped:!1,path:e,toolModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.toolModule)}return{toolModules:t,skippedTools:r}}(gC);return gO(t),e}(),a=async function(){let{promptModules:e,skippedPrompts:t}=await async function(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw gb(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw gb(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default prompt handler."}}:{skipped:!1,path:e,promptModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.promptModule)}return{promptModules:t,skippedPrompts:r}}(gI);return gS(t),e}(),i=async function(){let{resourceModules:e,skippedResources:t}=await async function(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw g$(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw g$(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default resource handler."}}:{skipped:!1,path:e,resourceModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.resourceModule)}return{resourceModules:t,skippedResources:r}}(gN);return gw(t),e}(),[n,o,s]=await Promise.all([t,a,i]);return async function(e,t,a,i){let n=await INJECTED_MIDDLEWARE?.(),o=function(e){if(void 0===e)return[];let t=Array.isArray(e)?[...e]:[e];if(!t.every(e=>"function"==typeof e))throw Error("src/middleware.ts must export mcp as a function or an array of functions");return t}(n?.mcp),s=function(e){if(void 0!==e){if("function"!=typeof e)throw Error("src/middleware.ts must export authorize as a function");return e}}(n?.authorize),l="u">typeof OBSERVABILITY_CONFIG&&OBSERVABILITY_CONFIG.enabled?function(e=e=>console.error(e)){let t=new Map,r=[];function a(t){try{e(JSON.stringify({"@timestamp":new Date().toISOString(),...t}))}catch{}}return{middleware:async(e,i)=>{let n,o,s;if("tools/call"!==e.method&&"prompts/get"!==e.method&&"resources/read"!==e.method)return i();try{o=performance.now(),n={log:{level:"info"},...g_(e._meta?.traceparent)??g_(e.http?.headers.traceparent)??{},transaction:{id:crypto.randomUUID()},...e.http?{http:{request:{id:e.http.id}}}:{},xmcp:{method:e.method,component:"resources/read"===e.method?function(e){try{let a=new URL(e).href;return t.get(a)??r.find(({template:e})=>e.uriTemplate.match(a))?.name??"unknown"}catch{return"unknown"}}(e.params.uri):e.params.name}}}catch{return i()}a({...n,event:{kind:"event",category:["api"],type:["start"],action:"execution.start"}});let l="unknown";try{let t=await i();try{l=e.signal.aborted?"cancelled":c0(t)?"input_required":"isError"in t&&!0===t.isError?"failure":"success","failure"===l&&(s={message:"Operation returned an error result"})}catch{}return t}catch(t){throw s={message:"cancelled"==(l=e.signal.aborted?"cancelled":"failure")?"Operation cancelled":"Operation threw an exception"},t}finally{try{a({...n,log:{level:"failure"===l?"error":"info"},event:{kind:"event",category:["api"],type:["end"],action:"execution.end",duration:Math.round((performance.now()-o)*1e6),outcome:"success"===l?"success":"failure"===l?"failure":"unknown"},xmcp:{...n.xmcp,status:l},...s?{error:s}:{}})}catch{}}},registerResource(e,a){try{"string"==typeof a?t.set(new URL(a).href,e):r.push({name:e,template:a})}catch{}}}}():void 0;l&&o.unshift(l.middleware),ht.clear();let c="u"<typeof COMPONENTS_CONFIG?void 0:COMPONENTS_CONFIG;return!function(e,t,r,a){let i=e.server,n=i.setRequestHandler,o=a?{tools:new Map,prompts:new Map,resources:new Map,templates:new Map,uiOwners:new Map}:void 0,s=a&&o?function(e,t){let r=async(t,r,a)=>!r||await e(t,r,a)===!0;async function a(e,t,a){if(!Array.isArray(t))return t;let i=await Promise.all(t.map(t=>r(e,a(t),"list")));return t.filter((e,t)=>i[t])}return async(e,i)=>{switch(e.method){case"tools/call":{let{name:a}=e.params;if(!await r(e,t.tools.get(a),"call"))throw new cv(cy.InvalidParams,`Tool ${a} not found`);return i()}case"prompts/get":{let{name:a}=e.params;if(!await r(e,t.prompts.get(a),"get"))throw new cv(cy.InvalidParams,`Prompt ${a} not found`);return i()}case"resources/read":{let{uri:a}=e.params;if(!await r(e,ho(t,a),"read"))throw new c_(a);return i()}case"completion/complete":{let{ref:a}=e.params,n="ref/prompt"===a.type?t.prompts.get(a.name):[...t.templates.values()].find(({component:e})=>e.uriTemplate===a.uri)?.component??t.uiOwners.get(a.uri)??t.resources.get(a.uri);if(!await r(e,n,"complete"))throw new cv(cy.InvalidParams,"ref/prompt"===a.type?`Prompt ${a.name} not found`:`Resource template ${a.uri} not found`);return i()}case"tools/list":{let r=await i();return{...r,tools:await a(e,r.tools,e=>t.tools.get(e.name))}}case"prompts/list":{let r=await i();return{...r,prompts:await a(e,r.prompts,e=>t.prompts.get(e.name))}}case"resources/list":{let r=await i();return{...r,resources:await a(e,r.resources,e=>ho(t,e.uri,!0))}}case"resources/templates/list":{let r=await i();return{...r,resourceTemplates:await a(e,r.resourceTemplates,e=>t.templates.get(e.name)?.component)}}default:return i()}}}(a,o):void 0,l=gl(s?[s,...t]:t),c=s?gl([s]):void 0;i.setRequestHandler=(e,...t)=>{if(1===t.length&&"function"==typeof t[0]){let r=t[0];gu.has(e)?t[0]=(e,t)=>l({method:e.method,params:e.params??{}},t,()=>r(e,t)):"tools/call"===e&&c&&o&&(t[0]=(e,t)=>{let a=o.tools.get(e.params.name);return a?c({method:"tools/call",params:{name:e.params.name,arguments:e.params.arguments??{}},tool:{metadata:a.metadata}},t,()=>r(e,t)):r(e,t)})}Reflect.apply(n,i,[e,...t])};try{if(o){let t=async(e,t,r)=>{let i=o.resources.get(t);return!i||await a(e,i,r)===!0},i={registerTool:e.registerTool,registerPrompt:e.registerPrompt,registerResource:e.registerResource};e.registerTool=(t,r,...a)=>{let n=gc({name:t,description:r.description??"",annotations:r.annotations,icons:r.icons,tags:hn(r._meta),_meta:r._meta});return o.tools.set(t,Object.freeze({type:"tool",name:t,metadata:n})),Reflect.apply(i.registerTool,e,[t,r,...a])},e.registerPrompt=(t,r,...a)=>{let n=gc({name:t,title:r.title,description:r.description,icons:r.icons,tags:hn(r._meta),_meta:r._meta});return o.prompts.set(t,Object.freeze({type:"prompt",name:t,metadata:n})),Reflect.apply(i.registerPrompt,e,[t,r,...a])},e.registerResource=(t,r,a,...n)=>{let s=gc({name:t,title:a.title,description:a.description,icons:a.icons,mimeType:a.mimeType,tags:hn(a._meta),_meta:a._meta});if("string"==typeof r)o.resources.set(r,Object.freeze({type:"resource",name:t,uri:r,metadata:s}));else{let e=r.uriTemplate.toString();o.templates.set(t,{component:Object.freeze({type:"resourceTemplate",name:t,uriTemplate:e,metadata:s}),template:r})}return Reflect.apply(i.registerResource,e,[t,r,a,...n])};try{r(t)}finally{Object.assign(e,i)}for(let[e,t]of ht.getAll()){let r=o.tools.get(e);r&&o.uiOwners.set(t.uri,r)}}else r()}finally{i.setRequestHandler=n}}(e,o,n=>{var s,u;!function(e,t,r=[]){t.forEach((t,a)=>{var i,n;let o,s,l,c,u={name:gg(a),description:"No description provided"},{default:d,metadata:p,schema:m,outputSchema:h}=t;if("object"==typeof p&&null!==p&&Object.assign(u,p),!1===u.enabled)return;if("function"==typeof d&&"__x402"in d){let e=global.__XMCP_X402_REGISTRY;e&&e.set(u.name,d.__x402)}let f={};if(ge(m)?(!function(e,t){let{type:r}=gt(e,"draft-2020-12","input");if(void 0!==r&&"object"!==r)throw Error(`Invalid schema for tool "${t}": tool input schemas must describe an object, got JSON Schema type ${JSON.stringify(r)}.`)}(m,u.name),f=m):gf(m)?f=m:null!=m&&console.warn(`Invalid schema for tool "${u.name}" at ${a}. Expected a zod schema or Record<string, z.ZodType>`),null!=h)if(ge(h))o=h;else if(gf(h))o=h;else throw Error(`Invalid outputSchema for tool "${u.name}" at ${a}. Expected a zod schema or Record<string, z.ZodType>`);u.annotations={...u.annotations??{}},void 0===u.annotations.title&&(u.annotations.title=u.name),u._meta={...he(u)._meta};let g=gd(a),y=!!(i=u._meta)&&"object"==typeof i&&"ui"in i&&"object"==typeof i.ui||g,v=u._meta;if(y){let e=`ui://app/${u.name}.html`;u._meta.ui||(u._meta.ui={}),u._meta.ui.resourceUri||(u._meta.ui.resourceUri=e);let t=function(e){let t={},r={};if(e.ui&&"object"==typeof e.ui){let a=e.ui,i={},n={};for(let[e,t]of Object.entries(a))gm.includes(e)?i[e]=t:gh.includes(e)?n[e]=t:i[e]=t;Object.keys(i).length>0&&(t.ui=i),Object.keys(n).length>0&&(r.ui=n)}for(let[r,a]of Object.entries(e))"ui"!==r&&(t[r]=a);return{toolMeta:t,resourceMeta:r}}(v);v=t.toolMeta;let r=t.resourceMeta;r.ui=r.ui||{},r.ui.csp=r.ui.csp||{},r.ui.csp.resourceDomains=r.ui.csp.resourceDomains||[],r.ui.csp.resourceDomains.includes("https://esm.sh")||r.ui.csp.resourceDomains.push("https://esm.sh"),ht.add(u.name,{name:u.name,uri:e,handler:d,mimeType:"text/html;profile=mcp-app",_meta:r,toolPath:g?a:void 0})}let _=gp(v),b=y?_:void 0;s=gd(a)&&y?async(e,t)=>({content:[{type:"text",text:""}],_meta:b,structuredContent:{args:e}}):function(e,t,r,a="unknown-tool"){return async(i,n)=>{let o,s,l=e(i,(o=gs(n),s=function(e){if(!e)return;let t={};return e.headers.forEach((e,r)=>{t[r]=e}),t}(n.http?.req),{signal:n.mcpReq.signal,authInfo:n.http?.authInfo,sessionId:n.sessionId,_meta:n.mcpReq._meta,requestId:n.mcpReq.id,requestInfo:s?{headers:s}:void 0,clientInfo:o,sendNotification:e=>n.mcpReq.notify(e),sendRequest:(e,t,r)=>n.mcpReq.send(e,t,r),elicit:(e,t)=>(async function(e,t,r){let a=function(e){let t=e.mode??"form";if("url"===t)return function(e){let t;hv(e,"Elicitation request must be a plain object."),hy(e,hu,"URL elicitation"),h_(e.message,"URL elicitation requires a string message."),hb(e.elicitationId,"URL elicitation requires a non-empty elicitationId."),hb(e.url,"URL elicitation requires a non-empty URL.");try{t=new URL(e.url)}catch{throw Error("URL elicitation requires a valid http or https URL.")}if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error("URL elicitation requires a valid http or https URL.")}(e),e;if("form"!==t)throw Error(`Unsupported elicitation mode "${String(e.mode)}". Expected "form" or "url".`);return function(e){hv(e,"Elicitation request must be a plain object."),hy(e,hc,"Form elicitation"),h_(e.message,"Form elicitation requires a string message.");let t=e.requestedSchema;if(hv(t,"Form elicitation requires a flat object schema."),hy(t,hd,"Form elicitation schema"),"object"!==t.type)throw Error('Form elicitation schema must use type "object".');for(let[e,r]of(hv(t.properties,"Form elicitation schema requires a properties object."),Object.entries(t.properties)))!function(e,t){if(hv(t,`Form elicitation field "${e}" must be a plain object.`),hS(t.title,`Form elicitation field "${e}" title must be a string.`),hS(t.description,`Form elicitation field "${e}" description must be a string.`),"string"===t.type&&"enum"in t){var r,a;if(hy(t,hm,`Form elicitation field "${e}"`),hw(t.enum,`Form elicitation field "${e}" enum values must be strings.`),r=t.enumNames,a=`Form elicitation field "${e}" enumNames must be strings.`,void 0!==r&&hw(r,a),void 0!==t.enumNames&&t.enumNames.length!==t.enum.length)throw Error(`Form elicitation field "${e}" enumNames length must match enum length.`);if(hS(t.default,`Form elicitation field "${e}" default must be a string.`),void 0!==t.default&&!t.enum.includes(t.default))throw Error(`Form elicitation field "${e}" default must be one of its enum values.`);return}if("string"===t.type&&!("enum"in t)){hy(t,hp,`Form elicitation field "${e}"`),h$(t.minLength,`Form elicitation field "${e}" minLength must be a number.`),h$(t.maxLength,`Form elicitation field "${e}" maxLength must be a number.`),hS(t.default,`Form elicitation field "${e}" default must be a string.`);let r=t.format;if(hS(r,`Form elicitation field "${e}" format must be a string.`),void 0!==r&&!hg.has(r))throw Error(`Form elicitation field "${e}" format must be one of: ${Array.from(hg).join(", ")}.`);return}if("boolean"===t.type){if(hy(t,hh,`Form elicitation field "${e}"`),void 0!==t.default&&"boolean"!=typeof t.default)throw Error(`Form elicitation field "${e}" default must be a boolean.`);return}if("number"===t.type||"integer"===t.type){hy(t,hf,`Form elicitation field "${e}"`),h$(t.minimum,`Form elicitation field "${e}" minimum must be a number.`),h$(t.maximum,`Form elicitation field "${e}" maximum must be a number.`),h$(t.default,`Form elicitation field "${e}" default must be a number.`);return}throw Error(`Form elicitation field "${e}" uses unsupported type "${String(t.type)}". Supported types are string, boolean, number, integer, and string enums.`)}(e,r);if(void 0!==t.required){if(!Array.isArray(t.required)||t.required.some(e=>"string"!=typeof e))throw Error("Form elicitation schema required fields must be a string array.");for(let e of t.required)if(!(e in t.properties))throw Error(`Form elicitation schema required field "${e}" is not defined in properties.`)}}(e),{...e,mode:"form"}}(t);try{let t=await e.mcpReq.elicitInput(a,r);return{...t,content:t.content??void 0}}catch(e){if(e instanceof lK&&e.code===lB.MethodNotSupportedByProtocolVersion)throw Error("extra.elicit() is not available on protocol revision 2026-07-28: server-initiated elicitation was replaced by multi round-trip requests. Return inputRequired({ ... }) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw e}})(n,e,t),sample:(e,t)=>(async function(e,t,r){let a=function(e){hP(e,"Sampling request must be a plain object.");let t=Object.keys(e),r=t.filter(e=>hk.has(e));if(r.length>0)throw Error(`Sampling request key(s) not supported by xmcp yet: ${r.join(", ")}.`);let a=t.filter(e=>!hR.has(e));if(a.length>0)throw Error(`Sampling request includes unsupported key(s): ${a.join(", ")}.`);if(!Array.isArray(e.messages)||0===e.messages.length)throw Error("Sampling requires at least one message.");for(let[t,r]of e.messages.entries())!function(e,t){if(hP(t,`Sampling message at index ${e} must be a plain object.`),"user"!==t.role&&"assistant"!==t.role)throw Error(`Sampling message at index ${e} requires role "user" or "assistant".`);let r=t.content;hP(r,`Sampling message at index ${e} requires a content object.`);let a=r.type;if("string"!=typeof a||!hx.has(a))throw Error(`Sampling message at index ${e} uses unsupported content type "${String(a)}". Supported types are text, image, and audio.`);if("text"===a&&"string"!=typeof r.text)throw Error(`Sampling message at index ${e} requires string text content.`);if(("image"===a||"audio"===a)&&("string"!=typeof r.data||"string"!=typeof r.mimeType))throw Error(`Sampling message at index ${e} requires base64 data and a mimeType.`)}(t,r);if("number"!=typeof e.maxTokens)throw Error("Sampling requires a numeric maxTokens.");return e}(t);try{return await e.mcpReq.requestSampling(a,r)}catch(e){if(e instanceof lK&&e.code===lB.MethodNotSupportedByProtocolVersion)throw Error("extra.sample() is not available on protocol revision 2026-07-28: server-initiated sampling was replaced by multi round-trip requests. Return inputRequired({ ... }) with inputRequired.createMessage(...) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw e}})(n,e,t),inputResponses:n.mcpReq.inputResponses,requestState:n.mcpReq.requestState}));if(l instanceof Promise&&(l=await l),c0(l))return l;if(r&&ge(r)&&void 0!==l&&!gn(l)){if(await gi(l,r,a,"returned data that does not match outputSchema"),"string"==typeof l||"number"==typeof l)return{content:[{type:"text",text:`${l}`}],structuredContent:l};l={structuredContent:l}}if("string"==typeof l||"number"==typeof l){if(r&&!ge(r)){let e=Object.entries(r);if(1===e.length){let[t,r]=e[0];try{return r.parse(l),{content:[{type:"text",text:"number"==typeof l?`${l}`:l}],structuredContent:{[t]:l}}}catch{}}}return go(t)?{content:[{type:"text",text:""}],structuredContent:{args:i},_meta:t}:{content:[{type:"text",text:"number"==typeof l?`${l}`:l}]}}if(r&&l&&"object"==typeof l&&!Array.isArray(l)&&!gn(l)&&(await gi(l,r,a,"returned data that does not match outputSchema"),l={structuredContent:l}),l&&"object"==typeof l&&"_meta"in l&&!("content"in l)&&!("structuredContent"in l)){let e=l._meta;if(go(e))return{content:[{type:"text",text:""}],_meta:e}}if(!l||"object"!=typeof l){let e=null===l?"null":typeof l,t=void 0===l?"undefined":null===l?"null":"object"==typeof l?JSON.stringify(l,null,2):String(l);throw Error(`Tool handler must return a CallToolResult, string, or number. Got ${e}: ${t}
94
94
 
95
95
  Expected CallToolResult format:
96
96
  {
@@ -119,7 +119,7 @@ Or for widget metadata only:
119
119
  _meta: {
120
120
  "ui/...": ...
121
121
  }
122
- }`)}let c="content"in l&&Array.isArray(l.content),u="structuredContent"in l,d="isError"in l&&!0===l.isError;if(!c&&!u&&!d){let e=JSON.stringify(l,null,2);throw Error(`Tool handler must return at least 'content' or 'structuredContent'. Got: ${e}
122
+ }`)}let c="content"in l&&Array.isArray(l.content),u="structuredContent"in l&&void 0!==l.structuredContent,d="isError"in l&&!0===l.isError;if(!c&&!u&&!d){let e=JSON.stringify(l,null,2);throw Error(`Tool handler must return at least 'content' or 'structuredContent'. Got: ${e}
123
123
 
124
124
  Expected CallToolResult format:
125
125
  {
@@ -140,7 +140,7 @@ Or both for backwards compatibility:
140
140
  {
141
141
  content: [{ type: "text", text: "fallback" }],
142
142
  structuredContent: { your: "data" }
143
- }`)}if(d&&!c&&!u){let{isError:e,...t}=l,r=Object.keys(t).length>0?`Tool execution failed: ${JSON.stringify(t)}`:"Tool execution failed";l.content=[{type:"text",text:r}],c=!0}if(r&&u&&!d&&hj(l.structuredContent,r,a,"returned structuredContent that does not match outputSchema"),!c&&u&&(l.content=[{type:"text",text:JSON.stringify(l.structuredContent)}],c=!0),c)for(let e=0;e<l.content.length;e++){let t=l.content[e],r=hT(t);if(!r.valid)throw Error(`Invalid content item at index ${e}: ${r.error}
143
+ }`)}if(d&&!c&&!u){let{isError:e,...t}=l,r=Object.keys(t).length>0?`Tool execution failed: ${JSON.stringify(t)}`:"Tool execution failed";l.content=[{type:"text",text:r}],c=!0}if(r&&u&&!d&&await gi(l.structuredContent,r,a,"returned structuredContent that does not match outputSchema"),!c&&u&&(l.content=[{type:"text",text:JSON.stringify(l.structuredContent)}],c=!0),c)for(let e=0;e<l.content.length;e++){let t=l.content[e],r=hT(t);if(!r.valid)throw Error(`Invalid content item at index ${e}: ${r.error}
144
144
 
145
145
  Content item: ${JSON.stringify(t,null,2)}
146
146
 
@@ -149,15 +149,7 @@ Expected content formats:
149
149
  - Image: { type: "image", data: "base64data", mimeType: "image/jpeg" }
150
150
  - Audio: { type: "audio", data: "base64data", mimeType: "audio/mpeg" }
151
151
  - Resource: { type: "resource_link", name: "name", uri: "uri" }
152
- All content types support an optional "_meta" object property`)}if(u){let e=l.structuredContent;if(null===e||"object"!=typeof e||Array.isArray(e)){let t=Array.isArray(e)?"array":typeof e;throw Error(`'structuredContent' must be a plain object (not an array or primitive). Got ${t}: ${JSON.stringify(e,null,2)}
153
-
154
- Expected format:
155
- {
156
- structuredContent: {
157
- key: "value",
158
- nested: { data: "here" }
159
- }
160
- }`)}}return l}}(d,b,o,u.name);let S={title:u.annotations?.title,description:u.description,inputSchema:gs(f),outputSchema:o?gs(o,{strict:!0}):void 0,annotations:u.annotations,icons:u.icons,_meta:_};e.registerTool(u.name,S,(n={name:u.name,description:S.description,annotations:S.annotations,icons:S.icons,tags:u.tags,_meta:S._meta},l=hI(r,!0),c=Object.freeze({metadata:hN(n)}),(e,t)=>l({method:"tools/call",params:{name:c.metadata.name,arguments:e},tool:c},t,()=>s(e,t))))})}(e,gh(t,c),o),gh(a,c).forEach((t,r)=>{let a=gp(r),i={name:a,title:a,description:"No description provided"},n={},{default:o,metadata:s,schema:l}=t;if("object"==typeof s&&null!==s&&Object.assign(i,s),!1===i.enabled)return;let c=function(e,t="assistant"){return async(r,a)=>{let i,n=e(r,a);if(n instanceof Promise&&(n=await n),Array.isArray(n)||null!==n&&"object"==typeof n&&"messages"in n){let e=Array.isArray(n)?{messages:n}:n,t=await uP.GetPromptResult["~standard"].validate(e);if(t.issues){let e=t.issues.map(e=>{let t=e.path?.map(e=>"object"==typeof e?e.key:e).join(".");return`${t||"result"}: ${e.message}`});throw Error(`Invalid prompt result: ${e.join("; ")}`)}return e}if("string"==typeof n||"number"==typeof n)i={type:"text",text:"number"==typeof n?`${n}`:n};else{let e=hT(n);if(e.valid)i=n;else{let t=null===n?"null":typeof n,r=void 0===n?"undefined":null===n?"null":"object"==typeof n?JSON.stringify(n,null,2):String(n);throw Error(`Prompt handler must return a PromptContent object, string, number, PromptMessage[], or GetPromptResult. Got ${t}: ${r}
152
+ All content types support an optional "_meta" object property`)}return l}}(d,b,o,u.name);let S={title:u.annotations?.title,description:u.description,inputSchema:ga(f),outputSchema:o?ga(o,{strict:!0}):void 0,annotations:u.annotations,icons:u.icons,_meta:_};e.registerTool(u.name,S,(n={name:u.name,description:S.description,annotations:S.annotations,icons:S.icons,tags:u.tags,_meta:S._meta},l=gl(r,!0),c=Object.freeze({metadata:gc(n)}),(e,t)=>l({method:"tools/call",params:{name:c.metadata.name,arguments:e},tool:c},t,()=>s(e,t))))})}(e,gv(t,c),o),gv(a,c).forEach((t,r)=>{let a=gg(r),i={name:a,title:a,description:"No description provided"},n={},{default:o,metadata:s,schema:l}=t;if("object"==typeof s&&null!==s&&Object.assign(i,s),!1===i.enabled)return;let c=function(e,t="assistant"){return async(r,a)=>{let i,n=e(r,a);if(n instanceof Promise&&(n=await n),Array.isArray(n)||null!==n&&"object"==typeof n&&"messages"in n){let e=Array.isArray(n)?{messages:n}:n,t=await uP.GetPromptResult["~standard"].validate(e);if(t.issues){let e=t.issues.map(e=>{let t=e.path?.map(e=>"object"==typeof e?e.key:e).join(".");return`${t||"result"}: ${e.message}`});throw Error(`Invalid prompt result: ${e.join("; ")}`)}return e}if("string"==typeof n||"number"==typeof n)i={type:"text",text:"number"==typeof n?`${n}`:n};else{let e=hT(n);if(e.valid)i=n;else{let t=null===n?"null":typeof n,r=void 0===n?"undefined":null===n?"null":"object"==typeof n?JSON.stringify(n,null,2):String(n);throw Error(`Prompt handler must return a PromptContent object, string, number, PromptMessage[], or GetPromptResult. Got ${t}: ${r}
161
153
 
162
154
  Validation error: ${e.error}
163
155
 
@@ -170,7 +162,7 @@ Expected formats:
170
162
  - Image content: { type: "image", data: "base64data", mimeType: "image/jpeg" }
171
163
  - Audio content: { type: "audio", data: "base64data", mimeType: "audio/mpeg" }
172
164
  - Resource link: { type: "resource_link", name: "resource name", uri: "resource://uri" }
173
- - All content types support an optional "_meta" object property`)}}if("user"!==t&&"assistant"!==t)throw Error(`Invalid role: ${t}`);return{messages:[{role:t,content:i}]}}}(o,i.role||"assistant");gd(l)?Object.assign(n,l):null!=l&&console.warn(`Invalid schema for prompt "${i.name}" at ${r}. Expected Record<string, z.ZodType>`),e.registerPrompt(i.name,{title:i.title,description:i.description,icons:i.icons,_meta:he(i)._meta,argsSchema:gs(n)},c)}),s=gh(i,c),u=l?.registerResource,[...ht.getAll()].forEach(([t,a])=>{let i=a.mimeType||"text/html;profile=mcp-app",n=a?._meta?gl(a._meta):void 0,o={name:a.name,description:`Auto-generated resource for ${a.name} tool`,mimeType:a.mimeType,_meta:n};u?.(a.name,a.uri),e.registerResource(a.name,a.uri,o,async(e,t)=>{if(a.mimeType&&a.toolPath)try{var n;let e,t,o=(n=a.toolPath,IS_CLOUDFLARE?function(e){let{normalizedPath:t,baseName:r}=g_(e),a=5381;for(let e=0;e<t.length;e++)a=Math.imul(a,33)+t.charCodeAt(e)>>>0;let i=a.toString(16).slice(0,6).padStart(6,"0");return`${r}_${i}`}(n):function(e){let{normalizedPath:t,baseName:a}=g_(e),i=r(6982).createHash("md5").update(t).digest("hex").slice(0,6);return`${a}_${i}`}(n)),s=function(e){if(INJECTED_CLIENT_BUNDLES)return INJECTED_CLIENT_BUNDLES[e]||null;if(!IS_CLOUDFLARE)try{let t=r(9896),a=r(6928);for(let r of[a.join(process.cwd(),"dist","client"),a.join(process.cwd(),"client")]){let i=a.join(r,`${e}.bundle.js`),n=a.join(r,`${e}.bundle.css`);if(t.existsSync(i)){let e,r=t.readFileSync(i,"utf-8");return t.existsSync(n)&&(e=t.readFileSync(n,"utf-8")),{js:r,css:e}}}}catch{}return null}(o);if(!s)throw Error(`React client bundle not found for "${a.name}" (bundle: "${o}").
165
+ - All content types support an optional "_meta" object property`)}}if("user"!==t&&"assistant"!==t)throw Error(`Invalid role: ${t}`);return{messages:[{role:t,content:i}]}}}(o,i.role||"assistant");gf(l)?Object.assign(n,l):null!=l&&console.warn(`Invalid schema for prompt "${i.name}" at ${r}. Expected Record<string, z.ZodType>`),e.registerPrompt(i.name,{title:i.title,description:i.description,icons:i.icons,_meta:he(i)._meta,argsSchema:gr(n)},c)}),s=gv(i,c),u=l?.registerResource,[...ht.getAll()].forEach(([t,a])=>{let i=a.mimeType||"text/html;profile=mcp-app",n=a?._meta?gp(a._meta):void 0,o={name:a.name,description:`Auto-generated resource for ${a.name} tool`,mimeType:a.mimeType,_meta:n};u?.(a.name,a.uri),e.registerResource(a.name,a.uri,o,async(e,t)=>{if(a.mimeType&&a.toolPath)try{var n;let e,t,o=(n=a.toolPath,IS_CLOUDFLARE?function(e){let{normalizedPath:t,baseName:r}=gR(e),a=5381;for(let e=0;e<t.length;e++)a=Math.imul(a,33)+t.charCodeAt(e)>>>0;let i=a.toString(16).slice(0,6).padStart(6,"0");return`${r}_${i}`}(n):function(e){let{normalizedPath:t,baseName:a}=gR(e),i=r(6982).createHash("md5").update(t).digest("hex").slice(0,6);return`${a}_${i}`}(n)),s=function(e){if(INJECTED_CLIENT_BUNDLES)return INJECTED_CLIENT_BUNDLES[e]||null;if(!IS_CLOUDFLARE)try{let t=r(9896),a=r(6928);for(let r of[a.join(process.cwd(),"dist","client"),a.join(process.cwd(),"client")]){let i=a.join(r,`${e}.bundle.js`),n=a.join(r,`${e}.bundle.css`);if(t.existsSync(i)){let e,r=t.readFileSync(i,"utf-8");return t.existsSync(n)&&(e=t.readFileSync(n,"utf-8")),{js:r,css:e}}}}catch{}return null}(o);if(!s)throw Error(`React client bundle not found for "${a.name}" (bundle: "${o}").
174
166
  React tool bundles are generated automatically when you run "xmcp build" (or "xmcp dev").
175
167
  Please re-run the build so the framework can regenerate the bundle.`);let l=s.js,c=s.css,u=(e=`
176
168
  <script type="module">
@@ -225,7 +217,7 @@ Please re-run the build so the framework can regenerate the bundle.`);let l=s.js
225
217
  <div id="root"></div>
226
218
  ${e}
227
219
  </body>
228
- </html>`);return{contents:[{uri:a.uri,text:u,mimeType:i,_meta:a._meta}]}}catch(e){throw console.error(`React failed for ${a.name}:`,e),e}let o=a.handler({},t);if(o instanceof Promise&&(o=await o),"string"==typeof o)return{contents:[{uri:a.uri,text:o,mimeType:i,_meta:a._meta}]};if(o&&"object"==typeof o&&"_meta"in o&&!("content"in o))return{contents:[{uri:a.uri,text:"",mimeType:i,_meta:a._meta}]};if(o&&"object"==typeof o&&"content"in o&&Array.isArray(o.content)){let e=o.content.find(e=>"text"===e.type);if(e&&"text"===e.type&&"string"==typeof e.text)return{contents:[{uri:a.uri,text:e.text,mimeType:i,_meta:a._meta}]}}return{contents:[{uri:a.uri,text:"",mimeType:i,_meta:a._meta}]}})}),s.forEach((t,r)=>{let a={name:gp(r),description:"No description provided"},{default:i,metadata:n,schema:o,complete:s}=t;if("object"==typeof n&&null!==n&&Object.assign(a,n),!1===a.enabled)return;let l={};gd(o)?l=o:null!=o&&console.warn(`Invalid schema for resource "${a.name}" at ${r}. Expected Record<string, z.ZodType>`);let c=gb(r);if(!c)return void console.warn(`Skipping resource "${a.name}" at ${r}: Invalid file path format`);let d=c.uriTemplate;a.mimeType&&a.mimeType.includes("html")&&(d=d.endsWith(".html")?d:`${d}.html`);let p=function(e,t,r={}){let a=gb(t);if(!a)throw Error(`Invalid resource file path: ${t}. Must follow (scheme)/path/[param] convention.`);return async(t,i)=>{let n=e(function(e,t,r){let a={},i={};if(0===t.parameters.length)return i;let n=t.uriTemplate.split("://")[1]||"",o=e.split("://")[1]||"",s=n.split("/"),l=o.split("/");for(let e=0;e<s.length&&e<l.length;e++){let t=s[e],r=l[e],i=t.match(/^\{(.+)\}$/);i&&(a[i[1]]=r)}for(let e of t.parameters){let t=a[e],n=r[e];if(void 0===t)throw Error(`Missing required parameter: ${e}`);if(!n){i[e]=t;continue}try{i[e]=n.parse(t)}catch(r){throw Error(`Invalid parameter "${e}": ${t}. Validation error: ${r instanceof Error?r.message:String(r)}`)}}return i}(t.href,a,r),i);if(n instanceof Promise&&(n=await n),c0(n))return n;if("string"==typeof n)return{contents:[{uri:t.href,text:n}]};if(!n||"object"!=typeof n||!Array.isArray(n.contents)){let e=null===n?"null":typeof n,t=void 0===n?"undefined":null===n?"null":"object"==typeof n?JSON.stringify(n,null,2):String(n);throw Error(`Resource handler must return a ReadResourceResult, InputRequiredResult, or string. Got ${e}: ${t}
220
+ </html>`);return{contents:[{uri:a.uri,text:u,mimeType:i,_meta:a._meta}]}}catch(e){throw console.error(`React failed for ${a.name}:`,e),e}let o=a.handler({},t);if(o instanceof Promise&&(o=await o),"string"==typeof o)return{contents:[{uri:a.uri,text:o,mimeType:i,_meta:a._meta}]};if(o&&"object"==typeof o&&"_meta"in o&&!("content"in o))return{contents:[{uri:a.uri,text:"",mimeType:i,_meta:a._meta}]};if(o&&"object"==typeof o&&"content"in o&&Array.isArray(o.content)){let e=o.content.find(e=>"text"===e.type);if(e&&"text"===e.type&&"string"==typeof e.text)return{contents:[{uri:a.uri,text:e.text,mimeType:i,_meta:a._meta}]}}return{contents:[{uri:a.uri,text:"",mimeType:i,_meta:a._meta}]}})}),s.forEach((t,r)=>{let a={name:gg(r),description:"No description provided"},{default:i,metadata:n,schema:o,complete:s}=t;if("object"==typeof n&&null!==n&&Object.assign(a,n),!1===a.enabled)return;let l={};gf(o)?l=o:null!=o&&console.warn(`Invalid schema for resource "${a.name}" at ${r}. Expected Record<string, z.ZodType>`);let c=gk(r);if(!c)return void console.warn(`Skipping resource "${a.name}" at ${r}: Invalid file path format`);let d=c.uriTemplate;a.mimeType&&a.mimeType.includes("html")&&(d=d.endsWith(".html")?d:`${d}.html`);let p=function(e,t,r={}){let a=gk(t);if(!a)throw Error(`Invalid resource file path: ${t}. Must follow (scheme)/path/[param] convention.`);return async(t,i)=>{let n=e(function(e,t,r){let a={},i={};if(0===t.parameters.length)return i;let n=t.uriTemplate.split("://")[1]||"",o=e.split("://")[1]||"",s=n.split("/"),l=o.split("/");for(let e=0;e<s.length&&e<l.length;e++){let t=s[e],r=l[e],i=t.match(/^\{(.+)\}$/);i&&(a[i[1]]=r)}for(let e of t.parameters){let t=a[e],n=r[e];if(void 0===t)throw Error(`Missing required parameter: ${e}`);if(!n){i[e]=t;continue}try{i[e]=n.parse(t)}catch(r){throw Error(`Invalid parameter "${e}": ${t}. Validation error: ${r instanceof Error?r.message:String(r)}`)}}return i}(t.href,a,r),i);if(n instanceof Promise&&(n=await n),c0(n))return n;if("string"==typeof n)return{contents:[{uri:t.href,text:n}]};if(!n||"object"!=typeof n||!Array.isArray(n.contents)){let e=null===n?"null":typeof n,t=void 0===n?"undefined":null===n?"null":"object"==typeof n?JSON.stringify(n,null,2):String(n);throw Error(`Resource handler must return a ReadResourceResult, InputRequiredResult, or string. Got ${e}: ${t}
229
221
 
230
222
  Expected ReadResourceResult format:
231
223
  {
@@ -234,4 +226,4 @@ Expected ReadResourceResult format:
234
226
  { uri: "resource://uri", mimeType: "application/json", text: "json content" },
235
227
  { uri: "resource://uri", blob: base64data }
236
228
  ]
237
- }`)}return n.contents.forEach(e=>{e.uri||(e.uri=t.href)}),n}}(i,r,l);if("direct"===c.type)u?.(a.name,d),e.registerResource(a.name,d,he(a),p);else{let t=Object.create(null);for(let e of c.parameters)s&&Object.hasOwn(s,e)&&(t[e]=s[e]);let r=new pD(d,{list:void 0,complete:t});u?.(a.name,r),e.registerResource(a.name,r,he(a),async(e,t,r)=>{let a={};for(let e of c.parameters){let r=t[e],i=l[e];if(void 0===r)throw Error(`Missing required parameter: ${e}. Available variables: ${Object.keys(t)}`);i?a[e]=i.parse(r):a[e]=r}let n=i(a,r);return n instanceof Promise&&(n=await n),"string"==typeof n?{contents:[{uri:e.href,text:n}]}:n})}}),function(e,t,r,a,i){let n=[...gh(new Map(t.map(e=>[e.uri,{metadata:{name:e.frontmatter.name},skill:e}])),r).values()].map(({skill:e})=>e);if(0===n.length)return;for(let{frontmatter:t,files:r}of n){let i=r[0].uri.slice(0,r[0].uri.lastIndexOf("/")+1);r.forEach(({uri:r,mimeType:n,text:o,blob:s},l)=>{let c=0===l?{mimeType:n,description:t.description}:{mimeType:n},u=0===l?t.name:`${t.name}/${decodeURIComponent(r.slice(i.length))}`,d=void 0!==o?{uri:r,mimeType:n,text:o}:{uri:r,mimeType:n,blob:s??""};a?.(u,r),e.registerResource(u,r,c,()=>({contents:[d]}))})}let o=n.map(gR),s=new Map(o.map(e=>[e.uri,e]));e.server.registerCapabilities({extensions:{"io.modelcontextprotocol/skills":{}}}),e.server.setRequestHandler("skills/list",{params:g$},(e,t)=>hi(t,hC(t),async()=>{let t=Object.freeze({...ha(),method:"skills/list",params:Object.freeze({...e})}),r=i?await Promise.all(o.map(e=>i(t,e.uri,"list"))):void 0,a=r?o.filter((e,t)=>r[t]):o,n=e?.cursor===void 0?0:function(e,t){let r=0/0;try{r=Number(atob(e))}catch{}if(!Number.isSafeInteger(r)||r<=0||r>=t)throw new cv(cy.InvalidParams,`Invalid cursor: ${e}`);return r}(e.cursor,a.length),s=n+50;return{skills:a.slice(n,s),...s<a.length?{nextCursor:btoa(String(s))}:{},...gS}})),e.server.setRequestHandler("skills/get",{params:gw},(e,t)=>hi(t,hC(t),async()=>{let{uri:t}=e,r=s.get(t),a=Object.freeze({...ha(),method:"skills/get",params:Object.freeze({...e})});if(!r||i&&!await i(a,t,"read"))throw new cv(cy.InvalidParams,`No skill is served at ${t}`);return{skill:r,...gS}}))}(e,gj,c,l?.registerResource,n)},s),e}(a,s,l,c)},{legacy:"stateless",maxSubscriptions:gC.maxSubscriptions,onerror:gC.debug?e=>console.error("[HTTP-server] MCP handler error:",e):void 0}),N={onerror:e=>console.error("[HTTP-server] Error handling MCP request:",e)},R=mY(N?.maxRequestBodySize),async(e,t,r)=>{let a,i;"function"==typeof r&&(r=void 0);let n=!1,o=new AbortController;t.on("close",()=>{n||o.abort()}),!0===t.destroyed&&o.abort();try{let t=await async function(e,t,r){let a,i=mY(r?.maxRequestBodySize),n=(e.method??"GET").toUpperCase(),o=`http://${mX(e.headers.host)??mX(e.headers[":authority"])??"localhost"}${e.url??"/"}`,s=new Headers;for(let[t,r]of Object.entries(e.headers))if(!(void 0===r||t.startsWith(":")))if(Array.isArray(r))for(let e of r)s.append(t,e);else s.set(t,r);if("GET"!==n&&"HEAD"!==n)if(void 0===t){if(Number(mX(e.headers["content-length"]))>i)throw new mW(i);let t=new TextDecoder,r="",n=0;for await(let a of e){if((n+="string"==typeof a?new TextEncoder().encode(a).byteLength:a.byteLength)>i)throw new mW(i);r+="string"==typeof a?a:t.decode(a,{stream:!0})}(r+=t.decode()).length>0&&(a=r)}else{let e=JSON.stringify(t);s.delete("content-encoding"),s.delete("transfer-encoding"),void 0===e?s.delete("content-length"):(a=e,s.set("content-length",String(new TextEncoder().encode(e).byteLength)))}return new Request(o,{method:n,headers:s,...r?.signal!==void 0&&{signal:r.signal},...void 0!==a&&{body:a}})}(e,r,{signal:o.signal,maxRequestBodySize:R});a=await I.fetch(t,{...void 0!==e.auth&&{authInfo:e.auth},...void 0!==r&&{parsedBody:r}})}catch(e){if(e instanceof mW)a=Response.json({jsonrpc:"2.0",error:{code:-32e3,message:e.message},id:null},{status:413,headers:{connection:"close"}});else{var s;try{N?.onerror?.(e instanceof Error?e:Error(String(e)))}catch{}s=function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let{method:t,id:r}=e;return"string"!=typeof t?null:"string"==typeof r||"number"==typeof r?r:null}(r),a=Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:s},{status:500})}}let l={};for(let[e,t]of a.headers)l[e]=t;if(t.writeHead(a.status,l),null===a.body){n=!0,t.end();return}t.on("drain",()=>{i?.(),i=void 0});let c=new Promise(e=>{o.signal.addEventListener("abort",()=>e(),{once:!0})});try{for await(let e of a.body){if(o.signal.aborted)break;!1===t.write(e)&&await Promise.race([new Promise(e=>{i=e}),c])}}catch{}n=!0,t.end()});async function gq(e,t){let r=(0,k.randomUUID)(),a=(e=>{for(let t of Array.isArray(e)?e:[e]){let e=m8(t);if(e)return e}})(e.body);await m3({id:r,headers:e.headers,clientInfo:a},async()=>{for(let[r,a]of Object.entries(function(e,t){let r={};if(void 0!==e.origin){if(!0===e.origin)t&&(r["Access-Control-Allow-Origin"]=t);else if(!1!==e.origin)if(Array.isArray(e.origin)){let a=t&&e.origin.includes(t)?t:e.origin[0]||"*";r["Access-Control-Allow-Origin"]=a}else r["Access-Control-Allow-Origin"]=String(e.origin)}return void 0!==e.methods&&(r["Access-Control-Allow-Methods"]=Array.isArray(e.methods)?e.methods.join(","):String(e.methods)),void 0!==e.allowedHeaders&&(r["Access-Control-Allow-Headers"]=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):String(e.allowedHeaders)),void 0!==e.exposedHeaders&&(r["Access-Control-Expose-Headers"]=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):String(e.exposedHeaders)),"boolean"==typeof e.credentials&&(r["Access-Control-Allow-Credentials"]=String(e.credentials)),"number"==typeof e.maxAge&&(r["Access-Control-Max-Age"]=String(e.maxAge)),r}(gI,e.headers.origin)))t.setHeader(r,a);await gN(e,t,e.body)})}})(),a})());
229
+ }`)}return n.contents.forEach(e=>{e.uri||(e.uri=t.href)}),n}}(i,r,l);if("direct"===c.type)u?.(a.name,d),e.registerResource(a.name,d,he(a),p);else{let t=Object.create(null);for(let e of c.parameters)s&&Object.hasOwn(s,e)&&(t[e]=s[e]);let r=new pD(d,{list:void 0,complete:t});u?.(a.name,r),e.registerResource(a.name,r,he(a),async(e,t,r)=>{let a={};for(let e of c.parameters){let r=t[e],i=l[e];if(void 0===r)throw Error(`Missing required parameter: ${e}. Available variables: ${Object.keys(t)}`);i?a[e]=i.parse(r):a[e]=r}let n=i(a,r);return n instanceof Promise&&(n=await n),"string"==typeof n?{contents:[{uri:e.href,text:n}]}:n})}}),function(e,t,r,a,i){let n=[...gv(new Map(t.map(e=>[e.uri,{metadata:{name:e.frontmatter.name},skill:e}])),r).values()].map(({skill:e})=>e);if(0===n.length)return;for(let{frontmatter:t,files:r}of n){let i=r[0].uri.slice(0,r[0].uri.lastIndexOf("/")+1);r.forEach(({uri:r,mimeType:n,text:o,blob:s},l)=>{let c=0===l?{mimeType:n,description:t.description}:{mimeType:n},u=0===l?t.name:`${t.name}/${decodeURIComponent(r.slice(i.length))}`,d=void 0!==o?{uri:r,mimeType:n,text:o}:{uri:r,mimeType:n,blob:s??""};a?.(u,r),e.registerResource(u,r,c,()=>({contents:[d]}))})}let o=n.map(gT),s=new Map(o.map(e=>[e.uri,e]));e.server.registerCapabilities({extensions:{"io.modelcontextprotocol/skills":{}}}),e.server.setRequestHandler("skills/list",{params:gP},(e,t)=>hi(t,gs(t),async()=>{let t=Object.freeze({...ha(),method:"skills/list",params:Object.freeze({...e})}),r=i?await Promise.all(o.map(e=>i(t,e.uri,"list"))):void 0,a=r?o.filter((e,t)=>r[t]):o,n=e?.cursor===void 0?0:function(e,t){let r=0/0;try{r=Number(atob(e))}catch{}if(!Number.isSafeInteger(r)||r<=0||r>=t)throw new cv(cy.InvalidParams,`Invalid cursor: ${e}`);return r}(e.cursor,a.length),s=n+50;return{skills:a.slice(n,s),...s<a.length?{nextCursor:btoa(String(s))}:{},...gx}})),e.server.setRequestHandler("skills/get",{params:gE},(e,t)=>hi(t,gs(t),async()=>{let{uri:t}=e,r=s.get(t),a=Object.freeze({...ha(),method:"skills/get",params:Object.freeze({...e})});if(!r||i&&!await i(a,t,"read"))throw new cv(cy.InvalidParams,`No skill is served at ${t}`);return{skill:r,...gx}}))}(e,gq,c,l?.registerResource,n)},s),e}(e,n,o,s)},{legacy:"stateless",maxSubscriptions:gz.maxSubscriptions,onerror:gz.debug?e=>console.error("[HTTP-server] MCP handler error:",e):void 0}),N={onerror:e=>console.error("[HTTP-server] Error handling MCP request:",e)},R=mY(N?.maxRequestBodySize),async(e,t,r)=>{let a,i;"function"==typeof r&&(r=void 0);let n=!1,o=new AbortController;t.on("close",()=>{n||o.abort()}),!0===t.destroyed&&o.abort();try{let t=await async function(e,t,r){let a,i=mY(r?.maxRequestBodySize),n=(e.method??"GET").toUpperCase(),o=`http://${mX(e.headers.host)??mX(e.headers[":authority"])??"localhost"}${e.url??"/"}`,s=new Headers;for(let[t,r]of Object.entries(e.headers))if(!(void 0===r||t.startsWith(":")))if(Array.isArray(r))for(let e of r)s.append(t,e);else s.set(t,r);if("GET"!==n&&"HEAD"!==n)if(void 0===t){if(Number(mX(e.headers["content-length"]))>i)throw new mW(i);let t=new TextDecoder,r="",n=0;for await(let a of e){if((n+="string"==typeof a?new TextEncoder().encode(a).byteLength:a.byteLength)>i)throw new mW(i);r+="string"==typeof a?a:t.decode(a,{stream:!0})}(r+=t.decode()).length>0&&(a=r)}else{let e=JSON.stringify(t);s.delete("content-encoding"),s.delete("transfer-encoding"),void 0===e?s.delete("content-length"):(a=e,s.set("content-length",String(new TextEncoder().encode(e).byteLength)))}return new Request(o,{method:n,headers:s,...r?.signal!==void 0&&{signal:r.signal},...void 0!==a&&{body:a}})}(e,r,{signal:o.signal,maxRequestBodySize:R});a=await I.fetch(t,{...void 0!==e.auth&&{authInfo:e.auth},...void 0!==r&&{parsedBody:r}})}catch(e){if(e instanceof mW)a=Response.json({jsonrpc:"2.0",error:{code:-32e3,message:e.message},id:null},{status:413,headers:{connection:"close"}});else{var s;try{N?.onerror?.(e instanceof Error?e:Error(String(e)))}catch{}s=function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return null;let{method:t,id:r}=e;return"string"!=typeof t?null:"string"==typeof r||"number"==typeof r?r:null}(r),a=Response.json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:s},{status:500})}}let l={};for(let[e,t]of a.headers)l[e]=t;if(t.writeHead(a.status,l),null===a.body){n=!0,t.end();return}t.on("drain",()=>{i?.(),i=void 0});let c=new Promise(e=>{o.signal.addEventListener("abort",()=>e(),{once:!0})});try{for await(let e of a.body){if(o.signal.aborted)break;!1===t.write(e)&&await Promise.race([new Promise(e=>{i=e}),c])}}catch{}n=!0,t.end()});async function gZ(e,t){let r=(0,k.randomUUID)(),a=(e=>{for(let t of Array.isArray(e)?e:[e]){let e=m8(t);if(e)return e}})(e.body);await m3({id:r,headers:e.headers,clientInfo:a},async()=>{for(let[r,a]of Object.entries(function(e,t){let r={};if(void 0!==e.origin){if(!0===e.origin)t&&(r["Access-Control-Allow-Origin"]=t);else if(!1!==e.origin)if(Array.isArray(e.origin)){let a=t&&e.origin.includes(t)?t:e.origin[0]||"*";r["Access-Control-Allow-Origin"]=a}else r["Access-Control-Allow-Origin"]=String(e.origin)}return void 0!==e.methods&&(r["Access-Control-Allow-Methods"]=Array.isArray(e.methods)?e.methods.join(","):String(e.methods)),void 0!==e.allowedHeaders&&(r["Access-Control-Allow-Headers"]=Array.isArray(e.allowedHeaders)?e.allowedHeaders.join(","):String(e.allowedHeaders)),void 0!==e.exposedHeaders&&(r["Access-Control-Expose-Headers"]=Array.isArray(e.exposedHeaders)?e.exposedHeaders.join(","):String(e.exposedHeaders)),"boolean"==typeof e.credentials&&(r["Access-Control-Allow-Credentials"]=String(e.credentials)),"number"==typeof e.maxAge&&(r["Access-Control-Max-Age"]=String(e.maxAge)),r}(gM,e.headers.origin)))t.setHeader(r,a);await gL(e,t,e.body)})}})(),a})());