xmcp 1.7.0 → 1.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.js +23 -21
- package/dist/index.js +40 -38
- package/dist/runtime/adapter-express.js +23 -25
- package/dist/runtime/adapter-fastify.js +23 -25
- package/dist/runtime/adapter-fetch-cloudflare.js +22 -24
- package/dist/runtime/adapter-fetch.js +23 -25
- package/dist/runtime/adapter-nestjs.js +23 -25
- package/dist/runtime/adapter-nextjs.js +38 -40
- package/dist/runtime/cloudflare-worker.js +30 -32
- package/dist/runtime/http.js +30 -32
- package/dist/runtime/stdio.js +18 -20
- package/dist/runtime/utils/transformers/resource.d.ts +3 -3
- package/dist/runtime/vercel.js +30 -32
- package/package.json +3 -3
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
let t,r,i,n,a,o,s,l,c,u,d,p,m,h,f,g,y,v,_,b,S,w,x,k;import{AsyncLocalStorage as R}from"async_hooks";var $,C,T,O,P,E,I,q,j,z,N,A,L,M,Z={},U={};function F(t){var r=U[t];if(void 0!==r)return r.exports;var i=U[t]={exports:{}};return Z[t](i,i.exports,F),i.exports}F.d=(t,r)=>{for(var i in r)F.o(r,i)&&!F.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:r[i]})},F.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(t){if("object"==typeof window)return window}})(),F.o=(t,r)=>Object.prototype.hasOwnProperty.call(t,r);var H={};F.d(H,{A:()=>hN});var J=Object.create,D=Object.defineProperty,V=Object.getOwnPropertyDescriptor,B=Object.getOwnPropertyNames,W=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;let K=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(t){let r=Object.values(t).filter(t=>"number"==typeof t);return Object.entries(t).filter(([t,i])=>-1===r.indexOf(+t)).map(([t,r])=>r)}function et(t,r="|"){return t.map(t=>ex(t)).join(r)}function er(t,r){return"bigint"==typeof r?r.toString():r}class ei{constructor(t){this._getter=t,this._value=void 0}get value(){let t=this._getter;return void 0!==t&&(this._value=t(),this._getter=void 0),this._value}}function en(t){return new ei(t)}function ea(t){let r=+!!t.startsWith("^"),i=t.endsWith("$")?t.length-1:t.length;return t.slice(r,i)}let eo=Symbol("evaluating");function es(t,r,i){Object.defineProperty(t,r,{value:i,writable:!0,enumerable:!0,configurable:!0})}function el(t){let r=Object.getOwnPropertyDescriptor(t,"shape");return r?.get?r.get.raw:r?.value}function ec(t){return el(t._zod.def)??t._zod.def.shape}function eu(t,r,i){Object.defineProperty(t,r,{get(){let t=i();return es(this,r,t),t},enumerable:!0,configurable:!0})}function ed(t,r,i){r in t?es(t,r,i):t[r]=i}function ep(t,r,i,n){let a=ec(r);for(let o of i){let i=Object.getOwnPropertyDescriptor(a,o);i.enumerable&&(i.get?eu(t,o,()=>{let t=r._zod.def.shape[o];return n?n(t,o):t}):ed(t,o,n?n(i.value,o):i.value))}}function em(...t){let r={};for(let i of t)Object.assign(r,Object.getOwnPropertyDescriptors(i));return Object.defineProperties({},r)}let eh="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function ef(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}let eg=en(()=>{if(eG.jitless||"undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(t){return!1}});function ey(t){if(!1===ef(t))return!1;let r=t.constructor;if(void 0===r||"function"!=typeof r)return!0;let i=r.prototype;return!1!==ef(i)&&!1!==Object.prototype.hasOwnProperty.call(i,"isPrototypeOf")}function ev(t){return ey(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}let e_=new Set(["string","number","symbol"]);function eb(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function eS(t,r,i){let n=new t._zod.constr(r??t._zod.def);return(!r||i?.parent)&&(n._zod.parent=t),n}function ew(t){if(!t)return{};if("string"==typeof t)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return(delete t.message,"string"==typeof t.error)?{...t,error:()=>t.error}:t}function ex(t){return"bigint"==typeof t?t.toString()+"n":"string"==typeof t?`"${t}"`:`${t}`}let ek={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]},eR={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function e$(t,r){let i=ec(t),n=[];for(let t of Reflect.ownKeys(r)){if(!Object.getOwnPropertyDescriptor(i,t)?.enumerable)throw Error(`Unrecognized key: "${String(t)}"`);r[t]&&n.push(t)}return n}function eC(t,r){let i={};ep(i,t,Reflect.ownKeys(ec(t)));for(let t of Reflect.ownKeys(r)){let n=Object.getOwnPropertyDescriptor(r,t);n.enumerable&&(n.get?eu(i,t,()=>r[t]):ed(i,t,n.value))}return i}function eT(t,r,i,n="partial"){let a=r._zod.def.checks;if(a&&a.length>0)throw Error(`.${n}() cannot be used on object schemas containing refinements`);let o=i?new Set(e$(r,i)):void 0,s={};return ep(s,r,Reflect.ownKeys(ec(r)),t&&((r,i)=>o&&!o.has(i)?r:new t({type:"optional",innerType:r}))),eS(r,em(r._zod.def,{shape:s,checks:[]}))}function eO(t,r=0){if(!0===t.aborted)return!0;for(let i=r;i<t.issues.length;i++)if(t.issues[i]?.continue!==!0)return!0;return!1}function eP(t,r){return r.map(r=>(r.path??(r.path=[]),r.path.unshift(t),r))}function eE(t){return"string"==typeof t?t:t?.message}function eI(t,r,i){var n;for(let a=r;a<t.length;a++)(n=t[a]).schema??(n.schema=i)}function eq(t,r,i){let n=t.inst?._zod?.traits;n?.has("$ZodType")&&(n.has("$ZodCheck")?t.schema??(t.schema=t.inst):t.schema=t.inst);let a=t.schema!==t.inst?t.schema?._zod.def?.error:void 0,o=t.message?t.message:eE(t.inst?._zod.def?.error?.(t))??eE(a?.(t))??eE(r?.error?.(t))??eE(i.customError?.(t))??eE(i.localeError?.(t))??"Invalid input",s={};for(let r of Object.keys(t))"inst"!==r&&"schema"!==r&&"continue"!==r&&"input"!==r&&"__proto__"!==r&&(s[r]=t[r]);return s.path??(s.path=[]),s.message=o,r?.reportInput&&(s.input=t.input),s}let ej=/[\uD800-\uDBFF]/;function ez(t){let r=t.length;if(!ej.test(t))return r;let i=r;for(let n=0;n<r-1;n++)(64512&t.charCodeAt(n))==55296&&(64512&t.charCodeAt(n+1))==56320&&(i--,n++);return i}function eN(t){return Array.isArray(t)?"array":"string"==typeof t?"string":"unknown"}function eA(...t){let[r,i,n]=t;return"string"==typeof r?{message:r,code:"custom",input:i,inst:n}:{...r}}function eL(t,r,i,n=!0){return Object.defineProperty(t,r,{configurable:!0,writable:!0,enumerable:n,value:i}),i}function eM(t,r){for(let i in t){let n=t[i];Object.defineProperty(r,i,{configurable:!0,enumerable:!0,get(){return eL(this,i,n(this))},set(t){eL(this,i,t)}})}return r}let eZ=!1,eU={configurable:!0,get(){eZ=!0}};function eF(r,i,n){let a=Object.getPrototypeOf(r._zod);if(i in a&&t!==r._zod){t=void 0;return}t=r._zod,Object.defineProperty(a,i,{configurable:!0,get(){Object.defineProperty(this,i,eU);let t=eZ;eZ=!1;try{let r=n(this);return eZ?delete this[i]:Object.defineProperty(this,i,{configurable:!0,writable:!0,value:r}),eZ=eZ||t,r}catch(r){throw delete this[i],eZ=eZ||t,r}},set(t){Object.defineProperty(this,i,{configurable:!0,writable:!0,value:t})}})}let eH=Object.freeze({status:"aborted"}),eJ={value:void 0,enumerable:!1},eD="captureStackTrace"in Error?Error:null;function eV(t,r,i,n){function a(t){this.def=t,this.constr=u,this.traits=new Set}a.prototype={};let o=i&&new WeakSet;function s(n,s){if(n._zod){if(n._zod.traits.has(t))return}else{eJ.value=new a(s);try{Object.defineProperty(n,"_zod",eJ)}finally{eJ.value=void 0}}if(n._zod.traits.add(t),r(n,s),o){let t=Object.getPrototypeOf(n),r=n._zod.constr.prototype,a=t;for(;a&&a!==r;)a=Object.getPrototypeOf(a);let s=a??t;if(!o.has(s)){o.add(s);for(let t in i){let r=Object.getOwnPropertyDescriptor(i,t);r.get?Object.defineProperty(s,t,{...r,enumerable:!1}):function(t,r,i){Object.defineProperty(t,r,{configurable:!0,get(){return this==null?i:eL(this,r,i.bind(this))},set(t){eL(this,r,t)}})}(s,t,r.value)}}}let l=u.prototype;for(let t in l)Object.prototype.hasOwnProperty.call(l,t)&&(t in n||(n[t]=l[t].bind(n)))}let l=n?.Parent??Object;class c extends l{}function u(t){let r=n?.Parent?function(t){let r=eD;if(r){let i=r.stackTraceLimit;if("number"==typeof i){try{r.stackTraceLimit=0}catch{return eD=null,new t}try{return new t}finally{r.stackTraceLimit=i}}}return new t}(c):this;s(r,t);let i=r._zod.deferred;if(i){for(let t of i)t();r._zod.deferred=void 0}let a=globalThis.__zod_globalConfig?.postProcessor;return a&&a(r),r}return Object.defineProperty(c,"name",{value:t}),Object.defineProperty(u,"init",{value:s}),Object.defineProperty(u,Symbol.hasInstance,{value:r=>!!n?.Parent&&r instanceof n.Parent||r?._zod?.traits?.has(t)}),Object.defineProperty(u,"name",{value:t}),u}class eB extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class eW extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(I=globalThis).__zod_globalConfig??(I.__zod_globalConfig={});let eG=globalThis.__zod_globalConfig;function eK(t){return t&&Object.assign(eG,t),eG}class eY extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}let eX="~memo",eQ=[];function e0(t){return null!==t&&"object"==typeof t}function e1(t){return t.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}let e2=new WeakMap,e9=[],e4={alloc(t,i,n){let a=r;if(!a)return n;r=void 0;let o={value:n,issues:null};return a.set(i.value,o),e9.push(o),n},guard(t){var r;(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred.push(()=>{let r=t._zod.parse,i=(t,i)=>{var n,a;let o;if("backward"!==i.direction&&(n=i,a=t.value,void 0!==(o=n[eX]?.backEdges)&&e0(a)&&o.has(a)))throw new eY;return r(t,i)};t._zod.parse=i,t._zod.run===r&&(t._zod.run=i)})},attach(t){var i;let n,a,o,s=!1;(i=t._zod).deferred??(i.deferred=[]),t._zod.deferred.push(()=>{let i=t._zod.parse,l=(c,u)=>{let d;if(void 0===n){let r=function t(r,i,n){var a,o;let s=e2.get(r);if(void 0!==s)return 2*!!s;if(i.has(r))return 2;i.add(r);let l=0,c=r=>{if(2!==l&&r?._zod){let a=t(r,i,n);a>l&&(l=a)}},u=t=>{t>l&&(l=t)},d=r._zod.def;switch(d.type){case"object":{let r=el(d);u(r?((r,a)=>{let o=0;for(let s of Reflect.ownKeys(r)){let l=Object.getOwnPropertyDescriptor(r,s);if(a&&!l.enumerable)continue;let c=l.get?1:l.value?._zod?t(l.value,i,n):0;c>o&&(o=c)}return o})(r,!0):1),c(d.catchall);break}case"array":c(d.element);break;case"tuple":for(let t of d.items)c(t);c(d.rest);break;case"record":case"map":c(d.keyType),c(d.valueType);break;case"set":c(d.valueType);break;case"union":for(let t of d.options)c(t);break;case"intersection":c(d.left),c(d.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":c(d.innerType);break;case"pipe":c(d.in),c(d.out);break;case"function":c(d.input),c(d.output);break;case"lazy":{let a=d._cachedInner??(n?r._zod.innerType:void 0);u(a?t(a,i,!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 t in d){let r=Object.getOwnPropertyDescriptor(d,t);if(!r||r.get)continue;let i=r.value;if(i&&"object"==typeof i){if(i._zod)c(i);else if(Array.isArray(i))for(let t of i)c(t)}}}return i.delete(r),a=r,1!==(o=l)&&e2.set(a,2===o),o}(t,new Set,!1);if(0===r)return t._zod.parse=i,t._zod.run===l&&(t._zod.run=i),i(c,u);2===r||s?n=!0:s=!0}let p=c.value;if(!e0(p))return i(c,u);let m=u[eX];if(m||(m={buckets:new WeakMap,backEdges:void 0},u[eX]=m),a===u)d=o;else{var h;let r;(r=(h=m).buckets.get(t))||(r=new WeakMap,h.buckets.set(t,r)),d=r,a=u,o=d}let f=d.get(p);if(f)return c.value=f.value,f.issues?f.issues.length&&c.issues.push(...e1(f.issues)):(c.memo=!0,m.backEdges??(m.backEdges=new WeakSet),m.backEdges.add(f.value)),c;r=d;let g=e9.length,y=i(c,u);r=void 0;let v=e9.length>g?e9.pop():void 0;return y instanceof Promise?y.then(t=>(v&&(v.issues=t.issues.length?e1(t.issues):eQ),t)):(v&&(v.issues=y.issues.length?e1(y.issues):eQ),y)};t._zod.parse=l,t._zod.run===i&&(t._zod.run=l)})}},e5=/^[cC][0-9a-z]{6,}$/,e3=/^[0-9a-z]+$/,e6=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,e7=/^[0-9a-vA-V]{20}$/,e8=/^[A-Za-z0-9]{27}$/,te=/^[a-zA-Z0-9_-]{21}$/,tt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tr=/^([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=t=>t?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|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,}$/,ta=`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,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(t){let r="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof t.precision?-1===t.precision?`${r}`:0===t.precision?`${r}:[0-5]\\d`:`${r}:[0-5]\\d\\.\\d{${t.precision}}`:t.seconds?`${r}:[0-5]\\d(?:\\.\\d+)?`:`${r}(?::[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]*$/,tw=eV("$ZodCheck",(t,r)=>{var i;t._zod??(t._zod={}),t._zod.def=r,(i=t._zod).onattach??(i.onattach=[])}),tx=t=>{let r=t.value;return null!=r&&void 0!==r.length},tk={number:"number",bigint:"bigint",object:"date"},tR=eV("$ZodCheckLessThan",(t,r)=>{tw.init(t,r);let i=tk[typeof r.value];t._zod.check=n=>{(r.inclusive?n.value<=r.value:n.value<r.value)||n.issues.push({origin:tk[typeof n.value]??i,code:"too_big",maximum:"object"==typeof r.value?r.value.getTime():r.value,input:n.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),t$=eV("$ZodCheckGreaterThan",(t,r)=>{tw.init(t,r);let i=tk[typeof r.value];t._zod.check=n=>{(r.inclusive?n.value>=r.value:n.value>r.value)||n.issues.push({origin:tk[typeof n.value]??i,code:"too_small",minimum:"object"==typeof r.value?r.value.getTime():r.value,input:n.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),tC=eV("$ZodCheckMultipleOf",(t,r)=>{tw.init(t,r),t._zod.check=i=>{let n,a,o;if(typeof i.value!=typeof r.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof i.value?r.value!==BigInt(0)&&i.value%r.value===BigInt(0):0==(a=Math.round(n=i.value/r.value),o=4*Number.EPSILON*Math.max(Math.abs(n),1),Math.abs(n-a)<o?0:n-a))||i.issues.push({origin:typeof i.value,code:"not_multiple_of",divisor:r.value,input:i.value,inst:t,continue:!r.abort})}}),tT=eV("$ZodCheckNumberFormat",(t,r)=>{tw.init(t,r),r.format=r.format||"float64";let i=r.format?.includes("int"),n=i?"int":"number",[a,o]=ek[r.format];t._zod.check=s=>{let l=s.value;if(i){if(!Number.isInteger(l))return void s.issues.push({expected:n,format:r.format,code:"invalid_type",continue:!1,input:l,inst:t});if(!Number.isSafeInteger(l))return void(l>0?s.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!r.abort}):s.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!r.abort}))}l<a&&s.issues.push({origin:"number",input:l,code:"too_small",minimum:a,inclusive:!0,inst:t,continue:!r.abort}),l>o&&s.issues.push({origin:"number",input:l,code:"too_big",maximum:o,inclusive:!0,inst:t,continue:!r.abort})}}),tO=eV("$ZodCheckMaxLength",(t,r)=>{var i;tw.init(t,r),(i=t._zod.def).when??(i.when=tx),t._zod.check=i=>{let n=i.value,a=n.length;if(("string"==typeof n&&a>r.maximum?ez(n):a)<=r.maximum)return;let o=eN(n);i.issues.push({origin:o,code:"too_big",maximum:r.maximum,inclusive:!0,input:n,inst:t,continue:!r.abort})}}),tP=eV("$ZodCheckMinLength",(t,r)=>{var i;tw.init(t,r),(i=t._zod.def).when??(i.when=tx),t._zod.check=i=>{let n=i.value,a=n.length;if(("string"==typeof n&&a>=r.minimum&&a<2*r.minimum?ez(n):a)>=r.minimum)return;let o=eN(n);i.issues.push({origin:o,code:"too_small",minimum:r.minimum,inclusive:!0,input:n,inst:t,continue:!r.abort})}}),tE=eV("$ZodCheckLengthEquals",(t,r)=>{var i;tw.init(t,r),(i=t._zod.def).when??(i.when=tx),t._zod.check=i=>{let n=i.value,a=n.length,o="string"==typeof n&&a>=r.length&&a<=2*r.length?ez(n):a;if(o===r.length)return;let s=eN(n),l=o>r.length;i.issues.push({origin:s,...l?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},inclusive:!0,exact:!0,input:i.value,inst:t,continue:!r.abort})}}),tI=eV("$ZodCheckStringFormat",(t,r)=>{var i,n;tw.init(t,r),r.pattern?(i=t._zod).check??(i.check=i=>{r.pattern.lastIndex=0,r.pattern.test(i.value)||i.issues.push({origin:"string",code:"invalid_format",format:r.format,input:i.value,...r.pattern?{pattern:r.pattern.toString()}:{},inst:t,continue:!r.abort})}):(n=t._zod).check??(n.check=()=>{})}),tq=eV("$ZodCheckRegex",(t,r)=>{tI.init(t,r),t._zod.check=i=>{r.pattern.lastIndex=0,r.pattern.test(i.value)||i.issues.push({origin:"string",code:"invalid_format",format:"regex",input:i.value,pattern:r.pattern.toString(),inst:t,continue:!r.abort})}}),tj=eV("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=tb),tI.init(t,r)}),tz=eV("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=tS),tI.init(t,r)}),tN=eV("$ZodCheckIncludes",(t,r)=>{tw.init(t,r);let i=eb(r.includes),n=new RegExp("number"==typeof r.position?`^.{${r.position},}${i}`:i);r.pattern=n,t._zod.check=i=>{i.value.includes(r.includes,r.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:r.includes,input:i.value,inst:t,continue:!r.abort})}}),tA=eV("$ZodCheckStartsWith",(t,r)=>{tw.init(t,r);let i=RegExp(`^${eb(r.prefix)}.*`);r.pattern??(r.pattern=i),t._zod.check=i=>{i.value.startsWith(r.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:r.prefix,input:i.value,inst:t,continue:!r.abort})}}),tL=eV("$ZodCheckEndsWith",(t,r)=>{tw.init(t,r);let i=RegExp(`.*${eb(r.suffix)}$`);r.pattern??(r.pattern=i),t._zod.check=i=>{i.value.endsWith(r.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:r.suffix,input:i.value,inst:t,continue:!r.abort})}}),tM=eV("$ZodCheckOverwrite",(t,r)=>{tw.init(t,r),t._zod.check=t=>{t.value=r.tx(t.value)}});class tZ{constructor(t=[],r={}){this.content=[],this.indent=0,this.args=t,this.closed=r}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if("function"==typeof t){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let r=t.split("\n").filter(t=>t),i=Math.min(...r.map(t=>t.length-t.trimStart().length));for(let t of r.map(t=>t.slice(i)).map(t=>" ".repeat(2*this.indent)+t))this.content.push(t)}compile(){let t=Function,r=this?.content??[""];return new t(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
|
1
|
+
let t,r,i,n,a,o,s,l,c,u,d,p,m,h,f,g,y,v,_,b,S,w,k,x;import{AsyncLocalStorage as R}from"async_hooks";var $,C,T,P,E,O,I,q,j,A,N,L,z,M={},Z={};function U(t){var r=Z[t];if(void 0!==r)return r.exports;var i=Z[t]={exports:{}};return M[t](i,i.exports,U),i.exports}U.d=(t,r)=>{for(var i in r)U.o(r,i)&&!U.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:r[i]})},U.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(t){if("object"==typeof window)return window}})(),U.o=(t,r)=>Object.prototype.hasOwnProperty.call(t,r);var F={};U.d(F,{A:()=>hC});var H=Object.create,D=Object.defineProperty,V=Object.getOwnPropertyDescriptor,J=Object.getOwnPropertyNames,B=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty;let G=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),K=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),Y=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),X=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function Q(t){let r=Object.values(t).filter(t=>"number"==typeof t);return Object.entries(t).filter(([t,i])=>-1===r.indexOf(+t)).map(([t,r])=>r)}function ee(t,r="|"){return t.map(t=>ew(t)).join(r)}function et(t,r){return"bigint"==typeof r?r.toString():r}class er{constructor(t){this._getter=t,this._value=void 0}get value(){let t=this._getter;return void 0!==t&&(this._value=t(),this._getter=void 0),this._value}}function ei(t){return new er(t)}function en(t){let r=+!!t.startsWith("^"),i=t.endsWith("$")?t.length-1:t.length;return t.slice(r,i)}let ea=Symbol("evaluating");function eo(t,r,i){Object.defineProperty(t,r,{value:i,writable:!0,enumerable:!0,configurable:!0})}function es(t){let r=Object.getOwnPropertyDescriptor(t,"shape");return r?.get?r.get.raw:r?.value}function el(t){return es(t._zod.def)??t._zod.def.shape}function ec(t,r,i){Object.defineProperty(t,r,{get(){let t=i();return eo(this,r,t),t},enumerable:!0,configurable:!0})}function eu(t,r,i){r in t?eo(t,r,i):t[r]=i}function ed(t,r,i,n){let a=el(r);for(let o of i){let i=Object.getOwnPropertyDescriptor(a,o);i.enumerable&&(i.get?ec(t,o,()=>{let t=r._zod.def.shape[o];return n?n(t,o):t}):eu(t,o,n?n(i.value,o):i.value))}}function ep(...t){let r={};for(let i of t)Object.assign(r,Object.getOwnPropertyDescriptors(i));return Object.defineProperties({},r)}let em="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function eh(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}let ef=ei(()=>{if(eW.jitless||"undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(t){return!1}});function eg(t){if(!1===eh(t))return!1;let r=t.constructor;if(void 0===r||"function"!=typeof r)return!0;let i=r.prototype;return!1!==eh(i)&&!1!==Object.prototype.hasOwnProperty.call(i,"isPrototypeOf")}function ey(t){return eg(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}let ev=new Set(["string","number","symbol"]);function e_(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function eb(t,r,i){let n=new t._zod.constr(r??t._zod.def);return(!r||i?.parent)&&(n._zod.parent=t),n}function eS(t){if(!t)return{};if("string"==typeof t)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return(delete t.message,"string"==typeof t.error)?{...t,error:()=>t.error}:t}function ew(t){return"bigint"==typeof t?t.toString()+"n":"string"==typeof t?`"${t}"`:`${t}`}let ek={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]},ex={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function eR(t,r){let i=el(t),n=[];for(let t of Reflect.ownKeys(r)){if(!Object.getOwnPropertyDescriptor(i,t)?.enumerable)throw Error(`Unrecognized key: "${String(t)}"`);r[t]&&n.push(t)}return n}function e$(t,r){let i={};ed(i,t,Reflect.ownKeys(el(t)));for(let t of Reflect.ownKeys(r)){let n=Object.getOwnPropertyDescriptor(r,t);n.enumerable&&(n.get?ec(i,t,()=>r[t]):eu(i,t,n.value))}return i}function eC(t,r,i,n="partial"){let a=r._zod.def.checks;if(a&&a.length>0)throw Error(`.${n}() cannot be used on object schemas containing refinements`);let o=i?new Set(eR(r,i)):void 0,s={};return ed(s,r,Reflect.ownKeys(el(r)),t&&((r,i)=>o&&!o.has(i)?r:new t({type:"optional",innerType:r}))),eb(r,ep(r._zod.def,{shape:s,checks:[]}))}function eT(t,r=0){if(!0===t.aborted)return!0;for(let i=r;i<t.issues.length;i++)if(t.issues[i]?.continue!==!0)return!0;return!1}function eP(t,r){return r.map(r=>(r.path??(r.path=[]),r.path.unshift(t),r))}function eE(t){return"string"==typeof t?t:t?.message}function eO(t,r,i){var n;for(let a=r;a<t.length;a++)(n=t[a]).schema??(n.schema=i)}function eI(t,r,i){let n=t.inst?._zod?.traits;n?.has("$ZodType")&&(n.has("$ZodCheck")?t.schema??(t.schema=t.inst):t.schema=t.inst);let a=t.schema!==t.inst?t.schema?._zod.def?.error:void 0,o=t.message?t.message:eE(t.inst?._zod.def?.error?.(t))??eE(a?.(t))??eE(r?.error?.(t))??eE(i.customError?.(t))??eE(i.localeError?.(t))??"Invalid input",s={};for(let r of Object.keys(t))"inst"!==r&&"schema"!==r&&"continue"!==r&&"input"!==r&&"__proto__"!==r&&(s[r]=t[r]);return s.path??(s.path=[]),s.message=o,r?.reportInput&&(s.input=t.input),s}let eq=/[\uD800-\uDBFF]/;function ej(t){let r=t.length;if(!eq.test(t))return r;let i=r;for(let n=0;n<r-1;n++)(64512&t.charCodeAt(n))==55296&&(64512&t.charCodeAt(n+1))==56320&&(i--,n++);return i}function eA(t){return Array.isArray(t)?"array":"string"==typeof t?"string":"unknown"}function eN(...t){let[r,i,n]=t;return"string"==typeof r?{message:r,code:"custom",input:i,inst:n}:{...r}}function eL(t,r,i,n=!0){return Object.defineProperty(t,r,{configurable:!0,writable:!0,enumerable:n,value:i}),i}function ez(t,r){for(let i in t){let n=t[i];Object.defineProperty(r,i,{configurable:!0,enumerable:!0,get(){return eL(this,i,n(this))},set(t){eL(this,i,t)}})}return r}let eM=!1,eZ={configurable:!0,get(){eM=!0}};function eU(r,i,n){let a=Object.getPrototypeOf(r._zod);if(i in a&&t!==r._zod){t=void 0;return}t=r._zod,Object.defineProperty(a,i,{configurable:!0,get(){Object.defineProperty(this,i,eZ);let t=eM;eM=!1;try{let r=n(this);return eM?delete this[i]:Object.defineProperty(this,i,{configurable:!0,writable:!0,value:r}),eM=eM||t,r}catch(r){throw delete this[i],eM=eM||t,r}},set(t){Object.defineProperty(this,i,{configurable:!0,writable:!0,value:t})}})}let eF=Object.freeze({status:"aborted"}),eH={value:void 0,enumerable:!1},eD="captureStackTrace"in Error?Error:null;function eV(t,r,i,n){function a(t){this.def=t,this.constr=u,this.traits=new Set}a.prototype={};let o=i&&new WeakSet;function s(n,s){if(n._zod){if(n._zod.traits.has(t))return}else{eH.value=new a(s);try{Object.defineProperty(n,"_zod",eH)}finally{eH.value=void 0}}if(n._zod.traits.add(t),r(n,s),o){let t=Object.getPrototypeOf(n),r=n._zod.constr.prototype,a=t;for(;a&&a!==r;)a=Object.getPrototypeOf(a);let s=a??t;if(!o.has(s)){o.add(s);for(let t in i){let r=Object.getOwnPropertyDescriptor(i,t);r.get?Object.defineProperty(s,t,{...r,enumerable:!1}):function(t,r,i){Object.defineProperty(t,r,{configurable:!0,get(){return this==null?i:eL(this,r,i.bind(this))},set(t){eL(this,r,t)}})}(s,t,r.value)}}}let l=u.prototype;for(let t in l)Object.prototype.hasOwnProperty.call(l,t)&&(t in n||(n[t]=l[t].bind(n)))}let l=n?.Parent??Object;class c extends l{}function u(t){let r=n?.Parent?function(t){let r=eD;if(r){let i=r.stackTraceLimit;if("number"==typeof i){try{r.stackTraceLimit=0}catch{return eD=null,new t}try{return new t}finally{r.stackTraceLimit=i}}}return new t}(c):this;s(r,t);let i=r._zod.deferred;if(i){for(let t of i)t();r._zod.deferred=void 0}let a=globalThis.__zod_globalConfig?.postProcessor;return a&&a(r),r}return Object.defineProperty(c,"name",{value:t}),Object.defineProperty(u,"init",{value:s}),Object.defineProperty(u,Symbol.hasInstance,{value:r=>!!n?.Parent&&r instanceof n.Parent||r?._zod?.traits?.has(t)}),Object.defineProperty(u,"name",{value:t}),u}class eJ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class eB extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(I=globalThis).__zod_globalConfig??(I.__zod_globalConfig={});let eW=globalThis.__zod_globalConfig;function eG(t){return t&&Object.assign(eW,t),eW}class eK extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}let eY="~memo",eX=[];function eQ(t){return null!==t&&"object"==typeof t}function e0(t){return t.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}let e1=new WeakMap,e2=[],e9={alloc(t,i,n){let a=r;if(!a)return n;r=void 0;let o={value:n,issues:null};return a.set(i.value,o),e2.push(o),n},guard(t){var r;(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred.push(()=>{let r=t._zod.parse,i=(t,i)=>{var n,a;let o;if("backward"!==i.direction&&(n=i,a=t.value,void 0!==(o=n[eY]?.backEdges)&&eQ(a)&&o.has(a)))throw new eK;return r(t,i)};t._zod.parse=i,t._zod.run===r&&(t._zod.run=i)})},attach(t){var i;let n,a,o,s=!1;(i=t._zod).deferred??(i.deferred=[]),t._zod.deferred.push(()=>{let i=t._zod.parse,l=(c,u)=>{let d;if(void 0===n){let r=function t(r,i,n){var a,o;let s=e1.get(r);if(void 0!==s)return 2*!!s;if(i.has(r))return 2;i.add(r);let l=0,c=r=>{if(2!==l&&r?._zod){let a=t(r,i,n);a>l&&(l=a)}},u=t=>{t>l&&(l=t)},d=r._zod.def;switch(d.type){case"object":{let r=es(d);u(r?((r,a)=>{let o=0;for(let s of Reflect.ownKeys(r)){let l=Object.getOwnPropertyDescriptor(r,s);if(a&&!l.enumerable)continue;let c=l.get?1:l.value?._zod?t(l.value,i,n):0;c>o&&(o=c)}return o})(r,!0):1),c(d.catchall);break}case"array":c(d.element);break;case"tuple":for(let t of d.items)c(t);c(d.rest);break;case"record":case"map":c(d.keyType),c(d.valueType);break;case"set":c(d.valueType);break;case"union":for(let t of d.options)c(t);break;case"intersection":c(d.left),c(d.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":c(d.innerType);break;case"pipe":c(d.in),c(d.out);break;case"function":c(d.input),c(d.output);break;case"lazy":{let a=d._cachedInner??(n?r._zod.innerType:void 0);u(a?t(a,i,!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 t in d){let r=Object.getOwnPropertyDescriptor(d,t);if(!r||r.get)continue;let i=r.value;if(i&&"object"==typeof i){if(i._zod)c(i);else if(Array.isArray(i))for(let t of i)c(t)}}}return i.delete(r),a=r,1!==(o=l)&&e1.set(a,2===o),o}(t,new Set,!1);if(0===r)return t._zod.parse=i,t._zod.run===l&&(t._zod.run=i),i(c,u);2===r||s?n=!0:s=!0}let p=c.value;if(!eQ(p))return i(c,u);let m=u[eY];if(m||(m={buckets:new WeakMap,backEdges:void 0},u[eY]=m),a===u)d=o;else{var h;let r;(r=(h=m).buckets.get(t))||(r=new WeakMap,h.buckets.set(t,r)),d=r,a=u,o=d}let f=d.get(p);if(f)return c.value=f.value,f.issues?f.issues.length&&c.issues.push(...e0(f.issues)):(c.memo=!0,m.backEdges??(m.backEdges=new WeakSet),m.backEdges.add(f.value)),c;r=d;let g=e2.length,y=i(c,u);r=void 0;let v=e2.length>g?e2.pop():void 0;return y instanceof Promise?y.then(t=>(v&&(v.issues=t.issues.length?e0(t.issues):eX),t)):(v&&(v.issues=y.issues.length?e0(y.issues):eX),y)};t._zod.parse=l,t._zod.run===i&&(t._zod.run=l)})}},e4=/^[cC][0-9a-z]{6,}$/,e5=/^[0-9a-z]+$/,e3=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,e6=/^[0-9a-vA-V]{20}$/,e7=/^[A-Za-z0-9]{27}$/,e8=/^[a-zA-Z0-9_-]{21}$/,te=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,tt=/^([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})$/,tr=t=>t?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ti=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,tn=`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,ta=/^(?:(?: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])$/,to=/^(([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}|:))$/,ts=/^((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])$/,tl=/^(([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])$/,tc=/^https?$/,tu=/^\+[1-9]\d{6,14}$/,td="(?:(?:\\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])))",tp=RegExp(`^${td}$`);function tm(t){let r="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof t.precision?-1===t.precision?`${r}`:0===t.precision?`${r}:[0-5]\\d`:`${r}:[0-5]\\d\\.\\d{${t.precision}}`:t.seconds?`${r}:[0-5]\\d(?:\\.\\d+)?`:`${r}(?::[0-5]\\d(?:\\.\\d+)?)?`}let th=/^[\s\S]{0,}$/,tf=/^-?\d+$/,tg=/^-?\d+(?:\.\d+)?$/,ty=/^(?:true|false)$/i,tv=/^null$/i,t_=/^[^A-Z]*$/,tb=/^[^a-z]*$/,tS=eV("$ZodCheck",(t,r)=>{var i;t._zod??(t._zod={}),t._zod.def=r,(i=t._zod).onattach??(i.onattach=[])}),tw=t=>{let r=t.value;return null!=r&&void 0!==r.length},tk={number:"number",bigint:"bigint",object:"date"},tx=eV("$ZodCheckLessThan",(t,r)=>{tS.init(t,r);let i=tk[typeof r.value];t._zod.check=n=>{(r.inclusive?n.value<=r.value:n.value<r.value)||n.issues.push({origin:tk[typeof n.value]??i,code:"too_big",maximum:"object"==typeof r.value?r.value.getTime():r.value,input:n.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),tR=eV("$ZodCheckGreaterThan",(t,r)=>{tS.init(t,r);let i=tk[typeof r.value];t._zod.check=n=>{(r.inclusive?n.value>=r.value:n.value>r.value)||n.issues.push({origin:tk[typeof n.value]??i,code:"too_small",minimum:"object"==typeof r.value?r.value.getTime():r.value,input:n.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),t$=eV("$ZodCheckMultipleOf",(t,r)=>{tS.init(t,r),t._zod.check=i=>{let n,a,o;if(typeof i.value!=typeof r.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof i.value?r.value!==BigInt(0)&&i.value%r.value===BigInt(0):0==(a=Math.round(n=i.value/r.value),o=4*Number.EPSILON*Math.max(Math.abs(n),1),Math.abs(n-a)<o?0:n-a))||i.issues.push({origin:typeof i.value,code:"not_multiple_of",divisor:r.value,input:i.value,inst:t,continue:!r.abort})}}),tC=eV("$ZodCheckNumberFormat",(t,r)=>{tS.init(t,r),r.format=r.format||"float64";let i=r.format?.includes("int"),n=i?"int":"number",[a,o]=ek[r.format];t._zod.check=s=>{let l=s.value;if(i){if(!Number.isInteger(l))return void s.issues.push({expected:n,format:r.format,code:"invalid_type",continue:!1,input:l,inst:t});if(!Number.isSafeInteger(l))return void(l>0?s.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!r.abort}):s.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!r.abort}))}l<a&&s.issues.push({origin:"number",input:l,code:"too_small",minimum:a,inclusive:!0,inst:t,continue:!r.abort}),l>o&&s.issues.push({origin:"number",input:l,code:"too_big",maximum:o,inclusive:!0,inst:t,continue:!r.abort})}}),tT=eV("$ZodCheckMaxLength",(t,r)=>{var i;tS.init(t,r),(i=t._zod.def).when??(i.when=tw),t._zod.check=i=>{let n=i.value,a=n.length;if(("string"==typeof n&&a>r.maximum?ej(n):a)<=r.maximum)return;let o=eA(n);i.issues.push({origin:o,code:"too_big",maximum:r.maximum,inclusive:!0,input:n,inst:t,continue:!r.abort})}}),tP=eV("$ZodCheckMinLength",(t,r)=>{var i;tS.init(t,r),(i=t._zod.def).when??(i.when=tw),t._zod.check=i=>{let n=i.value,a=n.length;if(("string"==typeof n&&a>=r.minimum&&a<2*r.minimum?ej(n):a)>=r.minimum)return;let o=eA(n);i.issues.push({origin:o,code:"too_small",minimum:r.minimum,inclusive:!0,input:n,inst:t,continue:!r.abort})}}),tE=eV("$ZodCheckLengthEquals",(t,r)=>{var i;tS.init(t,r),(i=t._zod.def).when??(i.when=tw),t._zod.check=i=>{let n=i.value,a=n.length,o="string"==typeof n&&a>=r.length&&a<=2*r.length?ej(n):a;if(o===r.length)return;let s=eA(n),l=o>r.length;i.issues.push({origin:s,...l?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},inclusive:!0,exact:!0,input:i.value,inst:t,continue:!r.abort})}}),tO=eV("$ZodCheckStringFormat",(t,r)=>{var i,n;tS.init(t,r),r.pattern?(i=t._zod).check??(i.check=i=>{r.pattern.lastIndex=0,r.pattern.test(i.value)||i.issues.push({origin:"string",code:"invalid_format",format:r.format,input:i.value,...r.pattern?{pattern:r.pattern.toString()}:{},inst:t,continue:!r.abort})}):(n=t._zod).check??(n.check=()=>{})}),tI=eV("$ZodCheckRegex",(t,r)=>{tO.init(t,r),t._zod.check=i=>{r.pattern.lastIndex=0,r.pattern.test(i.value)||i.issues.push({origin:"string",code:"invalid_format",format:"regex",input:i.value,pattern:r.pattern.toString(),inst:t,continue:!r.abort})}}),tq=eV("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=t_),tO.init(t,r)}),tj=eV("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=tb),tO.init(t,r)}),tA=eV("$ZodCheckIncludes",(t,r)=>{tS.init(t,r);let i=e_(r.includes),n=new RegExp("number"==typeof r.position?`^.{${r.position},}${i}`:i);r.pattern=n,t._zod.check=i=>{i.value.includes(r.includes,r.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:r.includes,input:i.value,inst:t,continue:!r.abort})}}),tN=eV("$ZodCheckStartsWith",(t,r)=>{tS.init(t,r);let i=RegExp(`^${e_(r.prefix)}.*`);r.pattern??(r.pattern=i),t._zod.check=i=>{i.value.startsWith(r.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:r.prefix,input:i.value,inst:t,continue:!r.abort})}}),tL=eV("$ZodCheckEndsWith",(t,r)=>{tS.init(t,r);let i=RegExp(`.*${e_(r.suffix)}$`);r.pattern??(r.pattern=i),t._zod.check=i=>{i.value.endsWith(r.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:r.suffix,input:i.value,inst:t,continue:!r.abort})}}),tz=eV("$ZodCheckOverwrite",(t,r)=>{tS.init(t,r),t._zod.check=t=>{t.value=r.tx(t.value)}});class tM{constructor(t=[],r={}){this.content=[],this.indent=0,this.args=t,this.closed=r}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if("function"==typeof t){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let r=t.split("\n").filter(t=>t),i=Math.min(...r.map(t=>t.length-t.trimStart().length));for(let t of r.map(t=>t.slice(i)).map(t=>" ".repeat(2*this.indent)+t))this.content.push(t)}compile(){let t=Function,r=this?.content??[""];return new t(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
|
2
2
|
${r.join("\n")}
|
|
3
|
-
};`)(...Object.values(this.closed))}}let tU={major:4,minor:6,patch:5},tF=eV("$ZodType",(t,r)=>{var i;t??(t={}),t._zod.def=r,t._zod.bag=t._zod.bag||{},t._zod.version=tU;let n=t._zod.def.checks,a=t._zod.traits.has("$ZodCheck")?[t,...n??[]]:n?.length?[...n]:[];for(let r of a)for(let i of r._zod.onattach)i(t);if(0===a.length)(i=t._zod).deferred??(i.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let r=(r,i,n)=>{let a;if(r.memo)return r;let o=eO(r);for(let s of i){if(s._zod.def.when){if(function(t,r=0){if(!0===t.aborted)return!0;for(let i=r;i<t.issues.length;i++)if(t.issues[i]?.continue===!1)return!0;return!1}(r)||!s._zod.def.when(r))continue}else if(o)continue;let i=r.issues.length,l=s._zod.check(r);if(l instanceof Promise&&n?.async===!1)throw new eB;if(a||l instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await l,r.issues.length!==i&&(eI(r.issues,i,t),o||(o=eO(r,i)))});else{if(r.issues.length===i)continue;eI(r.issues,i,t),o||(o=eO(r,i))}}return a?a.then(()=>r):r},i=(i,n,o)=>{if(eO(i))return i.aborted=!0,i;let s=r(n,a,o);if(s instanceof Promise){if(!1===o.async)throw new eB;return s.then(r=>t._zod.parse(r,o))}return t._zod.parse(s,o)};t._zod.run=(n,o)=>{if(o.skipChecks)return t._zod.parse(n,o);if("backward"===o.direction){let r=t._zod.parse({value:n.value,issues:[]},{...o,skipChecks:!0});return r instanceof Promise?r.then(t=>i(t,n,o)):i(r,n,o)}let s=t._zod.parse(n,o);if(s instanceof Promise){if(!1===o.async)throw new eB;return s.then(t=>r(t,a,o))}return r(s,a,o)}}},{get"~standard"(){return eL(this,"~standard",tD(this),!1)},set"~standard"(value){eL(this,"~standard",value)}}),tH=(t,r)=>t.issues.length?{issues:t.issues.map(t=>eq(t,r,eK()))}:{value:t.value};async function tJ(t,r){let i={async:!0};return tH(await t._zod.run({value:r,issues:[]},i),i)}function tD(t){return{validate:r=>{let i={async:!1};try{let n=t._zod.run({value:r,issues:[]},i);if(!(n instanceof Promise))return tH(n,i)}catch(t){}return tJ(t,r)},vendor:"zod",version:1}}let tV=eV("$ZodString",(t,r)=>{tF.init(t,r),t._zod.pattern=r.pattern??tf,t._zod.parse=(i,n)=>{if(r.coerce)try{i.value=String(i.value)}catch(t){}return"string"==typeof i.value||i.issues.push({expected:"string",code:"invalid_type",input:i.value,inst:t}),i}}),tB=eV("$ZodStringFormat",(t,r)=>{tI.init(t,r),tV.init(t,r)}),tW=eV("$ZodGUID",(t,r)=>{r.pattern??(r.pattern=tr),tB.init(t,r)}),tG=eV("$ZodUUID",(t,r)=>{if(r.version){let t={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[r.version];if(void 0===t)throw Error(`Invalid UUID version: "${r.version}"`);r.pattern??(r.pattern=ti(t))}else r.pattern??(r.pattern=ti());tB.init(t,r)}),tK=eV("$ZodEmail",(t,r)=>{r.pattern??(r.pattern=tn),tB.init(t,r)});function tY(t){try{if("undefined"!=typeof URL&&"function"==typeof URL.canParse)return URL.canParse(t);return new URL(t),!0}catch{return!1}}let tX=/[\t\n\r]/g;function tQ(t){return t.replace(tX,"")}let t0=eV("$ZodURL",(t,r)=>{tB.init(t,r),t._zod.check=i=>{try{var n,a;let o=i.value.trim(),s="normalize"in r||"hostname"in r||"protocol"in r?function(t,r){if(!r.normalize&&r.protocol?.source===tu.source&&!/^https?:\/\//i.test(t))return 1;try{if("undefined"!=typeof URL){let r=URL;if("function"==typeof r.parse)return r.parse(t)??2}return new URL(t)}catch{return 2}}(o,r):tY(o)||2;if(1===s)return void i.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:i.value,inst:t,continue:!r.abort});if(2===s)return void i.issues.push({code:"invalid_format",format:"url",input:i.value,inst:t,continue:!r.abort});if(!0===s){i.value=tQ(o);return}r.hostname&&((n=r.hostname).lastIndex=0,!n.test(s.hostname))&&i.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:r.hostname.source,input:i.value,inst:t,continue:!r.abort}),r.protocol&&((a=r.protocol).lastIndex=0,!a.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol))&&i.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:r.protocol.source,input:i.value,inst:t,continue:!r.abort}),i.value=r.normalize?s.href:tQ(o);return}catch(n){i.issues.push({code:"invalid_format",format:"url",input:i.value,inst:t,continue:!r.abort})}}}),t1=eV("$ZodEmoji",(t,r)=>{r.pattern??(r.pattern=RegExp(ta,"u")),tB.init(t,r)}),t2=eV("$ZodNanoID",(t,r)=>{var i;if(void 0!==r.length&&(!Number.isInteger(r.length)||r.length<1))throw Error(`Invalid nanoid length: ${r.length}`);r.pattern??(r.pattern=void 0===r.length?te:(i=r.length,RegExp(`^[a-zA-Z0-9_-]{${i}}$`))),tB.init(t,r)}),t9=eV("$ZodCUID",(t,r)=>{r.pattern??(r.pattern=e5),tB.init(t,r)}),t4=eV("$ZodCUID2",(t,r)=>{r.pattern??(r.pattern=e3),tB.init(t,r)}),t5=eV("$ZodULID",(t,r)=>{r.pattern??(r.pattern=e6),tB.init(t,r)}),t3=eV("$ZodXID",(t,r)=>{r.pattern??(r.pattern=e7),tB.init(t,r)}),t6=eV("$ZodKSUID",(t,r)=>{r.pattern??(r.pattern=e8),tB.init(t,r)}),t7=eV("$ZodISODateTime",(t,r)=>{let i,n,a;r.pattern??(i=["Z"],r.offset&&i.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)"),n=`${th({precision:r.precision,seconds:!0})}(?:${i.join("|")})`,a=r.local?`${n}|${th({precision:r.precision})}`:n,r.pattern=RegExp(`^${tp}T(?:${a})$`)),tB.init(t,r)}),t8=eV("$ZodISODate",(t,r)=>{r.pattern??(r.pattern=tm),tB.init(t,r)}),re=eV("$ZodISOTime",(t,r)=>{r.pattern??(r.pattern=RegExp(`^${th(r)}$`)),tB.init(t,r)}),rt=eV("$ZodISODuration",(t,r)=>{r.pattern??(r.pattern=tt),tB.init(t,r)}),rr=eV("$ZodIPv4",(t,r)=>{r.pattern??(r.pattern=to),tB.init(t,r)}),ri=/^[0-9a-fA-F:.]+$/;function rn(t){return!!ri.test(t)&&tY(`http://[${t}]`)}let ra=eV("$ZodIPv6",(t,r)=>{r.pattern??(r.pattern=ts),tB.init(t,r),t._zod.check=i=>{rn(i.value)||i.issues.push({code:"invalid_format",format:"ipv6",input:i.value,inst:t,continue:!r.abort})}}),ro=eV("$ZodCIDRv4",(t,r)=>{r.pattern??(r.pattern=tl),tB.init(t,r)}),rs=eV("$ZodCIDRv6",(t,r)=>{r.pattern??(r.pattern=tc),tB.init(t,r),t._zod.check=i=>{!function(t){let r=t.split("/");if(2!==r.length)return!1;let[i,n]=r;if(!n)return!1;let a=Number(n);return`${a}`===n&&!(a<0)&&!(a>128)&&rn(i)}(i.value)&&i.issues.push({code:"invalid_format",format:"cidrv6",input:i.value,inst:t,continue:!r.abort})}});function rl(t){if(""===t)return!0;if(/\s/.test(t)||t.length%4!=0)return!1;try{return atob(t),!0}catch{return!1}}let rc=/^[0-9a-zA-Z+/]*={0,2}$/,ru=eV("$ZodBase64",(t,r)=>{r.pattern??(r.pattern=rc),tB.init(t,r),t._zod.check=i=>{rl(i.value)||i.issues.push({code:"invalid_format",format:"base64",input:i.value,inst:t,continue:!r.abort})}}),rd=/^[A-Za-z0-9_-]*$/,rp=eV("$ZodBase64URL",(t,r)=>{r.pattern??(r.pattern=rd),tB.init(t,r),t._zod.check=i=>{!function(t){if(!rd.test(t))return!1;let r=t.replace(/[-_]/g,t=>"-"===t?"+":"/");return rl(r.padEnd(4*Math.ceil(r.length/4),"="))}(i.value)&&i.issues.push({code:"invalid_format",format:"base64url",input:i.value,inst:t,continue:!r.abort})}}),rm=eV("$ZodE164",(t,r)=>{r.pattern??(r.pattern=td),tB.init(t,r)}),rh=eV("$ZodJWT",(t,r)=>{tB.init(t,r),t._zod.check=i=>{!function(t,r=null){try{let i=t.split(".");if(3!==i.length)return!1;let[n]=i;if(!n)return!1;let a=JSON.parse(atob(n));if("typ"in a&&a?.typ!=="JWT"||!a.alg||r&&(!("alg"in a)||a.alg!==r))return!1;return!0}catch{return!1}}(i.value,r.alg)&&i.issues.push({code:"invalid_format",format:"jwt",input:i.value,inst:t,continue:!r.abort})}}),rf=eV("$ZodNumber",(t,r)=>{tF.init(t,r),t._zod.pattern=ty,t._zod.parse=(i,n)=>{if(r.coerce)try{i.value=Number(i.value)}catch(t){}let a=i.value;if("number"==typeof a&&!Number.isNaN(a)&&Number.isFinite(a))return i;let o="number"==typeof a?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:String(a):void 0;return i.issues.push({expected:"number",code:"invalid_type",input:a,inst:t,...o?{received:o}:{}}),i}}),rg=eV("$ZodNumberFormat",(t,r)=>{tT.init(t,r),rf.init(t,r)}),ry=eV("$ZodBoolean",(t,r)=>{tF.init(t,r),t._zod.pattern=tv,t._zod.parse=(i,n)=>{if(r.coerce)try{i.value=!!i.value}catch(t){}let a=i.value;return"boolean"==typeof a||i.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:t}),i}}),rv=eV("$ZodNull",(t,r)=>{tF.init(t,r),t._zod.pattern=t_,t._zod.values=new Set([null]),t._zod.parse=(r,i)=>{let n=r.value;return null===n||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:t}),r}}),r_=eV("$ZodAny",(t,r)=>{tF.init(t,r),t._zod.parse=t=>t}),rb=eV("$ZodUnknown",(t,r)=>{tF.init(t,r),t._zod.parse=t=>t}),rS=eV("$ZodNever",(t,r)=>{tF.init(t,r),t._zod.parse=(r,i)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function rw(t,r,i){t.issues.length&&r.issues.push(...eP(i,t.issues)),r.value[i]=t.value}let rx=eV("$ZodArray",(t,r)=>{tF.init(t,r);let i=eG.memoizer;i?.attach(t),t._zod.parse=(n,a)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=i?i.alloc(t,n,Array(o.length),a):Array(o.length);let s=[],l=a?.abortEarly;for(let t=0;t<o.length;t++){let i=o[t],c=r.element._zod.run({value:i,issues:[]},a);if(c instanceof Promise)s.push(c.then(r=>rw(r,n,t)));else if(rw(c,n,t),l&&0!==c.issues.length&&eO(c))break}return s.length?Promise.all(s).then(()=>n):n}});function rk(t,r,i,n,a,o){let s=i in n,l="optional"===o;if(s||!l||"optional"!==a){if(t.issues.length){if(void 0!==a&&l&&!s)return;r.issues.push(...eP(i,t.issues))}if(!s&&void 0===a){t.issues.length||r.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[i]});return}void 0===t.value?(s||"defaulted"===a&&!l)&&(r.value[i]=void 0):r.value[i]=t.value}}let rR=[];function r$(t){var r;let i=Object.keys(t.shape),n=Object.getOwnPropertySymbols(t.shape),a=n.length?n:rR,o=a.length?[...i,...a]:i;for(let r of o)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(r)}": expected a Zod schema`);let s=Object.keys(r=t.shape).filter(t=>void 0!==r[t]._zod.optin&&"optional"===r[t]._zod.optout);return{...t,allKeys:o,symbolKeys:a,keySet:new Set(i),numKeys:i.length,optionalKeys:new Set(s)}}function rC(t,r,i,n,a,o,s){let l=[],c=a.keySet,u=a.catchall._zod,d=u.def.type,p=u.optin,m=u.optout,h=0;for(let a in r){if(s&&i.issues.length!==h){if(eO(i,h))break;h=i.issues.length}if(c.has(a))continue;if("__proto__"===a){"never"===d&&l.push(a);continue}if("never"===d){l.push(a);continue}let o=u.run({value:r[a],issues:[]},n);o instanceof Promise?t.push(o.then(t=>rk(t,i,a,r,p,m))):rk(o,i,a,r,p,m)}return(l.length&&i.issues.push({code:"unrecognized_keys",keys:l,input:r,inst:o,continue:!0}),t.length)?Promise.all(t).then(()=>i):i}let rT=eV("$ZodObject",(t,r)=>{let i;tF.init(t,r);let n=Object.getOwnPropertyDescriptor(r,"shape"),a=n?.get?n.get.raw:r.shape??{};if(a){let t=()=>{let i={...a};return Object.defineProperty(r,"shape",{value:i}),t.raw=i,i};t.raw=a,Object.defineProperty(r,"shape",{get:t})}let o=en(()=>r$(r));eF(t,"propValues",t=>{let r=t.def.shape,i={};for(let t in r){let n=r[t]._zod;if(n.values){for(let r of(Object.prototype.hasOwnProperty.call(i,t)||es(i,t,new Set),n.values))i[t].add(r);void 0!==n.optin&&i[t].add(void 0)}}return i});let s=r.catchall,l=eG.memoizer;l?.attach(t),t._zod.parse=(r,n)=>{i??(i=o.value);let a=r.value;if(!ef(a))return r.issues.push({expected:"object",code:"invalid_type",input:a,inst:t}),r;r.value=l?l.alloc(t,r,{},n):{};let c=[],u=i.shape,d=n?.abortEarly,p=r.issues.length;for(let t of i.allKeys){if(d&&r.issues.length!==p){if(eO(r,p))break;p=r.issues.length}if("__proto__"===t)continue;let i=u[t],o=i._zod.optin,s=i._zod.optout,l=i._zod.run({value:a[t],issues:[]},n);l instanceof Promise?c.push(l.then(i=>rk(i,r,t,a,o,s))):rk(l,r,t,a,o,s)}return s?rC(c,a,r,n,o.value,t,!0===d):c.length?Promise.all(c).then(()=>r):r}}),rO=eV("$ZodObjectJIT",(t,r)=>{let i,n;rT.init(t,r);let a=t._zod.parse,o=en(()=>r$(r)),s=eG.memoizer,l=!eG.jitless,c=l&&eg.value,u=r.catchall;t._zod.parse=(d,p)=>{n??(n=o.value);let m=d.value;return ef(m)?l&&c&&p?.async===!1&&!0!==p.jitless?(i||(i=(r=>{let i=o.value,n=i.symbolKeys,a=new tZ(["payload","ctx"],{shape:r,inst:t,memo:s,syms:n}),l=t=>`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`,c=(t,r)=>`
|
|
3
|
+
};`)(...Object.values(this.closed))}}let tZ={major:4,minor:6,patch:5},tU=eV("$ZodType",(t,r)=>{var i;t??(t={}),t._zod.def=r,t._zod.bag=t._zod.bag||{},t._zod.version=tZ;let n=t._zod.def.checks,a=t._zod.traits.has("$ZodCheck")?[t,...n??[]]:n?.length?[...n]:[];for(let r of a)for(let i of r._zod.onattach)i(t);if(0===a.length)(i=t._zod).deferred??(i.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let r=(r,i,n)=>{let a;if(r.memo)return r;let o=eT(r);for(let s of i){if(s._zod.def.when){if(function(t,r=0){if(!0===t.aborted)return!0;for(let i=r;i<t.issues.length;i++)if(t.issues[i]?.continue===!1)return!0;return!1}(r)||!s._zod.def.when(r))continue}else if(o)continue;let i=r.issues.length,l=s._zod.check(r);if(l instanceof Promise&&n?.async===!1)throw new eJ;if(a||l instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await l,r.issues.length!==i&&(eO(r.issues,i,t),o||(o=eT(r,i)))});else{if(r.issues.length===i)continue;eO(r.issues,i,t),o||(o=eT(r,i))}}return a?a.then(()=>r):r},i=(i,n,o)=>{if(eT(i))return i.aborted=!0,i;let s=r(n,a,o);if(s instanceof Promise){if(!1===o.async)throw new eJ;return s.then(r=>t._zod.parse(r,o))}return t._zod.parse(s,o)};t._zod.run=(n,o)=>{if(o.skipChecks)return t._zod.parse(n,o);if("backward"===o.direction){let r=t._zod.parse({value:n.value,issues:[]},{...o,skipChecks:!0});return r instanceof Promise?r.then(t=>i(t,n,o)):i(r,n,o)}let s=t._zod.parse(n,o);if(s instanceof Promise){if(!1===o.async)throw new eJ;return s.then(t=>r(t,a,o))}return r(s,a,o)}}},{get"~standard"(){return eL(this,"~standard",tD(this),!1)},set"~standard"(value){eL(this,"~standard",value)}}),tF=(t,r)=>t.issues.length?{issues:t.issues.map(t=>eI(t,r,eG()))}:{value:t.value};async function tH(t,r){let i={async:!0};return tF(await t._zod.run({value:r,issues:[]},i),i)}function tD(t){return{validate:r=>{let i={async:!1};try{let n=t._zod.run({value:r,issues:[]},i);if(!(n instanceof Promise))return tF(n,i)}catch(t){}return tH(t,r)},vendor:"zod",version:1}}let tV=eV("$ZodString",(t,r)=>{tU.init(t,r),t._zod.pattern=r.pattern??th,t._zod.parse=(i,n)=>{if(r.coerce)try{i.value=String(i.value)}catch(t){}return"string"==typeof i.value||i.issues.push({expected:"string",code:"invalid_type",input:i.value,inst:t}),i}}),tJ=eV("$ZodStringFormat",(t,r)=>{tO.init(t,r),tV.init(t,r)}),tB=eV("$ZodGUID",(t,r)=>{r.pattern??(r.pattern=tt),tJ.init(t,r)}),tW=eV("$ZodUUID",(t,r)=>{if(r.version){let t={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[r.version];if(void 0===t)throw Error(`Invalid UUID version: "${r.version}"`);r.pattern??(r.pattern=tr(t))}else r.pattern??(r.pattern=tr());tJ.init(t,r)}),tG=eV("$ZodEmail",(t,r)=>{r.pattern??(r.pattern=ti),tJ.init(t,r)});function tK(t){try{if("undefined"!=typeof URL&&"function"==typeof URL.canParse)return URL.canParse(t);return new URL(t),!0}catch{return!1}}let tY=/[\t\n\r]/g;function tX(t){return t.replace(tY,"")}let tQ=eV("$ZodURL",(t,r)=>{tJ.init(t,r),t._zod.check=i=>{try{var n,a;let o=i.value.trim(),s="normalize"in r||"hostname"in r||"protocol"in r?function(t,r){if(!r.normalize&&r.protocol?.source===tc.source&&!/^https?:\/\//i.test(t))return 1;try{if("undefined"!=typeof URL){let r=URL;if("function"==typeof r.parse)return r.parse(t)??2}return new URL(t)}catch{return 2}}(o,r):tK(o)||2;if(1===s)return void i.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:i.value,inst:t,continue:!r.abort});if(2===s)return void i.issues.push({code:"invalid_format",format:"url",input:i.value,inst:t,continue:!r.abort});if(!0===s){i.value=tX(o);return}r.hostname&&((n=r.hostname).lastIndex=0,!n.test(s.hostname))&&i.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:r.hostname.source,input:i.value,inst:t,continue:!r.abort}),r.protocol&&((a=r.protocol).lastIndex=0,!a.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol))&&i.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:r.protocol.source,input:i.value,inst:t,continue:!r.abort}),i.value=r.normalize?s.href:tX(o);return}catch(n){i.issues.push({code:"invalid_format",format:"url",input:i.value,inst:t,continue:!r.abort})}}}),t0=eV("$ZodEmoji",(t,r)=>{r.pattern??(r.pattern=RegExp(tn,"u")),tJ.init(t,r)}),t1=eV("$ZodNanoID",(t,r)=>{var i;if(void 0!==r.length&&(!Number.isInteger(r.length)||r.length<1))throw Error(`Invalid nanoid length: ${r.length}`);r.pattern??(r.pattern=void 0===r.length?e8:(i=r.length,RegExp(`^[a-zA-Z0-9_-]{${i}}$`))),tJ.init(t,r)}),t2=eV("$ZodCUID",(t,r)=>{r.pattern??(r.pattern=e4),tJ.init(t,r)}),t9=eV("$ZodCUID2",(t,r)=>{r.pattern??(r.pattern=e5),tJ.init(t,r)}),t4=eV("$ZodULID",(t,r)=>{r.pattern??(r.pattern=e3),tJ.init(t,r)}),t5=eV("$ZodXID",(t,r)=>{r.pattern??(r.pattern=e6),tJ.init(t,r)}),t3=eV("$ZodKSUID",(t,r)=>{r.pattern??(r.pattern=e7),tJ.init(t,r)}),t6=eV("$ZodISODateTime",(t,r)=>{let i,n,a;r.pattern??(i=["Z"],r.offset&&i.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)"),n=`${tm({precision:r.precision,seconds:!0})}(?:${i.join("|")})`,a=r.local?`${n}|${tm({precision:r.precision})}`:n,r.pattern=RegExp(`^${td}T(?:${a})$`)),tJ.init(t,r)}),t7=eV("$ZodISODate",(t,r)=>{r.pattern??(r.pattern=tp),tJ.init(t,r)}),t8=eV("$ZodISOTime",(t,r)=>{r.pattern??(r.pattern=RegExp(`^${tm(r)}$`)),tJ.init(t,r)}),re=eV("$ZodISODuration",(t,r)=>{r.pattern??(r.pattern=te),tJ.init(t,r)}),rt=eV("$ZodIPv4",(t,r)=>{r.pattern??(r.pattern=ta),tJ.init(t,r)}),rr=/^[0-9a-fA-F:.]+$/;function ri(t){return!!rr.test(t)&&tK(`http://[${t}]`)}let rn=eV("$ZodIPv6",(t,r)=>{r.pattern??(r.pattern=to),tJ.init(t,r),t._zod.check=i=>{ri(i.value)||i.issues.push({code:"invalid_format",format:"ipv6",input:i.value,inst:t,continue:!r.abort})}}),ra=eV("$ZodCIDRv4",(t,r)=>{r.pattern??(r.pattern=ts),tJ.init(t,r)}),ro=eV("$ZodCIDRv6",(t,r)=>{r.pattern??(r.pattern=tl),tJ.init(t,r),t._zod.check=i=>{!function(t){let r=t.split("/");if(2!==r.length)return!1;let[i,n]=r;if(!n)return!1;let a=Number(n);return`${a}`===n&&!(a<0)&&!(a>128)&&ri(i)}(i.value)&&i.issues.push({code:"invalid_format",format:"cidrv6",input:i.value,inst:t,continue:!r.abort})}});function rs(t){if(""===t)return!0;if(/\s/.test(t)||t.length%4!=0)return!1;try{return atob(t),!0}catch{return!1}}let rl=/^[0-9a-zA-Z+/]*={0,2}$/,rc=eV("$ZodBase64",(t,r)=>{r.pattern??(r.pattern=rl),tJ.init(t,r),t._zod.check=i=>{rs(i.value)||i.issues.push({code:"invalid_format",format:"base64",input:i.value,inst:t,continue:!r.abort})}}),ru=/^[A-Za-z0-9_-]*$/,rd=eV("$ZodBase64URL",(t,r)=>{r.pattern??(r.pattern=ru),tJ.init(t,r),t._zod.check=i=>{!function(t){if(!ru.test(t))return!1;let r=t.replace(/[-_]/g,t=>"-"===t?"+":"/");return rs(r.padEnd(4*Math.ceil(r.length/4),"="))}(i.value)&&i.issues.push({code:"invalid_format",format:"base64url",input:i.value,inst:t,continue:!r.abort})}}),rp=eV("$ZodE164",(t,r)=>{r.pattern??(r.pattern=tu),tJ.init(t,r)}),rm=eV("$ZodJWT",(t,r)=>{tJ.init(t,r),t._zod.check=i=>{!function(t,r=null){try{let i=t.split(".");if(3!==i.length)return!1;let[n]=i;if(!n)return!1;let a=JSON.parse(atob(n));if("typ"in a&&a?.typ!=="JWT"||!a.alg||r&&(!("alg"in a)||a.alg!==r))return!1;return!0}catch{return!1}}(i.value,r.alg)&&i.issues.push({code:"invalid_format",format:"jwt",input:i.value,inst:t,continue:!r.abort})}}),rh=eV("$ZodNumber",(t,r)=>{tU.init(t,r),t._zod.pattern=tg,t._zod.parse=(i,n)=>{if(r.coerce)try{i.value=Number(i.value)}catch(t){}let a=i.value;if("number"==typeof a&&!Number.isNaN(a)&&Number.isFinite(a))return i;let o="number"==typeof a?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:String(a):void 0;return i.issues.push({expected:"number",code:"invalid_type",input:a,inst:t,...o?{received:o}:{}}),i}}),rf=eV("$ZodNumberFormat",(t,r)=>{tC.init(t,r),rh.init(t,r)}),rg=eV("$ZodBoolean",(t,r)=>{tU.init(t,r),t._zod.pattern=ty,t._zod.parse=(i,n)=>{if(r.coerce)try{i.value=!!i.value}catch(t){}let a=i.value;return"boolean"==typeof a||i.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:t}),i}}),ry=eV("$ZodNull",(t,r)=>{tU.init(t,r),t._zod.pattern=tv,t._zod.values=new Set([null]),t._zod.parse=(r,i)=>{let n=r.value;return null===n||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:t}),r}}),rv=eV("$ZodAny",(t,r)=>{tU.init(t,r),t._zod.parse=t=>t}),r_=eV("$ZodUnknown",(t,r)=>{tU.init(t,r),t._zod.parse=t=>t}),rb=eV("$ZodNever",(t,r)=>{tU.init(t,r),t._zod.parse=(r,i)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function rS(t,r,i){t.issues.length&&r.issues.push(...eP(i,t.issues)),r.value[i]=t.value}let rw=eV("$ZodArray",(t,r)=>{tU.init(t,r);let i=eW.memoizer;i?.attach(t),t._zod.parse=(n,a)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=i?i.alloc(t,n,Array(o.length),a):Array(o.length);let s=[],l=a?.abortEarly;for(let t=0;t<o.length;t++){let i=o[t],c=r.element._zod.run({value:i,issues:[]},a);if(c instanceof Promise)s.push(c.then(r=>rS(r,n,t)));else if(rS(c,n,t),l&&0!==c.issues.length&&eT(c))break}return s.length?Promise.all(s).then(()=>n):n}});function rk(t,r,i,n,a,o){let s=i in n,l="optional"===o;if(s||!l||"optional"!==a){if(t.issues.length){if(void 0!==a&&l&&!s)return;r.issues.push(...eP(i,t.issues))}if(!s&&void 0===a){t.issues.length||r.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[i]});return}void 0===t.value?(s||"defaulted"===a&&!l)&&(r.value[i]=void 0):r.value[i]=t.value}}let rx=[];function rR(t){var r;let i=Object.keys(t.shape),n=Object.getOwnPropertySymbols(t.shape),a=n.length?n:rx,o=a.length?[...i,...a]:i;for(let r of o)if(!t.shape?.[r]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(r)}": expected a Zod schema`);let s=Object.keys(r=t.shape).filter(t=>void 0!==r[t]._zod.optin&&"optional"===r[t]._zod.optout);return{...t,allKeys:o,symbolKeys:a,keySet:new Set(i),numKeys:i.length,optionalKeys:new Set(s)}}function r$(t,r,i,n,a,o,s){let l=[],c=a.keySet,u=a.catchall._zod,d=u.def.type,p=u.optin,m=u.optout,h=0;for(let a in r){if(s&&i.issues.length!==h){if(eT(i,h))break;h=i.issues.length}if(c.has(a))continue;if("__proto__"===a){"never"===d&&l.push(a);continue}if("never"===d){l.push(a);continue}let o=u.run({value:r[a],issues:[]},n);o instanceof Promise?t.push(o.then(t=>rk(t,i,a,r,p,m))):rk(o,i,a,r,p,m)}return(l.length&&i.issues.push({code:"unrecognized_keys",keys:l,input:r,inst:o,continue:!0}),t.length)?Promise.all(t).then(()=>i):i}let rC=eV("$ZodObject",(t,r)=>{let i;tU.init(t,r);let n=Object.getOwnPropertyDescriptor(r,"shape"),a=n?.get?n.get.raw:r.shape??{};if(a){let t=()=>{let i={...a};return Object.defineProperty(r,"shape",{value:i}),t.raw=i,i};t.raw=a,Object.defineProperty(r,"shape",{get:t})}let o=ei(()=>rR(r));eU(t,"propValues",t=>{let r=t.def.shape,i={};for(let t in r){let n=r[t]._zod;if(n.values){for(let r of(Object.prototype.hasOwnProperty.call(i,t)||eo(i,t,new Set),n.values))i[t].add(r);void 0!==n.optin&&i[t].add(void 0)}}return i});let s=r.catchall,l=eW.memoizer;l?.attach(t),t._zod.parse=(r,n)=>{i??(i=o.value);let a=r.value;if(!eh(a))return r.issues.push({expected:"object",code:"invalid_type",input:a,inst:t}),r;r.value=l?l.alloc(t,r,{},n):{};let c=[],u=i.shape,d=n?.abortEarly,p=r.issues.length;for(let t of i.allKeys){if(d&&r.issues.length!==p){if(eT(r,p))break;p=r.issues.length}if("__proto__"===t)continue;let i=u[t],o=i._zod.optin,s=i._zod.optout,l=i._zod.run({value:a[t],issues:[]},n);l instanceof Promise?c.push(l.then(i=>rk(i,r,t,a,o,s))):rk(l,r,t,a,o,s)}return s?r$(c,a,r,n,o.value,t,!0===d):c.length?Promise.all(c).then(()=>r):r}}),rT=eV("$ZodObjectJIT",(t,r)=>{let i,n;rC.init(t,r);let a=t._zod.parse,o=ei(()=>rR(r)),s=eW.memoizer,l=!eW.jitless,c=l&&ef.value,u=r.catchall;t._zod.parse=(d,p)=>{n??(n=o.value);let m=d.value;return eh(m)?l&&c&&p?.async===!1&&!0!==p.jitless?(i||(i=(r=>{let i=o.value,n=i.symbolKeys,a=new tM(["payload","ctx"],{shape:r,inst:t,memo:s,syms:n}),l=t=>`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`,c=(t,r)=>`
|
|
4
4
|
let ${t}_ab = false;
|
|
5
5
|
for (let i = 0; i < ${t}.issues.length; i++) {
|
|
6
6
|
const iss = ${t}.issues[i];
|
|
@@ -50,16 +50,16 @@ ${r.join("\n")}
|
|
|
50
50
|
newResult[${o}] = ${i}.value;
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
-
`)}return a.write("payload.value = newResult;"),a.write("return payload;"),a.compile()})(r.shape)),d=i(d,p),u)?rC([],m,d,p,n,t,p?.abortEarly===!0):d:a(d,p):(d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d)}});function rP(t,r,i,n){for(let i of t)if(0===i.issues.length)return r.value=i.value,r;let a=t.filter(t=>!eO(t));return 1===a.length?(r.value=a[0].value,a[0]):(r.issues.push({code:"invalid_union",input:r.value,inst:i,errors:t.map(t=>t.issues.map(t=>eq(t,n,eK())))}),r)}let rE=eV("$ZodUnion",(t,r)=>{tF.init(t,r),eF(t,"optin",t=>t.def.options.some(t=>"defaulted"===t._zod.optin)?"defaulted":t.def.options.some(t=>void 0!==t._zod.optin)?"optional":void 0),eF(t,"optout",t=>t.def.options.some(t=>"optional"===t._zod.optout)?"optional":void 0),eF(t,"values",t=>{if(t.def.options.every(t=>t._zod.values))return new Set(t.def.options.flatMap(t=>Array.from(t._zod.values)))}),eF(t,"pattern",t=>{if(t.def.options.every(t=>t._zod.pattern)){let r=t.def.options.map(t=>t._zod.pattern);return RegExp(`^(${r.map(t=>ea(t.source)).join("|")})$`)}});let i=1===r.options.length?r.options[0]._zod.run:null;t._zod.parse=(n,a)=>{if(i)return i(n,a);let o=!1,s=[];for(let t of r.options){let r=t._zod.run({value:n.value,issues:[]},a);if(r instanceof Promise)s.push(r),o=!0;else{if(0===r.issues.length)return r;s.push(r)}}return o?Promise.all(s).then(r=>rP(r,n,t,a)):rP(s,n,t,a)}}),rI=eV("$ZodDiscriminatedUnion",(t,r)=>{r.inclusive=!1,rE.init(t,r);let i=t._zod.parse;eF(t,"propValues",t=>{let r={},i=0;for(let n of t.def.options){let a=n._zod.propValues;if(!a||0===Object.keys(a).length)throw Error(`Invalid discriminated union option at index "${t.def.options.indexOf(n)}"`);for(let[n,o]of(a[t.def.discriminator]?.has(void 0)&&i++,Object.entries(a)))for(let t of(Object.prototype.hasOwnProperty.call(r,n)||es(r,n,new Set),o))r[n].add(t)}return!t.def.unionFallback&&i>1&&r[t.def.discriminator]?.delete(void 0),r}),r.options.forEach((t,i)=>{let n=el(t._zod.def);if(n&&!Object.prototype.hasOwnProperty.call(n,r.discriminator))throw Error(`Invalid discriminated union option at index "${i}"`)});let n=en(()=>(function(t){let r=new Map;for(let i of t.options){let n=i._zod.propValues?.[t.discriminator];if(!n||0===n.size)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let t of n)if(r.has(t)){if(void 0!==t)throw Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,null)}else r.set(t,i)}return r})(r));t._zod.parse=(a,o)=>{let s=a.value;if(!ef(s))return a.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),a;let l=s?.[r.discriminator],c=n.value.get(l);return c&&(void 0!==l||"backward"!==o.direction)?c._zod.run(a,o):r.unionFallback||"backward"===o.direction?i(a,o):(a.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:r.discriminator,options:Array.from(n.value.keys()).filter(t=>null!==n.value.get(t)),input:s,path:[r.discriminator],inst:t}),a)}}),rq=eV("$ZodIntersection",(t,r)=>{tF.init(t,r),t._zod.parse=(t,i)=>{let n=t.value,a=r.left._zod.run({value:n,issues:[]},i),o=r.right._zod.run({value:n,issues:[]},i);return a instanceof Promise||o instanceof Promise?Promise.all([a,o]).then(([r,i])=>rj(t,r,i)):rj(t,a,o)}});function rj(t,r,i){let n,a=new Map,o=new Map,s=(t,r)=>{let i;if("unrecognized_keys"!==t.code||t.path?.length)if("invalid_key"!==t.code||"record"!==t.origin||t.path?.length!==1)return!1;else{let r=String(t.path[0]);o.has(r)||o.set(r,t),i=[r]}else n??(n=t),i=t.keys;for(let t of i)a.has(t)||a.set(t,{}),a.get(t)[r]=!0;return!0};for(let i of r.issues)s(i,"l")||t.issues.push(i);for(let r of i.issues)s(r,"r")||t.issues.push(r);let l=[...a].filter(([,t])=>t.l&&t.r).map(([t])=>t);if(l.length){let r=n?l.filter(t=>n.keys.includes(t)):[];for(let i of(r.length&&t.issues.push({...n,keys:r}),l))!r.includes(i)&&o.has(i)&&t.issues.push(o.get(i))}let c=function t(r,i){if(r===i||r instanceof Date&&i instanceof Date&&+r==+i)return{valid:!0,data:r};if(ey(r)&&ey(i)){let n=Object.keys(i),a=Object.keys(r).filter(t=>-1!==n.indexOf(t)),o={...r,...i};for(let n of(Object.prototype.hasOwnProperty.call(o,"__proto__")&&delete o.__proto__,a)){if("__proto__"===n)continue;let a=t(r[n],i[n]);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};o[n]=a.data}return{valid:!0,data:o}}if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let a=0;a<r.length;a++){let o=t(r[a],i[a]);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}(r.value,i.value);if(!c.valid){if(eO(t))return t;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return t.value=c.data,t}let rz=eV("$ZodRecord",(t,r)=>{tF.init(t,r);let i=eG.memoizer;i?.attach(t),t._zod.parse=(n,a)=>{let o=n.value;if(!ey(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[],l=r.keyType._zod.values;if(l&&!r.partial){let c;n.value=i?i.alloc(t,n,{},a):{};let u=new Set;for(let i of l)if("string"==typeof i||"number"==typeof i||"symbol"==typeof i){if(u.add("number"==typeof i?i.toString():i),"__proto__"===i)continue;let l=r.keyType._zod.run({value:i,issues:[]},a);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(l.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(t=>eq(t,a,eK())),input:i,path:[i],inst:t});continue}let c=l.value;if("__proto__"===c)continue;let d=r.valueType._zod.run({value:o[i],issues:[]},a);d instanceof Promise?s.push(d.then(t=>{t.issues.length&&n.issues.push(...eP(i,t.issues)),n.value[c]=t.value})):(d.issues.length&&n.issues.push(...eP(i,d.issues)),n.value[c]=d.value)}for(let t in o)if(!u.has(t))if("loose"===r.mode){if("__proto__"===t)continue;n.value[t]=o[t]}else(c=c??[]).push(t);c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c,continue:!0})}else{let c;for(let u of(n.value=i?i.alloc(t,n,{},a):{},Reflect.ownKeys(o))){if("__proto__"===u||!Object.prototype.propertyIsEnumerable.call(o,u))continue;let i=r.keyType._zod.run({value:u,issues:[]},a);if(i instanceof Promise)throw Error("Async schemas not supported in object keys currently");if("string"==typeof u&&ty.test(u)&&i.issues.length){let t=r.keyType._zod.run({value:Number(u),issues:[]},a);if(t instanceof Promise)throw Error("Async schemas not supported in object keys currently");0===t.issues.length&&(i=t)}if(i.issues.length){"loose"===r.mode?n.value[u]=o[u]:l?(c=c??[]).push(u):n.issues.push({code:"invalid_key",origin:"record",issues:i.issues.map(t=>eq(t,a,eK())),input:u,path:[u],inst:t});continue}let d=i.value;if("__proto__"===d)continue;let p=r.valueType._zod.run({value:o[u],issues:[]},a);p instanceof Promise?s.push(p.then(t=>{t.issues.length&&n.issues.push(...eP(u,t.issues)),n.value[d]=t.value})):(p.issues.length&&n.issues.push(...eP(u,p.issues)),n.value[d]=p.value)}c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c,continue:!0})}return s.length?Promise.all(s).then(()=>n):n}}),rN=eV("$ZodEnum",(t,r)=>{tF.init(t,r);let i=ee(r.entries),n=new Set(i);t._zod.values=n,eF(t,"pattern",t=>{let r=ee(t.def.entries).filter(t=>e_.has(typeof t));return new RegExp(r.length?`^(${r.map(t=>eb(t.toString())).join("|")})$`:"^[^\\s\\S]$")}),t._zod.parse=(r,a)=>{let o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:i,input:o,inst:t}),r}}),rA=eV("$ZodLiteral",(t,r)=>{tF.init(t,r);let i=new Set(r.values);t._zod.values=i,eF(t,"pattern",t=>{let r=t.def.values;return new RegExp(r.length?`^(${r.map(t=>"string"==typeof t?eb(t):t?eb(t.toString()):String(t)).join("|")})$`:"^[^\\s\\S]$")}),t._zod.parse=(n,a)=>{let o=n.value;return i.has(o)||n.issues.push({code:"invalid_value",values:r.values,input:o,inst:t}),n}}),rL=eV("$ZodTransform",(t,r)=>{tF.init(t,r),t._zod.optin="optional",eG.memoizer?.guard(t),t._zod.parse=(i,n)=>{if("backward"===n.direction)throw new eW(t.constructor.name);let a=r.transform(i.value,i);if(n.async)return(a instanceof Promise?a:Promise.resolve(a)).then(t=>(i.value=t,i));if(a instanceof Promise)throw new eB;return i.value=a,i}});function rM(t,r){return t.value=r.issues.length?void 0:r.value,t}let rZ=eV("$ZodOptional",(t,r)=>{tF.init(t,r),eF(t,"optin",t=>"defaulted"===t.def.innerType._zod.optin?"defaulted":"optional"),t._zod.optout="optional",eF(t,"values",t=>{let r=t.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),eF(t,"pattern",t=>{let r=t.def.innerType._zod.pattern;return r?RegExp(`^(${ea(r.source)})?$`):void 0}),t._zod.parse=(t,i)=>{if(void 0===t.value){if("defaulted"!==r.innerType._zod.optin)return t;let n=r.innerType._zod.run({value:t.value,issues:[]},i);return n instanceof Promise?n.then(r=>rM(t,r)):rM(t,n)}return r.innerType._zod.run(t,i)}}),rU=eV("$ZodExactOptional",(t,r)=>{rZ.init(t,r),eF(t,"values",t=>t.def.innerType._zod.values),eF(t,"pattern",t=>t.def.innerType._zod.pattern),t._zod.parse=(t,i)=>r.innerType._zod.run(t,i)}),rF=eV("$ZodNullable",(t,r)=>{tF.init(t,r),eF(t,"optin",t=>t.def.innerType._zod.optin),eF(t,"optout",t=>t.def.innerType._zod.optout),eF(t,"pattern",t=>{let r=t.def.innerType._zod.pattern;return r?RegExp(`^(${ea(r.source)}|null)$`):void 0}),eF(t,"values",t=>t.def.innerType._zod.values?new Set([...t.def.innerType._zod.values,null]):void 0),t._zod.parse=(t,i)=>null===t.value?t:r.innerType._zod.run(t,i)}),rH=eV("$ZodDefault",(t,r)=>{tF.init(t,r),t._zod.optin="defaulted",eF(t,"values",t=>t.def.innerType._zod.values),t._zod.parse=(t,i)=>{if("backward"===i.direction)return r.innerType._zod.run(t,i);if(void 0===t.value)return t.value=r.defaultValue,t;let n=r.innerType._zod.run(t,i);return n instanceof Promise?n.then(t=>rJ(t,r)):rJ(n,r)}});function rJ(t,r){return void 0===t.value&&(t.value=r.defaultValue),t}let rD=eV("$ZodPrefault",(t,r)=>{tF.init(t,r),t._zod.optin="defaulted",eF(t,"values",t=>t.def.innerType._zod.values),t._zod.parse=(t,i)=>("backward"===i.direction||void 0===t.value&&(t.value=r.defaultValue),r.innerType._zod.run(t,i))}),rV=eV("$ZodNonOptional",(t,r)=>{tF.init(t,r),eF(t,"values",t=>{let r=t.def.innerType._zod.values;return r?new Set([...r].filter(t=>void 0!==t)):void 0}),t._zod.parse=(i,n)=>{let a=r.innerType._zod.run(i,n);return a instanceof Promise?a.then(r=>rB(r,t)):rB(a,t)}});function rB(t,r){return t.issues.length||void 0!==t.value||t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:r}),t}function rW(t,r,i,n){return r.issues.length?t.value=i.catchValue({...r,value:t.value,error:{issues:r.issues.map(t=>eq(t,n,eK()))},input:t.value}):(t.value=r.value,r.memo&&(t.memo=!0)),t}let rG=eV("$ZodCatch",(t,r)=>{tF.init(t,r),eF(t,"optin",t=>"defaulted"===t.def.innerType._zod.optin?"defaulted":"optional"),eF(t,"optout",t=>t.def.innerType._zod.optout),eF(t,"values",t=>t.def.innerType._zod.values),t._zod.parse=(t,i)=>{if("backward"===i.direction)return r.innerType._zod.run(t,i);let n=r.innerType._zod.run({value:t.value,issues:[]},i);return n instanceof Promise?n.then(n=>rW(t,n,r,i)):rW(t,n,r,i)}}),rK=eV("$ZodPipe",(t,r)=>{tF.init(t,r),eF(t,"values",t=>t.def.in._zod.values),eF(t,"optin",t=>t.def.in._zod.optin),eF(t,"optout",t=>t.def.out._zod.optout),eF(t,"propValues",t=>t.def.in._zod.propValues),t._zod.parse=(t,i)=>{if("backward"===i.direction){let n=r.out._zod.run(t,i);return n instanceof Promise?n.then(t=>rY(t,r.in,i)):rY(n,r.in,i)}let n=r.in._zod.run(t,i);return n instanceof Promise?n.then(t=>rY(t,r.out,i)):rY(n,r.out,i)}});function rY(t,r,i){return t.issues.some(t=>"unrecognized_keys"!==t.code)?(t.aborted=!0,t):r._zod.run({value:t.value,issues:t.issues},i)}let rX=eV("$ZodPreprocess",(t,r)=>{rK.init(t,r)}),rQ=eV("$ZodReadonly",(t,r)=>{tF.init(t,r),eF(t,"propValues",t=>t.def.innerType._zod.propValues),eF(t,"values",t=>t.def.innerType._zod.values),eF(t,"optin",t=>t.def.innerType?._zod?.optin),eF(t,"optout",t=>t.def.innerType?._zod?.optout),t._zod.parse=(t,i)=>{if("backward"===i.direction)return r.innerType._zod.run(t,i);let n=r.innerType._zod.run(t,i);return n instanceof Promise?n.then(r0):r0(n)}});function r0(t){return t.memo||(t.value=Object.freeze(t.value)),t}let r1=eV("$ZodLazy",(t,r)=>{var i;let n;tF.init(t,r),i=t._zod,Object.defineProperty(i,"innerType",{get(){if(n!==eo)return void 0===n&&(n=eo,n=(()=>(r._cachedInner||(r._cachedInner=r.getter()),r._cachedInner))()),n},set(t){Object.defineProperty(i,"innerType",{value:t})},configurable:!0}),eF(t,"pattern",t=>t.innerType?._zod?.pattern),eF(t,"propValues",t=>t.innerType?._zod?.propValues),eF(t,"optin",t=>t.innerType?._zod?.optin??void 0),eF(t,"optout",t=>t.innerType?._zod?.optout??void 0),t._zod.parse=(r,i)=>t._zod.innerType._zod.run(r,i)}),r2=eV("$ZodCustom",(t,r)=>{tw.init(t,r),tF.init(t,r),t._zod.parse=(t,r)=>t,t._zod.check=i=>{let n=i.value,a=r.fn(n);if(a instanceof Promise)return a.then(r=>r9(r,i,n,t));r9(a,i,n,t)}});function r9(t,r,i,n){if(!t){let t={code:"custom",input:i,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(t.params=n._zod.def.params),r.issues.push(eA(t))}}(q=globalThis).__zod_globalRegistry??(q.__zod_globalRegistry=new class t{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let i=r[0];return this._map.set(t,i),i&&"object"==typeof i&&"id"in i&&this._idmap.set(i.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&"object"==typeof r&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let i={...this.get(r)??{}};delete i.id;let n={...i,...this._map.get(t)};return Object.keys(n).length?n:void 0}return this._map.get(t)}has(t){return this._map.has(t)}});let r4=globalThis.__zod_globalRegistry;function r5(t){return t.checks&&(t.checks=[...t.checks]),t}function r3(t,r){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ew(r)})}function r6(t,r){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ew(r)})}function r7(t,r){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ew(r)})}function r8(t,r){return new t({type:"string",format:"date",check:"string_format",...ew(r)})}function ie(t,r){return new tR({check:"less_than",...ew(r),value:t,inclusive:!1})}function it(t,r){return new tR({check:"less_than",...ew(r),value:t,inclusive:!0})}function ir(t,r){return new t$({check:"greater_than",...ew(r),value:t,inclusive:!1})}function ii(t,r){return new t$({check:"greater_than",...ew(r),value:t,inclusive:!0})}function ia(t,r){return new tC({check:"multiple_of",...ew(r),value:t})}function io(t,r){return new tO({check:"max_length",...ew(r),maximum:t})}function is(t,r){return new tP({check:"min_length",...ew(r),minimum:t})}function il(t,r){return new tE({check:"length_equals",...ew(r),length:t})}function ic(t){return new tM({check:"overwrite",tx:t})}function iu(t,...r){for(let i of r)for(let r of Reflect.ownKeys(i))Object.prototype.propertyIsEnumerable.call(i,r)&&es(t,r,i[r]);return t}function id(t){let r=t?.target??"draft-2020-12";return"draft-4"===r&&(r="draft-04"),"draft-7"===r&&(r="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??r4,target:r,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:t?.cycles??"ref",reused:t?.reused??"inline",intersections:[],deferred:[],external:t?.external??void 0}}function ip(t,r,i,n,a){let o="function"==typeof r.unrepresentable?r.unrepresentable({zodSchema:t,path:n.path,message:a}):r.unrepresentable;if("any"===o)return!1;if(void 0===o||"throw"===o)throw Error(a);return Object.assign(i,o),!0}function im(t,r,i={path:[],schemaPath:[]}){var n;let a=t._zod.def,o=r.seen.get(t);if(o)return o.count++,i.schemaPath.includes(t)&&(o.cycle=i.path),o.schema;let s={schema:{},count:1,cycle:void 0,path:i.path};r.seen.set(t,s),r.sharedDefsExtractedFor=void 0,r.sharedEmitDoneFor=void 0;let l=t._zod.toJSONSchema?.();if(l)s.schema=l;else{let n={...i,schemaPath:[...i.schemaPath,t],path:i.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(r,s.schema,n);else{let i=s.schema,o=r.processors[a.type];if(!o)throw Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);o(t,r,i,n)}let o=t._zod.parent;o&&(s.ref||(s.ref=o),im(o,r,n),r.seen.get(o).isParent=!0)}let c=r.metadataRegistry.get(t);return c&&iu(s.schema,c),"input"===r.io&&function t(r,i){let n=i??{seen:new Set};if(n.seen.has(r))return!1;n.seen.add(r);let a=r._zod.def;if("transform"===a.type)return!0;if("array"===a.type)return t(a.element,n);if("set"===a.type)return t(a.valueType,n);if("lazy"===a.type)return t(a.getter(),n);if("promise"===a.type||"optional"===a.type||"nonoptional"===a.type||"nullable"===a.type||"readonly"===a.type||"default"===a.type||"prefault"===a.type||"catch"===a.type)return t(a.innerType,n);if("intersection"===a.type)return t(a.left,n)||t(a.right,n);if("record"===a.type||"map"===a.type)return t(a.keyType,n)||t(a.valueType,n);if("pipe"===a.type)return!!r._zod.traits.has("$ZodCodec")||t(a.in,n)||t(a.out,n);if("object"===a.type){for(let r in a.shape)if(t(a.shape[r],n))return!0;return!1}if("union"===a.type){for(let r of a.options)if(t(r,n))return!0;return!1}if("tuple"===a.type){for(let r of a.items)if(t(r,n))return!0;if(a.rest&&t(a.rest,n))return!0}return!1}(t)&&(delete s.schema.examples,delete s.schema.default),"input"===r.io&&"_prefault"in s.schema&&((n=s.schema).default??(n.default=s.schema._prefault)),delete s.schema._prefault,r.seen.get(t).schema}function ih(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function ig(t,r){let i=t.seen.get(r);if(!i)throw Error("Unprocessed schema. This is a bug in Zod.");if(t.external&&t.sharedDefsExtractedFor===t.external)return;let n=new Map;for(let r of t.seen.entries()){let i=t.metadataRegistry.get(r[0])?.id;if(i){let t=n.get(i);if(t&&t!==r[0])throw Error(`Duplicate schema id "${i}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(i,r[0])}}let a=r=>{if(r[1].schema.$ref)return;let n=r[1],{ref:a,defId:o}=(r=>{let n="draft-2020-12"===t.target?"$defs":"definitions";if(t.external){let i=t.external.registry.get(r[0])?.id,a=t.external.uri??(t=>t);if(i)return{ref:a(i)};let o=r[1].defId??r[1].schema.id??`schema${t.counter++}`;return r[1].defId=o,{defId:o,ref:`${a("__shared")}#/${n}/${ih(o)}`}}let a=`#/${n}/`;if(r[1]===i&&!r[1].schema.id)return{ref:"#"};let o=r[1].schema.id??`__schema${t.counter++}`;return{defId:o,ref:a+ih(o)}})(r);n.def={...n.schema},o&&(n.defId=o);let s=n.schema;for(let t in s)delete s[t];s.$ref=a};if("throw"===t.cycles)for(let r of t.seen.entries()){let t=r[1];if(t.cycle)throw Error(`Cycle detected: #/${t.cycle?.join("/")}/<root>
|
|
53
|
+
`)}return a.write("payload.value = newResult;"),a.write("return payload;"),a.compile()})(r.shape)),d=i(d,p),u)?r$([],m,d,p,n,t,p?.abortEarly===!0):d:a(d,p):(d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d)}});function rP(t,r,i,n){for(let i of t)if(0===i.issues.length)return r.value=i.value,r;let a=t.filter(t=>!eT(t));return 1===a.length?(r.value=a[0].value,a[0]):(r.issues.push({code:"invalid_union",input:r.value,inst:i,errors:t.map(t=>t.issues.map(t=>eI(t,n,eG())))}),r)}let rE=eV("$ZodUnion",(t,r)=>{tU.init(t,r),eU(t,"optin",t=>t.def.options.some(t=>"defaulted"===t._zod.optin)?"defaulted":t.def.options.some(t=>void 0!==t._zod.optin)?"optional":void 0),eU(t,"optout",t=>t.def.options.some(t=>"optional"===t._zod.optout)?"optional":void 0),eU(t,"values",t=>{if(t.def.options.every(t=>t._zod.values))return new Set(t.def.options.flatMap(t=>Array.from(t._zod.values)))}),eU(t,"pattern",t=>{if(t.def.options.every(t=>t._zod.pattern)){let r=t.def.options.map(t=>t._zod.pattern);return RegExp(`^(${r.map(t=>en(t.source)).join("|")})$`)}});let i=1===r.options.length?r.options[0]._zod.run:null;t._zod.parse=(n,a)=>{if(i)return i(n,a);let o=!1,s=[];for(let t of r.options){let r=t._zod.run({value:n.value,issues:[]},a);if(r instanceof Promise)s.push(r),o=!0;else{if(0===r.issues.length)return r;s.push(r)}}return o?Promise.all(s).then(r=>rP(r,n,t,a)):rP(s,n,t,a)}}),rO=eV("$ZodDiscriminatedUnion",(t,r)=>{r.inclusive=!1,rE.init(t,r);let i=t._zod.parse;eU(t,"propValues",t=>{let r={},i=0;for(let n of t.def.options){let a=n._zod.propValues;if(!a||0===Object.keys(a).length)throw Error(`Invalid discriminated union option at index "${t.def.options.indexOf(n)}"`);for(let[n,o]of(a[t.def.discriminator]?.has(void 0)&&i++,Object.entries(a)))for(let t of(Object.prototype.hasOwnProperty.call(r,n)||eo(r,n,new Set),o))r[n].add(t)}return!t.def.unionFallback&&i>1&&r[t.def.discriminator]?.delete(void 0),r}),r.options.forEach((t,i)=>{let n=es(t._zod.def);if(n&&!Object.prototype.hasOwnProperty.call(n,r.discriminator))throw Error(`Invalid discriminated union option at index "${i}"`)});let n=ei(()=>(function(t){let r=new Map;for(let i of t.options){let n=i._zod.propValues?.[t.discriminator];if(!n||0===n.size)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let t of n)if(r.has(t)){if(void 0!==t)throw Error(`Duplicate discriminator value "${String(t)}"`);r.set(t,null)}else r.set(t,i)}return r})(r));t._zod.parse=(a,o)=>{let s=a.value;if(!eh(s))return a.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),a;let l=s?.[r.discriminator],c=n.value.get(l);return c&&(void 0!==l||"backward"!==o.direction)?c._zod.run(a,o):r.unionFallback||"backward"===o.direction?i(a,o):(a.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:r.discriminator,options:Array.from(n.value.keys()).filter(t=>null!==n.value.get(t)),input:s,path:[r.discriminator],inst:t}),a)}}),rI=eV("$ZodIntersection",(t,r)=>{tU.init(t,r),t._zod.parse=(t,i)=>{let n=t.value,a=r.left._zod.run({value:n,issues:[]},i),o=r.right._zod.run({value:n,issues:[]},i);return a instanceof Promise||o instanceof Promise?Promise.all([a,o]).then(([r,i])=>rq(t,r,i)):rq(t,a,o)}});function rq(t,r,i){let n,a=new Map,o=new Map,s=(t,r)=>{let i;if("unrecognized_keys"!==t.code||t.path?.length)if("invalid_key"!==t.code||"record"!==t.origin||t.path?.length!==1)return!1;else{let r=String(t.path[0]);o.has(r)||o.set(r,t),i=[r]}else n??(n=t),i=t.keys;for(let t of i)a.has(t)||a.set(t,{}),a.get(t)[r]=!0;return!0};for(let i of r.issues)s(i,"l")||t.issues.push(i);for(let r of i.issues)s(r,"r")||t.issues.push(r);let l=[...a].filter(([,t])=>t.l&&t.r).map(([t])=>t);if(l.length){let r=n?l.filter(t=>n.keys.includes(t)):[];for(let i of(r.length&&t.issues.push({...n,keys:r}),l))!r.includes(i)&&o.has(i)&&t.issues.push(o.get(i))}let c=function t(r,i){if(r===i||r instanceof Date&&i instanceof Date&&+r==+i)return{valid:!0,data:r};if(eg(r)&&eg(i)){let n=Object.keys(i),a=Object.keys(r).filter(t=>-1!==n.indexOf(t)),o={...r,...i};for(let n of(Object.prototype.hasOwnProperty.call(o,"__proto__")&&delete o.__proto__,a)){if("__proto__"===n)continue;let a=t(r[n],i[n]);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};o[n]=a.data}return{valid:!0,data:o}}if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let a=0;a<r.length;a++){let o=t(r[a],i[a]);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}(r.value,i.value);if(!c.valid){if(eT(t))return t;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return t.value=c.data,t}let rj=eV("$ZodRecord",(t,r)=>{tU.init(t,r);let i=eW.memoizer;i?.attach(t),t._zod.parse=(n,a)=>{let o=n.value;if(!eg(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[],l=r.keyType._zod.values;if(l&&!r.partial){let c;n.value=i?i.alloc(t,n,{},a):{};let u=new Set;for(let i of l)if("string"==typeof i||"number"==typeof i||"symbol"==typeof i){if(u.add("number"==typeof i?i.toString():i),"__proto__"===i)continue;let l=r.keyType._zod.run({value:i,issues:[]},a);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(l.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(t=>eI(t,a,eG())),input:i,path:[i],inst:t});continue}let c=l.value;if("__proto__"===c)continue;let d=r.valueType._zod.run({value:o[i],issues:[]},a);d instanceof Promise?s.push(d.then(t=>{t.issues.length&&n.issues.push(...eP(i,t.issues)),n.value[c]=t.value})):(d.issues.length&&n.issues.push(...eP(i,d.issues)),n.value[c]=d.value)}for(let t in o)if(!u.has(t))if("loose"===r.mode){if("__proto__"===t)continue;n.value[t]=o[t]}else(c=c??[]).push(t);c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c,continue:!0})}else{let c;for(let u of(n.value=i?i.alloc(t,n,{},a):{},Reflect.ownKeys(o))){if("__proto__"===u||!Object.prototype.propertyIsEnumerable.call(o,u))continue;let i=r.keyType._zod.run({value:u,issues:[]},a);if(i instanceof Promise)throw Error("Async schemas not supported in object keys currently");if("string"==typeof u&&tg.test(u)&&i.issues.length){let t=r.keyType._zod.run({value:Number(u),issues:[]},a);if(t instanceof Promise)throw Error("Async schemas not supported in object keys currently");0===t.issues.length&&(i=t)}if(i.issues.length){"loose"===r.mode?n.value[u]=o[u]:l?(c=c??[]).push(u):n.issues.push({code:"invalid_key",origin:"record",issues:i.issues.map(t=>eI(t,a,eG())),input:u,path:[u],inst:t});continue}let d=i.value;if("__proto__"===d)continue;let p=r.valueType._zod.run({value:o[u],issues:[]},a);p instanceof Promise?s.push(p.then(t=>{t.issues.length&&n.issues.push(...eP(u,t.issues)),n.value[d]=t.value})):(p.issues.length&&n.issues.push(...eP(u,p.issues)),n.value[d]=p.value)}c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c,continue:!0})}return s.length?Promise.all(s).then(()=>n):n}}),rA=eV("$ZodEnum",(t,r)=>{tU.init(t,r);let i=Q(r.entries),n=new Set(i);t._zod.values=n,eU(t,"pattern",t=>{let r=Q(t.def.entries).filter(t=>ev.has(typeof t));return new RegExp(r.length?`^(${r.map(t=>e_(t.toString())).join("|")})$`:"^[^\\s\\S]$")}),t._zod.parse=(r,a)=>{let o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:i,input:o,inst:t}),r}}),rN=eV("$ZodLiteral",(t,r)=>{tU.init(t,r);let i=new Set(r.values);t._zod.values=i,eU(t,"pattern",t=>{let r=t.def.values;return new RegExp(r.length?`^(${r.map(t=>"string"==typeof t?e_(t):t?e_(t.toString()):String(t)).join("|")})$`:"^[^\\s\\S]$")}),t._zod.parse=(n,a)=>{let o=n.value;return i.has(o)||n.issues.push({code:"invalid_value",values:r.values,input:o,inst:t}),n}}),rL=eV("$ZodTransform",(t,r)=>{tU.init(t,r),t._zod.optin="optional",eW.memoizer?.guard(t),t._zod.parse=(i,n)=>{if("backward"===n.direction)throw new eB(t.constructor.name);let a=r.transform(i.value,i);if(n.async)return(a instanceof Promise?a:Promise.resolve(a)).then(t=>(i.value=t,i));if(a instanceof Promise)throw new eJ;return i.value=a,i}});function rz(t,r){return t.value=r.issues.length?void 0:r.value,t}let rM=eV("$ZodOptional",(t,r)=>{tU.init(t,r),eU(t,"optin",t=>"defaulted"===t.def.innerType._zod.optin?"defaulted":"optional"),t._zod.optout="optional",eU(t,"values",t=>{let r=t.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),eU(t,"pattern",t=>{let r=t.def.innerType._zod.pattern;return r?RegExp(`^(${en(r.source)})?$`):void 0}),t._zod.parse=(t,i)=>{if(void 0===t.value){if("defaulted"!==r.innerType._zod.optin)return t;let n=r.innerType._zod.run({value:t.value,issues:[]},i);return n instanceof Promise?n.then(r=>rz(t,r)):rz(t,n)}return r.innerType._zod.run(t,i)}}),rZ=eV("$ZodExactOptional",(t,r)=>{rM.init(t,r),eU(t,"values",t=>t.def.innerType._zod.values),eU(t,"pattern",t=>t.def.innerType._zod.pattern),t._zod.parse=(t,i)=>r.innerType._zod.run(t,i)}),rU=eV("$ZodNullable",(t,r)=>{tU.init(t,r),eU(t,"optin",t=>t.def.innerType._zod.optin),eU(t,"optout",t=>t.def.innerType._zod.optout),eU(t,"pattern",t=>{let r=t.def.innerType._zod.pattern;return r?RegExp(`^(${en(r.source)}|null)$`):void 0}),eU(t,"values",t=>t.def.innerType._zod.values?new Set([...t.def.innerType._zod.values,null]):void 0),t._zod.parse=(t,i)=>null===t.value?t:r.innerType._zod.run(t,i)}),rF=eV("$ZodDefault",(t,r)=>{tU.init(t,r),t._zod.optin="defaulted",eU(t,"values",t=>t.def.innerType._zod.values),t._zod.parse=(t,i)=>{if("backward"===i.direction)return r.innerType._zod.run(t,i);if(void 0===t.value)return t.value=r.defaultValue,t;let n=r.innerType._zod.run(t,i);return n instanceof Promise?n.then(t=>rH(t,r)):rH(n,r)}});function rH(t,r){return void 0===t.value&&(t.value=r.defaultValue),t}let rD=eV("$ZodPrefault",(t,r)=>{tU.init(t,r),t._zod.optin="defaulted",eU(t,"values",t=>t.def.innerType._zod.values),t._zod.parse=(t,i)=>("backward"===i.direction||void 0===t.value&&(t.value=r.defaultValue),r.innerType._zod.run(t,i))}),rV=eV("$ZodNonOptional",(t,r)=>{tU.init(t,r),eU(t,"values",t=>{let r=t.def.innerType._zod.values;return r?new Set([...r].filter(t=>void 0!==t)):void 0}),t._zod.parse=(i,n)=>{let a=r.innerType._zod.run(i,n);return a instanceof Promise?a.then(r=>rJ(r,t)):rJ(a,t)}});function rJ(t,r){return t.issues.length||void 0!==t.value||t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:r}),t}function rB(t,r,i,n){return r.issues.length?t.value=i.catchValue({...r,value:t.value,error:{issues:r.issues.map(t=>eI(t,n,eG()))},input:t.value}):(t.value=r.value,r.memo&&(t.memo=!0)),t}let rW=eV("$ZodCatch",(t,r)=>{tU.init(t,r),eU(t,"optin",t=>"defaulted"===t.def.innerType._zod.optin?"defaulted":"optional"),eU(t,"optout",t=>t.def.innerType._zod.optout),eU(t,"values",t=>t.def.innerType._zod.values),t._zod.parse=(t,i)=>{if("backward"===i.direction)return r.innerType._zod.run(t,i);let n=r.innerType._zod.run({value:t.value,issues:[]},i);return n instanceof Promise?n.then(n=>rB(t,n,r,i)):rB(t,n,r,i)}}),rG=eV("$ZodPipe",(t,r)=>{tU.init(t,r),eU(t,"values",t=>t.def.in._zod.values),eU(t,"optin",t=>t.def.in._zod.optin),eU(t,"optout",t=>t.def.out._zod.optout),eU(t,"propValues",t=>t.def.in._zod.propValues),t._zod.parse=(t,i)=>{if("backward"===i.direction){let n=r.out._zod.run(t,i);return n instanceof Promise?n.then(t=>rK(t,r.in,i)):rK(n,r.in,i)}let n=r.in._zod.run(t,i);return n instanceof Promise?n.then(t=>rK(t,r.out,i)):rK(n,r.out,i)}});function rK(t,r,i){return t.issues.some(t=>"unrecognized_keys"!==t.code)?(t.aborted=!0,t):r._zod.run({value:t.value,issues:t.issues},i)}let rY=eV("$ZodPreprocess",(t,r)=>{rG.init(t,r)}),rX=eV("$ZodReadonly",(t,r)=>{tU.init(t,r),eU(t,"propValues",t=>t.def.innerType._zod.propValues),eU(t,"values",t=>t.def.innerType._zod.values),eU(t,"optin",t=>t.def.innerType?._zod?.optin),eU(t,"optout",t=>t.def.innerType?._zod?.optout),t._zod.parse=(t,i)=>{if("backward"===i.direction)return r.innerType._zod.run(t,i);let n=r.innerType._zod.run(t,i);return n instanceof Promise?n.then(rQ):rQ(n)}});function rQ(t){return t.memo||(t.value=Object.freeze(t.value)),t}let r0=eV("$ZodLazy",(t,r)=>{var i;let n;tU.init(t,r),i=t._zod,Object.defineProperty(i,"innerType",{get(){if(n!==ea)return void 0===n&&(n=ea,n=(()=>(r._cachedInner||(r._cachedInner=r.getter()),r._cachedInner))()),n},set(t){Object.defineProperty(i,"innerType",{value:t})},configurable:!0}),eU(t,"pattern",t=>t.innerType?._zod?.pattern),eU(t,"propValues",t=>t.innerType?._zod?.propValues),eU(t,"optin",t=>t.innerType?._zod?.optin??void 0),eU(t,"optout",t=>t.innerType?._zod?.optout??void 0),t._zod.parse=(r,i)=>t._zod.innerType._zod.run(r,i)}),r1=eV("$ZodCustom",(t,r)=>{tS.init(t,r),tU.init(t,r),t._zod.parse=(t,r)=>t,t._zod.check=i=>{let n=i.value,a=r.fn(n);if(a instanceof Promise)return a.then(r=>r2(r,i,n,t));r2(a,i,n,t)}});function r2(t,r,i,n){if(!t){let t={code:"custom",input:i,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(t.params=n._zod.def.params),r.issues.push(eN(t))}}(q=globalThis).__zod_globalRegistry??(q.__zod_globalRegistry=new class t{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let i=r[0];return this._map.set(t,i),i&&"object"==typeof i&&"id"in i&&this._idmap.set(i.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&"object"==typeof r&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let i={...this.get(r)??{}};delete i.id;let n={...i,...this._map.get(t)};return Object.keys(n).length?n:void 0}return this._map.get(t)}has(t){return this._map.has(t)}});let r9=globalThis.__zod_globalRegistry;function r4(t){return t.checks&&(t.checks=[...t.checks]),t}function r5(t,r){return new t({type:"string",format:"email",check:"string_format",abort:!1,...eS(r)})}function r3(t,r){return new t({type:"string",format:"url",check:"string_format",abort:!1,...eS(r)})}function r6(t,r){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...eS(r)})}function r7(t,r){return new t({type:"string",format:"date",check:"string_format",...eS(r)})}function r8(t,r){return new tx({check:"less_than",...eS(r),value:t,inclusive:!1})}function ie(t,r){return new tx({check:"less_than",...eS(r),value:t,inclusive:!0})}function it(t,r){return new tR({check:"greater_than",...eS(r),value:t,inclusive:!1})}function ir(t,r){return new tR({check:"greater_than",...eS(r),value:t,inclusive:!0})}function ii(t,r){return new t$({check:"multiple_of",...eS(r),value:t})}function ia(t,r){return new tT({check:"max_length",...eS(r),maximum:t})}function io(t,r){return new tP({check:"min_length",...eS(r),minimum:t})}function is(t,r){return new tE({check:"length_equals",...eS(r),length:t})}function il(t){return new tz({check:"overwrite",tx:t})}function ic(t,...r){for(let i of r)for(let r of Reflect.ownKeys(i))Object.prototype.propertyIsEnumerable.call(i,r)&&eo(t,r,i[r]);return t}function iu(t){let r=t?.target??"draft-2020-12";return"draft-4"===r&&(r="draft-04"),"draft-7"===r&&(r="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??r9,target:r,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:t?.cycles??"ref",reused:t?.reused??"inline",intersections:[],deferred:[],external:t?.external??void 0}}function id(t,r,i,n,a){let o="function"==typeof r.unrepresentable?r.unrepresentable({zodSchema:t,path:n.path,message:a}):r.unrepresentable;if("any"===o)return!1;if(void 0===o||"throw"===o)throw Error(a);return Object.assign(i,o),!0}function ip(t,r,i={path:[],schemaPath:[]}){var n;let a=t._zod.def,o=r.seen.get(t);if(o)return o.count++,i.schemaPath.includes(t)&&(o.cycle=i.path),o.schema;let s={schema:{},count:1,cycle:void 0,path:i.path};r.seen.set(t,s),r.sharedDefsExtractedFor=void 0,r.sharedEmitDoneFor=void 0;let l=t._zod.toJSONSchema?.();if(l)s.schema=l;else{let n={...i,schemaPath:[...i.schemaPath,t],path:i.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(r,s.schema,n);else{let i=s.schema,o=r.processors[a.type];if(!o)throw Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);o(t,r,i,n)}let o=t._zod.parent;o&&(s.ref||(s.ref=o),ip(o,r,n),r.seen.get(o).isParent=!0)}let c=r.metadataRegistry.get(t);return c&&ic(s.schema,c),"input"===r.io&&function t(r,i){let n=i??{seen:new Set};if(n.seen.has(r))return!1;n.seen.add(r);let a=r._zod.def;if("transform"===a.type)return!0;if("array"===a.type)return t(a.element,n);if("set"===a.type)return t(a.valueType,n);if("lazy"===a.type)return t(a.getter(),n);if("promise"===a.type||"optional"===a.type||"nonoptional"===a.type||"nullable"===a.type||"readonly"===a.type||"default"===a.type||"prefault"===a.type||"catch"===a.type)return t(a.innerType,n);if("intersection"===a.type)return t(a.left,n)||t(a.right,n);if("record"===a.type||"map"===a.type)return t(a.keyType,n)||t(a.valueType,n);if("pipe"===a.type)return!!r._zod.traits.has("$ZodCodec")||t(a.in,n)||t(a.out,n);if("object"===a.type){for(let r in a.shape)if(t(a.shape[r],n))return!0;return!1}if("union"===a.type){for(let r of a.options)if(t(r,n))return!0;return!1}if("tuple"===a.type){for(let r of a.items)if(t(r,n))return!0;if(a.rest&&t(a.rest,n))return!0}return!1}(t)&&(delete s.schema.examples,delete s.schema.default),"input"===r.io&&"_prefault"in s.schema&&((n=s.schema).default??(n.default=s.schema._prefault)),delete s.schema._prefault,r.seen.get(t).schema}function im(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function ih(t,r){let i=t.seen.get(r);if(!i)throw Error("Unprocessed schema. This is a bug in Zod.");if(t.external&&t.sharedDefsExtractedFor===t.external)return;let n=new Map;for(let r of t.seen.entries()){let i=t.metadataRegistry.get(r[0])?.id;if(i){let t=n.get(i);if(t&&t!==r[0])throw Error(`Duplicate schema id "${i}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(i,r[0])}}let a=r=>{if(r[1].schema.$ref)return;let n=r[1],{ref:a,defId:o}=(r=>{let n="draft-2020-12"===t.target?"$defs":"definitions";if(t.external){let i=t.external.registry.get(r[0])?.id,a=t.external.uri??(t=>t);if(i)return{ref:a(i)};let o=r[1].defId??r[1].schema.id??`schema${t.counter++}`;return r[1].defId=o,{defId:o,ref:`${a("__shared")}#/${n}/${im(o)}`}}let a=`#/${n}/`;if(r[1]===i&&!r[1].schema.id)return{ref:"#"};let o=r[1].schema.id??`__schema${t.counter++}`;return{defId:o,ref:a+im(o)}})(r);n.def={...n.schema},o&&(n.defId=o);let s=n.schema;for(let t in s)delete s[t];s.$ref=a};if("throw"===t.cycles)for(let r of t.seen.entries()){let t=r[1];if(t.cycle)throw Error(`Cycle detected: #/${t.cycle?.join("/")}/<root>
|
|
54
54
|
|
|
55
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let n=i[1];if(r===i[0]){a(i);continue}if(t.external){let n=t.external.registry.get(i[0])?.id;if(r!==i[0]&&n){a(i);continue}}if(t.metadataRegistry.get(i[0])?.id||n.cycle){a(i);continue}n.count>1&&"ref"===t.reused&&a(i)}t.external&&(t.sharedDefsExtractedFor=t.external)}let iy=new Set(["type","properties","required","additionalProperties"]),iv=["oneOf","anyOf"];function i_(t){let r=t.additionalProperties;return void 0===r||!1===r||"object"!=typeof r||null===r?null:Object.keys(r).length?r:null}function ib(t){let r=[];for(let i of t){if("object"!=typeof i||"object"!==i.type)return null;for(let t in i)if(!iy.has(t))return null;r.push(i)}let i={},n=new Set;for(let t of r){for(let n in t.properties){if(Object.prototype.hasOwnProperty.call(i,n))continue;let t=[];for(let i of r){let r=i.properties?.[n]??i_(i);null!=r&&(t.some(t=>JSON.stringify(t)===JSON.stringify(r))||t.push(r))}es(i,n,1===t.length?t[0]:ib(t)??{allOf:t})}for(let r of t.required??[])n.add(r)}let a={type:"object",properties:i};if(n.size&&(a.required=[...n]),r.every(t=>!1===t.additionalProperties))a.additionalProperties=!1;else{let t=[];for(let i of r){let r=i_(i);r&&!t.some(t=>JSON.stringify(t)===JSON.stringify(r))&&t.push(r)}1===t.length?a.additionalProperties=t[0]:t.length>1&&(a.additionalProperties={allOf:t})}return a}function iS(t,r){let i=t.seen.get(r);if(!i)throw Error("Unprocessed schema. This is a bug in Zod.");let n=r=>{let i=t.seen.get(r);if(null===i.ref)return;let a=i.def??i.schema,o={...a},s=i.ref;if(i.ref=null,s){n(s);let i=t.seen.get(s),l=i.schema;if(l.$ref&&("draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target)?(a.allOf=a.allOf??[],a.allOf.push(l)):iu(a,l),iu(a,o),r._zod.parent===s)for(let t in a)"$ref"!==t&&"allOf"!==t&&(t in o||delete a[t]);if(l.$ref&&i.def)for(let t in a)"$ref"!==t&&"allOf"!==t&&t in i.def&&JSON.stringify(a[t])===JSON.stringify(i.def[t])&&delete a[t]}let l=r._zod.parent;if(l&&l!==s){n(l);let r=t.seen.get(l);if(r?.schema.$ref&&(a.$ref=r.schema.$ref,r.def))for(let t in a)"$ref"!==t&&"allOf"!==t&&t in r.def&&JSON.stringify(a[t])===JSON.stringify(r.def[t])&&delete a[t]}t.override({zodSchema:r,jsonSchema:a,path:i.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let r of[...t.seen.entries()].reverse())n(r[0]);if("openapi-3.0"!==t.target)for(let r of t.seen.entries())!function t(r){let i=r.anyOf;if(!Array.isArray(i)||0===i.length||void 0!==r.type)return;let n=[];for(let r of i){if(!r||"object"!=typeof r)return;t(r);let i=Object.keys(r);if(1!==i.length||"type"!==i[0])return;let a=r.type;for(let t of Array.isArray(a)?a:[a]){if("string"!=typeof t)return;n.includes(t)||n.push(t)}}delete r.anyOf,r.type=1===n.length?n[0]:n}(r[1].def??r[1].schema);for(let r of t.deferred)r();if(t.intersections.length){let r=new Map;for(let i of t.seen.values())for(let t of[i.schema,i.def]){let i=t?.allOf;if(!Array.isArray(i))continue;let n=r.get(i);n?n.push(t):r.set(i,[t])}for(let i of t.intersections)for(let t of r.get(i)??[])!function(t){let r=t.allOf;if(!Array.isArray(r)||r.length<2)return;for(let r of iy)if(r in t)return;let i=r.filter(t=>iv.some(r=>Array.isArray(t[r]))),n=null;if(i.length){let t=i[0],a=iv.find(r=>Array.isArray(t[r]));if(1!==Object.keys(t).length)return;let o=r.filter(r=>r!==t),s=t[a].map(t=>ib([...o,t]));if(s.some(t=>!t))return;n={[a]:s}}else n=ib(r);n&&(delete t.allOf,iu(t,n))}(t)}}let a={};if("draft-2020-12"===t.target?a.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===t.target?a.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===t.target?a.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let i=t.external.registry.get(r)?.id;if(!i)throw Error("Schema is missing an `id` property");a.$id=t.external.uri(i)}iu(a,i.defId?i.schema:i.def??i.schema);let o=t.metadataRegistry.get(r)?.id;void 0!==o&&a.id===o&&delete a.id;let s=t.external?.defs??{};if(!t.external||t.sharedEmitDoneFor!==t.external)for(let r of t.seen.entries()){let t=r[1];t.def&&t.defId&&(t.def.id===t.defId&&delete t.def.id,es(s,t.defId,t.def))}t.external&&(t.sharedEmitDoneFor=t.external),t.external||Object.keys(s).length>0&&("draft-2020-12"===t.target?a.$defs=s:a.definitions=s);try{let i=JSON.parse(JSON.stringify(a));return Object.defineProperty(i,"~standard",{value:{...r["~standard"],jsonSchema:{input:iw(r,"input",t.processors),output:iw(r,"output",t.processors)}},enumerable:!1,writable:!1}),i}catch(t){throw Error("Error converting schema to JSON.")}}let iw=(t,r,i={})=>n=>{let{libraryOptions:a,target:o}=n??{},s=id({...a??{},target:o,io:r,processors:i});return im(t,s),ig(s,t),iS(s,t)},ix=(t,r,i)=>{(void 0===t[r]||i>t[r])&&(t[r]=i)},ik=(t,r,i)=>{(void 0===t[r]||i<t[r])&&(t[r]=i)},iR=(t,r)=>{ix(t,"minimum",r),ik(t,"maximum",r)},i$=(t,r)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(r)||t.multipleOf.push(r)},iC=(t,r)=>{t.patterns??(t.patterns=new Set),t.patterns.add(r)},iT=(t,r)=>{t.mime=t.mime?t.mime.filter(t=>r.includes(t)):[...r]},iO=(t,r)=>{t.format=r,r.includes("int")&&(t.isInt=!0)},iP=(t,r)=>ix(t,"minimum",r.minimum),iE=(t,r)=>ik(t,"maximum",r.maximum),iI=t=>(r,i)=>{iO(r,i.format);let[n,a]=t[i.format];ix(r,"minimum",n),ik(r,"maximum",a)},iq={greater_than:(t,r)=>ix(t,r.inclusive?"minimum":"exclusiveMinimum",r.value),less_than:(t,r)=>ik(t,r.inclusive?"maximum":"exclusiveMaximum",r.value),multiple_of:(t,r)=>i$(t,r.value),number_format:iI(ek),bigint_format:iI(eR),min_length:iP,max_length:iE,length_equals:(t,r)=>iR(t,r.length),min_size:iP,max_size:iE,size_equals:(t,r)=>iR(t,r.size),string_format:(t,r)=>{iO(t,r.format),r.pattern&&iC(t,r.pattern),("base64"===r.format||"base64url"===r.format)&&(t.contentEncoding=r.format),(r.local||-1===r.precision)&&(t.laxFormat=!0)},mime_type:(t,r)=>iT(t,r.mime)};function ij(t){let r={},i=t._zod.def;for(let n of t._zod.traits.has("$ZodCheck")?[t,...i.checks??[]]:i.checks??[])iq[n._zod.def.check]?.(r,n._zod.def);let n=t._zod.bag;for(let t of(void 0!==n.minimum&&ix(r,"minimum",n.minimum),void 0!==n.exclusiveMinimum&&ix(r,"exclusiveMinimum",n.exclusiveMinimum),void 0!==n.maximum&&ik(r,"maximum",n.maximum),void 0!==n.exclusiveMaximum&&ik(r,"exclusiveMaximum",n.exclusiveMaximum),void 0!==n.multipleOf&&i$(r,n.multipleOf),void 0!==n.format&&(r.format??(r.format=n.format),n.format.includes("int")&&(r.isInt=!0)),n.mime&&iT(r,n.mime),n.patterns??[]))iC(r,t);return r}let iz={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},iN=new Map([[rc,/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/],[rd,/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/]]),iA=t=>iN.get(t)??t,iL=(t,r,i,n)=>{i.type="string";let{minimum:a,maximum:o,format:s,patterns:l,contentEncoding:c,laxFormat:u}=ij(t);if("number"==typeof a&&(i.minLength=a),"number"==typeof o&&(i.maxLength=o),s&&(i.format=iz[s]??s,""===i.format&&delete i.format,("time"===s||u)&&delete i.format),c&&(i.contentEncoding=c),l&&l.size>0){let t=[...l].map(iA);1===t.length?i.pattern=t[0].source:t.length>1&&(i.allOf=[...t.map(t=>({..."draft-07"===r.target||"draft-04"===r.target||"openapi-3.0"===r.target?{type:"string"}:{},pattern:t.source}))])}},iM=(t,r,i,n)=>{let{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:l,exclusiveMinimum:c,isInt:u}=ij(t);i.type=u?"integer":"number";let d="number"==typeof c&&c>=(a??-1/0),p="number"==typeof l&&l<=(o??1/0),m="draft-04"===r.target||"openapi-3.0"===r.target;if(d?m?(i.minimum=c,i.exclusiveMinimum=!0):i.exclusiveMinimum=c:"number"==typeof a&&(i.minimum=a),p?m?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:"number"==typeof o&&(i.maximum=o),s){let a=new Set;for(let o of s)Number.isFinite(o)&&0!==o?a.add(Math.abs(o)):ip(t,r,i,n,`A multipleOf divisor of ${o} cannot be represented in JSON Schema`);let[o,...l]=a;void 0!==o&&(i.multipleOf=o),l.length&&(i.allOf=[...i.allOf??[],...l.map(t=>({multipleOf:t}))])}},iZ=(t,r,i,n)=>{i.type="boolean"},iU=(t,r,i,n)=>{"openapi-3.0"===r.target?(i.type="string",i.nullable=!0,i.enum=[null]):i.type="null"},iF=(t,r,i,n)=>{i.not={}},iH=(t,r,i,n)=>{},iJ=(t,r,i,n)=>{},iD=(t,r,i,n)=>{let a=ee(t._zod.def.entries);if(0===a.length){i.not={};return}a.every(t=>"number"==typeof t)&&(i.type="number"),a.every(t=>"string"==typeof t)&&(i.type="string"),i.enum=a},iV=(t,r,i,n)=>{let a=t._zod.def;if(0===a.values.length){i.not={};return}let o=[];for(let s of a.values)if(void 0===s){if(ip(t,r,i,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if("bigint"==typeof s){if(ip(t,r,i,n,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(s))}else o.push(s);if(0===o.length);else if(1===o.length){let t=o[0];i.type=null===t?"null":typeof t,"draft-04"===r.target||"openapi-3.0"===r.target?i.enum=[t]:i.const=t}else o.every(t=>"number"==typeof t)&&(i.type="number"),o.every(t=>"string"==typeof t)&&(i.type="string"),o.every(t=>"boolean"==typeof t)&&(i.type="boolean"),o.every(t=>null===t)&&(i.type="null"),i.enum=o},iB=(t,r,i,n)=>{ip(t,r,i,n,"Custom types cannot be represented in JSON Schema")},iW=(t,r,i,n)=>{ip(t,r,i,n,"Transforms cannot be represented in JSON Schema")},iG=(t,r,i,n)=>{let a=t._zod.def,{minimum:o,maximum:s}=ij(t);"number"==typeof o&&(i.minItems=o),"number"==typeof s&&(i.maxItems=s),i.type="array",i.items=im(a.element,r,{...n,path:[...n.path,"items"]})};function iK(t){let r=t._zod.def;return"pipe"===r.type&&r.in._zod.traits.has("$ZodTransform")?iK(r.out):"catch"===r.type?iK(r.innerType):t._zod.optin}let iY=(t,r,i,n)=>{let a=t._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&ip(t,r,i,n,"Symbol keys cannot be represented in JSON Schema"))return;for(let t in i.type="object",i.properties={},o)es(i.properties,t,im(o[t],r,{...n,path:[...n.path,"properties",t]}));let s=[];for(let t of Object.keys(o)){let i=a.shape[t];("input"===r.io?void 0===iK(i):void 0===i._zod.optout)&&s.push(t)}s.length>0&&(i.required=s),a.catchall?._zod.def.type==="never"?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=im(a.catchall,r,{...n,path:[...n.path,"additionalProperties"]})):"output"===r.io&&(i.additionalProperties=!1)},iX=(t,r,i,n)=>{let a=t._zod.def,o=!1===a.inclusive,s=a.options.map((t,i)=>im(t,r,{...n,path:[...n.path,o?"oneOf":"anyOf",i]}));o?i.oneOf=s:i.anyOf=s},iQ=(t,r,i,n)=>{let a=t._zod.def,o=im(a.left,r,{...n,path:[...n.path,"allOf",0]}),s=im(a.right,r,{...n,path:[...n.path,"allOf",1]}),l=t=>"allOf"in t&&1===Object.keys(t).length,c=[...l(o)?o.allOf:[o],...l(s)?s.allOf:[s]];i.allOf=c,r.intersections.push(c)},i0=new WeakMap,i1=(t,r,i,n)=>{let a=t._zod.def;i.type="object";let o=a.keyType,s=ij(o).patterns;if("loose"===a.mode&&s&&s.size>0){let t=im(a.valueType,r,{...n,path:[...n.path,"patternProperties","*"]});for(let r of(i.patternProperties={},s))es(i.patternProperties,iA(r).source,t)}else{if("draft-07"===r.target||"draft-2020-12"===r.target){i.propertyNames=im(a.keyType,r,{...n,path:[...n.path,"propertyNames"]});let o=i0.get(r);o||(o=[],i0.set(r,o),r.deferred.push(()=>(function(t){let r=new Map;for(let i of t.seen.values())i.def&&!r.has(i.schema)&&r.set(i.schema,i);let i=new Map;for(let n of i0.get(t)??[]){let a=t.seen.get(n),o=(a?.def??a?.schema)?.propertyNames;if(!o||!0===o||i.has(o))continue;let s=function t(r,i,n){if(i.$ref){if(n.has(i))return i;n.add(i);let a=r.get(i)?.def;if(!a)return i;let o=t(r,a,n);return o===a?i:o}for(let a of["anyOf","oneOf"]){let o=i[a];if(!Array.isArray(o))continue;let s=o.map(i=>t(r,i,n));s.some((t,r)=>t!==o[r])&&(i={...i,[a]:s})}let a=Array.isArray(i.type)?i.type:[i.type],o=!a.includes("string")&&a.some(t=>"number"===t||"integer"===t),s=i.enum??(void 0!==i.const?[i.const]:void 0);if(!o&&!s?.some(t=>"number"==typeof t))return i;let{minimum:l,maximum:c,exclusiveMinimum:u,exclusiveMaximum:d,multipleOf:p,format:m,id:h,...f}=i;return f.enum?f.enum=f.enum.map(t=>"number"==typeof t?String(t):t):"number"==typeof f.const&&(f.const=String(f.const)),o&&(f.type="string",s||(f.pattern=(a.includes("number")?ty:tg).source)),f}(r,o,new Set);s!==o&&i.set(o,s)}if(i.size)for(let r of t.seen.values())for(let t of[r.schema,r.def]){let r=t&&i.get(t.propertyNames);r&&(t.propertyNames=r)}})(r))),o.push(t)}i.additionalProperties=im(a.valueType,r,{...n,path:[...n.path,"additionalProperties"]})}let l=o._zod.values,c="input"===r.io&&void 0!==iK(a.valueType);if(l&&!a.partial&&!c){let t=[...l].filter(t=>"string"==typeof t||"number"==typeof t);t.length>0&&(i.required=t.map(String))}},i2=(t,r,i,n)=>{let a=t._zod.def,o=im(a.innerType,r,n),s=r.seen.get(t);"openapi-3.0"===r.target?(s.ref=a.innerType,i.nullable=!0):i.anyOf=[o,{type:"null"}]},i9=(t,r,i,n)=>{let a=t._zod.def;im(a.innerType,r,n),r.seen.get(t).ref=a.innerType},i4=Symbol();function i5(t,r,i,n,a){let o=!1,s=JSON.stringify(t,(t,r)=>"bigint"!=typeof r?r:(o=!0,null));return o?(ip(r,i,n,a,"BigInt defaults cannot be represented in JSON Schema"),i4):JSON.parse(s)}let i3=(t,r,i,n)=>{let a=t._zod.def;im(a.innerType,r,n),r.seen.get(t).ref=a.innerType;let o=i5(a.defaultValue,t,r,i,n);o!==i4&&(i.default=o)},i6=(t,r,i,n)=>{let a=t._zod.def;if(im(a.innerType,r,n),r.seen.get(t).ref=a.innerType,"input"!==r.io)return;let o=i5(a.defaultValue,t,r,i,n);o!==i4&&(i._prefault=o)},i7=(t,r,i,n)=>{let a,o=t._zod.def;im(o.innerType,r,n),r.seen.get(t).ref=o.innerType;try{a=o.catchValue(void 0)}catch{ip(t,r,i,n,"Dynamic catch values are not supported in JSON Schema");return}i.default=a},i8=(t,r,i,n)=>{let a=t._zod.def,o=a.in._zod.traits.has("$ZodTransform"),s="input"===r.io?o?a.out:a.in:a.out;im(s,r,n),r.seen.get(t).ref=s},ne=(t,r,i,n)=>{let a=t._zod.def;im(a.innerType,r,n),r.seen.get(t).ref=a.innerType,i.readOnly=!0},nt=(t,r,i,n)=>{let a=t._zod.def;im(a.innerType,r,n),r.seen.get(t).ref=a.innerType},nr=(t,r,i,n)=>{let a=t._zod.innerType;im(a,r,n),r.seen.get(t).ref=a},ni={string:iL,number:iM,boolean:iZ,bigint:(t,r,i,n)=>{ip(t,r,i,n,"BigInt cannot be represented in JSON Schema")},symbol:(t,r,i,n)=>{ip(t,r,i,n,"Symbols cannot be represented in JSON Schema")},null:iU,undefined:(t,r,i,n)=>{ip(t,r,i,n,"Undefined cannot be represented in JSON Schema")},void:(t,r,i,n)=>{ip(t,r,i,n,"Void cannot be represented in JSON Schema")},never:iF,any:iH,unknown:iJ,date:(t,r,i,n)=>{ip(t,r,i,n,"Date cannot be represented in JSON Schema")},enum:iD,literal:iV,nan:(t,r,i,n)=>{ip(t,r,i,n,"NaN cannot be represented in JSON Schema")},template_literal:(t,r,i,n)=>{let a=t._zod.pattern;if(!a)throw Error("Pattern not found in template literal");i.type="string",i.pattern=a.source},file:(t,r,i,n)=>{i.type="string",i.format="binary",i.contentEncoding="binary";let{minimum:a,maximum:o,mime:s}=ij(t);void 0!==a&&(i.minLength=a),void 0!==o&&(i.maxLength=o),s&&(0===s.length?i.not={}:1===s.length?i.contentMediaType=s[0]:i.anyOf=s.map(t=>({contentMediaType:t})))},success:(t,r,i,n)=>{i.type="boolean"},custom:iB,function:(t,r,i,n)=>{ip(t,r,i,n,"Function types cannot be represented in JSON Schema")},transform:iW,map:(t,r,i,n)=>{ip(t,r,i,n,"Map cannot be represented in JSON Schema")},set:(t,r,i,n)=>{ip(t,r,i,n,"Set cannot be represented in JSON Schema")},array:iG,object:iY,union:iX,intersection:iQ,tuple:(t,r,i,n)=>{let a=t._zod.def;i.type="array";let o="draft-2020-12"===r.target?"prefixItems":"items",s="draft-2020-12"===r.target||"openapi-3.0"===r.target?"items":"additionalItems",l=a.items.map((t,i)=>im(t,r,{...n,path:[...n.path,o,i]})),c=a.rest?im(a.rest,r,{...n,path:[...n.path,s,..."openapi-3.0"===r.target?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let t=a.items[u-1];if(!("input"===r.io?void 0!==iK(t):"optional"===t._zod.optout))break;u--}let d=a.items.length,p=!a.rest;"draft-2020-12"===r.target?(i.prefixItems=l,p?i.items=!1:c&&(i.items=c)):"openapi-3.0"===r.target?(i.items={anyOf:l},c&&i.items.anyOf.push(c)):(i.items=l,p?i.additionalItems=!1:c&&(i.additionalItems=c)),u>0&&(i.minItems=u),p&&(i.maxItems=d);let{minimum:m,maximum:h}=ij(t);"number"==typeof m&&(i.minItems=m),"number"==typeof h&&(i.maxItems=h)},record:i1,nullable:i2,nonoptional:i9,default:i3,prefault:i6,catch:i7,pipe:i8,readonly:ne,promise:(t,r,i,n)=>{let a=t._zod.def;im(a.innerType,r,n),r.seen.get(t).ref=a.innerType},optional:nt,lazy:nr};function nn(t,r){if("_idmap"in t){let i=id({...r,processors:ni}),n={};for(let r of t._idmap.entries()){let[t,n]=r;im(n,i)}let a={};for(let o of(i.external={registry:t,uri:r?.uri,defs:n},t._idmap.entries())){let[t,r]=o;ig(i,r),es(a,t,iS(i,r))}return Object.keys(n).length>0&&(a.__shared={["draft-2020-12"===i.target?"$defs":"definitions"]:n}),{schemas:a}}let i=id({...r,processors:ni});return im(t,i),ig(i,t),iS(i,t)}let na={get:function(){let t=this._zod;return t.message??(t.message=JSON.stringify(t.def,er,2)),t.message},set:function(t){this._zod.message=t},enumerable:!0,configurable:!0},no={value:void 0,enumerable:!1},ns=new WeakSet([Object.prototype,Error.prototype]),nl=(t,r)=>{t.name="$ZodError",no.value=r,Object.defineProperty(t,"issues",no),no.value=void 0,Object.defineProperty(t,"message",na);let i=Object.getPrototypeOf(t);ns.has(i)||(ns.add(i),Object.defineProperty(i,"toString",{configurable:!0,enumerable:!1,get(){let t=()=>this.message;return Object.defineProperty(this,"toString",{value:t,configurable:!0,writable:!0}),t},set(t){Object.defineProperty(this,"toString",{value:t,configurable:!0,writable:!0})}}))},nc=eV("$ZodError",nl);function nu(t,r){return{callee:r?.callee??t,Err:r?.Err}}eV("$ZodError",nl,void 0,{Parent:Error});let nd=t=>{let r=(i,n,a,o)=>{let s=a?{...a,async:!1}:{async:!1},l=i._zod.run({value:n,issues:[]},s);if(l instanceof Promise)throw new eB;if(l.issues.length){let i=new(o?.Err??t)(l.issues.map(t=>eq(t,s,eK())));throw eh(i,o?.callee??r),i}return l.value};return r},np=t=>{let r=async(i,n,a,o)=>{let s=a?{...a,async:!0}:{async:!0},l=i._zod.run({value:n,issues:[]},s);if(l instanceof Promise&&(l=await l),l.issues.length){let i=new(o?.Err??t)(l.issues.map(t=>eq(t,s,eK())));throw eh(i,o?.callee??r),i}return l.value};return r},nm=t=>(r,i,n)=>{let a=n?{...n,async:!1}:{async:!1},o=r._zod.run({value:i,issues:[]},a);if(o instanceof Promise)throw new eB;return o.issues.length?nh(t,o.issues,a):{success:!0,data:o.value}};function nh(t,r,i){let n;return{success:!1,get error(){return n||(n=new t(r.map(t=>eq(t,i,eK()))),r=void 0,i=void 0),n},set error(e){n=e,r=void 0,i=void 0}}}let nf=t=>async(r,i,n)=>{let a=n?{...n,async:!0}:{async:!0},o=r._zod.run({value:i,issues:[]},a);return o instanceof Promise&&(o=await o),o.issues.length?nh(t,o.issues,a):{success:!0,data:o.value}},ng=Symbol.for("zod.compile.invalid"),ny=Symbol.for("zod.compile.fallback"),nv=async(t,r,i)=>{let n=i?{...i,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},a=t._zod.run({value:r,issues:[]},n);return a instanceof Promise&&(a=await a),0===a.issues.length},n_=new WeakSet([Object.prototype,Error.prototype]);function nb(t,r,i){Object.defineProperty(t,r,{configurable:!0,enumerable:!1,get(){let t=i(this);return Object.defineProperty(this,r,{value:t,configurable:!0,writable:!0}),t},set(t){Object.defineProperty(this,r,{value:t,configurable:!0,writable:!0})}})}let nS=eV("ZodError",(t,r)=>{nc.init(t,r),t.name="ZodError";let i=Object.getPrototypeOf(t);n_.has(i)||(n_.add(i),nb(i,"format",t=>r=>(function(t,r=t=>t.message){let i={_errors:[]},n=(t,a=[])=>{for(let o of t.issues)if("invalid_union"===o.code&&o.errors.length)o.errors.map(t=>n({issues:t},[...a,...o.path]));else if("invalid_key"===o.code)n({issues:o.issues},[...a,...o.path]);else if("invalid_element"===o.code)n({issues:o.issues},[...a,...o.path]);else{let t=[...a,...o.path];if(0===t.length)i._errors.push(r(o));else{let n=i,a=0;for(;a<t.length;){let i=t[a],s=a===t.length-1;if("_errors"===i){s&&n._errors.push(r(o)),a++;continue}Object.prototype.hasOwnProperty.call(n,i)||Object.defineProperty(n,i,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let l=n[i];s&&l._errors.push(r(o)),n=l,a++}}}};return n(t),i})(t,r)),nb(i,"flatten",t=>r=>(function(t,r=t=>t.message){let i={},n=[];for(let s of t.issues)if(s.path.length>0){var a,o;(a=s.path[0],o=()=>[],!Object.prototype.hasOwnProperty.call(i,a)&&("__proto__"===a?Object.defineProperty(i,a,{value:o(),writable:!0,enumerable:!0,configurable:!0}):i[a]=o()),i[a]).push(r(s))}else n.push(r(s));return{formErrors:n,fieldErrors:i}})(t,r)),nb(i,"addIssue",t=>r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,er,2)}),nb(i,"addIssues",t=>r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,er,2)}),Object.defineProperty(i,"isEmpty",{configurable:!0,enumerable:!1,get(){return 0===this.issues.length}}))},void 0,{Parent:Error}),nw=nd(nS),nx=np(nS),nk=nm(nS),nR=nf(nS),n$=(m=nd(nS),h=(t,r,i,n)=>m(t,r,i?{...i,direction:"backward"}:{direction:"backward"},nu(h,n))),nC=(f=nd(nS),g=(t,r,i,n)=>f(t,r,i,nu(g,n))),nT=(y=np(nS),v=async(t,r,i,n)=>{let a=i?{...i,direction:"backward"}:{direction:"backward"};return await y(t,r,a,nu(v,n))}),nO=(_=np(nS),b=async(t,r,i,n)=>await _(t,r,i,nu(b,n))),nP=(t,r,i)=>{let n=i?{...i,direction:"backward"}:{direction:"backward"};return nm(nS)(t,r,n)},nE=(t,r,i)=>nm(nS)(t,r,i),nI=async(t,r,i)=>{let n=i?{...i,direction:"backward"}:{direction:"backward"};return nf(nS)(t,r,n)},nq=async(t,r,i)=>nf(nS)(t,r,i);function nj(){eG.memoizer||eK({memoizer:e4})}let nz=eV("ZodType",(t,r)=>(eG.localeError||eK({localeError:(()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}},r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},i={nan:"NaN"};function n(t,r){return"number"!==t||"number"!=typeof r||Number.isFinite(r)?i[t]??t:String(r)}return i=>{switch(i.code){case"invalid_type":{let t=n(i.expected),r=n(function(t){let r=typeof t;switch(r){case"number":return Number.isNaN(t)?"nan":"number";case"object":if(null===t)return"null";if(Array.isArray(t))return"array";if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}return r}(i.input),i.input);return`Invalid input: expected ${t}, received ${r}`}case"invalid_value":if(1===i.values.length)return`Invalid input: expected ${ex(i.values[0])}`;return`Invalid option: expected one of ${et(i.values,"|")}`;case"too_big":{let r=i.exact?"exactly ":i.inclusive?"<=":"<",n=t[i.origin]??null;if(n)return`Too big: expected ${i.origin??"value"} to have ${r}${i.maximum.toString()} ${n.unit??"elements"}`;return`Too big: expected ${i.origin??"value"} to be ${r}${i.maximum.toString()}`}case"too_small":{let r=i.exact?"exactly ":i.inclusive?">=":">",n=t[i.origin]??null;if(n)return`Too small: expected ${i.origin} to have ${r}${i.minimum.toString()} ${n.unit}`;return`Too small: expected ${i.origin} to be ${r}${i.minimum.toString()}`}case"invalid_format":if("starts_with"===i.format)return`Invalid string: must start with "${i.prefix}"`;if("ends_with"===i.format)return`Invalid string: must end with "${i.suffix}"`;if("includes"===i.format)return`Invalid string: must include "${i.includes}"`;if("regex"===i.format)return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.format]??i.format}`;case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${et(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":if(i.options&&Array.isArray(i.options)&&i.options.length>0){let t=i.options.map(t=>`'${t}'`).join(" | ");return`Invalid discriminator value. Expected ${t}`}if(!1===i.inclusive)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}})()}),tF.init(t,r),t.def=r,t.type=r.type,t),{check(...t){let r=this.def;return this.clone(em(r,{checks:[...r.checks??[],...t.map(t=>"function"==typeof t?{_zod:{check:t,def:{check:"custom"},onattach:[]}}:t)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,r){return eS(this,t,r)},brand(){return this},register(t,r){return t.add(this,r),this},refine(t,r){return this.check(function(t,r={}){return new aD({type:"custom",check:"custom",fn:t,...ew(r)})}(t,r))},superRefine(t,r){return this.check(function(t,r){var i;let n,a;return i=r=>(r.addIssue=t=>{"string"==typeof t?r.issues.push(eA(t,r.value,n._zod.def)):(t.fatal&&(t.continue=!1),t.code??(t.code="custom"),"input"in t||(t.input=r.value),t.inst??(t.inst=n),t.continue??(t.continue=!n._zod.def.abort),r.issues.push(eA(t)))},t(r.value,r)),(a=new tw({check:"custom",...ew(r)}))._zod.check=i,n=a}(t,r))},overwrite(t){return this.check(ic(t))},optional(){return aE(this)},exactOptional(){var t;return t=this,new aI({type:"optional",innerType:t})},nullable(){return aj(this)},nullish(){return aE(aj(this))},nonoptional(t){var r;return r=this,new aA({type:"nonoptional",innerType:r,...ew(t)})},array(){return ap(this)},or(t){return ay([this,t])},and(t){return aS(this,t)},transform(t){return aZ(this,aO(t))},default(t){var r,i;return r=this,i=t,new az({type:"default",innerType:r,get defaultValue(){return"function"==typeof i?i():ev(i)}})},prefault(t){var r,i;return r=this,i=t,new aN({type:"prefault",innerType:r,get defaultValue(){return"function"==typeof i?i():ev(i)}})},catch(t){return function(t,r){let i;return new aL({type:"catch",innerType:t,catchValue:"function"==typeof r?r:((i=()=>r)["~constantCatch"]=!0,i)})}(this,t)},pipe(t){return aZ(this,t)},readonly(){var t;return t=this,new aF({type:"readonly",innerType:t})},describe(t){let r=this.clone();return r4.add(r,{description:t}),r},meta(...t){if(0===t.length)return r4.get(this);let r=this.clone();return r4.add(r,t[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...r){return 0===r.length?t(this):t(this,...r)},get"~standard"(){return eL(this,"~standard",{...tD(this),jsonSchema:{input:iw(this,"input"),output:iw(this,"output")}},!1)},set"~standard"(value){eL(this,"~standard",value)},parse:function t(r,i){return nw(this,r,i,{callee:t})},parseAsync:async function t(r,i){return await nx(this,r,i,{callee:t})},safeParse(t,r){return nk(this,t,r)},async safeParseAsync(t,r){return nR(this,t,r)},get spa(){return this?.safeParseAsync},set spa(value){eL(this,"spa",value)},validate(t,r){let i=this._zod.bag.validator;if(void 0!==i){if(i(t)!==ng)return!0;if(!0===i.definite&&void 0===r)return!1}return function(t,r,i){let n,a=i?{...i,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=t._zod.bag.fallbackRun;if(o?(a[ny]=!0,n=o({value:r,issues:[]},a)):n=t._zod.run({value:r,issues:[]},a),n instanceof Promise)throw new eB;return 0===n.issues.length}(this,t,r)},validateAsync(t,r){return nv(this,t,r)},encode:function t(r,i){return n$(this,r,i,{callee:t})},decode:function t(r,i){return nC(this,r,i,{callee:t})},encodeAsync:async function t(r,i){return await nT(this,r,i,{callee:t})},decodeAsync:async function t(r,i){return await nO(this,r,i,{callee:t})},safeEncode(t,r){return nP(this,t,r)},safeDecode(t,r){return nE(this,t,r)},async safeEncodeAsync(t,r){return nI(this,t,r)},async safeDecodeAsync(t,r){return nq(this,t,r)},toJSONSchema(t){return((t,r={})=>i=>{let n=id({...i,processors:r});return im(t,n),ig(n,t),iS(n,t)})(this,{})(t)},get description(){return r4.get(this)?.description},get _def(){return this._zod.def}}),nN=eV("_ZodString",(t,r)=>{tV.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iL(t,r,i,n)},eM({format:t=>ij(t).format??null,minLength:t=>ij(t).minimum??null,maxLength:t=>ij(t).maximum??null},{regex(...t){return this.check(function(t,r){return new tq({check:"string_format",format:"regex",...ew(r),pattern:t})}(...t))},includes(...t){return this.check(function(t,r){return new tN({check:"string_format",format:"includes",...ew(r),includes:t})}(...t))},startsWith(...t){return this.check(function(t,r){return new tA({check:"string_format",format:"starts_with",...ew(r),prefix:t})}(...t))},endsWith(...t){return this.check(function(t,r){return new tL({check:"string_format",format:"ends_with",...ew(r),suffix:t})}(...t))},min(...t){return this.check(is(...t))},max(...t){return this.check(io(...t))},length(...t){return this.check(il(...t))},nonempty(...t){return this.check(is(1,...t))},lowercase(t){return this.check(new tj({check:"string_format",format:"lowercase",...ew(t)}))},uppercase(t){return this.check(new tz({check:"string_format",format:"uppercase",...ew(t)}))},trim(){return this.check(ic(t=>t.trim()))},normalize(...t){return this.check(function(t){return ic(r=>r.normalize(t))}(...t))},toLowerCase(){return this.check(ic(t=>t.toLowerCase()))},toUpperCase(){return this.check(ic(t=>t.toUpperCase()))},slugify(){return this.check(ic(t=>t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")))}})),nA=eV("ZodString",(t,r)=>{tV.init(t,r),nN.init(t,r)},{email(t){return this.check(r3(nJ,t))},url(t){return this.check(r6(nB,t))},jwt(t){return this.check(new n7({type:"string",format:"jwt",check:"string_format",abort:!1,...ew(t)}))},emoji(t){return this.check(new nW({type:"string",format:"emoji",check:"string_format",abort:!1,...ew(t)}))},guid(t){return this.check(new nD({type:"string",format:"guid",check:"string_format",abort:!1,...ew(t)}))},uuid(t){return this.check(new nV({type:"string",format:"uuid",check:"string_format",abort:!1,...ew(t)}))},uuidv4(t){return this.check(new nV({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ew(t)}))},uuidv6(t){return this.check(new nV({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ew(t)}))},uuidv7(t){return this.check(new nV({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ew(t)}))},nanoid(t){return this.check(new nG({type:"string",format:"nanoid",check:"string_format",abort:!1,...ew(t)}))},cuid(t){return this.check(new nK({type:"string",format:"cuid",check:"string_format",abort:!1,...ew(t)}))},cuid2(t){return this.check(new nY({type:"string",format:"cuid2",check:"string_format",abort:!1,...ew(t)}))},ulid(t){return this.check(new nX({type:"string",format:"ulid",check:"string_format",abort:!1,...ew(t)}))},base64(t){return this.check(new n5({type:"string",format:"base64",check:"string_format",abort:!1,...ew(t)}))},base64url(t){return this.check(new n3({type:"string",format:"base64url",check:"string_format",abort:!1,...ew(t)}))},xid(t){return this.check(new nQ({type:"string",format:"xid",check:"string_format",abort:!1,...ew(t)}))},ksuid(t){return this.check(new n0({type:"string",format:"ksuid",check:"string_format",abort:!1,...ew(t)}))},ipv4(t){return this.check(new n1({type:"string",format:"ipv4",check:"string_format",abort:!1,...ew(t)}))},ipv6(t){return this.check(new n2({type:"string",format:"ipv6",check:"string_format",abort:!1,...ew(t)}))},cidrv4(t){return this.check(new n9({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ew(t)}))},cidrv6(t){return this.check(new n4({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ew(t)}))},e164(t){return this.check(new n6({type:"string",format:"e164",check:"string_format",abort:!1,...ew(t)}))},datetime(t){return this.check(r7(nZ,t))},date(t){return this.check(r8(nU,t))},time(t){return this.check(new nF({type:"string",format:"time",check:"string_format",precision:null,...ew(t)}))},duration(t){return this.check(new nH({type:"string",format:"duration",check:"string_format",...ew(t)}))}});function nL(t){return new nA(r5({type:"string",...ew(t)}))}let nM=eV("ZodStringFormat",(t,r)=>{tB.init(t,r),nN.init(t,r)}),nZ=eV("ZodISODateTime",(t,r)=>{t7.init(t,r),nM.init(t,r)}),nU=eV("ZodISODate",(t,r)=>{t8.init(t,r),nM.init(t,r)}),nF=eV("ZodISOTime",(t,r)=>{re.init(t,r),nM.init(t,r)}),nH=eV("ZodISODuration",(t,r)=>{rt.init(t,r),nM.init(t,r)}),nJ=eV("ZodEmail",(t,r)=>{tK.init(t,r),nM.init(t,r)}),nD=eV("ZodGUID",(t,r)=>{tW.init(t,r),nM.init(t,r)}),nV=eV("ZodUUID",(t,r)=>{tG.init(t,r),nM.init(t,r)}),nB=eV("ZodURL",(t,r)=>{t0.init(t,r),nM.init(t,r)}),nW=eV("ZodEmoji",(t,r)=>{t1.init(t,r),nM.init(t,r)}),nG=eV("ZodNanoID",(t,r)=>{t2.init(t,r),nM.init(t,r)}),nK=eV("ZodCUID",(t,r)=>{t9.init(t,r),nM.init(t,r)}),nY=eV("ZodCUID2",(t,r)=>{t4.init(t,r),nM.init(t,r)}),nX=eV("ZodULID",(t,r)=>{t5.init(t,r),nM.init(t,r)}),nQ=eV("ZodXID",(t,r)=>{t3.init(t,r),nM.init(t,r)}),n0=eV("ZodKSUID",(t,r)=>{t6.init(t,r),nM.init(t,r)}),n1=eV("ZodIPv4",(t,r)=>{rr.init(t,r),nM.init(t,r)}),n2=eV("ZodIPv6",(t,r)=>{ra.init(t,r),nM.init(t,r)}),n9=eV("ZodCIDRv4",(t,r)=>{ro.init(t,r),nM.init(t,r)}),n4=eV("ZodCIDRv6",(t,r)=>{rs.init(t,r),nM.init(t,r)}),n5=eV("ZodBase64",(t,r)=>{ru.init(t,r),nM.init(t,r)}),n3=eV("ZodBase64URL",(t,r)=>{rp.init(t,r),nM.init(t,r)}),n6=eV("ZodE164",(t,r)=>{rm.init(t,r),nM.init(t,r)}),n7=eV("ZodJWT",(t,r)=>{rh.init(t,r),nM.init(t,r)}),n8=eV("ZodNumber",(t,r)=>{rf.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iM(t,r,i,n),t.isFinite=!0},eM({minValue:t=>{let{minimum:r,exclusiveMinimum:i}=ij(t);return Math.max(r??-1/0,i??-1/0)},maxValue:t=>{let{maximum:r,exclusiveMaximum:i}=ij(t);return Math.min(r??1/0,i??1/0)},isInt:t=>{let{isInt:r,multipleOf:i}=ij(t);return!!r||!!i?.some(Number.isSafeInteger)},format:t=>ij(t).format??null},{gt(t,r){return this.check(ir(t,r))},gte(t,r){return this.check(ii(t,r))},min(t,r){return this.check(ii(t,r))},lt(t,r){return this.check(ie(t,r))},lte(t,r){return this.check(it(t,r))},max(t,r){return this.check(it(t,r))},int(t){return this.check(ar(t))},safe(t){return this.check(ar(t))},positive(t){return this.check(ir(0,t))},nonnegative(t){return this.check(ii(0,t))},negative(t){return this.check(ie(0,t))},nonpositive(t){return this.check(it(0,t))},multipleOf(t,r){return this.check(ia(t,r))},step(t,r){return this.check(ia(t,r))},finite(){return this}}));function ae(t){return new n8(r5({type:"number",checks:[],...ew(t)}))}let at=eV("ZodNumberFormat",(t,r)=>{rg.init(t,r),n8.init(t,r)});function ar(t){return new at({type:"number",check:"number_format",abort:!1,format:"safeint",...ew(t)})}let ai=eV("ZodBoolean",(t,r)=>{ry.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iZ(t,r,i,n)});function an(t){return new ai({type:"boolean",...ew(t)})}let aa=eV("ZodNull",(t,r)=>{rv.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iU(t,r,i,n)});function ao(t){return new aa({type:"null",...ew(t)})}let as=eV("ZodAny",(t,r)=>{r_.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iH(t,r,i,n)}),al=eV("ZodUnknown",(t,r)=>{rb.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iJ(t,r,i,n)});function ac(){return new al({type:"unknown"})}let au=eV("ZodNever",(t,r)=>{rS.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iF(t,r,i,n)}),ad=eV("ZodArray",(t,r)=>{nj(),rx.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iG(t,r,i,n),t.element=r.element},{min(t,r){return this.check(is(t,r))},nonempty(t){return this.check(is(1,t))},max(t,r){return this.check(io(t,r))},length(t,r){return this.check(il(t,r))},unwrap(){return this.element}});function ap(t,r){return new ad({type:"array",element:t,...ew(r)})}let am=eV("ZodObject",(t,r)=>{var i;let n,a;nj(),rO.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iY(t,r,i,n),i="shape",(a=i in(n=Object.getPrototypeOf(t))?void 0:n)&&Object.defineProperty(a,i,{configurable:!0,get(){let t={configurable:!0,writable:!0,enumerable:!1,value:void 0};return Object.defineProperty(this,i,t),t.value=(t=>t._zod.def.shape)(this),Object.defineProperty(this,i,t),t.value},set(t){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!1,value:t})}})},{keyof(){return aR(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(em(this._zod.def,{catchall:t}))},passthrough(){return this.clone(em(this._zod.def,{catchall:ac()}))},loose(){return this.clone(em(this._zod.def,{catchall:ac()}))},strict(){return this.clone(em(this._zod.def,{catchall:new au({type:"never",...ew(void 0)})}))},strip(){return this.clone(em(this._zod.def,{catchall:void 0}))},extend(t){if(!ey(t))throw Error("Invalid input to extend: expected a plain object");let r=this._zod.def.checks;if(r&&r.length>0){let r=ec(this);for(let i of Reflect.ownKeys(t))if(void 0!==Object.getOwnPropertyDescriptor(r,i))throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return eS(this,em(this._zod.def,{shape:eC(this,t)}))},safeExtend(t){if(!ey(t))throw Error("Invalid input to safeExtend: expected a plain object");return eS(this,em(this._zod.def,{shape:eC(this,t)}))},merge(t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(this._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r={};return ep(r,this,Reflect.ownKeys(ec(this))),ep(r,t,Reflect.ownKeys(ec(t))),eS(this,em(this._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))},pick(t){return function(t,r){let i=t._zod.def,n=i.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let a={};return ep(a,t,e$(t,r)),eS(t,em(i,{shape:a,checks:[]}))}(this,t)},omit(t){return function(t,r){let i=t._zod.def,n=i.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let a=new Set(e$(t,r)),o={};return ep(o,t,Reflect.ownKeys(ec(t)).filter(t=>!a.has(t))),eS(t,em(i,{shape:o,checks:[]}))}(this,t)},partial(...t){return eT(aP,this,t[0])},exactPartial(...t){return eT(aI,this,t[0],"exactPartial")},required(...t){var r;let i,n;return i=(r=t[0])?new Set(e$(this,r)):void 0,ep(n={},this,Reflect.ownKeys(ec(this)),(t,r)=>i&&!i.has(r)?t:new aA({type:"nonoptional",innerType:t})),eS(this,em(this._zod.def,{shape:n}))}});function ah(t,r){return new am({type:"object",shape:t??{},...ew(r)})}function af(t,r){return new am({type:"object",shape:t,catchall:ac(),...ew(r)})}let ag=eV("ZodUnion",(t,r)=>{rE.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iX(t,r,i,n),t.options=r.options});function ay(t,r){return new ag({type:"union",options:t,...ew(r)})}let av=eV("ZodDiscriminatedUnion",(t,r)=>{ag.init(t,r),rI.init(t,r)});function a_(t,r,i){return new av({type:"union",options:r,discriminator:t,...ew(i)})}let ab=eV("ZodIntersection",(t,r)=>{rq.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iQ(t,r,i,n)});function aS(t,r){return new ab({type:"intersection",left:t,right:r})}let aw=eV("ZodRecord",(t,r)=>{nj(),rz.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i1(t,r,i,n),t.keyType=r.keyType,t.valueType=r.valueType});function ax(t,r,i){return new aw(r&&r._zod?{type:"record",keyType:t,valueType:r,...ew(i)}:{type:"record",keyType:nL(),valueType:t,...ew(r)})}let ak=eV("ZodEnum",(t,r)=>{rN.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iD(t,r,i,n),t.enum=r.entries,t.options=[...t._zod.values];let i=new Set(Object.keys(r.entries));t.extract=(t,n)=>{let a={};for(let n of t)if(i.has(n))a[n]=r.entries[n];else throw Error(`Key ${n} not found in enum`);return new ak({...r,checks:[],...ew(n),entries:a})},t.exclude=(t,n)=>{let a={...r.entries};for(let r of t)if(i.has(r))delete a[r];else throw Error(`Key ${r} not found in enum`);return new ak({...r,checks:[],...ew(n),entries:a})}});function aR(t,r){return new ak({type:"enum",entries:Array.isArray(t)?Object.fromEntries(t.map(t=>[t,t])):t,...ew(r)})}let a$=eV("ZodLiteral",(t,r)=>{rA.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iV(t,r,i,n),t.values=new Set(r.values),Object.defineProperty(t,"value",{get(){if(r.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return r.values[0]}})});function aC(t,r){return new a$({type:"literal",values:Array.isArray(t)?t:[t],...ew(r)})}let aT=eV("ZodTransform",(t,r)=>{nj(),rL.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iW(t,r,i,n),t._zod.parse=(i,n)=>{if("backward"===n.direction)throw new eW(t.constructor.name);i.addIssue=n=>{"string"==typeof n?i.issues.push(eA(n,i.value,r)):(n.fatal&&(n.continue=!1),n.code??(n.code="custom"),"input"in n||(n.input=i.value),n.inst??(n.inst=t),i.issues.push(eA(n)))};let a=r.transform(i.value,i);return a instanceof Promise?a.then(t=>(i.value=t,i)):(i.value=a,i)}});function aO(t){return new aT({type:"transform",transform:t})}let aP=eV("ZodOptional",(t,r)=>{rZ.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>nt(t,r,i,n),t.unwrap=()=>t._zod.def.innerType});function aE(t){return new aP({type:"optional",innerType:t})}let aI=eV("ZodExactOptional",(t,r)=>{rU.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>nt(t,r,i,n),t.unwrap=()=>t._zod.def.innerType}),aq=eV("ZodNullable",(t,r)=>{rF.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i2(t,r,i,n),t.unwrap=()=>t._zod.def.innerType});function aj(t){return new aq({type:"nullable",innerType:t})}let az=eV("ZodDefault",(t,r)=>{rH.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i3(t,r,i,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap}),aN=eV("ZodPrefault",(t,r)=>{rD.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i6(t,r,i,n),t.unwrap=()=>t._zod.def.innerType}),aA=eV("ZodNonOptional",(t,r)=>{rV.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i9(t,r,i,n),t.unwrap=()=>t._zod.def.innerType}),aL=eV("ZodCatch",(t,r)=>{rG.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i7(t,r,i,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap}),aM=eV("ZodPipe",(t,r)=>{rK.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i8(t,r,i,n),t.in=r.in,t.out=r.out});function aZ(t,r){return new aM({type:"pipe",in:t,out:r})}let aU=eV("ZodPreprocess",(t,r)=>{aM.init(t,r),rX.init(t,r)}),aF=eV("ZodReadonly",(t,r)=>{rQ.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>ne(t,r,i,n),t.unwrap=()=>t._zod.def.innerType}),aH=eV("ZodLazy",(t,r)=>{r1.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>nr(t,r,i,n),t.unwrap=()=>t._zod.def.getter()});function aJ(t){return new aH({type:"lazy",getter:t})}let aD=eV("ZodCustom",(t,r)=>{r2.init(t,r),nz.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iB(t,r,i,n)});function aV(t,r){return new aU({type:"pipe",in:aO(t),out:r})}j||(j={});let aB="2025-11-25",aW=[aB,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],aG="io.modelcontextprotocol/protocolVersion",aK="io.modelcontextprotocol/clientInfo",aY="io.modelcontextprotocol/serverInfo",aX="io.modelcontextprotocol/clientCapabilities",aQ="io.modelcontextprotocol/subscriptionId",a0="io.modelcontextprotocol/logLevel",a1=aJ(()=>ay([nL(),ae(),an(),ao(),ax(nL(),a1),ap(a1)])),a2=ax(nL(),a1),a9=ap(a1),a4=ay([nL(),ae().int()]),a5=nL(),a3=ah({ttl:ae().optional()}),a6=ah({taskId:nL()}),a7=af({progressToken:a4.optional(),"io.modelcontextprotocol/related-task":a6.optional()}),a8=ah({_meta:a7.optional()}),oe=a8.extend({task:a3.optional()}),ot=ah({method:nL(),params:a8.loose().optional()}),or=ah({_meta:a7.optional()}),oi=ah({method:nL(),params:or.loose().optional()}),on=af({get[aY](){return o_.optional().catch(void 0)}}),oa=af({_meta:on.optional()}),oo=ay([nL(),ae().int()]),os=ah({jsonrpc:aC("2.0"),id:oo,...ot.shape}).strict(),ol=ah({jsonrpc:aC("2.0"),...oi.shape}).strict(),oc=ah({jsonrpc:aC("2.0"),id:oo,result:oa}).strict(),ou=ah({jsonrpc:aC("2.0"),id:oo.optional(),error:ah({code:ae().int(),message:nL(),data:ac().optional()})}).strict(),od=ay([os,ol,oc,ou]),op=ay([oc,ou]),om=oa.strict(),oh=or.extend({requestId:oo.optional(),reason:nL().optional()}),of=oi.extend({method:aC("notifications/cancelled"),params:oh}),og=ah({src:nL(),mimeType:nL().optional(),sizes:ap(nL()).optional(),theme:aR(["light","dark"]).optional()}),oy=ah({icons:ap(og).optional()}),ov=ah({name:nL(),title:nL().optional()}),o_=ov.extend({...ov.shape,...oy.shape,version:nL(),websiteUrl:nL().optional(),description:nL().optional()}),ob=aS(ah({applyDefaults:an().optional()}),a2),oS=aV(t=>t&&"object"==typeof t&&!Array.isArray(t)&&0===Object.keys(t).length?{form:{}}:t,aS(ah({form:ob.optional(),url:a2.optional()}),a2.optional())),ow=af({list:a2.optional(),cancel:a2.optional(),requests:af({sampling:af({createMessage:a2.optional()}).optional(),elicitation:af({create:a2.optional()}).optional()}).optional()}),ox=af({list:a2.optional(),cancel:a2.optional(),requests:af({tools:af({call:a2.optional()}).optional()}).optional()}),ok=ah({experimental:ax(nL(),a2).optional(),sampling:ah({context:a2.optional(),tools:a2.optional()}).optional(),elicitation:oS.optional(),roots:ah({listChanged:an().optional()}).optional(),tasks:ow.optional(),extensions:ax(nL(),a2).optional()}),oR=a8.extend({protocolVersion:nL(),capabilities:ok,clientInfo:o_}),o$=ot.extend({method:aC("initialize"),params:oR}),oC=ah({experimental:ax(nL(),a2).optional(),logging:a2.optional(),completions:a2.optional(),prompts:ah({listChanged:an().optional()}).optional(),resources:ah({subscribe:an().optional(),listChanged:an().optional()}).optional(),tools:ah({listChanged:an().optional()}).optional(),tasks:ox.optional(),extensions:ax(nL(),a2).optional()}),oT=oa.extend({protocolVersion:nL(),capabilities:oC,serverInfo:o_,instructions:nL().optional()}),oO=oi.extend({method:aC("notifications/initialized"),params:or.optional()}),oP=ot.extend({method:aC("server/discover"),params:a8.optional()}),oE=oa.extend({supportedVersions:ap(nL()),capabilities:oC,instructions:nL().optional()}),oI=ot.extend({method:aC("ping"),params:a8.optional()}),oq=ah({progress:ae(),total:aE(ae()),message:aE(nL())}),oj=ah({...or.shape,...oq.shape,progressToken:a4}),oz=oi.extend({method:aC("notifications/progress"),params:oj}),oN=a8.extend({cursor:a5.optional()}),oA=ot.extend({params:oN.optional()}),oL=oa.extend({nextCursor:a5.optional()}),oM=ah({uri:nL(),mimeType:aE(nL()),_meta:ax(nL(),ac()).optional()}),oZ=oM.extend({text:nL()}),oU=nL().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),oF=oM.extend({blob:oU}),oH=aR(["user","assistant"]),oJ=ah({audience:ap(oH).optional(),priority:ae().min(0).max(1).optional(),lastModified:r7(nZ,{offset:!0}).optional()}),oD=ah({...ov.shape,...oy.shape,uri:nL(),description:aE(nL()),mimeType:aE(nL()),size:aE(ae()),annotations:oJ.optional(),_meta:aE(af({}))}),oV=ah({...ov.shape,...oy.shape,uriTemplate:nL(),description:aE(nL()),mimeType:aE(nL()),annotations:oJ.optional(),_meta:aE(af({}))}),oB=oA.extend({method:aC("resources/list")}),oW=oL.extend({resources:ap(oD)}),oG=oA.extend({method:aC("resources/templates/list")}),oK=oL.extend({resourceTemplates:ap(oV)}),oY=a8.extend({uri:nL()}),oX=ot.extend({method:aC("resources/read"),params:oY}),oQ=oa.extend({contents:ap(ay([oZ,oF]))}),o0=oi.extend({method:aC("notifications/resources/list_changed"),params:or.optional()}),o1=ot.extend({method:aC("resources/subscribe"),params:oY}),o2=ot.extend({method:aC("resources/unsubscribe"),params:oY}),o9=ah({toolsListChanged:an().optional(),promptsListChanged:an().optional(),resourcesListChanged:an().optional(),resourceSubscriptions:ap(nL()).optional()}),o4=a8.extend({notifications:o9}),o5=ot.extend({method:aC("subscriptions/listen"),params:o4}),o3=or.extend({notifications:o9}),o6=oi.extend({method:aC("notifications/subscriptions/acknowledged"),params:o3}),o7=on.extend({[aQ]:oo}),o8=oa.extend({_meta:o7}),se=or.extend({uri:nL()}),st=oi.extend({method:aC("notifications/resources/updated"),params:se}),sr=ah({name:nL(),description:aE(nL()),required:aE(an())}),si=ah({...ov.shape,...oy.shape,description:aE(nL()),arguments:aE(ap(sr)),_meta:aE(af({}))}),sn=oA.extend({method:aC("prompts/list")}),sa=oL.extend({prompts:ap(si)}),so=a8.extend({name:nL(),arguments:ax(nL(),nL()).optional()}),ss=ot.extend({method:aC("prompts/get"),params:so}),sl=ah({type:aC("text"),text:nL(),annotations:oJ.optional(),_meta:ax(nL(),ac()).optional()}),sc=ah({type:aC("image"),data:oU,mimeType:nL(),annotations:oJ.optional(),_meta:ax(nL(),ac()).optional()}),su=ah({type:aC("audio"),data:oU,mimeType:nL(),annotations:oJ.optional(),_meta:ax(nL(),ac()).optional()}),sd=ah({type:aC("tool_use"),name:nL(),id:nL(),input:ax(nL(),ac()),_meta:ax(nL(),ac()).optional()}),sp=ah({type:aC("resource"),resource:ay([oZ,oF]),annotations:oJ.optional(),_meta:ax(nL(),ac()).optional()}),sm=oD.extend({type:aC("resource_link")}),sh=ay([sl,sc,su,sm,sp]),sf=ah({role:oH,content:sh}),sg=oa.extend({description:nL().optional(),messages:ap(sf)}),sy=oi.extend({method:aC("notifications/prompts/list_changed"),params:or.optional()}),sv=ah({title:nL().optional(),readOnlyHint:an().optional(),destructiveHint:an().optional(),idempotentHint:an().optional(),openWorldHint:an().optional()}),s_=ah({taskSupport:aR(["required","optional","forbidden"]).optional()}),sb=ah({...ov.shape,...oy.shape,description:nL().optional(),inputSchema:ah({type:aC("object"),properties:ax(nL(),a1).optional(),required:ap(nL()).optional()}).catchall(ac()),outputSchema:af({$schema:nL().optional()}).optional(),annotations:sv.optional(),execution:s_.optional(),_meta:ax(nL(),ac()).optional()}),sS=oA.extend({method:aC("tools/list")}),sw=oL.extend({tools:ap(sb)}),sx=oa.extend({content:ap(sh).default([]),structuredContent:ac().optional(),isError:an().optional()}),sk=sx.or(oa.extend({toolResult:ac()})),sR=oe.extend({name:nL(),arguments:ax(nL(),ac()).optional()}),s$=ot.extend({method:aC("tools/call"),params:sR}),sC=oi.extend({method:aC("notifications/tools/list_changed"),params:or.optional()}),sT=ah({autoRefresh:an().default(!0),debounceMs:ae().int().nonnegative().default(300)}),sO=aR(["debug","info","notice","warning","error","critical","alert","emergency"]),sP=a8.extend({level:sO}),sE=ot.extend({method:aC("logging/setLevel"),params:sP}),sI=or.extend({level:sO,logger:nL().optional(),data:ac()}),sq=oi.extend({method:aC("notifications/message"),params:sI}),sj=ah({name:nL().optional()}),sz=ah({hints:ap(sj).optional(),costPriority:ae().min(0).max(1).optional(),speedPriority:ae().min(0).max(1).optional(),intelligencePriority:ae().min(0).max(1).optional()}),sN=ah({mode:aR(["auto","required","none"]).optional()}),sA=ah({type:aC("tool_result"),toolUseId:nL().describe("The unique identifier for the corresponding tool call."),content:ap(sh),structuredContent:ac().optional(),isError:an().optional(),_meta:ax(nL(),ac()).optional()}),sL=a_("type",[sl,sc,su]),sM=a_("type",[sl,sc,su,sd,sA]),sZ=ah({role:oH,content:ay([sM,ap(sM)]),_meta:ax(nL(),ac()).optional()}),sU=oe.extend({messages:ap(sZ),modelPreferences:sz.optional(),systemPrompt:nL().optional(),includeContext:aR(["none","thisServer","allServers"]).optional(),temperature:ae().optional(),maxTokens:ae().int(),stopSequences:ap(nL()).optional(),metadata:a2.optional(),tools:ap(sb).optional(),toolChoice:sN.optional()}),sF=ot.extend({method:aC("sampling/createMessage"),params:sU}),sH=oa.extend({model:nL(),stopReason:aE(aR(["endTurn","stopSequence","maxTokens"]).or(nL())),role:oH,content:sL}),sJ=oa.extend({model:nL(),stopReason:aE(aR(["endTurn","stopSequence","maxTokens","toolUse"]).or(nL())),role:oH,content:ay([sM,ap(sM)])}),sD=ah({type:aC("boolean"),title:nL().optional(),description:nL().optional(),default:an().optional()}),sV=ah({type:aC("string"),title:nL().optional(),description:nL().optional(),minLength:ae().optional(),maxLength:ae().optional(),format:aR(["email","uri","date","date-time"]).optional(),default:nL().optional()}),sB=ah({type:aR(["number","integer"]),title:nL().optional(),description:nL().optional(),minimum:ae().optional(),maximum:ae().optional(),default:ae().optional()}),sW=ah({type:aC("string"),title:nL().optional(),description:nL().optional(),enum:ap(nL()),default:nL().optional()}),sG=ah({type:aC("string"),title:nL().optional(),description:nL().optional(),oneOf:ap(ah({const:nL(),title:nL()})),default:nL().optional()}),sK=ah({type:aC("string"),title:nL().optional(),description:nL().optional(),enum:ap(nL()),enumNames:ap(nL()).optional(),default:nL().optional()}),sY=ay([sW,sG]),sX=ah({type:aC("array"),title:nL().optional(),description:nL().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:ah({type:aC("string"),enum:ap(nL())}),default:ap(nL()).optional()}),sQ=ah({type:aC("array"),title:nL().optional(),description:nL().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:ah({anyOf:ap(ah({const:nL(),title:nL()}))}),default:ap(nL()).optional()}),s0=ay([sX,sQ]),s1=ay([sK,sY,s0]),s2=ay([s1,sD,sV,sB]),s9=oe.extend({mode:aC("form").optional(),message:nL(),requestedSchema:ah({type:aC("object"),properties:ax(nL(),s2),required:ap(nL()).optional()}).catchall(ac())}),s4=oe.extend({mode:aC("url"),message:nL(),elicitationId:nL(),url:nL().url()}),s5=ay([s9,s4]),s3=ot.extend({method:aC("elicitation/create"),params:s5}),s6=or.extend({elicitationId:nL()}),s7=oi.extend({method:aC("notifications/elicitation/complete"),params:s6}),s8=oa.extend({action:aR(["accept","decline","cancel"]),content:aV(t=>null===t?void 0:t,ax(nL(),ay([nL(),ae(),an(),ap(nL())])).optional())}),le=ah({type:aC("ref/resource"),uri:nL()}),lt=ah({type:aC("ref/prompt"),name:nL()}),lr=a8.extend({ref:ay([lt,le]),argument:ah({name:nL(),value:nL()}),context:ah({arguments:ax(nL(),nL()).optional()}).optional()}),li=ot.extend({method:aC("completion/complete"),params:lr}),ln=oa.extend({completion:af({values:ap(nL()).max(100),total:aE(ae().int()),hasMore:aE(an())})}),la=ah({uri:nL().startsWith("file://"),name:nL().optional(),_meta:ax(nL(),ac()).optional()}),lo=ot.extend({method:aC("roots/list"),params:a8.optional()}),ls=oa.extend({roots:ap(la)}),ll=oi.extend({method:aC("notifications/roots/list_changed"),params:or.optional()}),lc=af({ttl:ae().optional(),pollInterval:ae().optional()}),lu=aR(["working","input_required","completed","failed","cancelled"]),ld=ah({taskId:nL(),status:lu,ttl:ay([ae(),ao()]),createdAt:nL(),lastUpdatedAt:nL(),pollInterval:aE(ae()),statusMessage:aE(nL())}),lp=oa.extend({task:ld}),lm=or.merge(ld),lh=oi.extend({method:aC("notifications/tasks/status"),params:lm}),lf=ot.extend({method:aC("tasks/get"),params:a8.extend({taskId:nL()})}),lg=oa.merge(ld),ly=ot.extend({method:aC("tasks/result"),params:a8.extend({taskId:nL()})}),lv=oa.loose(),l_=oA.extend({method:aC("tasks/list")}),lb=oL.extend({tasks:ap(ld)}),lS=ot.extend({method:aC("tasks/cancel"),params:a8.extend({taskId:nL()})}),lw=oa.merge(ld),lx=ay([oI,o$,oP,li,sE,ss,sn,oB,oG,oX,o1,o2,o5,s$,sS]),lk=ay([of,oz,oO,ll]),lR=ay([om,sH,sJ,s8,ls]),l$=ay([oI,sF,s3,lo]),lC=ay([of,oz,sq,st,o0,sC,sy,o6,s7]),lT=ay([om,oT,oE,ln,sg,sa,oW,oK,oQ,sx,sw,o8]),lO=r6(nB,void 0).superRefine((t,r)=>{if(!URL.canParse(t))return r.addIssue({code:"custom",message:"URL must be parseable",fatal:!0}),eH}).refine(t=>{let r=new URL(t);return"javascript:"!==r.protocol&&"data:"!==r.protocol&&"vbscript:"!==r.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),lP=af({resource:nL().url(),authorization_servers:ap(lO).optional(),jwks_uri:nL().url().optional(),scopes_supported:ap(nL()).optional(),bearer_methods_supported:ap(nL()).optional(),resource_signing_alg_values_supported:ap(nL()).optional(),resource_name:nL().optional(),resource_documentation:nL().optional(),resource_policy_uri:nL().url().optional(),resource_tos_uri:nL().url().optional(),tls_client_certificate_bound_access_tokens:an().optional(),authorization_details_types_supported:ap(nL()).optional(),dpop_signing_alg_values_supported:ap(nL()).optional(),dpop_bound_access_tokens_required:an().optional()}),lE=af({issuer:nL(),authorization_endpoint:lO,token_endpoint:lO,registration_endpoint:lO.optional(),scopes_supported:ap(nL()).optional(),response_types_supported:ap(nL()),response_modes_supported:ap(nL()).optional(),grant_types_supported:ap(nL()).optional(),token_endpoint_auth_methods_supported:ap(nL()).optional(),token_endpoint_auth_signing_alg_values_supported:ap(nL()).optional(),service_documentation:lO.optional(),revocation_endpoint:lO.optional(),revocation_endpoint_auth_methods_supported:ap(nL()).optional(),revocation_endpoint_auth_signing_alg_values_supported:ap(nL()).optional(),introspection_endpoint:nL().optional(),introspection_endpoint_auth_methods_supported:ap(nL()).optional(),introspection_endpoint_auth_signing_alg_values_supported:ap(nL()).optional(),code_challenge_methods_supported:ap(nL()).optional(),client_id_metadata_document_supported:an().optional(),authorization_response_iss_parameter_supported:an().optional().catch(void 0)}),lI=af({issuer:nL(),authorization_endpoint:lO,token_endpoint:lO,userinfo_endpoint:lO.optional(),jwks_uri:lO,registration_endpoint:lO.optional(),scopes_supported:ap(nL()).optional(),response_types_supported:ap(nL()),response_modes_supported:ap(nL()).optional(),grant_types_supported:ap(nL()).optional(),acr_values_supported:ap(nL()).optional(),subject_types_supported:ap(nL()),id_token_signing_alg_values_supported:ap(nL()),id_token_encryption_alg_values_supported:ap(nL()).optional(),id_token_encryption_enc_values_supported:ap(nL()).optional(),userinfo_signing_alg_values_supported:ap(nL()).optional(),userinfo_encryption_alg_values_supported:ap(nL()).optional(),userinfo_encryption_enc_values_supported:ap(nL()).optional(),request_object_signing_alg_values_supported:ap(nL()).optional(),request_object_encryption_alg_values_supported:ap(nL()).optional(),request_object_encryption_enc_values_supported:ap(nL()).optional(),token_endpoint_auth_methods_supported:ap(nL()).optional(),token_endpoint_auth_signing_alg_values_supported:ap(nL()).optional(),display_values_supported:ap(nL()).optional(),claim_types_supported:ap(nL()).optional(),claims_supported:ap(nL()).optional(),service_documentation:nL().optional(),claims_locales_supported:ap(nL()).optional(),ui_locales_supported:ap(nL()).optional(),claims_parameter_supported:an().optional(),request_parameter_supported:an().optional(),request_uri_parameter_supported:an().optional(),require_request_uri_registration:an().optional(),op_policy_uri:lO.optional(),op_tos_uri:lO.optional(),client_id_metadata_document_supported:an().optional(),authorization_response_iss_parameter_supported:an().optional().catch(void 0)}),lq=ah({...lI.shape,...lE.pick({code_challenge_methods_supported:!0}).shape}),lj=ah({access_token:nL(),id_token:nL().optional(),token_type:nL(),expires_in:new n8(r5({type:"number",coerce:!0,checks:[],...ew(void 0)})).optional(),scope:nL().optional(),refresh_token:nL().optional()}).strip(),lz=ah({issued_token_type:aC("urn:ietf:params:oauth:token-type:id-jag"),access_token:nL(),token_type:nL().optional(),expires_in:ae().optional(),scope:nL().optional()}).strip(),lN=ah({error:nL(),error_description:nL().optional(),error_uri:nL().optional()}),lA=lO.optional().or(aC("").transform(()=>void 0)),lL=ah({redirect_uris:ap(lO),token_endpoint_auth_method:nL().optional(),grant_types:ap(nL()).optional(),response_types:ap(nL()).optional(),application_type:nL().optional(),client_name:nL().optional(),client_uri:lO.optional(),logo_uri:lA,scope:nL().optional(),contacts:ap(nL()).optional(),tos_uri:lA,policy_uri:nL().optional(),jwks_uri:lO.optional(),jwks:new as({type:"any"}).optional(),software_id:nL().optional(),software_version:nL().optional(),software_statement:nL().optional()}).strip(),lM=ah({client_id:nL(),client_secret:nL().optional(),client_id_issued_at:ae().optional(),client_secret_expires_at:ae().optional()}).strip(),lZ=lL.merge(lM),lU=ah({error:nL(),error_description:nL().optional()}).strip(),lF=ah({token:nL(),token_type_hint:nL().optional()}).strip(),lH=Symbol.for("mcp.sdk.errorBrands");function lJ(t,r){let i=new Set,n=r;for(;"function"==typeof n;){let t=n.mcpBrand;Object.prototype.hasOwnProperty.call(n,"mcpBrand")&&"string"==typeof t&&i.add(t),n=Object.getPrototypeOf(n)}0!==i.size&&Object.defineProperty(t,lH,{value:i,enumerable:!1,configurable:!0})}function lD(t,r){try{if("object"==typeof r&&null!==r&&Object.prototype.hasOwnProperty.call(t,"mcpBrand")&&"string"==typeof t.mcpBrand&&Object.prototype.hasOwnProperty.call(r,lH)){let i=r[lH];if(i&&"function"==typeof i.has&&i.has(t.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(t,r)}(class t extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return lD(this,t)}static isInstance(t){if("function"!=typeof this)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return lD(this,t)}constructor(t,r,i){super(r),this.code=t,this.errorUri=i,this.name="OAuthError",lJ(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(r){return new t(r.error,r.error_description??r.error,r.error_uri)}});let lV=(($={}).NotConnected="NOT_CONNECTED",$.AlreadyConnected="ALREADY_CONNECTED",$.NotInitialized="NOT_INITIALIZED",$.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",$.RequestTimeout="REQUEST_TIMEOUT",$.ConnectionClosed="CONNECTION_CLOSED",$.SendFailed="SEND_FAILED",$.InvalidResult="INVALID_RESULT",$.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",$.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",$.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",$.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",$.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",$.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",$.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",$.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",$.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",$.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",$.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",$);var lB=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](t){return lD(this,t)}static isInstance(t){if("function"!=typeof this)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return lD(this,t)}constructor(t,r,i){super(r),this.code=t,this.data=i,this.name="SdkError",lJ(this,new.target)}};(class extends lB{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(t,r,i){super(t,r,i),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}});let lW={};function lG(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function lK(t,r){let i={};for(let[n,a]of Object.entries(t)){if(void 0===a)continue;let t=void 0===r?void 0:r[n];if(void 0===t){i[n]=a;continue}if(lG(a)&&lG(t)){let r={};for(let[i,o]of Object.entries(a))void 0!==o&&void 0===t[i]&&("elicitation"!==n||"form"!==i||void 0!==t.form||void 0!==t.url)&&(r[i]=o);Object.keys(r).length>0&&(i[n]=r)}}return Object.keys(i).length>0?i:void 0}let lY="2026-07-28",lX=[lY];function lQ(t){return t.filter(t=>t>=lY)}function l0(t){let r=t.structuredContent;return void 0===r||!("object"!=typeof r||null===r||Array.isArray(r))||t.content?.some(t=>"text"===t.type)?t:{...t,content:[...t.content??[],{type:"text",text:JSON.stringify(r)}]}}let l1=["task","inputRequests","requestState"];function l2(t){return null===t||"object"!=typeof t||Array.isArray(t)||void 0!==t.content||l1.some(r=>r in t)?t:{...t,content:[]}}function l9(){let t,r,n,a,o,s,l,c,u,d,p,m,h,f,g,y,v,_,b,S,w,x,k,R,$,C,T,O,P,E,I,q,j,z,N,A,L,M,Z,U,F,H,J,D,V,B,W,G,K,Y,X,Q,ee,et,er,ei,en,ea,eo,es,el,ec,eu,ed,ep,em,eh,ef,eg,ey,ev,e_,eb,eS,ew,ex,ek,eR,e$,eC,eT,eO,eP,eE,eI,eq,ej,ez,eN,eA,eL,eM,eZ,eU,eF,eH,eJ,eD,eV,eB,eW,eG,eK,eY,eX,eQ,e0,e1,e2,e9,e4,e5,e3,e6,e7,e8,te,tt,tr,ti,tn,ta,to,ts,tl,tc,tu,td,tp,tm,th,tf,tg,ty,tv,t_,tb,tS,tw,tx;return i??=(t=aJ(()=>ay([nL(),ae(),an(),ao(),ax(nL(),t),ap(t)])),r=ax(nL(),t),n=ay([nL(),ae().int()]),a=nL(),o=ah({ttl:ae().optional()}),s=ah({taskId:nL()}),u=(c=ah({_meta:(l=af({progressToken:n.optional(),"io.modelcontextprotocol/related-task":s.optional()})).optional()})).extend({task:o.optional()}),d=ah({method:nL(),params:c.loose().optional()}),p=ah({_meta:l.optional()}),m=ah({method:nL(),params:p.loose().optional()}),h=af({_meta:l.optional()}),f=ay([nL(),ae().int()]),g=h.strict(),y=p.extend({requestId:f.optional(),reason:nL().optional()}),v=m.extend({method:aC("notifications/cancelled"),params:y}),_=ah({src:nL(),mimeType:nL().optional(),sizes:ap(nL()).optional(),theme:aR(["light","dark"]).optional()}),b=ah({icons:ap(_).optional()}),w=(S=ah({name:nL(),title:nL().optional()})).extend({...S.shape,...b.shape,version:nL(),websiteUrl:nL().optional(),description:nL().optional()}),x=aS(ah({applyDefaults:an().optional()}),r),k=aV(t=>t&&"object"==typeof t&&!Array.isArray(t)&&0===Object.keys(t).length?{form:{}}:t,aS(ah({form:x.optional(),url:r.optional()}),r.optional())),R=af({list:r.optional(),cancel:r.optional(),requests:af({sampling:af({createMessage:r.optional()}).optional(),elicitation:af({create:r.optional()}).optional()}).optional()}),$=af({list:r.optional(),cancel:r.optional(),requests:af({tools:af({call:r.optional()}).optional()}).optional()}),C=ah({experimental:ax(nL(),r).optional(),sampling:ah({context:r.optional(),tools:r.optional()}).optional(),elicitation:k.optional(),roots:ah({listChanged:an().optional()}).optional(),tasks:R.optional(),extensions:ax(nL(),r).optional()}),T=c.extend({protocolVersion:nL(),capabilities:C,clientInfo:w}),O=d.extend({method:aC("initialize"),params:T}),P=ah({experimental:ax(nL(),r).optional(),logging:r.optional(),completions:r.optional(),prompts:ah({listChanged:an().optional()}).optional(),resources:ah({subscribe:an().optional(),listChanged:an().optional()}).optional(),tools:ah({listChanged:an().optional()}).optional(),tasks:$.optional(),extensions:ax(nL(),r).optional()}),E=h.extend({protocolVersion:nL(),capabilities:P,serverInfo:w,instructions:nL().optional()}),I=m.extend({method:aC("notifications/initialized"),params:p.optional()}),q=d.extend({method:aC("ping"),params:c.optional()}),j=ah({progress:ae(),total:aE(ae()),message:aE(nL())}),z=ah({...p.shape,...j.shape,progressToken:n}),N=m.extend({method:aC("notifications/progress"),params:z}),A=c.extend({cursor:a.optional()}),L=d.extend({params:A.optional()}),M=h.extend({nextCursor:a.optional()}),U=(Z=ah({uri:nL(),mimeType:aE(nL()),_meta:ax(nL(),ac()).optional()})).extend({text:nL()}),F=nL().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),H=Z.extend({blob:F}),D=ah({audience:ap(J=aR(["user","assistant"])).optional(),priority:ae().min(0).max(1).optional(),lastModified:r7(nZ,{offset:!0}).optional()}),V=ah({...S.shape,...b.shape,uri:nL(),description:aE(nL()),mimeType:aE(nL()),size:aE(ae()),annotations:D.optional(),_meta:aE(af({}))}),B=ah({...S.shape,...b.shape,uriTemplate:nL(),description:aE(nL()),mimeType:aE(nL()),annotations:D.optional(),_meta:aE(af({}))}),W=L.extend({method:aC("resources/list")}),G=M.extend({resources:ap(V)}),K=L.extend({method:aC("resources/templates/list")}),Y=M.extend({resourceTemplates:ap(B)}),X=c.extend({uri:nL()}),Q=d.extend({method:aC("resources/read"),params:X}),ee=h.extend({contents:ap(ay([U,H]))}),et=m.extend({method:aC("notifications/resources/list_changed"),params:p.optional()}),er=d.extend({method:aC("resources/subscribe"),params:X}),ei=d.extend({method:aC("resources/unsubscribe"),params:X}),en=p.extend({uri:nL()}),ea=m.extend({method:aC("notifications/resources/updated"),params:en}),eo=ah({name:nL(),description:aE(nL()),required:aE(an())}),es=ah({...S.shape,...b.shape,description:aE(nL()),arguments:aE(ap(eo)),_meta:aE(af({}))}),el=L.extend({method:aC("prompts/list")}),ec=M.extend({prompts:ap(es)}),eu=c.extend({name:nL(),arguments:ax(nL(),nL()).optional()}),ed=d.extend({method:aC("prompts/get"),params:eu}),ep=ah({type:aC("text"),text:nL(),annotations:D.optional(),_meta:ax(nL(),ac()).optional()}),em=ah({type:aC("image"),data:F,mimeType:nL(),annotations:D.optional(),_meta:ax(nL(),ac()).optional()}),eh=ah({type:aC("audio"),data:F,mimeType:nL(),annotations:D.optional(),_meta:ax(nL(),ac()).optional()}),ef=ah({type:aC("tool_use"),name:nL(),id:nL(),input:ax(nL(),ac()),_meta:ax(nL(),ac()).optional()}),eg=ah({type:aC("resource"),resource:ay([U,H]),annotations:D.optional(),_meta:ax(nL(),ac()).optional()}),e_=ah({role:J,content:ev=ay([ep,em,eh,ey=V.extend({type:aC("resource_link")}),eg])}),eb=h.extend({description:nL().optional(),messages:ap(e_)}),eS=m.extend({method:aC("notifications/prompts/list_changed"),params:p.optional()}),ew=ah({title:nL().optional(),readOnlyHint:an().optional(),destructiveHint:an().optional(),idempotentHint:an().optional(),openWorldHint:an().optional()}),ex=ah({taskSupport:aR(["required","optional","forbidden"]).optional()}),ek=ah({...S.shape,...b.shape,description:nL().optional(),inputSchema:ah({type:aC("object"),properties:ax(nL(),t).optional(),required:ap(nL()).optional()}).catchall(ac()),outputSchema:ah({type:aC("object"),properties:ax(nL(),t).optional(),required:ap(nL()).optional()}).catchall(ac()).optional(),annotations:ew.optional(),execution:ex.optional(),_meta:ax(nL(),ac()).optional()}),eR=L.extend({method:aC("tools/list")}),e$=M.extend({tools:ap(ek)}),eC=h.extend({content:ap(ev),structuredContent:ax(nL(),ac()).optional(),isError:an().optional()}),eT=u.extend({name:nL(),arguments:ax(nL(),ac()).optional()}),eO=d.extend({method:aC("tools/call"),params:eT}),eP=m.extend({method:aC("notifications/tools/list_changed"),params:p.optional()}),eE=aR(["debug","info","notice","warning","error","critical","alert","emergency"]),eI=c.extend({level:eE}),eq=d.extend({method:aC("logging/setLevel"),params:eI}),ej=p.extend({level:eE,logger:nL().optional(),data:ac()}),ez=m.extend({method:aC("notifications/message"),params:ej}),eN=ah({name:nL().optional()}),eA=ah({hints:ap(eN).optional(),costPriority:ae().min(0).max(1).optional(),speedPriority:ae().min(0).max(1).optional(),intelligencePriority:ae().min(0).max(1).optional()}),eL=ah({mode:aR(["auto","required","none"]).optional()}),eM=ah({type:aC("tool_result"),toolUseId:nL().describe("The unique identifier for the corresponding tool call."),content:ap(ev),structuredContent:ah({}).loose().optional(),isError:an().optional(),_meta:ax(nL(),ac()).optional()}),eZ=a_("type",[ep,em,eh]),eF=ah({role:J,content:ay([eU=a_("type",[ep,em,eh,ef,eM]),ap(eU)]),_meta:ax(nL(),ac()).optional()}),eH=u.extend({messages:ap(eF),modelPreferences:eA.optional(),systemPrompt:nL().optional(),includeContext:aR(["none","thisServer","allServers"]).optional(),temperature:ae().optional(),maxTokens:ae().int(),stopSequences:ap(nL()).optional(),metadata:r.optional(),tools:ap(ek).optional(),toolChoice:eL.optional()}),eJ=d.extend({method:aC("sampling/createMessage"),params:eH}),eD=h.extend({model:nL(),stopReason:aE(aR(["endTurn","stopSequence","maxTokens"]).or(nL())),role:J,content:eZ}),eV=h.extend({model:nL(),stopReason:aE(aR(["endTurn","stopSequence","maxTokens","toolUse"]).or(nL())),role:J,content:ay([eU,ap(eU)])}),eB=ah({type:aC("boolean"),title:nL().optional(),description:nL().optional(),default:an().optional()}),eW=ah({type:aC("string"),title:nL().optional(),description:nL().optional(),minLength:ae().optional(),maxLength:ae().optional(),format:aR(["email","uri","date","date-time"]).optional(),default:nL().optional()}),eG=ah({type:aR(["number","integer"]),title:nL().optional(),description:nL().optional(),minimum:ae().optional(),maximum:ae().optional(),default:ae().optional()}),eK=ah({type:aC("string"),title:nL().optional(),description:nL().optional(),enum:ap(nL()),default:nL().optional()}),eY=ah({type:aC("string"),title:nL().optional(),description:nL().optional(),oneOf:ap(ah({const:nL(),title:nL()})),default:nL().optional()}),eX=ah({type:aC("string"),title:nL().optional(),description:nL().optional(),enum:ap(nL()),enumNames:ap(nL()).optional(),default:nL().optional()}),eQ=ay([eK,eY]),e0=ah({type:aC("array"),title:nL().optional(),description:nL().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:ah({type:aC("string"),enum:ap(nL())}),default:ap(nL()).optional()}),e2=ay([e0,e1=ah({type:aC("array"),title:nL().optional(),description:nL().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:ah({anyOf:ap(ah({const:nL(),title:nL()}))}),default:ap(nL()).optional()})]),e9=ay([eX,eQ,e2]),e4=ay([e9,eB,eW,eG]),e5=u.extend({mode:aC("form").optional(),message:nL(),requestedSchema:ah({type:aC("object"),properties:ax(nL(),e4),required:ap(nL()).optional()}).catchall(ac())}),e6=ay([e5,e3=u.extend({mode:aC("url"),message:nL(),elicitationId:nL(),url:nL().url()})]),e7=d.extend({method:aC("elicitation/create"),params:e6}),e8=p.extend({elicitationId:nL()}),te=m.extend({method:aC("notifications/elicitation/complete"),params:e8}),tt=h.extend({action:aR(["accept","decline","cancel"]),content:aV(t=>null===t?void 0:t,ax(nL(),ay([nL(),ae(),an(),ap(nL())])).optional())}),tr=ah({type:aC("ref/resource"),uri:nL()}),ti=ah({type:aC("ref/prompt"),name:nL()}),tn=c.extend({ref:ay([ti,tr]),argument:ah({name:nL(),value:nL()}),context:ah({arguments:ax(nL(),nL()).optional()}).optional()}),ta=d.extend({method:aC("completion/complete"),params:tn}),to=h.extend({completion:af({values:ap(nL()).max(100),total:aE(ae().int()),hasMore:aE(an())})}),ts=ah({uri:nL().startsWith("file://"),name:nL().optional(),_meta:ax(nL(),ac()).optional()}),tl=d.extend({method:aC("roots/list"),params:c.optional()}),tc=h.extend({roots:ap(ts)}),tu=m.extend({method:aC("notifications/roots/list_changed"),params:p.optional()}),td=af({ttl:ae().optional(),pollInterval:ae().optional()}),tp=aR(["working","input_required","completed","failed","cancelled"]),tm=ah({taskId:nL(),status:tp,ttl:ay([ae(),ao()]),createdAt:nL(),lastUpdatedAt:nL(),pollInterval:aE(ae()),statusMessage:aE(nL())}),th=h.extend({task:tm}),tf=p.merge(tm),tg=m.extend({method:aC("notifications/tasks/status"),params:tf}),ty=d.extend({method:aC("tasks/get"),params:c.extend({taskId:nL()})}),tv=h.merge(tm),t_=d.extend({method:aC("tasks/result"),params:c.extend({taskId:nL()})}),tb=h.loose(),tS=L.extend({method:aC("tasks/list")}),tw=M.extend({tasks:ap(tm)}),tx=d.extend({method:aC("tasks/cancel"),params:c.extend({taskId:nL()})}),{JSONValueSchema:t,JSONObjectSchema:r,ProgressTokenSchema:n,CursorSchema:a,TaskMetadataSchema:o,RelatedTaskMetadataSchema:s,RequestMetaSchema:l,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:u,RequestSchema:d,NotificationsParamsSchema:p,NotificationSchema:m,ResultSchema:h,RequestIdSchema:f,EmptyResultSchema:g,CancelledNotificationParamsSchema:y,CancelledNotificationSchema:v,IconSchema:_,IconsSchema:b,BaseMetadataSchema:S,ImplementationSchema:w,ClientTasksCapabilitySchema:R,ServerTasksCapabilitySchema:$,ClientCapabilitiesSchema:C,InitializeRequestParamsSchema:T,InitializeRequestSchema:O,ServerCapabilitiesSchema:P,InitializeResultSchema:E,InitializedNotificationSchema:I,PingRequestSchema:q,ProgressSchema:j,ProgressNotificationParamsSchema:z,ProgressNotificationSchema:N,PaginatedRequestParamsSchema:A,PaginatedRequestSchema:L,PaginatedResultSchema:M,ResourceContentsSchema:Z,TextResourceContentsSchema:U,BlobResourceContentsSchema:H,RoleSchema:J,AnnotationsSchema:D,ResourceSchema:V,ResourceTemplateSchema:B,ListResourcesRequestSchema:W,ListResourcesResultSchema:G,ListResourceTemplatesRequestSchema:K,ListResourceTemplatesResultSchema:Y,ResourceRequestParamsSchema:X,ReadResourceRequestParamsSchema:X,ReadResourceRequestSchema:Q,ReadResourceResultSchema:ee,ResourceListChangedNotificationSchema:et,SubscribeRequestParamsSchema:X,SubscribeRequestSchema:er,UnsubscribeRequestParamsSchema:X,UnsubscribeRequestSchema:ei,ResourceUpdatedNotificationParamsSchema:en,ResourceUpdatedNotificationSchema:ea,PromptArgumentSchema:eo,PromptSchema:es,ListPromptsRequestSchema:el,ListPromptsResultSchema:ec,GetPromptRequestParamsSchema:eu,GetPromptRequestSchema:ed,TextContentSchema:ep,ImageContentSchema:em,AudioContentSchema:eh,ToolUseContentSchema:ef,EmbeddedResourceSchema:eg,ResourceLinkSchema:ey,ContentBlockSchema:ev,PromptMessageSchema:e_,GetPromptResultSchema:eb,PromptListChangedNotificationSchema:eS,ToolAnnotationsSchema:ew,ToolExecutionSchema:ex,ToolSchema:ek,ListToolsRequestSchema:eR,ListToolsResultSchema:e$,CallToolResultSchema:eC,CallToolRequestParamsSchema:eT,CallToolRequestSchema:eO,ToolListChangedNotificationSchema:eP,LoggingLevelSchema:eE,SetLevelRequestParamsSchema:eI,SetLevelRequestSchema:eq,LoggingMessageNotificationParamsSchema:ej,LoggingMessageNotificationSchema:ez,ModelHintSchema:eN,ModelPreferencesSchema:eA,ToolChoiceSchema:eL,ToolResultContentSchema:eM,SamplingContentSchema:eZ,SamplingMessageContentBlockSchema:eU,SamplingMessageSchema:eF,CreateMessageRequestParamsSchema:eH,CreateMessageRequestSchema:eJ,CreateMessageResultSchema:eD,CreateMessageResultWithToolsSchema:eV,BooleanSchemaSchema:eB,StringSchemaSchema:eW,NumberSchemaSchema:eG,UntitledSingleSelectEnumSchemaSchema:eK,TitledSingleSelectEnumSchemaSchema:eY,LegacyTitledEnumSchemaSchema:eX,SingleSelectEnumSchemaSchema:eQ,UntitledMultiSelectEnumSchemaSchema:e0,TitledMultiSelectEnumSchemaSchema:e1,MultiSelectEnumSchemaSchema:e2,EnumSchemaSchema:e9,PrimitiveSchemaDefinitionSchema:e4,ElicitRequestFormParamsSchema:e5,ElicitRequestURLParamsSchema:e3,ElicitRequestParamsSchema:e6,ElicitRequestSchema:e7,ElicitationCompleteNotificationParamsSchema:e8,ElicitationCompleteNotificationSchema:te,ElicitResultSchema:tt,ResourceTemplateReferenceSchema:tr,PromptReferenceSchema:ti,CompleteRequestParamsSchema:tn,CompleteRequestSchema:ta,CompleteResultSchema:to,RootSchema:ts,ListRootsRequestSchema:tl,ListRootsResultSchema:tc,RootsListChangedNotificationSchema:tu,TaskCreationParamsSchema:td,TaskStatusSchema:tp,TaskSchema:tm,CreateTaskResultSchema:th,TaskStatusNotificationParamsSchema:tf,TaskStatusNotificationSchema:tg,GetTaskRequestSchema:ty,GetTaskResultSchema:tv,GetTaskPayloadRequestSchema:t_,GetTaskPayloadResultSchema:tb,ListTasksRequestSchema:tS,ListTasksResultSchema:tw,CancelTaskRequestSchema:tx,CancelTaskResultSchema:h.merge(tm),ClientRequestSchema:ay([q,O,ta,eq,ed,el,W,K,Q,er,ei,eO,eR,ty,t_,tS,tx]),ClientNotificationSchema:ay([v,N,I,tu,tg]),ClientResultSchema:ay([g,eD,eV,tt,tc,tv,tw,th]),ServerRequestSchema:ay([q,eJ,e7,tl,ty,t_,tS,tx]),ServerNotificationSchema:ay([v,N,ez,ea,et,eP,eS,tg,te]),ServerResultSchema:ay([g,E,to,eb,ec,G,Y,ee,eC,e$,tv,tw,th]),CallToolResultWireSchema:ac().superRefine((t,r)=>{if(!("object"!=typeof t||null===t||Array.isArray(t))&&void 0===t.content){for(let i of l1)if(i in t)return void r.addIssue({code:"custom",message:`content is required when the body carries '${i}' — another result family cannot default into an empty tools/call success`})}}).transform(l2).pipe(eC)})}function l4(t){return"object"!==t.type}let l5=new Set(["const","enum","default","examples"]),l3=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function l6(t){return void 0!==t&&!("string"==typeof t&&t.startsWith("#"))}let l7={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},l8={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},ce={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};function ct(){if(n)return n;let t=l9();return n={requestSchemas:{ping:t.PingRequestSchema,initialize:t.InitializeRequestSchema,"completion/complete":t.CompleteRequestSchema,"logging/setLevel":t.SetLevelRequestSchema,"prompts/get":t.GetPromptRequestSchema,"prompts/list":t.ListPromptsRequestSchema,"resources/list":t.ListResourcesRequestSchema,"resources/templates/list":t.ListResourceTemplatesRequestSchema,"resources/read":t.ReadResourceRequestSchema,"resources/subscribe":t.SubscribeRequestSchema,"resources/unsubscribe":t.UnsubscribeRequestSchema,"tools/call":t.CallToolRequestSchema,"tools/list":t.ListToolsRequestSchema,"tasks/get":t.GetTaskRequestSchema,"tasks/result":t.GetTaskPayloadRequestSchema,"tasks/list":t.ListTasksRequestSchema,"tasks/cancel":t.CancelTaskRequestSchema,"sampling/createMessage":t.CreateMessageRequestSchema,"elicitation/create":t.ElicitRequestSchema,"roots/list":t.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":t.CancelledNotificationSchema,"notifications/progress":t.ProgressNotificationSchema,"notifications/initialized":t.InitializedNotificationSchema,"notifications/roots/list_changed":t.RootsListChangedNotificationSchema,"notifications/tasks/status":t.TaskStatusNotificationSchema,"notifications/message":t.LoggingMessageNotificationSchema,"notifications/resources/updated":t.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":t.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":t.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":t.PromptListChangedNotificationSchema,"notifications/elicitation/complete":t.ElicitationCompleteNotificationSchema},resultSchemas:{ping:t.EmptyResultSchema,initialize:t.InitializeResultSchema,"completion/complete":t.CompleteResultSchema,"logging/setLevel":t.EmptyResultSchema,"prompts/get":t.GetPromptResultSchema,"prompts/list":t.ListPromptsResultSchema,"resources/list":t.ListResourcesResultSchema,"resources/templates/list":t.ListResourceTemplatesResultSchema,"resources/read":t.ReadResourceResultSchema,"resources/subscribe":t.EmptyResultSchema,"resources/unsubscribe":t.EmptyResultSchema,"tools/call":t.CallToolResultWireSchema,"tools/list":t.ListToolsResultSchema,"sampling/createMessage":t.CreateMessageResultWithToolsSchema,"elicitation/create":t.ElicitResultSchema,"roots/list":t.ListRootsResultSchema}}}function cr(t){return Object.prototype.hasOwnProperty.call(l7,t)}function ci(t){return Object.prototype.hasOwnProperty.call(l8,t)}function cn(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function ca(t,r){if(void 0===t)return{ok:!1,reason:"not-in-era"};let i=t.safeParse(r);return i.success?{ok:!0,value:i.data}:{ok:!1,reason:"invalid",message:String(i.error)}}Object.keys(l7),Object.keys(l8);let co={ok:!1,reason:"not-in-era"};function cs(t){return cn(t)&&cn(t.outputSchema)&&l4(t.outputSchema)}let cl={era:"2025-11-25",hasRequestMethod:cr,hasNotificationMethod:ci,validateRequest:(t,r)=>ca(cr(t)?ct().requestSchemas[t]:void 0,r),validateResult:(t,r)=>ca(Object.prototype.hasOwnProperty.call(ce,t)?ct().resultSchemas[t]:void 0,r),validateNotification:(t,r)=>ca(ci(t)?ct().notificationSchemas[t]:void 0,r),hasInputRequestMethod:()=>!1,validateInputRequest:()=>co,validateInputResponse:()=>co,samplingResultVariant:(t,r)=>{let i=l9();return ca(t?i.CreateMessageResultWithToolsSchema:i.CreateMessageResultSchema,r)},outboundEnvelope:t=>void 0,validateEnvelopeMeta:t=>[],projectCallToolResult(t,r){let i=l0(t),n=i.structuredContent;if(void 0===n)return i;let a="object"!=typeof n||null===n||Array.isArray(n),o=void 0!==r&&l4(r);return a||o?{...i,structuredContent:{result:n}}:i},decodeResult(t,r){if(cn(r)&&"resultType"in r){let t={...r};return delete t.resultType,{kind:"complete",result:t}}return{kind:"complete",result:r}},encodeResult(t,r){if("tools/list"!==t)return r;let i=r.tools;return Array.isArray(i)&&i.some(t=>cs(t))?{...r,tools:i.map(t=>cs(t)?{...t,outputSchema:function(t){var r;let i="string"==typeof t.$schema?t.$schema:void 0;if(l6(t.$id))return{...void 0!==i&&{$schema:i},type:"object",properties:{result:t},required:["result"]};let n="string"==typeof(r=t.$schema)&&Y.has(r.replace(/#$/,""))&&!0!==t.$recursiveAnchor,a=(t,r)=>{if(Array.isArray(t))return t.map(t=>a(t,!1));if(null===t||"object"!=typeof t||!r&&l6(t.$id))return t;let i={},o=!1;for(let[s,l]of Object.entries(t))r?i[s]=a(l,!1):("$ref"===s||"$dynamicRef"===s)&&"string"==typeof l?i[s]="#"===l?"#/properties/result":l.startsWith("#/")?`#/properties/result${l.slice(1)}`:l:"$recursiveRef"===s&&"#"===l&&n?o=!0:l5.has(s)?i[s]=l:l3.has(s)?i[s]=a(l,!0):i[s]=a(l,!1);return o&&("$ref"in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:"#/properties/result"}]:i.$ref="#/properties/result"),i};return{...void 0!==i&&{$schema:i},type:"object",properties:{result:a(t,!1)},required:["result"]}}(t.outputSchema)}:t)}:r},encodeErrorCode:t=>-32002===t?-32602:t,checkInboundEnvelope:t=>void 0};function cc(){return a??=function(){let t=aJ(()=>ay([nL(),ae(),an(),ao(),ax(nL(),t),ap(t)])),r=ax(nL(),t),i=ay([nL(),ae().int()]),n=nL(),a=ay([nL(),ae().int()]),o=aR(["user","assistant"]),s=aR(["debug","info","notice","warning","error","critical","alert","emergency"]),l=nL().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),c=ah({ttl:ae().optional()}),u=ah({taskId:nL()}),d=af({progressToken:i.optional(),"io.modelcontextprotocol/related-task":u.optional()}),p=ah({_meta:d.optional()}),m=p.extend({task:c.optional()}),h=ah({_meta:d.optional()}),f=ah({method:nL(),params:h.loose().optional()}),g=ah({src:nL(),mimeType:nL().optional(),sizes:ap(nL()).optional(),theme:aR(["light","dark"]).optional()}),y=ah({icons:ap(g).optional()}),v=ah({name:nL(),title:nL().optional()}),_=v.extend({...v.shape,...y.shape,version:nL(),websiteUrl:nL().optional(),description:nL().optional()}),b=aS(ah({applyDefaults:an().optional()}),r),S=aV(t=>t&&"object"==typeof t&&!Array.isArray(t)&&0===Object.keys(t).length?{form:{}}:t,aS(ah({form:b.optional(),url:r.optional()}),r.optional())),w=af({list:r.optional(),cancel:r.optional(),requests:af({sampling:af({createMessage:r.optional()}).optional(),elicitation:af({create:r.optional()}).optional()}).optional()}),x=af({list:r.optional(),cancel:r.optional(),requests:af({tools:af({call:r.optional()}).optional()}).optional()}),k=ah({experimental:ax(nL(),r).optional(),sampling:ah({context:r.optional(),tools:r.optional()}).optional(),elicitation:S.optional(),roots:ah({listChanged:an().optional()}).optional(),tasks:w.optional(),extensions:ax(nL(),r).optional()}),R=ah({experimental:ax(nL(),r).optional(),logging:r.optional(),completions:r.optional(),prompts:ah({listChanged:an().optional()}).optional(),resources:ah({subscribe:an().optional(),listChanged:an().optional()}).optional(),tools:ah({listChanged:an().optional()}).optional(),tasks:x.optional(),extensions:ax(nL(),r).optional()}),$=ah({progress:ae(),total:aE(ae()),message:aE(nL())}),C=ah({...h.shape,...$.shape,progressToken:i}),T=f.extend({method:aC("notifications/progress"),params:C}),O=h.extend({level:s,logger:nL().optional(),data:ac()}),P=f.extend({method:aC("notifications/message"),params:O}),E=ah({uri:nL(),mimeType:aE(nL()),_meta:ax(nL(),ac()).optional()}),I=E.extend({text:nL()}),q=E.extend({blob:l}),j=ah({audience:ap(o).optional(),priority:ae().min(0).max(1).optional(),lastModified:r7(nZ,{offset:!0}).optional()}),z=ah({...v.shape,...y.shape,uri:nL(),description:aE(nL()),mimeType:aE(nL()),size:aE(ae()),annotations:j.optional(),_meta:aE(af({}))}),N=ah({...v.shape,...y.shape,uriTemplate:nL(),description:aE(nL()),mimeType:aE(nL()),annotations:j.optional(),_meta:aE(af({}))}),A=f.extend({method:aC("notifications/resources/list_changed"),params:h.optional()}),L=h.extend({uri:nL()}),M=f.extend({method:aC("notifications/resources/updated"),params:L}),Z=ah({name:nL(),description:aE(nL()),required:aE(an())}),U=ah({...v.shape,...y.shape,description:aE(nL()),arguments:aE(ap(Z)),_meta:aE(af({}))}),F=f.extend({method:aC("notifications/prompts/list_changed"),params:h.optional()}),H=ah({type:aC("text"),text:nL(),annotations:j.optional(),_meta:ax(nL(),ac()).optional()}),J=ah({type:aC("image"),data:l,mimeType:nL(),annotations:j.optional(),_meta:ax(nL(),ac()).optional()}),D=ah({type:aC("audio"),data:l,mimeType:nL(),annotations:j.optional(),_meta:ax(nL(),ac()).optional()}),V=ah({type:aC("tool_use"),name:nL(),id:nL(),input:ax(nL(),ac()),_meta:ax(nL(),ac()).optional()}),B=ah({type:aC("resource"),resource:ay([I,q]),annotations:j.optional(),_meta:ax(nL(),ac()).optional()}),W=z.extend({type:aC("resource_link")}),G=ay([H,J,D,W,B]),K=ah({role:o,content:G}),Y=ah({title:nL().optional(),readOnlyHint:an().optional(),destructiveHint:an().optional(),idempotentHint:an().optional(),openWorldHint:an().optional()}),X=f.extend({method:aC("notifications/tools/list_changed"),params:h.optional()}),Q=ah({name:nL().optional()}),ee=ah({hints:ap(Q).optional(),costPriority:ae().min(0).max(1).optional(),speedPriority:ae().min(0).max(1).optional(),intelligencePriority:ae().min(0).max(1).optional()}),et=ah({mode:aR(["auto","required","none"]).optional()}),er=ah({type:aC("boolean"),title:nL().optional(),description:nL().optional(),default:an().optional()}),ei=ah({type:aC("string"),title:nL().optional(),description:nL().optional(),minLength:ae().optional(),maxLength:ae().optional(),format:aR(["email","uri","date","date-time"]).optional(),default:nL().optional()}),en=ah({type:aR(["number","integer"]),title:nL().optional(),description:nL().optional(),minimum:ae().optional(),maximum:ae().optional(),default:ae().optional()}),ea=ah({type:aC("string"),title:nL().optional(),description:nL().optional(),enum:ap(nL()),default:nL().optional()}),eo=ah({type:aC("string"),title:nL().optional(),description:nL().optional(),oneOf:ap(ah({const:nL(),title:nL()})),default:nL().optional()}),es=ah({type:aC("string"),title:nL().optional(),description:nL().optional(),enum:ap(nL()),enumNames:ap(nL()).optional(),default:nL().optional()}),el=ay([ea,eo]),ec=ah({type:aC("array"),title:nL().optional(),description:nL().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:ah({type:aC("string"),enum:ap(nL())}),default:ap(nL()).optional()}),eu=ah({type:aC("array"),title:nL().optional(),description:nL().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:ah({anyOf:ap(ah({const:nL(),title:nL()}))}),default:ap(nL()).optional()}),ed=ay([ec,eu]),ep=ay([es,el,ed]),em=ay([ep,er,ei,en]),eh=m.extend({mode:aC("form").optional(),message:nL(),requestedSchema:ah({type:aC("object"),properties:ax(nL(),em),required:ap(nL()).optional()}).catchall(ac())}),ef=ah({type:aC("ref/resource"),uri:nL()}),eg=ah({type:aC("ref/prompt"),name:nL()}),ey=ah({uri:nL().startsWith("file://"),name:nL().optional(),_meta:ax(nL(),ac()).optional()}),ev=k.shape,e_=ah({experimental:ev.experimental,sampling:ev.sampling,elicitation:ev.elicitation,roots:ev.roots,extensions:ev.extensions}),eb=R.shape,eS=ah({experimental:eb.experimental,logging:eb.logging,completions:eb.completions,prompts:eb.prompts,resources:eb.resources,tools:eb.tools,extensions:eb.extensions}),ew=af({progressToken:i.optional(),[aG]:nL(),[aK]:_.optional(),[aX]:e_,[a0]:s.optional()}),ex=ah({...v.shape,...y.shape,description:nL().optional(),inputSchema:af({$schema:nL().optional(),type:aC("object")}),outputSchema:af({$schema:nL().optional()}).optional(),annotations:Y.optional(),_meta:ax(nL(),ac()).optional()}),ek=ah({type:aC("tool_result"),toolUseId:nL(),content:ap(G),structuredContent:ac().optional(),isError:an().optional(),_meta:ax(nL(),ac()).optional()}),eR=ay([H,J,D,V,ek]),e$=ah({role:o,content:ay([eR,ap(eR)]),_meta:ax(nL(),ac()).optional()}),eC=nL(),eT=af({[aY]:_.optional().catch(void 0)}),eO=eT.optional();function eP(t){return af({_meta:eO,resultType:eC.default("complete"),...t})}let eE=eP({}),eI=eP({nextCursor:n.optional()}),eq=eP({content:ap(G),structuredContent:ac().optional(),isError:an().optional()}),ej=eP({ttlMs:ae().int().min(0),cacheScope:aR(["public","private"]),tools:ap(ex),nextCursor:n.optional()}),ez=eP({ttlMs:ae().int().min(0),cacheScope:aR(["public","private"]),prompts:ap(U),nextCursor:n.optional()}),eN=eP({description:nL().optional(),messages:ap(K)}),eA=eP({ttlMs:ae().int().min(0),cacheScope:aR(["public","private"]),resources:ap(z),nextCursor:n.optional()}),eL=eP({ttlMs:ae().int().min(0),cacheScope:aR(["public","private"]),resourceTemplates:ap(N),nextCursor:n.optional()}),eM=eP({ttlMs:ae().int().min(0),cacheScope:aR(["public","private"]),contents:ap(ay([I,q]))}),eZ=eP({completion:ah({values:ap(nL()).max(100),total:ae().int().optional(),hasMore:an().optional()}).loose()}),eU=eP({ttlMs:ae().int().min(0),cacheScope:aR(["public","private"])}),eF=eP({ttlMs:ae().int().min(0).catch(0),cacheScope:aR(["public","private"]).catch("private"),supportedVersions:ap(nL()),capabilities:eS,instructions:nL().optional()}),eH=ah({messages:ap(e$),modelPreferences:ee.optional(),systemPrompt:nL().optional(),includeContext:aR(["none","thisServer","allServers"]).optional(),temperature:ae().optional(),maxTokens:ae().int(),stopSequences:ap(nL()).optional(),metadata:r.optional(),tools:ap(ex).optional(),toolChoice:et.optional()}),eJ=ah({method:aC("sampling/createMessage"),params:eH}),eD=ah({method:aC("roots/list"),params:ah({_meta:ax(nL(),ac()).optional()}).optional()}),eV=ah({...e$.shape,model:nL(),stopReason:nL().optional()}),eB=ah({roots:ap(ey)}),eW=ah({action:aR(["accept","decline","cancel"]),content:ax(nL(),ay([nL(),ae(),an(),ap(nL())])).optional()}),eG=ah({mode:aC("url"),message:nL(),url:nL().url()}),eK=ay([eh,eG]),eY=ah({method:aC("elicitation/create"),params:eK}),eX=ay([eJ,eD,eY]),eQ=ay([eV,eB,eW]),e0=ax(nL(),eX),e1=ax(nL(),eQ),e2=eP({inputRequests:e0.optional(),requestState:nL().optional()}),e9={inputResponses:e1.optional(),requestState:nL().optional()},e4=ah({_meta:ew,...e9}),e5=af({progressToken:i.optional()});function e3(t,r){return ah({method:aC(t),params:ah({_meta:ew,...r})})}function e6(t,r){return ah({method:aC(t),params:ah({_meta:e5.optional(),...r}).optional()})}let e7={name:nL(),arguments:ax(nL(),ac()).optional(),...e9},e8={cursor:n.optional()},te=e3("tools/call",e7),tt=e3("tools/list",e8),tr=e3("prompts/list",e8),ti=e3("prompts/get",{name:nL(),arguments:ax(nL(),nL()).optional(),...e9}),tn=e3("resources/list",e8),ta=e3("resources/templates/list",e8),to=e3("resources/read",{uri:nL(),...e9}),ts={ref:ay([eg,ef]),argument:ah({name:nL(),value:nL()}),context:ah({arguments:ax(nL(),nL()).optional()}).optional()},tl=e3("completion/complete",ts),tc=e3("server/discover",{}),tu=ah({toolsListChanged:an().optional(),promptsListChanged:an().optional(),resourcesListChanged:an().optional(),resourceSubscriptions:ap(nL()).optional()}),td={notifications:tu},tp=e3("subscriptions/listen",td),tm=eT.extend({"io.modelcontextprotocol/subscriptionId":a}),th=af({_meta:tm,resultType:eC.default("complete")}),tf={"tools/call":e6("tools/call",e7),"tools/list":e6("tools/list",e8),"prompts/get":e6("prompts/get",{name:nL(),arguments:ax(nL(),nL()).optional()}),"prompts/list":e6("prompts/list",e8),"resources/list":e6("resources/list",e8),"resources/templates/list":e6("resources/templates/list",e8),"resources/read":e6("resources/read",{uri:nL()}),"completion/complete":e6("completion/complete",ts),"server/discover":e6("server/discover",{}),"subscriptions/listen":e6("subscriptions/listen",td)};function tg(t){return af({_meta:eO,...t})}let ty={"tools/call":tg({content:ap(G),structuredContent:ac().optional(),isError:an().optional()}),"tools/list":tg({ttlMs:ae().int().min(0),cacheScope:aR(["public","private"]),tools:ap(ex),nextCursor:n.optional()}),"prompts/get":tg({description:nL().optional(),messages:ap(K)}),"prompts/list":tg({ttlMs:ae().int().min(0),cacheScope:aR(["public","private"]),prompts:ap(U),nextCursor:n.optional()}),"resources/list":tg({ttlMs:ae().int().min(0),cacheScope:aR(["public","private"]),resources:ap(z),nextCursor:n.optional()}),"resources/templates/list":tg({ttlMs:ae().int().min(0),cacheScope:aR(["public","private"]),resourceTemplates:ap(N),nextCursor:n.optional()}),"resources/read":tg({ttlMs:ae().int().min(0),cacheScope:aR(["public","private"]),contents:ap(ay([I,q]))}),"completion/complete":tg({completion:ah({values:ap(nL()).max(100),total:ae().int().optional(),hasMore:an().optional()}).loose()}),"server/discover":tg({ttlMs:ae().int().min(0).catch(0),cacheScope:aR(["public","private"]).catch("private"),supportedVersions:ap(nL()),capabilities:eS,instructions:nL().optional()}),"subscriptions/listen":tg({})},tv=af({"io.modelcontextprotocol/subscriptionId":a.optional()}),t_=ah({method:aC("notifications/subscriptions/acknowledged"),params:ah({_meta:tv.optional(),notifications:tu})}),tb=ah({_meta:tv.optional(),requestId:a,reason:nL().optional()}),tS=ah({method:aC("notifications/cancelled"),params:tb}),tw=t=>ah({jsonrpc:aC("2.0"),id:ay([nL(),ae().int()]),result:t}).strict();return{JSONValueSchema:t,JSONObjectSchema:r,ProgressTokenSchema:i,CursorSchema:n,RequestIdSchema:a,RoleSchema:o,LoggingLevelSchema:s,TaskMetadataSchema:c,RelatedTaskMetadataSchema:u,RequestMetaSchema:d,BaseRequestParamsSchema:p,TaskAugmentedRequestParamsSchema:m,NotificationsParamsSchema:h,NotificationSchema:f,IconSchema:g,IconsSchema:y,BaseMetadataSchema:v,ImplementationSchema:_,ClientTasksCapabilitySchema:w,ServerTasksCapabilitySchema:x,ClientCapabilitiesSchema:k,ServerCapabilitiesSchema:R,ProgressSchema:$,ProgressNotificationParamsSchema:C,ProgressNotificationSchema:T,LoggingMessageNotificationParamsSchema:O,LoggingMessageNotificationSchema:P,ResourceContentsSchema:E,TextResourceContentsSchema:I,BlobResourceContentsSchema:q,AnnotationsSchema:j,ResourceSchema:z,ResourceTemplateSchema:N,ResourceListChangedNotificationSchema:A,ResourceUpdatedNotificationParamsSchema:L,ResourceUpdatedNotificationSchema:M,PromptArgumentSchema:Z,PromptSchema:U,PromptListChangedNotificationSchema:F,TextContentSchema:H,ImageContentSchema:J,AudioContentSchema:D,ToolUseContentSchema:V,EmbeddedResourceSchema:B,ResourceLinkSchema:W,ContentBlockSchema:G,PromptMessageSchema:K,ToolAnnotationsSchema:Y,ToolListChangedNotificationSchema:X,ModelHintSchema:Q,ModelPreferencesSchema:ee,ToolChoiceSchema:et,BooleanSchemaSchema:er,StringSchemaSchema:ei,NumberSchemaSchema:en,UntitledSingleSelectEnumSchemaSchema:ea,TitledSingleSelectEnumSchemaSchema:eo,LegacyTitledEnumSchemaSchema:es,SingleSelectEnumSchemaSchema:el,UntitledMultiSelectEnumSchemaSchema:ec,TitledMultiSelectEnumSchemaSchema:eu,MultiSelectEnumSchemaSchema:ed,EnumSchemaSchema:ep,PrimitiveSchemaDefinitionSchema:em,ElicitRequestFormParamsSchema:eh,ResourceTemplateReferenceSchema:ef,PromptReferenceSchema:eg,RootSchema:ey,ClientCapabilities2026Schema:e_,ServerCapabilities2026Schema:eS,RequestMetaEnvelopeSchema:ew,ToolSchema:ex,ToolResultContentSchema:ek,SamplingMessageContentBlockSchema:eR,SamplingMessageSchema:e$,ResultTypeSchema:eC,ResultMetaSchema:eT,ResultSchema:eE,PaginatedResultSchema:eI,CallToolResultSchema:eq,ListToolsResultSchema:ej,ListPromptsResultSchema:ez,GetPromptResultSchema:eN,ListResourcesResultSchema:eA,ListResourceTemplatesResultSchema:eL,ReadResourceResultSchema:eM,CompleteResultSchema:eZ,CacheableResultSchema:eU,DiscoverResultSchema:eF,CreateMessageRequestParamsSchema:eH,CreateMessageRequestSchema:eJ,ListRootsRequestSchema:eD,CreateMessageResultSchema:eV,ListRootsResultSchema:eB,ElicitResultSchema:eW,ElicitRequestURLParamsSchema:eG,ElicitRequestParamsSchema:eK,ElicitRequestSchema:eY,InputRequestSchema:eX,InputResponseSchema:eQ,InputRequestsSchema:e0,InputResponsesSchema:e1,InputRequiredResultSchema:e2,InputResponseRequestParamsSchema:e4,CallToolRequestSchema:te,ListToolsRequestSchema:tt,ListPromptsRequestSchema:tr,GetPromptRequestSchema:ti,ListResourcesRequestSchema:tn,ListResourceTemplatesRequestSchema:ta,ReadResourceRequestSchema:to,CompleteRequestSchema:tl,DiscoverRequestSchema:tc,SubscriptionFilterSchema:tu,SubscriptionsListenRequestSchema:tp,SubscriptionsListenResultMetaSchema:tm,SubscriptionsListenResultSchema:th,dispatchRequestSchemas:tf,dispatchResultSchemas:ty,NotificationMetaSchema:tv,SubscriptionsAcknowledgedNotificationSchema:t_,CancelledNotificationParamsSchema:tb,CancelledNotificationSchema:tS,notificationSchemas2026:{"notifications/cancelled":tS,"notifications/progress":T,"notifications/message":P,"notifications/resources/updated":M,"notifications/resources/list_changed":A,"notifications/tools/list_changed":X,"notifications/prompts/list_changed":F,"notifications/subscriptions/acknowledged":t_},JSONRPCResultResponseSchema:tw(eE),CallToolResultResponseSchema:tw(ay([eq,e2])),ListToolsResultResponseSchema:tw(ej),ListPromptsResultResponseSchema:tw(ez),GetPromptResultResponseSchema:tw(ay([eN,e2])),ListResourcesResultResponseSchema:tw(eA),ListResourceTemplatesResultResponseSchema:tw(eL),ReadResourceResultResponseSchema:tw(ay([eM,e2])),CompleteResultResponseSchema:tw(eZ),DiscoverResultResponseSchema:tw(eF)}}()}let cu=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"],cd=Symbol("modelcontextprotocol.resultCacheHintFallback");function cp(t,r){if(void 0===r)return t;let i=t[cd];if(void 0===i)return{...t,[cd]:r};let n={},a=i.ttlMs??r.ttlMs;void 0!==a&&(n.ttlMs=a);let o=i.cacheScope??r.cacheScope;return void 0!==o&&(n.cacheScope=o),{...t,[cd]:n}}function cm(t){return"number"==typeof t&&Number.isSafeInteger(t)&&t>=0}function ch(t){return"public"===t||"private"===t}function cf(t,r){if(void 0!==t.ttlMs&&!cm(t.ttlMs))throw RangeError(`Invalid cache hint for ${r}: ttlMs must be a non-negative safe integer (got ${String(t.ttlMs)})`);if(void 0!==t.cacheScope&&!ch(t.cacheScope))throw RangeError(`Invalid cache hint for ${r}: cacheScope must be 'public' or 'private' (got ${String(t.cacheScope)})`)}let cg=((C={})[C.ParseError=-32700]="ParseError",C[C.InvalidRequest=-32600]="InvalidRequest",C[C.MethodNotFound=-32601]="MethodNotFound",C[C.InvalidParams=-32602]="InvalidParams",C[C.InternalError=-32603]="InternalError",C[C.ResourceNotFound=-32002]="ResourceNotFound",C[C.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",C[C.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",C[C.UrlElicitationRequired=-32042]="UrlElicitationRequired",C);var cy=class t extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return lD(this,t)}static isInstance(t){if("function"!=typeof this)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return lD(this,t)}constructor(t,r,i){super(r),this.code=t,this.data=i,this.name="ProtocolError",lJ(this,new.target)}static fromError(r,i,n){return r===cg.UrlElicitationRequired&&n&&n.elicitations?new c_(n.elicitations,i):r===cg.UnsupportedProtocolVersion&&n&&Array.isArray(n.supported)&&"string"==typeof n.requested?new cb({supported:n.supported,requested:n.requested},i):(r===cg.InvalidParams||r===cg.ResourceNotFound)&&"string"==typeof n?.uri&&(r===cg.ResourceNotFound||1===Object.keys(n).length)?new cv(n.uri,i):r===cg.MissingRequiredClientCapability&&n&&null!==n.requiredCapabilities&&"object"==typeof n.requiredCapabilities&&!Array.isArray(n.requiredCapabilities)?new cS({requiredCapabilities:n.requiredCapabilities},i):new t(r,i,n)}},cv=class extends cy{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(t,r=`Resource not found: ${t}`){super(cg.InvalidParams,r,{uri:t})}get uri(){return this.data.uri}},c_=class extends cy{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(cg.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}},cb=class extends cy{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(t,r=`Unsupported protocol version: ${t.requested}`){super(cg.UnsupportedProtocolVersion,r,t)}get supported(){return this.data.supported}get requested(){return this.data.requested}},cS=class extends cy{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(t,r=`Missing required client capabilities: ${Object.keys(t.requiredCapabilities).join(", ")}`){super(cg.MissingRequiredClientCapability,r,t)}get requiredCapabilities(){return this.data.requiredCapabilities}};let cw=["tools/call","prompts/get","resources/read"],cx=["elicitation/create","sampling/createMessage","roots/list"];function ck(){if(o)return o;let t=cc();return o={request:{"elicitation/create":ah({method:aC("elicitation/create"),params:t.ElicitRequestParamsSchema}),"sampling/createMessage":ah({method:aC("sampling/createMessage"),params:t.CreateMessageRequestParamsSchema}),"roots/list":ah({method:aC("roots/list"),params:af({}).optional()})},response:{"elicitation/create":t.ElicitResultSchema,"sampling/createMessage":t.CreateMessageResultSchema,"roots/list":t.ListRootsResultSchema}}}function cR(t){return cx.includes(t)}function c$(t){return cR(t)?ck().request[t]:void 0}let cC={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},cT={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function cO(t){return Object.prototype.hasOwnProperty.call(cC,t)}function cP(t){return Object.prototype.hasOwnProperty.call(cT,t)}function cE(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function cI(t,r){if(void 0===t)return{ok:!1,reason:"not-in-era"};let i=t.safeParse(r);return i.success?{ok:!0,value:i.data}:{ok:!1,reason:"invalid",message:String(i.error)}}Object.keys(cC),Object.keys(cT);let cq={ok:!1,reason:"not-in-era"},cj=[aG,aX],cz={era:"2026-07-28",hasRequestMethod:cO,hasNotificationMethod:cP,hasInputRequestMethod:t=>void 0!==c$(t),validateRequest:(t,r)=>cI(cO(t)?cc().dispatchRequestSchemas[t]:void 0,r),validateResult:(t,r)=>cI(Object.prototype.hasOwnProperty.call(cC,t)?cc().dispatchResultSchemas[t]:void 0,r),validateNotification:(t,r)=>cI(cP(t)?cc().notificationSchemas2026[t]:void 0,r),validateInputRequest:(t,r)=>cI(c$(t),r),validateInputResponse:(t,r)=>cI(cR(t)?ck().response[t]:void 0,r),samplingResultVariant:()=>cq,outboundEnvelope:t=>({[aG]:t.protocolVersion,[aK]:t.clientInfo,[aX]:t.clientCapabilities,...void 0!==t.logLevel&&{[a0]:t.logLevel}}),validateEnvelopeMeta(t){let r=[];for(let i of cj)i in t||r.push({key:i,problem:"missing"});let i=cc().RequestMetaEnvelopeSchema.safeParse(t);if(!i.success)for(let t of i.error.issues){let i=t.path.map(String),n=i.length>0?i.join("."):"_meta";1===i.length&&r.some(t=>t.key===n&&"missing"===t.problem)||r.push({key:n,problem:t.message})}return r},projectCallToolResult:t=>l0(t),inputRequestSchema:c$,decodeResult(t,r){if(!cE(r))return{kind:"invalid",error:new lB(lV.InvalidResult,`Invalid result for ${t}: not an object`,{method:t})};let i=r.resultType;if(void 0===i)return{kind:"invalid",error:new lB(lV.InvalidResult,`Invalid result for ${t}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:t,violation:"missing-resultType"})};if("string"!=typeof i)return{kind:"invalid",error:new lB(lV.InvalidResult,`Invalid result for ${t}: non-string resultType`,{method:t,resultType:i})};if("input_required"===i){let i=r.inputRequests,n=cE(i)?i:{},a=r.requestState;return 0===Object.keys(n).length&&"string"!=typeof a?{kind:"invalid",error:new lB(lV.InvalidResult,`Invalid result for ${t}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:t,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:n,..."string"==typeof a&&{requestState:a}}}if("complete"!==i)return{kind:"invalid",error:new lB(lV.UnsupportedResultType,`Unsupported result type '${i}' for ${t}`,{resultType:i,method:t})};let n=cN(),a=Object.hasOwn(n,t)?n[t]:void 0;if(void 0!==a){let i=a.safeParse(r);if(!i.success)return{kind:"invalid",error:new lB(lV.InvalidResult,`Invalid result for ${t}: ${i.error}`,{method:t})}}let o={...r};return delete o.resultType,{kind:"complete",result:o}},encodeResult:(t,r,i)=>(function(t,r){if(void 0===r)return t;let i=t._meta;return void 0===i?{...t,_meta:{[aY]:r}}:null===i||"object"!=typeof i||Array.isArray(i)||void 0!==i[aY]?t:{...t,_meta:{...i,[aY]:r}}})(function(t,r){var i,n;let a=r[cd];if("complete"!==r.resultType||!cu.includes(t)){let t;return void 0===a?r:(t={...r},delete t[cd],t)}let o=cm(r.ttlMs)?r.ttlMs:void 0!==(i=a)&&cm(i.ttlMs)?i.ttlMs:0,s=ch(r.cacheScope)?r.cacheScope:void 0!==(n=a)&&ch(n.cacheScope)?n.cacheScope:"private",l={...r,ttlMs:o,cacheScope:s};return delete l[cd],l}(t,function(t,r){let i=r.resultType;if(void 0===i)return{...r,resultType:"complete"};if("complete"===i||cw.includes(t))return r;throw new cy(cg.InternalError,`Handler for ${t} returned resultType '${String(i)}', but results of ${t} only support 'complete' on protocol revision 2026-07-28`)}(t,function(t,r){let i=r,n=!1,a=()=>(n||(i={...i},n=!0),i),o=r.tools;"tools/list"===t&&Array.isArray(o)&&o.some(t=>cE(t)&&"execution"in t)&&(a().tools=o.map(t=>{if(!cE(t)||!("execution"in t))return t;let r={...t};return delete r.execution,r}));let s=r.capabilities;if(cE(s)&&"tasks"in s){let t={...s};delete t.tasks,a().capabilities=t}return i}(t,r))),i),encodeErrorCode:t=>-32002===t?-32602:t,checkInboundEnvelope(t){if(void 0===t.envelope)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let r=cc().RequestMetaEnvelopeSchema.safeParse(t.envelope);if(!r.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${r.error.issues.map(t=>t.message).join("; ")}`}};function cN(){if(s)return s;let t=cc();return s={"tools/call":t.CallToolResultSchema,"tools/list":t.ListToolsResultSchema,"prompts/get":t.GetPromptResultSchema,"prompts/list":t.ListPromptsResultSchema,"resources/list":t.ListResourcesResultSchema,"resources/templates/list":t.ListResourceTemplatesResultSchema,"resources/read":t.ReadResourceResultSchema,"completion/complete":t.CompleteResultSchema,"server/discover":t.DiscoverResultSchema}}let cA="2026-07-28";function cL(t){return void 0!==t&&t>=lY?cz:cl}function cM(t){return void 0!==t.revision?cL(t.revision).era:"modern"===t.era?cz.era:cl.era}function cZ(t){return cF.some(r=>r.hasRequestMethod(t))}function cU(t){return cF.some(r=>r.hasNotificationMethod(t))}let cF=[cl,cz];function cH(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function cJ(t){if(!cH(t))return;let r=t._meta;return cH(r)?r:void 0}function cD(t){let r=cJ(t);return void 0!==r&&aG in r}function cV(t){let r=cJ(t)?.[aG];return"string"==typeof r?r:void 0}function cB(t){return cL(cA).validateEnvelopeMeta(t)}var cW=((t,r)=>{let i={};for(var n in t)D(i,n,{get:t[n],enumerable:!0});return r&&D(i,Symbol.toStringTag,{value:"Module"}),i})({AnnotationsSchema:()=>oJ,AudioContentSchema:()=>su,BaseMetadataSchema:()=>ov,BaseRequestParamsSchema:()=>a8,BlobResourceContentsSchema:()=>oF,BooleanSchemaSchema:()=>sD,CallToolRequestParamsSchema:()=>sR,CallToolRequestSchema:()=>s$,CallToolResultSchema:()=>sx,CancelTaskRequestSchema:()=>lS,CancelTaskResultSchema:()=>lw,CancelledNotificationParamsSchema:()=>oh,CancelledNotificationSchema:()=>of,ClientCapabilitiesSchema:()=>ok,ClientNotificationSchema:()=>lk,ClientRequestSchema:()=>lx,ClientResultSchema:()=>lR,ClientTasksCapabilitySchema:()=>ow,CompatibilityCallToolResultSchema:()=>sk,CompleteRequestParamsSchema:()=>lr,CompleteRequestSchema:()=>li,CompleteResultSchema:()=>ln,ContentBlockSchema:()=>sh,CreateMessageRequestParamsSchema:()=>sU,CreateMessageRequestSchema:()=>sF,CreateMessageResultSchema:()=>sH,CreateMessageResultWithToolsSchema:()=>sJ,CreateTaskResultSchema:()=>lp,CursorSchema:()=>a5,DiscoverRequestSchema:()=>oP,DiscoverResultSchema:()=>oE,ElicitRequestFormParamsSchema:()=>s9,ElicitRequestParamsSchema:()=>s5,ElicitRequestSchema:()=>s3,ElicitRequestURLParamsSchema:()=>s4,ElicitResultSchema:()=>s8,ElicitationCompleteNotificationParamsSchema:()=>s6,ElicitationCompleteNotificationSchema:()=>s7,EmbeddedResourceSchema:()=>sp,EmptyResultSchema:()=>om,EnumSchemaSchema:()=>s1,GetPromptRequestParamsSchema:()=>so,GetPromptRequestSchema:()=>ss,GetPromptResultSchema:()=>sg,GetTaskPayloadRequestSchema:()=>ly,GetTaskPayloadResultSchema:()=>lv,GetTaskRequestSchema:()=>lf,GetTaskResultSchema:()=>lg,IconSchema:()=>og,IconsSchema:()=>oy,ImageContentSchema:()=>sc,ImplementationSchema:()=>o_,InitializeRequestParamsSchema:()=>oR,InitializeRequestSchema:()=>o$,InitializeResultSchema:()=>oT,InitializedNotificationSchema:()=>oO,JSONArraySchema:()=>a9,JSONObjectSchema:()=>a2,JSONRPCErrorResponseSchema:()=>ou,JSONRPCMessageSchema:()=>od,JSONRPCNotificationSchema:()=>ol,JSONRPCRequestSchema:()=>os,JSONRPCResponseSchema:()=>op,JSONRPCResultResponseSchema:()=>oc,JSONValueSchema:()=>a1,LegacyTitledEnumSchemaSchema:()=>sK,ListChangedOptionsBaseSchema:()=>sT,ListPromptsRequestSchema:()=>sn,ListPromptsResultSchema:()=>sa,ListResourceTemplatesRequestSchema:()=>oG,ListResourceTemplatesResultSchema:()=>oK,ListResourcesRequestSchema:()=>oB,ListResourcesResultSchema:()=>oW,ListRootsRequestSchema:()=>lo,ListRootsResultSchema:()=>ls,ListTasksRequestSchema:()=>l_,ListTasksResultSchema:()=>lb,ListToolsRequestSchema:()=>sS,ListToolsResultSchema:()=>sw,LoggingLevelSchema:()=>sO,LoggingMessageNotificationParamsSchema:()=>sI,LoggingMessageNotificationSchema:()=>sq,ModelHintSchema:()=>sj,ModelPreferencesSchema:()=>sz,MultiSelectEnumSchemaSchema:()=>s0,NotificationSchema:()=>oi,NotificationsParamsSchema:()=>or,NumberSchemaSchema:()=>sB,PaginatedRequestParamsSchema:()=>oN,PaginatedRequestSchema:()=>oA,PaginatedResultSchema:()=>oL,PingRequestSchema:()=>oI,PrimitiveSchemaDefinitionSchema:()=>s2,ProgressNotificationParamsSchema:()=>oj,ProgressNotificationSchema:()=>oz,ProgressSchema:()=>oq,ProgressTokenSchema:()=>a4,PromptArgumentSchema:()=>sr,PromptListChangedNotificationSchema:()=>sy,PromptMessageSchema:()=>sf,PromptReferenceSchema:()=>lt,PromptSchema:()=>si,ReadResourceRequestParamsSchema:()=>oY,ReadResourceRequestSchema:()=>oX,ReadResourceResultSchema:()=>oQ,RelatedTaskMetadataSchema:()=>a6,RequestIdSchema:()=>oo,RequestMetaSchema:()=>a7,RequestSchema:()=>ot,ResourceContentsSchema:()=>oM,ResourceLinkSchema:()=>sm,ResourceListChangedNotificationSchema:()=>o0,ResourceRequestParamsSchema:()=>oY,ResourceSchema:()=>oD,ResourceTemplateReferenceSchema:()=>le,ResourceTemplateSchema:()=>oV,ResourceUpdatedNotificationParamsSchema:()=>se,ResourceUpdatedNotificationSchema:()=>st,ResultMetaObjectSchema:()=>on,ResultSchema:()=>oa,RoleSchema:()=>oH,RootSchema:()=>la,RootsListChangedNotificationSchema:()=>ll,SamplingContentSchema:()=>sL,SamplingMessageContentBlockSchema:()=>sM,SamplingMessageSchema:()=>sZ,ServerCapabilitiesSchema:()=>oC,ServerNotificationSchema:()=>lC,ServerRequestSchema:()=>l$,ServerResultSchema:()=>lT,ServerTasksCapabilitySchema:()=>ox,SetLevelRequestParamsSchema:()=>sP,SetLevelRequestSchema:()=>sE,SingleSelectEnumSchemaSchema:()=>sY,StringSchemaSchema:()=>sV,SubscribeRequestParamsSchema:()=>oY,SubscribeRequestSchema:()=>o1,SubscriptionFilterSchema:()=>o9,SubscriptionsAcknowledgedNotificationParamsSchema:()=>o3,SubscriptionsAcknowledgedNotificationSchema:()=>o6,SubscriptionsListenRequestParamsSchema:()=>o4,SubscriptionsListenRequestSchema:()=>o5,SubscriptionsListenResultMetaSchema:()=>o7,SubscriptionsListenResultSchema:()=>o8,TaskAugmentedRequestParamsSchema:()=>oe,TaskCreationParamsSchema:()=>lc,TaskMetadataSchema:()=>a3,TaskSchema:()=>ld,TaskStatusNotificationParamsSchema:()=>lm,TaskStatusNotificationSchema:()=>lh,TaskStatusSchema:()=>lu,TextContentSchema:()=>sl,TextResourceContentsSchema:()=>oZ,TitledMultiSelectEnumSchemaSchema:()=>sQ,TitledSingleSelectEnumSchemaSchema:()=>sG,ToolAnnotationsSchema:()=>sv,ToolChoiceSchema:()=>sN,ToolExecutionSchema:()=>s_,ToolListChangedNotificationSchema:()=>sC,ToolResultContentSchema:()=>sA,ToolSchema:()=>sb,ToolUseContentSchema:()=>sd,UnsubscribeRequestParamsSchema:()=>oY,UnsubscribeRequestSchema:()=>o2,UntitledMultiSelectEnumSchemaSchema:()=>sX,UntitledSingleSelectEnumSchemaSchema:()=>sW});let cG=t=>os.safeParse(t).success,cK=t=>ol.safeParse(t).success,cY=t=>oc.safeParse(t).success,cX=t=>ou.safeParse(t).success,cQ=t=>"object"==typeof t&&null!==t&&!Array.isArray(t)&&"input_required"===t.resultType,c0="x-mcp-header",c1=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,c2=new Set(["string","integer","boolean","number"]);function c9(t){let r=[],i=new Map,n=(t,a,o)=>{if(null===t||"object"!=typeof t)return;if(c0 in t){if(!o||0===a.length)return`${c3(a)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let n=t[c0];if("string"!=typeof n||0===n.length)return`${c3(a)}: x-mcp-header MUST be a non-empty string`;if(!c1.test(n))return`${c3(a)}: x-mcp-header '${n}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let s="string"==typeof t.type?t.type:void 0;if(void 0===s||!c2.has(s))return`${c3(a)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${s??"<none>"}`;let l=n.toLowerCase(),c=i.get(l);if(void 0!==c)return`x-mcp-header '${n}' is not case-insensitively unique (also declared as '${c}')`;i.set(l,n),r.push({path:a,headerName:n,type:s})}let s=t.properties;if(null!==s&&"object"==typeof s)for(let[t,r]of Object.entries(s)){let i=n(r,[...a,t],o);if(void 0!==i)return i}for(let r of c4){let i=t[r];if(void 0!==i)for(let t of Array.isArray(i)?i:null!==i&&"object"==typeof i&&c5.has(r)?Object.values(i):[i]){let i=n(t,[...a,`<${r}>`],!1);if(void 0!==i)return i}}},a=n(t,[],!0);return void 0===a?{valid:!0,declarations:r}:{valid:!1,reason:a}}let c4=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],c5=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function c3(t){return 0===t.length?"<root>":t.join(".")}let c6=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,c7=/^-?\d+(\.\d+)?$/;function c8(t){if(!(t.startsWith("=?base64?")&&t.endsWith("?=")))return t;let r=t.slice(9,t.length-2);if(c6.test(r))try{let t=atob(r),i=new Uint8Array(t.length);for(let r=0;r<t.length;r++)i[r]=t.codePointAt(r);return new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return}}function ue(t,r,i){return{kind:"reject",rung:"param-header-validation",cell:t,httpStatus:400,code:ut,message:`Bad Request: the request headers and body disagree: ${i}`,data:{mismatch:{header:r,body:i}},settled:!0}}let ut=-32020;cg.InvalidRequest,cg.UnsupportedProtocolVersion,cg.InvalidParams,cg.MethodNotFound,cg.InvalidParams,cg.MissingRequiredClientCapability;let ur={[cg.ParseError]:400,[cg.InvalidRequest]:400,[cg.MethodNotFound]:404,[cg.UnsupportedProtocolVersion]:400,[cg.MissingRequiredClientCapability]:400,[ut]:400};function ui(t,r,i,n,a){return{kind:"reject",rung:t,cell:r,httpStatus:i,code:n.code,message:n.message,...void 0!==n.data&&{data:n.data},settled:a}}function un(t,r,i,n="era-classification"){return ui(n,t,400,new cy(ut,`Bad Request: the request headers and body disagree: ${i}`,{mismatch:{header:r,body:i}}),!0)}let ua={"tools/call":"name","prompts/get":"name","resources/read":"uri"};function uo(t){let r=0;for(;r<t.length;){let i=t.codePointAt(r);if(9!==i&&32!==i)break;r+=1}let i=t.length;for(;i>r;){let r=t.codePointAt(i-1);if(9!==r&&32!==r)break;i-=1}return 0===r&&i===t.length?t:t.slice(r,i)}function us(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function ul(t){return void 0===t?{era:"modern"}:{era:t>=lY?"modern":"legacy",revision:t}}function uc(t){return new Set(t.flatMap(t=>Object.keys(t.shape)))}function uu(t){if(null==t)return!1;let r=typeof t;return("object"===r||"function"===r)&&"~standard"in t&&"function"==typeof t["~standard"]?.validate}let ud=!1,up="draft-2020-12";function um(t,r="input"){let i,n=t["~standard"];if(n.jsonSchema)i=n.jsonSchema[r]({target:up});else if("zod"===n.vendor){if(!("_zod"in t))throw Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");ud||(ud=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),i=nn(t,{target:up,io:r})}else throw Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if("output"===r)return void 0!==i.type||!function t(r){if("properties"in r||"patternProperties"in r||"additionalProperties"in r||"required"in r)return!0;for(let i of["oneOf","anyOf","allOf"]){let n=r[i];if(Array.isArray(n)&&n.length>0)return n.every(r=>null!==r&&"object"==typeof r&&("object"===r.type||t(r)))}return!1}(i)?i:{type:"object",...i};if(void 0!==i.type&&"object"!==i.type)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(i.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...i}}async function uh(t,r){let i=await t["~standard"].validate(r);return i.issues&&i.issues.length>0?{success:!1,error:i.issues.map(t=>t.path?.length?`${t.path.map(t=>String("object"==typeof t?t.key:t)).join(".")}: ${t.message}`:t.message).join(", ")}:{success:!0,data:i.value}}let uf=/\\\.\\d\{(\d+)\}/;function ug(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}let uy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function uv(t){return uy.has(t)||t.startsWith("x-")}let u_=new Set(["$schema",...Object.keys(s9.shape.requestedSchema.shape)]),ub={string:uc([sV,sW,sG,sK]),number:uc([sB]),integer:uc([sB]),boolean:uc([sD]),array:uc([sX,sQ])},uS=new Set(sV.shape.format.unwrap().options);Object.assign(function(t){let r=void 0!==t.inputRequests&&Object.keys(t.inputRequests).length>0,i="string"==typeof t.requestState;if(!r&&!i)throw TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...void 0!==t.inputRequests&&{inputRequests:t.inputRequests},...void 0!==t.requestState&&{requestState:t.requestState}}},{elicit(t){try{return{method:"elicitation/create",params:function(t){var r;if(!uu(t.requestedSchema))return{...t,mode:"form",requestedSchema:t.requestedSchema};let i=t.requestedSchema["~standard"].vendor,n=function(t,r){let i={},n=[];for(let[a,o]of Object.entries(t))"properties"===a&&ug(o)?i[a]=Object.fromEntries(Object.entries(o).map(([t,i])=>[t,function(t,r,i,n){if(!ug(t))return t;let a="string"==typeof t.type&&Object.hasOwn(ub,t.type)?ub[t.type]:void 0;if(void 0===a)return t;let o={};for(let[l,c]of Object.entries(t))if(a.has(l)||uv(l))o[l]=c;else if("pattern"===l&&"string"===t.type&&"string"==typeof t.format)if(uS.has(t.format)){var s;"string"==typeof c&&(s=t.format,"zod"!==i||(function(t,r){let i;switch(t){case"email":i=[r3(nJ,void 0)];break;case"uri":i=[r6(nB,void 0)];break;case"date":i=[r8(nU,void 0)];break;case"date-time":let n,a;n=uf.exec(r),a=[void 0,-1,0],n&&a.push(Number(n[1])),i=[!1,!0].flatMap(t=>[!1,!0].flatMap(r=>a.map(i=>r7(nZ,{local:t,offset:r,precision:i}))))}return new Set(i.map(t=>{let r;return r=nn(t,{target:up,io:"input"}),"string"==typeof r.pattern?r.pattern:void 0}).filter(t=>void 0!==t))})(s,c).has(c))||n.push(`${r}.${l}`)}else o[l]=c;else n.push(`${r}.${l}`);return o}(i,`properties.${t}`,r,n)])):u_.has(a)?i[a]=o:uv(a)||n.push(a);if(n.length>0)throw new cy(cg.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return i}(function(t){try{return um(t,"input")}catch(r){let t=r instanceof Error?r.message:String(r);throw new cy(cg.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${t}`)}}(t.requestedSchema),i),a=(r=s9.shape.requestedSchema,nk(r,n));if(!a.success)throw new cy(cg.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${function(t,r){if(!ug(t.properties))return r;let i=Object.entries(t.properties).filter(([,t])=>!nk(s2,t).success).map(([t])=>`properties.${t}`);return i.length>0?i.join(", "):r}(n,a.error.message)}`);let o=function t(r,i,n=""){return Array.isArray(r)&&Array.isArray(i)?r.flatMap((r,a)=>t(r,i[a],`${n}[${a}]`)):ug(r)&&ug(i)?Object.entries(r).flatMap(([r,a])=>{let o=n?`${n}.${r}`:r;return Object.prototype.hasOwnProperty.call(i,r)?t(a,i[r],o):uv(r)?[]:[o]}):[]}(n,a.data);if(o.length>0)throw new cy(cg.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);let s=(a.data.required??[]).filter(t=>!Object.prototype.hasOwnProperty.call(a.data.properties,t));if(s.length>0)throw new cy(cg.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...t,mode:"form",requestedSchema:a.data}}(t)}}catch(t){throw t instanceof cy?TypeError(t.message,{cause:t}):t}},elicitUrl:t=>({method:"elicitation/create",params:{...t,mode:"url"}}),createMessage:t=>({method:"sampling/createMessage",params:t}),listRoots:()=>({method:"roots/list"})});let uw={},ux={};function uk(t,r){let i=t.slice(0,-6);uw[i]=r,ux[i]=t=>r.safeParse(t).success}for(let t of["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"])uk(t,cW[t]);for(let[t,r]of Object.entries({IdJagTokenExchangeResponseSchema:lz,OAuthClientInformationFullSchema:lZ,OAuthClientInformationSchema:lM,OAuthClientMetadataSchema:lL,OAuthClientRegistrationErrorSchema:lU,OAuthErrorResponseSchema:lN,OAuthMetadataSchema:lE,OAuthProtectedResourceMetadataSchema:lP,OAuthTokenRevocationRequestSchema:lF,OAuthTokensSchema:lj,OpenIdProviderDiscoveryMetadataSchema:lq,OpenIdProviderMetadataSchema:lI}))uk(t,r);let uR=Object.freeze(uw);Object.freeze(ux);let u$=[aG,aK,aX,a0],uC=["inputResponses","requestState"];function uT(t,r){let i=t.params;if(!uq(i))return{message:t,lifted:{}};let n=i._meta,a=uq(n)?u$.filter(t=>t in n):[],o="request"===r?uC.filter(t=>t in i):[];if(0===a.length&&0===o.length)return{message:t,lifted:{}};let s={},l={...i};if(a.length>0&&uq(n)){let t={},r={...n};for(let i of a)t[i]=n[i],delete r[i];s.envelope=t,Object.keys(r).length>0?l._meta=r:delete l._meta}for(let t of o)"inputResponses"===t&&(s.inputResponses=l[t]),"requestState"===t&&(s.requestState=l[t]),delete l[t];return{message:{...t,params:l},lifted:s}}function uO(t,r){let i=t.validateResult(r,void 0);if(i.ok||"not-in-era"!==i.reason)return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(i){let n=t.validateResult(r,i);return n.ok?{value:n.value}:{issues:[{message:"invalid"===n.reason?n.message:`not-in-era: ${r}`}]}}}}}let uP=(T=void 0,()=>T);function uE(t,r){return{...t,mcpReq:{...t.mcpReq,requestState:()=>r}}}var uI=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{l=(t,r)=>{t._negotiatedProtocolVersion=r}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(t){this._options=t,this._supportedProtocolVersions=t?.supportedProtocolVersions??aW,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(t){}_outboundMetaEnvelope(){}_envelopeOutbound(t){let r=this._outboundMetaEnvelope();if(void 0===r)return t;let i=t.params??{};return{...t,params:{...i,_meta:{...r,...i._meta}}}}_resolveNonCompleteResult(t,r){return Promise.reject(new lB(lV.UnsupportedResultType,`Unsupported result type '${t.kind}' for ${r.request.method}`,{resultType:t.kind,method:r.request.method}))}_getRequestHandler(t){return this._requestHandlers.get(t)}async _oncancel(t){t.params.requestId&&this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,i,n,a=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:i,resetTimeoutOnProgress:a,onTimeout:n})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let i=Date.now()-r.startTime;if(r.maxTotalTimeout&&i>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),new lB(lV.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:i});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{try{r?.()}finally{this._onclose()}};let i=this.transport?.onerror;this._transport.onerror=t=>{i?.(t),this._onerror(t)};let n=this._transport?.onmessage;this._transport.onmessage=(t,r)=>{n?.(t,r),cY(t)||cX(t)?this._onresponse(t):cG(t)?this._onrequest(t,r):cK(t)?this._onnotification(t,r):this._onerror(Error(`Unknown message type: ${JSON.stringify(t)}`))},t.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let t=this._responseHandlers;for(let t of(this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._timeoutInfo.values()))clearTimeout(t.timeoutId);this._timeoutInfo.clear();let r=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let i=new lB(lV.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let r of t.values())r(i);for(let t of r.values())t.abort(i)}}_onerror(t){this.onerror?.(t)}_onnotification(t,r){let{message:i}=uT(t,"notification"),n=this._negotiatedWireCodec();if(r?.classification===void 0&&"drop"===this._shouldDropInbound(t))return;if(r?.classification!==void 0){let t=cM(r.classification);if(t!==n.era)return void this._onerror(Error(`Era mismatch on inbound notification '${i.method}': classified as ${t} but this instance serves ${n.era}`))}if(cU(i.method)&&!n.hasNotificationMethod(i.method))return;let a=this._notificationHandlers.get(i.method),o=this.fallbackNotificationHandler;(void 0!==a||void 0!==o)&&Promise.resolve().then(()=>void 0===a?o(i):a(i,n)).catch(t=>this._onerror(Error(`Uncaught error in notification handler: ${t}`)))}_onrequest(t,r){var i;let{message:n,lifted:a}=uT(t,"request"),o=this._negotiatedWireCodec();if(r?.classification===void 0&&"drop"===this._shouldDropInbound(t))return void this._onerror(Error(`Dropped inbound request '${t.method}': not servable on this connection's protocol era`));let s=this._transport,l=(t,r,i)=>{let a={jsonrpc:"2.0",id:n.id,error:{code:t,message:r,...void 0!==i&&{data:i}}};s?.send(a).catch(t=>this._onerror(Error(`Failed to send an error response: ${t}`)))};if(r?.classification!==void 0){let t=cM(r.classification);if(t!==o.era){this._onerror(Error(`Era mismatch on inbound request '${n.method}': classified as ${t} but this instance serves ${o.era}`));let i=r.classification.revision??t;l(cg.UnsupportedProtocolVersion,`Unsupported protocol version: ${i}`,{supported:this._supportedProtocolVersions,requested:i});return}}if(cZ(n.method)&&!o.hasRequestMethod(n.method))return void l(cg.MethodNotFound,"Method not found");let c=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(void 0===c)return void l(cg.MethodNotFound,"Method not found");let u=o.checkInboundEnvelope(a);if(void 0!==u)return void l(cg.InvalidParams,u);let d=(t,r)=>this._notificationViaCodec(this._resolveOutboundCodec(t.method),t,{...r,relatedRequestId:n.id}),p=(t,r,i)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(t.method),t,r,{...i,relatedRequestId:n.id}),m=new AbortController;this._requestHandlerAbortControllers.set(n.id,m);let h=void 0===a.inputResponses?void 0:function(t){let r={},i=[];if(!uj(t))return{accepted:r,droppedKeys:i};for(let[n,a]of Object.entries(t)){if(!uj(a)||"method"in a||"result"in a){i.push(n);continue}r[n]=a}return{accepted:r,droppedKeys:i}}(a.inputResponses),f={sessionId:s?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...void 0!==a.envelope&&{envelope:a.envelope},...void 0!==h&&{inputResponses:h.accepted},...void 0!==h&&h.droppedKeys.length>0&&{droppedInputResponseKeys:h.droppedKeys},requestState:void 0===a.requestState?uP:(i=a.requestState,()=>i),signal:m.signal,send:(t,r,i)=>{let n=this._resolveOutboundCodec(t.method);if(this._assertOutboundRequestInEra(n,t.method),uu(r))return p(t,r,i);let a=uO(n,t.method);if(void 0===a)throw TypeError(`'${t.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return p(t,a,r)},notify:d},http:r?.authInfo?{authInfo:r.authInfo}:void 0},g=this.buildContext(f,r);Promise.resolve().then(()=>c(n,g)).then(async t=>{let r;if(m.signal.aborted)return;try{r=o.encodeResult(n.method,t,this._outboundServerInfo())}catch(t){this._onerror(Error(`Failed to encode result for ${n.method}: ${t}`)),l(cg.InternalError,"Internal error");return}let i={result:r,jsonrpc:"2.0",id:n.id};await s?.send(i)},async t=>{if(m.signal.aborted)return;let r=Number.isSafeInteger(t.code)?t.code:cg.InternalError,i={jsonrpc:"2.0",id:n.id,error:{code:o.encodeErrorCode(r),message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};await s?.send(i)}).catch(t=>this._onerror(Error(`Failed to send response: ${t}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===m&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(t){let{progressToken:r,...i}=t.params,n=Number(r),a=this._progressHandlers.get(n);if(!a)return void this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));let o=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(t){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),o(t);return}a(i)}_onresponse(t){let r=Number(t.id),i=this._responseHandlers.get(r);void 0===i?this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`)):(this._responseHandlers.delete(r),this._cleanupTimeout(r),this._progressHandlers.delete(r),i(cY(t)?t:cy.fromError(t.error.code,t.error.message,t.error.data)))}get transport(){return this._transport}async close(){await this._transport?.close()}request(t,r,i){let n=this._resolveOutboundCodec(t.method);if(this._assertOutboundRequestInEra(n,t.method),uu(r))return this._requestWithSchemaViaCodec(n,t,r,i);let a=uO(n,t.method);if(void 0===a)throw TypeError(`'${t.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(n,t,a,r)}_negotiatedWireCodec(){return cL(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(t){if(void 0===this._negotiatedProtocolVersion){let r=function(t){switch(t){case"initialize":case"notifications/initialized":return cL(void 0);case"server/discover":return cL(cA);default:return}}(t);if(r)return r}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(t,r){if(cZ(r)&&!t.hasRequestMethod(r))throw new lB(lV.MethodNotSupportedByProtocolVersion,`Method '${r}' is not supported by the negotiated protocol version (wire era ${t.era})`,{method:r,era:t.era})}_requestWithSchema(t,r,i){let n=this._resolveOutboundCodec(t.method);return this._assertOutboundRequestInEra(n,t.method),this._requestWithSchemaViaCodec(n,t,r,i)}_requestWithSchemaViaCodec(t,r,i,n){let a,o,{relatedRequestId:s,resumptionToken:l,onresumptiontoken:c,headers:u}=n??{},d=Date.now();return new Promise((p,m)=>{let h=t=>{m(t)};if(!this._transport)return void h(Error("Not connected"));if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(r.method)}catch(t){h(t);return}if(n?.signal?.aborted){let t=n.signal.reason;throw t instanceof lB?t:new lB(lV.RequestTimeout,String(t))}let f=t.era===cA&&!0===this._transport.hasPerRequestStream?new AbortController:void 0,g=this._requestMessageId++;o=g;let y={...r,jsonrpc:"2.0",id:g};n?.onprogress&&(this._progressHandlers.set(g,n.onprogress),y.params={...r.params,_meta:{...r.params?._meta,progressToken:g}});let v=this._envelopeOutbound(y),_=!1,b=t=>{_||(this._progressHandlers.delete(g),void 0===f?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(t)}}),{relatedRequestId:s,resumptionToken:l,onresumptiontoken:c}).catch(t=>this._onerror(Error(`Failed to send cancellation: ${t}`))):f.abort(),m(t instanceof lB?t:new lB(lV.RequestTimeout,String(t))))};this._responseHandlers.set(g,a=>{let o;if(!n?.signal?.aborted){if(_=!0,a instanceof Error)return m(a);try{o=t.decodeResult(r.method,a.result)}catch(t){return m(t instanceof Error?t:Error(String(t)))}if("invalid"===o.kind)return m(o.error);if("input_required"===o.kind){var s;return n?.allowInputRequired===!0?p({resultType:"input_required",inputRequests:(s=o).inputRequests,...void 0!==s.requestState&&{requestState:s.requestState}}):p(this._resolveNonCompleteResult(o,{codec:t,request:r,resultSchema:i,options:n,flowStartedAt:d,retry:(n,a)=>this._requestWithSchemaViaCodec(t,void 0===n?{method:r.method}:{method:r.method,params:n},i,a)}))}uh(i,o.result).then(t=>{t.success?p(t.data):m(new lB(lV.InvalidResult,`Invalid result for ${r.method}: ${t.error}`))},m)}}),a=()=>b(n?.signal?.reason),n?.signal?.addEventListener("abort",a,{once:!0});let S=n?.timeout??6e4;this._setupTimeout(g,S,n?.maxTotalTimeout,()=>b(new lB(lV.RequestTimeout,"Request timed out",{timeout:S})),n?.resetTimeoutOnProgress??!1),this._transport.send(v,{relatedRequestId:s,resumptionToken:l,onresumptiontoken:c,headers:u,requestSignal:f?.signal}).catch(t=>{this._progressHandlers.delete(g),m(t)})}).finally(()=>{a&&n?.signal?.removeEventListener("abort",a),void 0!==o&&(this._responseHandlers.delete(o),this._cleanupTimeout(o))})}async notification(t,r){return this._notificationViaCodec(this._resolveOutboundCodec(t.method),t,r)}async _notificationViaCodec(t,r,i){if(!this._transport)throw new lB(lV.NotConnected,"Not connected");if(cU(r.method)&&!t.hasNotificationMethod(r.method))throw new lB(lV.MethodNotSupportedByProtocolVersion,`Notification '${r.method}' is not supported by the negotiated protocol version (wire era ${t.era})`,{method:r.method,era:t.era});this.assertNotificationCapability(r.method);let n=this._envelopeOutbound({jsonrpc:"2.0",...r});if((this._options?.debouncedNotificationMethods??[]).includes(r.method)&&!r.params&&!i?.relatedRequestId){if(this._pendingDebouncedNotifications.has(r.method))return;this._pendingDebouncedNotifications.add(r.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(r.method),this._transport&&this._transport?.send(n,i).catch(t=>this._onerror(t))});return}await this._transport.send(n,i)}setRequestHandler(t,r,i){let n;if(this.assertRequestHandlerCapability(t),"function"==typeof r){if(!cZ(t))throw TypeError(`'${t}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);n=(i,n)=>{let a=this._negotiatedWireCodec(),o=a.validateRequest(t,i);if(o.ok||"not-in-era"!==o.reason||(o=a.validateInputRequest(t,i)),!o.ok){if("not-in-era"===o.reason)throw new cy(cg.InternalError,`No wire schema for ${t} in the resolved era`);throw Error(o.message)}return Promise.resolve(r(o.value,n))}}else if(i)n=async(n,a)=>{let o=await uh(r.params,{...n.params});if(!o.success)throw new cy(cg.InvalidParams,`Invalid params for ${t}: ${o.error}`);return i(o.data,a)};else throw TypeError("setRequestHandler: handler is required");this._requestHandlers.set(t,this._wrapHandler(t,n))}_wrapHandler(t,r){return r}_outboundServerInfo(){}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r,i){if("function"==typeof r){if(!cU(t))throw TypeError(`'${t}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(t,(i,n)=>{let a=n.validateNotification(t,i);if(!a.ok){if("not-in-era"===a.reason)throw new cy(cg.InternalError,`No wire schema for ${t} in the resolved era`);throw Error(a.message)}return Promise.resolve(r(a.value))});return}if(!i)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(t,async n=>{let a=await uh(r.params,{...n.params});if(!a.success)throw new cy(cg.InvalidParams,`Invalid params for notification ${t}: ${a.error}`);await i(a.data,n)})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}};function uq(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function uj(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}var uz=((t,r,i,n)=>{if(r&&"object"==typeof r||"function"==typeof r)for(var a,o=B(r),s=0,l=o.length;s<l;s++)a=o[s],G.call(t,a)||a===i||D(t,a,{get:(t=>r[t]).bind(null,a),enumerable:!(n=V(r,a))||n.enumerable});return t})(D(null!=(x=(S=t=>{var r=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,i=/\\([\u000b\u0020-\u00ff])/g,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function a(t){this.parameters=Object.create(null),this.type=t}t.parse=function(t){if(!t)throw TypeError("argument string is required");var o,s,l,c="object"==typeof t?function(t){var r;if("function"==typeof t.getHeader?r=t.getHeader("content-type"):"object"==typeof t.headers&&(r=t.headers&&t.headers["content-type"]),"string"!=typeof r)throw TypeError("content-type header is missing from object");return r}(t):t;if("string"!=typeof c)throw TypeError("argument string is required to be a string");var u=c.indexOf(";"),d=-1!==u?c.slice(0,u).trim():c.trim();if(!n.test(d))throw TypeError("invalid media type");var p=new a(d.toLowerCase());if(-1!==u){for(r.lastIndex=u;s=r.exec(c);){if(s.index!==u)throw TypeError("invalid parameter format");u+=s[0].length,o=s[1].toLowerCase(),34===(l=s[2]).charCodeAt(0)&&-1!==(l=l.slice(1,-1)).indexOf("\\")&&(l=l.replace(i,"$1")),p.parameters[o]=l}if(u!==c.length)throw TypeError("invalid parameter format")}return p}},()=>(w||S((w={exports:{}}).exports,w),w.exports))())?J(W(x)):{},"default",{value:x,enumerable:!0}),x);function uN(t){if(t)try{return uz.parse(t).type}catch{let r=(t.split(";",1)[0]??"").trim().toLowerCase();if(""===r||t.slice(r.length).includes(","))return;return r}}function uA(t){return"application/json"===t||"application/json"===uN(t)}let uL=/^[A-Za-z0-9._-]{1,128}$/;function uM(t){let r=function(t){let r=[];if(0===t.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&r.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&r.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&r.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&r.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!uL.test(t)){let i=[...t].filter(t=>!/[A-Za-z0-9._-]/.test(t)).filter((t,r,i)=>i.indexOf(t)===r);return r.push(`Tool name contains invalid characters: ${i.map(t=>`"${t}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:r}}return{isValid:!0,warnings:r}}(t);var i=r.warnings;if(i.length>0){for(let r of(console.warn(`Tool name validation warning for "${t}":`),i))console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}return r.isValid}var uZ=class t{static isTemplate(t){return/\{[^}\s]+\}/.test(t)}static validateLength(t,r,i){if(t.length>r)throw Error(`${i} exceeds maximum length of ${r} characters (got ${t.length})`)}template;parts;get variableNames(){return this.parts.flatMap(t=>"string"==typeof t?[]:t.names)}constructor(r){t.validateLength(r,1e6,"Template"),this.template=r,this.parts=this.parse(r)}toString(){return this.template}parse(r){let i=[],n="",a=0,o=0;for(;a<r.length;)if("{"===r[a]){n&&(i.push(n),n="");let s=r.indexOf("}",a);if(-1===s)throw Error("Unclosed template expression");if(++o>1e4)throw Error("Template contains too many expressions (max 10000)");let l=r.slice(a+1,s),c=this.getOperator(l),u=l.includes("*"),d=this.getNames(l),p=d[0];for(let r of d)t.validateLength(r,1e6,"Variable name");i.push({name:p,operator:c,names:d,exploded:u}),a=s+1}else n+=r[a],a++;return n&&i.push(n),i}getOperator(t){return["+","#",".","/","?","&"].find(r=>t.startsWith(r))||""}getNames(t){let r=this.getOperator(t);return t.slice(r.length).split(",").map(t=>t.replace("*","").trim()).filter(t=>t.length>0)}encodeValue(r,i){return(t.validateLength(r,1e6,"Variable value"),"+"===i||"#"===i)?encodeURI(r):encodeURIComponent(r)}expandPart(t,r){if("?"===t.operator||"&"===t.operator){let i=t.names.map(i=>{let n=r[i];return void 0===n?"":`${i}=${Array.isArray(n)?n.map(r=>this.encodeValue(r,t.operator)).join(","):this.encodeValue(n.toString(),t.operator)}`}).filter(t=>t.length>0);return 0===i.length?"":("?"===t.operator?"?":"&")+i.join("&")}if(t.names.length>1){let i=t.names.map(t=>r[t]).filter(t=>void 0!==t);return 0===i.length?"":i.map(t=>Array.isArray(t)?t[0]:t).join(",")}let i=r[t.name];if(void 0===i)return"";let n=(Array.isArray(i)?i:[i]).map(r=>this.encodeValue(r,t.operator));switch(t.operator){case"":case"+":default:return n.join(",");case"#":return"#"+n.join(",");case".":return"."+n.join(".");case"/":return"/"+n.join("/")}}expand(t){let r="",i=!1;for(let n of this.parts){if("string"==typeof n){r+=n;continue}let a=this.expandPart(n,t);a&&(r+=("?"===n.operator||"&"===n.operator)&&i?a.replace("?","&"):a,("?"===n.operator||"&"===n.operator)&&(i=!0))}return r}escapeRegExp(t){return t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(r){let i,n=[];for(let i of r.names)t.validateLength(i,1e6,"Variable name");if("?"===r.operator||"&"===r.operator){for(let t=0;t<r.names.length;t++){let i=r.names[t],a=0===t?"\\"+r.operator:"&";n.push({pattern:a+this.escapeRegExp(i)+"=([^&]+)",name:i})}return n}let a=r.name;switch(r.operator){case"":i=r.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":i="(.+)";break;case".":i=String.raw`\.([^/,]+)`;break;case"/":i="/"+(r.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:i="([^/]+)"}return n.push({pattern:i,name:a}),n}match(r){t.validateLength(r,1e6,"URI");let i="^",n=[];for(let t of this.parts)if("string"==typeof t)i+=this.escapeRegExp(t);else for(let{pattern:r,name:a}of this.partToRegExp(t))i+=r,n.push({name:a,exploded:t.exploded});i+="$",t.validateLength(i,1e6,"Generated regex pattern");let a=new RegExp(i),o=r.match(a);if(!o)return null;let s={};for(let[t,r]of n.entries()){let{name:i,exploded:n}=r,a=o[t+1];s[i.replace("*","")]=n&&a.includes(",")?a.split(","):a}return s}};function uU(t){if(void 0!==t){if(function(t){if("object"!=typeof t||null===t||uu(t))return!1;let r=Object.getPrototypeOf(t);return(r===Object.prototype||null===r)&&Object.values(t).every(t=>"object"==typeof t&&null!==t&&"_zod"in t)}(t))return ah(t);if("object"==typeof t&&null!==t&&!uu(t)&&Object.values(t).some(t=>"object"==typeof t&&null!==t&&!("_zod"in t)&&"_def"in t&&"string"==typeof t._def?.typeName))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!uu(t))throw TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return t}}function uF(){l9(),cc(),ct(),ck(),cN()}function uH(t,r){let i=typeof t;if(i!==typeof r)return!1;if(Array.isArray(t)){if(!Array.isArray(r))return!1;let i=t.length;if(i!==r.length)return!1;for(let n=0;n<i;n++)if(!uH(t[n],r[n]))return!1;return!0}if("object"===i){if(!t||!r)return t===r;let i=Object.keys(t),n=Object.keys(r);if(i.length!==n.length)return!1;for(let n of i)if(!uH(t[n],r[n]))return!1;return!0}return t===r}function uJ(t){return encodeURI(t.replace(/~/g,"~0").replace(/\//g,"~1"))}let uD={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},uV={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},uB={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},uW="undefined"!=typeof self&&self.location&&"null"!==self.location.origin?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function uG(t,r=Object.create(null),i=uW,n=""){if(t&&"object"==typeof t&&!Array.isArray(t)){let a=t.$id||t.id;if(a){let o=new URL(a,i.href);o.hash.length>1?r[o.href]=t:(o.hash="",""===n?i=o:uG(t,r,i))}}else if(!0!==t&&!1!==t)return r;let a=i.href+(n?"#"+n:"");if(void 0!==r[a])throw Error(`Duplicate schema URI "${a}".`);if(r[a]=t,!0===t||!1===t)return r;if(void 0===t.__absolute_uri__&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:a}),t.$ref&&void 0===t.__absolute_ref__){let r=new URL(t.$ref,i.href);r.hash=r.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:r.href})}if(t.$recursiveRef&&void 0===t.__absolute_recursive_ref__){let r=new URL(t.$recursiveRef,i.href);r.hash=r.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:r.href})}for(let a in t.$anchor&&(r[new URL("#"+t.$anchor,i.href).href]=t),t){if(uB[a])continue;let o=`${n}/${uJ(a)}`,s=t[a];if(Array.isArray(s)){if(uD[a]){let t=s.length;for(let n=0;n<t;n++)uG(s[n],r,i,`${o}/${n}`)}}else if(uV[a])for(let t in s)uG(s[t],r,i,`${o}/${uJ(t)}`);else uG(s,r,i,o)}return r}let uK=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,uY=[0,31,28,31,30,31,30,31,31,30,31,30,31],uX=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;function uQ(t){return t.test.bind(t)}let u0={date:u1,time:u2.bind(void 0,!1),"date-time":function(t){let r=t.split(u9);return 2==r.length&&u1(r[0])&&u2(!0,r[1])},duration:t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t)),uri:function(t){return u4.test(t)&&u5.test(t)},"uri-reference":uQ(/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i),"uri-template":uQ(/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i),url:uQ(/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu),email:t=>{if('"'===t[0])return!1;let[r,i,...n]=t.split("@");return!(!r||!i||0!==n.length||r.length>64||i.length>253||"."===r[0]||r.endsWith(".")||r.includes(".."))&&!!/^[a-z0-9.-]+$/i.test(i)&&!!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(r)&&i.split(".").every(t=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(t))},hostname:uQ(/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i),ipv4:uQ(/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/),ipv6:uQ(/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i),regex:function(t){if(u3.test(t))return!1;try{return RegExp(t,"u"),!0}catch(t){return!1}},uuid:uQ(/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i),"json-pointer":uQ(/^(?:\/(?:[^~/]|~0|~1)*)*$/),"json-pointer-uri-fragment":uQ(/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i),"relative-json-pointer":uQ(/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/)};function u1(t){var r;let i=t.match(uK);if(!i)return!1;let n=+i[1],a=+i[2],o=+i[3];return a>=1&&a<=12&&o>=1&&o<=(2==a&&(r=n)%4==0&&(r%100!=0||r%400==0)?29:uY[a])}function u2(t,r){let i=r.match(uX);if(!i)return!1;let n=+i[1],a=+i[2],o=+i[3],s=!!i[5];return(n<=23&&a<=59&&o<=59||23==n&&59==a&&60==o)&&(!t||s)}let u9=/t|\s/i,u4=/\/|:/,u5=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,u3=/[^\\]\\Z/;var u6=class{schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",i=!0){this.schema=t,this.draft=r,this.shortCircuit=i,this.lookup=uG(t)}validate(t){return function t(r,i,n="2019-09",a=uG(i),o=!0,s=null,l="#",c="#",u=Object.create(null)){let d;if(!0===i)return{valid:!0,errors:[]};if(!1===i)return{valid:!1,errors:[{instanceLocation:l,keyword:"false",keywordLocation:l,error:"False boolean schema."}]};let p=typeof r;switch(p){case"boolean":case"number":case"string":d=p;break;case"object":d=null===r?"null":Array.isArray(r)?"array":"object";break;default:throw Error(`Instances of "${p}" type are not supported.`)}let{$ref:m,$recursiveRef:h,$recursiveAnchor:f,type:g,const:y,enum:v,required:_,not:b,anyOf:S,allOf:w,oneOf:x,if:k,then:R,else:$,format:C,properties:T,patternProperties:O,additionalProperties:P,unevaluatedProperties:E,minProperties:I,maxProperties:q,propertyNames:j,dependentRequired:z,dependentSchemas:N,dependencies:A,prefixItems:L,items:M,additionalItems:Z,unevaluatedItems:U,contains:F,minContains:H,maxContains:J,minItems:D,maxItems:V,uniqueItems:B,minimum:W,maximum:G,exclusiveMinimum:K,exclusiveMaximum:Y,multipleOf:X,minLength:Q,maxLength:ee,pattern:et,__absolute_ref__:er,__absolute_recursive_ref__:ei}=i,en=[];if(!0===f&&null===s&&(s=i),"#"===h){let d=null===s?a[ei]:s,p=`${c}/$recursiveRef`,m=t(r,null===s?i:s,n,a,o,d,l,p,u);m.valid||en.push({instanceLocation:l,keyword:"$recursiveRef",keywordLocation:p,error:"A subschema had errors."},...m.errors)}if(void 0!==m){let i=a[er||m];if(void 0===i){let t=`Unresolved $ref "${m}".`;throw er&&er!==m&&(t+=` Absolute URI "${er}".`),Error(t+=`
|
|
55
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let n=i[1];if(r===i[0]){a(i);continue}if(t.external){let n=t.external.registry.get(i[0])?.id;if(r!==i[0]&&n){a(i);continue}}if(t.metadataRegistry.get(i[0])?.id||n.cycle){a(i);continue}n.count>1&&"ref"===t.reused&&a(i)}t.external&&(t.sharedDefsExtractedFor=t.external)}let ig=new Set(["type","properties","required","additionalProperties"]),iy=["oneOf","anyOf"];function iv(t){let r=t.additionalProperties;return void 0===r||!1===r||"object"!=typeof r||null===r?null:Object.keys(r).length?r:null}function i_(t){let r=[];for(let i of t){if("object"!=typeof i||"object"!==i.type)return null;for(let t in i)if(!ig.has(t))return null;r.push(i)}let i={},n=new Set;for(let t of r){for(let n in t.properties){if(Object.prototype.hasOwnProperty.call(i,n))continue;let t=[];for(let i of r){let r=i.properties?.[n]??iv(i);null!=r&&(t.some(t=>JSON.stringify(t)===JSON.stringify(r))||t.push(r))}eo(i,n,1===t.length?t[0]:i_(t)??{allOf:t})}for(let r of t.required??[])n.add(r)}let a={type:"object",properties:i};if(n.size&&(a.required=[...n]),r.every(t=>!1===t.additionalProperties))a.additionalProperties=!1;else{let t=[];for(let i of r){let r=iv(i);r&&!t.some(t=>JSON.stringify(t)===JSON.stringify(r))&&t.push(r)}1===t.length?a.additionalProperties=t[0]:t.length>1&&(a.additionalProperties={allOf:t})}return a}function ib(t,r){let i=t.seen.get(r);if(!i)throw Error("Unprocessed schema. This is a bug in Zod.");let n=r=>{let i=t.seen.get(r);if(null===i.ref)return;let a=i.def??i.schema,o={...a},s=i.ref;if(i.ref=null,s){n(s);let i=t.seen.get(s),l=i.schema;if(l.$ref&&("draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target)?(a.allOf=a.allOf??[],a.allOf.push(l)):ic(a,l),ic(a,o),r._zod.parent===s)for(let t in a)"$ref"!==t&&"allOf"!==t&&(t in o||delete a[t]);if(l.$ref&&i.def)for(let t in a)"$ref"!==t&&"allOf"!==t&&t in i.def&&JSON.stringify(a[t])===JSON.stringify(i.def[t])&&delete a[t]}let l=r._zod.parent;if(l&&l!==s){n(l);let r=t.seen.get(l);if(r?.schema.$ref&&(a.$ref=r.schema.$ref,r.def))for(let t in a)"$ref"!==t&&"allOf"!==t&&t in r.def&&JSON.stringify(a[t])===JSON.stringify(r.def[t])&&delete a[t]}t.override({zodSchema:r,jsonSchema:a,path:i.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(let r of[...t.seen.entries()].reverse())n(r[0]);if("openapi-3.0"!==t.target)for(let r of t.seen.entries())!function t(r){let i=r.anyOf;if(!Array.isArray(i)||0===i.length||void 0!==r.type)return;let n=[];for(let r of i){if(!r||"object"!=typeof r)return;t(r);let i=Object.keys(r);if(1!==i.length||"type"!==i[0])return;let a=r.type;for(let t of Array.isArray(a)?a:[a]){if("string"!=typeof t)return;n.includes(t)||n.push(t)}}delete r.anyOf,r.type=1===n.length?n[0]:n}(r[1].def??r[1].schema);for(let r of t.deferred)r();if(t.intersections.length){let r=new Map;for(let i of t.seen.values())for(let t of[i.schema,i.def]){let i=t?.allOf;if(!Array.isArray(i))continue;let n=r.get(i);n?n.push(t):r.set(i,[t])}for(let i of t.intersections)for(let t of r.get(i)??[])!function(t){let r=t.allOf;if(!Array.isArray(r)||r.length<2)return;for(let r of ig)if(r in t)return;let i=r.filter(t=>iy.some(r=>Array.isArray(t[r]))),n=null;if(i.length){let t=i[0],a=iy.find(r=>Array.isArray(t[r]));if(1!==Object.keys(t).length)return;let o=r.filter(r=>r!==t),s=t[a].map(t=>i_([...o,t]));if(s.some(t=>!t))return;n={[a]:s}}else n=i_(r);n&&(delete t.allOf,ic(t,n))}(t)}}let a={};if("draft-2020-12"===t.target?a.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===t.target?a.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===t.target?a.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let i=t.external.registry.get(r)?.id;if(!i)throw Error("Schema is missing an `id` property");a.$id=t.external.uri(i)}ic(a,i.defId?i.schema:i.def??i.schema);let o=t.metadataRegistry.get(r)?.id;void 0!==o&&a.id===o&&delete a.id;let s=t.external?.defs??{};if(!t.external||t.sharedEmitDoneFor!==t.external)for(let r of t.seen.entries()){let t=r[1];t.def&&t.defId&&(t.def.id===t.defId&&delete t.def.id,eo(s,t.defId,t.def))}t.external&&(t.sharedEmitDoneFor=t.external),t.external||Object.keys(s).length>0&&("draft-2020-12"===t.target?a.$defs=s:a.definitions=s);try{let i=JSON.parse(JSON.stringify(a));return Object.defineProperty(i,"~standard",{value:{...r["~standard"],jsonSchema:{input:iS(r,"input",t.processors),output:iS(r,"output",t.processors)}},enumerable:!1,writable:!1}),i}catch(t){throw Error("Error converting schema to JSON.")}}let iS=(t,r,i={})=>n=>{let{libraryOptions:a,target:o}=n??{},s=iu({...a??{},target:o,io:r,processors:i});return ip(t,s),ih(s,t),ib(s,t)},iw=(t,r,i)=>{(void 0===t[r]||i>t[r])&&(t[r]=i)},ik=(t,r,i)=>{(void 0===t[r]||i<t[r])&&(t[r]=i)},ix=(t,r)=>{iw(t,"minimum",r),ik(t,"maximum",r)},iR=(t,r)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(r)||t.multipleOf.push(r)},i$=(t,r)=>{t.patterns??(t.patterns=new Set),t.patterns.add(r)},iC=(t,r)=>{t.mime=t.mime?t.mime.filter(t=>r.includes(t)):[...r]},iT=(t,r)=>{t.format=r,r.includes("int")&&(t.isInt=!0)},iP=(t,r)=>iw(t,"minimum",r.minimum),iE=(t,r)=>ik(t,"maximum",r.maximum),iO=t=>(r,i)=>{iT(r,i.format);let[n,a]=t[i.format];iw(r,"minimum",n),ik(r,"maximum",a)},iI={greater_than:(t,r)=>iw(t,r.inclusive?"minimum":"exclusiveMinimum",r.value),less_than:(t,r)=>ik(t,r.inclusive?"maximum":"exclusiveMaximum",r.value),multiple_of:(t,r)=>iR(t,r.value),number_format:iO(ek),bigint_format:iO(ex),min_length:iP,max_length:iE,length_equals:(t,r)=>ix(t,r.length),min_size:iP,max_size:iE,size_equals:(t,r)=>ix(t,r.size),string_format:(t,r)=>{iT(t,r.format),r.pattern&&i$(t,r.pattern),("base64"===r.format||"base64url"===r.format)&&(t.contentEncoding=r.format),(r.local||-1===r.precision)&&(t.laxFormat=!0)},mime_type:(t,r)=>iC(t,r.mime)};function iq(t){let r={},i=t._zod.def;for(let n of t._zod.traits.has("$ZodCheck")?[t,...i.checks??[]]:i.checks??[])iI[n._zod.def.check]?.(r,n._zod.def);let n=t._zod.bag;for(let t of(void 0!==n.minimum&&iw(r,"minimum",n.minimum),void 0!==n.exclusiveMinimum&&iw(r,"exclusiveMinimum",n.exclusiveMinimum),void 0!==n.maximum&&ik(r,"maximum",n.maximum),void 0!==n.exclusiveMaximum&&ik(r,"exclusiveMaximum",n.exclusiveMaximum),void 0!==n.multipleOf&&iR(r,n.multipleOf),void 0!==n.format&&(r.format??(r.format=n.format),n.format.includes("int")&&(r.isInt=!0)),n.mime&&iC(r,n.mime),n.patterns??[]))i$(r,t);return r}let ij={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},iA=new Map([[rl,/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/],[ru,/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/]]),iN=t=>iA.get(t)??t,iL=(t,r,i,n)=>{i.type="string";let{minimum:a,maximum:o,format:s,patterns:l,contentEncoding:c,laxFormat:u}=iq(t);if("number"==typeof a&&(i.minLength=a),"number"==typeof o&&(i.maxLength=o),s&&(i.format=ij[s]??s,""===i.format&&delete i.format,("time"===s||u)&&delete i.format),c&&(i.contentEncoding=c),l&&l.size>0){let t=[...l].map(iN);1===t.length?i.pattern=t[0].source:t.length>1&&(i.allOf=[...t.map(t=>({..."draft-07"===r.target||"draft-04"===r.target||"openapi-3.0"===r.target?{type:"string"}:{},pattern:t.source}))])}},iz=(t,r,i,n)=>{let{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:l,exclusiveMinimum:c,isInt:u}=iq(t);i.type=u?"integer":"number";let d="number"==typeof c&&c>=(a??-1/0),p="number"==typeof l&&l<=(o??1/0),m="draft-04"===r.target||"openapi-3.0"===r.target;if(d?m?(i.minimum=c,i.exclusiveMinimum=!0):i.exclusiveMinimum=c:"number"==typeof a&&(i.minimum=a),p?m?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:"number"==typeof o&&(i.maximum=o),s){let a=new Set;for(let o of s)Number.isFinite(o)&&0!==o?a.add(Math.abs(o)):id(t,r,i,n,`A multipleOf divisor of ${o} cannot be represented in JSON Schema`);let[o,...l]=a;void 0!==o&&(i.multipleOf=o),l.length&&(i.allOf=[...i.allOf??[],...l.map(t=>({multipleOf:t}))])}},iM=(t,r,i,n)=>{i.type="boolean"},iZ=(t,r,i,n)=>{"openapi-3.0"===r.target?(i.type="string",i.nullable=!0,i.enum=[null]):i.type="null"},iU=(t,r,i,n)=>{i.not={}},iF=(t,r,i,n)=>{},iH=(t,r,i,n)=>{},iD=(t,r,i,n)=>{let a=Q(t._zod.def.entries);if(0===a.length){i.not={};return}a.every(t=>"number"==typeof t)&&(i.type="number"),a.every(t=>"string"==typeof t)&&(i.type="string"),i.enum=a},iV=(t,r,i,n)=>{let a=t._zod.def;if(0===a.values.length){i.not={};return}let o=[];for(let s of a.values)if(void 0===s){if(id(t,r,i,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if("bigint"==typeof s){if(id(t,r,i,n,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(s))}else o.push(s);if(0===o.length);else if(1===o.length){let t=o[0];i.type=null===t?"null":typeof t,"draft-04"===r.target||"openapi-3.0"===r.target?i.enum=[t]:i.const=t}else o.every(t=>"number"==typeof t)&&(i.type="number"),o.every(t=>"string"==typeof t)&&(i.type="string"),o.every(t=>"boolean"==typeof t)&&(i.type="boolean"),o.every(t=>null===t)&&(i.type="null"),i.enum=o},iJ=(t,r,i,n)=>{id(t,r,i,n,"Custom types cannot be represented in JSON Schema")},iB=(t,r,i,n)=>{id(t,r,i,n,"Transforms cannot be represented in JSON Schema")},iW=(t,r,i,n)=>{let a=t._zod.def,{minimum:o,maximum:s}=iq(t);"number"==typeof o&&(i.minItems=o),"number"==typeof s&&(i.maxItems=s),i.type="array",i.items=ip(a.element,r,{...n,path:[...n.path,"items"]})};function iG(t){let r=t._zod.def;return"pipe"===r.type&&r.in._zod.traits.has("$ZodTransform")?iG(r.out):"catch"===r.type?iG(r.innerType):t._zod.optin}let iK=(t,r,i,n)=>{let a=t._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&id(t,r,i,n,"Symbol keys cannot be represented in JSON Schema"))return;for(let t in i.type="object",i.properties={},o)eo(i.properties,t,ip(o[t],r,{...n,path:[...n.path,"properties",t]}));let s=[];for(let t of Object.keys(o)){let i=a.shape[t];("input"===r.io?void 0===iG(i):void 0===i._zod.optout)&&s.push(t)}s.length>0&&(i.required=s),a.catchall?._zod.def.type==="never"?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=ip(a.catchall,r,{...n,path:[...n.path,"additionalProperties"]})):"output"===r.io&&(i.additionalProperties=!1)},iY=(t,r,i,n)=>{let a=t._zod.def,o=!1===a.inclusive,s=a.options.map((t,i)=>ip(t,r,{...n,path:[...n.path,o?"oneOf":"anyOf",i]}));o?i.oneOf=s:i.anyOf=s},iX=(t,r,i,n)=>{let a=t._zod.def,o=ip(a.left,r,{...n,path:[...n.path,"allOf",0]}),s=ip(a.right,r,{...n,path:[...n.path,"allOf",1]}),l=t=>"allOf"in t&&1===Object.keys(t).length,c=[...l(o)?o.allOf:[o],...l(s)?s.allOf:[s]];i.allOf=c,r.intersections.push(c)},iQ=new WeakMap,i0=(t,r,i,n)=>{let a=t._zod.def;i.type="object";let o=a.keyType,s=iq(o).patterns;if("loose"===a.mode&&s&&s.size>0){let t=ip(a.valueType,r,{...n,path:[...n.path,"patternProperties","*"]});for(let r of(i.patternProperties={},s))eo(i.patternProperties,iN(r).source,t)}else{if("draft-07"===r.target||"draft-2020-12"===r.target){i.propertyNames=ip(a.keyType,r,{...n,path:[...n.path,"propertyNames"]});let o=iQ.get(r);o||(o=[],iQ.set(r,o),r.deferred.push(()=>(function(t){let r=new Map;for(let i of t.seen.values())i.def&&!r.has(i.schema)&&r.set(i.schema,i);let i=new Map;for(let n of iQ.get(t)??[]){let a=t.seen.get(n),o=(a?.def??a?.schema)?.propertyNames;if(!o||!0===o||i.has(o))continue;let s=function t(r,i,n){if(i.$ref){if(n.has(i))return i;n.add(i);let a=r.get(i)?.def;if(!a)return i;let o=t(r,a,n);return o===a?i:o}for(let a of["anyOf","oneOf"]){let o=i[a];if(!Array.isArray(o))continue;let s=o.map(i=>t(r,i,n));s.some((t,r)=>t!==o[r])&&(i={...i,[a]:s})}let a=Array.isArray(i.type)?i.type:[i.type],o=!a.includes("string")&&a.some(t=>"number"===t||"integer"===t),s=i.enum??(void 0!==i.const?[i.const]:void 0);if(!o&&!s?.some(t=>"number"==typeof t))return i;let{minimum:l,maximum:c,exclusiveMinimum:u,exclusiveMaximum:d,multipleOf:p,format:m,id:h,...f}=i;return f.enum?f.enum=f.enum.map(t=>"number"==typeof t?String(t):t):"number"==typeof f.const&&(f.const=String(f.const)),o&&(f.type="string",s||(f.pattern=(a.includes("number")?tg:tf).source)),f}(r,o,new Set);s!==o&&i.set(o,s)}if(i.size)for(let r of t.seen.values())for(let t of[r.schema,r.def]){let r=t&&i.get(t.propertyNames);r&&(t.propertyNames=r)}})(r))),o.push(t)}i.additionalProperties=ip(a.valueType,r,{...n,path:[...n.path,"additionalProperties"]})}let l=o._zod.values,c="input"===r.io&&void 0!==iG(a.valueType);if(l&&!a.partial&&!c){let t=[...l].filter(t=>"string"==typeof t||"number"==typeof t);t.length>0&&(i.required=t.map(String))}},i1=(t,r,i,n)=>{let a=t._zod.def,o=ip(a.innerType,r,n),s=r.seen.get(t);"openapi-3.0"===r.target?(s.ref=a.innerType,i.nullable=!0):i.anyOf=[o,{type:"null"}]},i2=(t,r,i,n)=>{let a=t._zod.def;ip(a.innerType,r,n),r.seen.get(t).ref=a.innerType},i9=Symbol();function i4(t,r,i,n,a){let o=!1,s=JSON.stringify(t,(t,r)=>"bigint"!=typeof r?r:(o=!0,null));return o?(id(r,i,n,a,"BigInt defaults cannot be represented in JSON Schema"),i9):JSON.parse(s)}let i5=(t,r,i,n)=>{let a=t._zod.def;ip(a.innerType,r,n),r.seen.get(t).ref=a.innerType;let o=i4(a.defaultValue,t,r,i,n);o!==i9&&(i.default=o)},i3=(t,r,i,n)=>{let a=t._zod.def;if(ip(a.innerType,r,n),r.seen.get(t).ref=a.innerType,"input"!==r.io)return;let o=i4(a.defaultValue,t,r,i,n);o!==i9&&(i._prefault=o)},i6=(t,r,i,n)=>{let a,o=t._zod.def;ip(o.innerType,r,n),r.seen.get(t).ref=o.innerType;try{a=o.catchValue(void 0)}catch{id(t,r,i,n,"Dynamic catch values are not supported in JSON Schema");return}i.default=a},i7=(t,r,i,n)=>{let a=t._zod.def,o=a.in._zod.traits.has("$ZodTransform"),s="input"===r.io?o?a.out:a.in:a.out;ip(s,r,n),r.seen.get(t).ref=s},i8=(t,r,i,n)=>{let a=t._zod.def;ip(a.innerType,r,n),r.seen.get(t).ref=a.innerType,i.readOnly=!0},ne=(t,r,i,n)=>{let a=t._zod.def;ip(a.innerType,r,n),r.seen.get(t).ref=a.innerType},nt=(t,r,i,n)=>{let a=t._zod.innerType;ip(a,r,n),r.seen.get(t).ref=a},nr={string:iL,number:iz,boolean:iM,bigint:(t,r,i,n)=>{id(t,r,i,n,"BigInt cannot be represented in JSON Schema")},symbol:(t,r,i,n)=>{id(t,r,i,n,"Symbols cannot be represented in JSON Schema")},null:iZ,undefined:(t,r,i,n)=>{id(t,r,i,n,"Undefined cannot be represented in JSON Schema")},void:(t,r,i,n)=>{id(t,r,i,n,"Void cannot be represented in JSON Schema")},never:iU,any:iF,unknown:iH,date:(t,r,i,n)=>{id(t,r,i,n,"Date cannot be represented in JSON Schema")},enum:iD,literal:iV,nan:(t,r,i,n)=>{id(t,r,i,n,"NaN cannot be represented in JSON Schema")},template_literal:(t,r,i,n)=>{let a=t._zod.pattern;if(!a)throw Error("Pattern not found in template literal");i.type="string",i.pattern=a.source},file:(t,r,i,n)=>{i.type="string",i.format="binary",i.contentEncoding="binary";let{minimum:a,maximum:o,mime:s}=iq(t);void 0!==a&&(i.minLength=a),void 0!==o&&(i.maxLength=o),s&&(0===s.length?i.not={}:1===s.length?i.contentMediaType=s[0]:i.anyOf=s.map(t=>({contentMediaType:t})))},success:(t,r,i,n)=>{i.type="boolean"},custom:iJ,function:(t,r,i,n)=>{id(t,r,i,n,"Function types cannot be represented in JSON Schema")},transform:iB,map:(t,r,i,n)=>{id(t,r,i,n,"Map cannot be represented in JSON Schema")},set:(t,r,i,n)=>{id(t,r,i,n,"Set cannot be represented in JSON Schema")},array:iW,object:iK,union:iY,intersection:iX,tuple:(t,r,i,n)=>{let a=t._zod.def;i.type="array";let o="draft-2020-12"===r.target?"prefixItems":"items",s="draft-2020-12"===r.target||"openapi-3.0"===r.target?"items":"additionalItems",l=a.items.map((t,i)=>ip(t,r,{...n,path:[...n.path,o,i]})),c=a.rest?ip(a.rest,r,{...n,path:[...n.path,s,..."openapi-3.0"===r.target?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let t=a.items[u-1];if(!("input"===r.io?void 0!==iG(t):"optional"===t._zod.optout))break;u--}let d=a.items.length,p=!a.rest;"draft-2020-12"===r.target?(i.prefixItems=l,p?i.items=!1:c&&(i.items=c)):"openapi-3.0"===r.target?(i.items={anyOf:l},c&&i.items.anyOf.push(c)):(i.items=l,p?i.additionalItems=!1:c&&(i.additionalItems=c)),u>0&&(i.minItems=u),p&&(i.maxItems=d);let{minimum:m,maximum:h}=iq(t);"number"==typeof m&&(i.minItems=m),"number"==typeof h&&(i.maxItems=h)},record:i0,nullable:i1,nonoptional:i2,default:i5,prefault:i3,catch:i6,pipe:i7,readonly:i8,promise:(t,r,i,n)=>{let a=t._zod.def;ip(a.innerType,r,n),r.seen.get(t).ref=a.innerType},optional:ne,lazy:nt};function ni(t,r){if("_idmap"in t){let i=iu({...r,processors:nr}),n={};for(let r of t._idmap.entries()){let[t,n]=r;ip(n,i)}let a={};for(let o of(i.external={registry:t,uri:r?.uri,defs:n},t._idmap.entries())){let[t,r]=o;ih(i,r),eo(a,t,ib(i,r))}return Object.keys(n).length>0&&(a.__shared={["draft-2020-12"===i.target?"$defs":"definitions"]:n}),{schemas:a}}let i=iu({...r,processors:nr});return ip(t,i),ih(i,t),ib(i,t)}let nn={get:function(){let t=this._zod;return t.message??(t.message=JSON.stringify(t.def,et,2)),t.message},set:function(t){this._zod.message=t},enumerable:!0,configurable:!0},na={value:void 0,enumerable:!1},no=new WeakSet([Object.prototype,Error.prototype]),ns=(t,r)=>{t.name="$ZodError",na.value=r,Object.defineProperty(t,"issues",na),na.value=void 0,Object.defineProperty(t,"message",nn);let i=Object.getPrototypeOf(t);no.has(i)||(no.add(i),Object.defineProperty(i,"toString",{configurable:!0,enumerable:!1,get(){let t=()=>this.message;return Object.defineProperty(this,"toString",{value:t,configurable:!0,writable:!0}),t},set(t){Object.defineProperty(this,"toString",{value:t,configurable:!0,writable:!0})}}))},nl=eV("$ZodError",ns);function nc(t,r){return{callee:r?.callee??t,Err:r?.Err}}eV("$ZodError",ns,void 0,{Parent:Error});let nu=t=>{let r=(i,n,a,o)=>{let s=a?{...a,async:!1}:{async:!1},l=i._zod.run({value:n,issues:[]},s);if(l instanceof Promise)throw new eJ;if(l.issues.length){let i=new(o?.Err??t)(l.issues.map(t=>eI(t,s,eG())));throw em(i,o?.callee??r),i}return l.value};return r},nd=t=>{let r=async(i,n,a,o)=>{let s=a?{...a,async:!0}:{async:!0},l=i._zod.run({value:n,issues:[]},s);if(l instanceof Promise&&(l=await l),l.issues.length){let i=new(o?.Err??t)(l.issues.map(t=>eI(t,s,eG())));throw em(i,o?.callee??r),i}return l.value};return r},np=t=>(r,i,n)=>{let a=n?{...n,async:!1}:{async:!1},o=r._zod.run({value:i,issues:[]},a);if(o instanceof Promise)throw new eJ;return o.issues.length?nm(t,o.issues,a):{success:!0,data:o.value}};function nm(t,r,i){let n;return{success:!1,get error(){return n||(n=new t(r.map(t=>eI(t,i,eG()))),r=void 0,i=void 0),n},set error(e){n=e,r=void 0,i=void 0}}}let nh=t=>async(r,i,n)=>{let a=n?{...n,async:!0}:{async:!0},o=r._zod.run({value:i,issues:[]},a);return o instanceof Promise&&(o=await o),o.issues.length?nm(t,o.issues,a):{success:!0,data:o.value}},nf=Symbol.for("zod.compile.invalid"),ng=Symbol.for("zod.compile.fallback"),ny=async(t,r,i)=>{let n=i?{...i,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},a=t._zod.run({value:r,issues:[]},n);return a instanceof Promise&&(a=await a),0===a.issues.length},nv=new WeakSet([Object.prototype,Error.prototype]);function n_(t,r,i){Object.defineProperty(t,r,{configurable:!0,enumerable:!1,get(){let t=i(this);return Object.defineProperty(this,r,{value:t,configurable:!0,writable:!0}),t},set(t){Object.defineProperty(this,r,{value:t,configurable:!0,writable:!0})}})}let nb=eV("ZodError",(t,r)=>{nl.init(t,r),t.name="ZodError";let i=Object.getPrototypeOf(t);nv.has(i)||(nv.add(i),n_(i,"format",t=>r=>(function(t,r=t=>t.message){let i={_errors:[]},n=(t,a=[])=>{for(let o of t.issues)if("invalid_union"===o.code&&o.errors.length)o.errors.map(t=>n({issues:t},[...a,...o.path]));else if("invalid_key"===o.code)n({issues:o.issues},[...a,...o.path]);else if("invalid_element"===o.code)n({issues:o.issues},[...a,...o.path]);else{let t=[...a,...o.path];if(0===t.length)i._errors.push(r(o));else{let n=i,a=0;for(;a<t.length;){let i=t[a],s=a===t.length-1;if("_errors"===i){s&&n._errors.push(r(o)),a++;continue}Object.prototype.hasOwnProperty.call(n,i)||Object.defineProperty(n,i,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let l=n[i];s&&l._errors.push(r(o)),n=l,a++}}}};return n(t),i})(t,r)),n_(i,"flatten",t=>r=>(function(t,r=t=>t.message){let i={},n=[];for(let s of t.issues)if(s.path.length>0){var a,o;(a=s.path[0],o=()=>[],!Object.prototype.hasOwnProperty.call(i,a)&&("__proto__"===a?Object.defineProperty(i,a,{value:o(),writable:!0,enumerable:!0,configurable:!0}):i[a]=o()),i[a]).push(r(s))}else n.push(r(s));return{formErrors:n,fieldErrors:i}})(t,r)),n_(i,"addIssue",t=>r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,et,2)}),n_(i,"addIssues",t=>r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,et,2)}),Object.defineProperty(i,"isEmpty",{configurable:!0,enumerable:!1,get(){return 0===this.issues.length}}))},void 0,{Parent:Error}),nS=nu(nb),nw=nd(nb),nk=np(nb),nx=nh(nb),nR=(m=nu(nb),h=(t,r,i,n)=>m(t,r,i?{...i,direction:"backward"}:{direction:"backward"},nc(h,n))),n$=(f=nu(nb),g=(t,r,i,n)=>f(t,r,i,nc(g,n))),nC=(y=nd(nb),v=async(t,r,i,n)=>{let a=i?{...i,direction:"backward"}:{direction:"backward"};return await y(t,r,a,nc(v,n))}),nT=(_=nd(nb),b=async(t,r,i,n)=>await _(t,r,i,nc(b,n))),nP=(t,r,i)=>{let n=i?{...i,direction:"backward"}:{direction:"backward"};return np(nb)(t,r,n)},nE=(t,r,i)=>np(nb)(t,r,i),nO=async(t,r,i)=>{let n=i?{...i,direction:"backward"}:{direction:"backward"};return nh(nb)(t,r,n)},nI=async(t,r,i)=>nh(nb)(t,r,i);function nq(){eW.memoizer||eG({memoizer:e9})}let nj=eV("ZodType",(t,r)=>(eW.localeError||eG({localeError:(()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}},r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},i={nan:"NaN"};function n(t,r){return"number"!==t||"number"!=typeof r||Number.isFinite(r)?i[t]??t:String(r)}return i=>{switch(i.code){case"invalid_type":{let t=n(i.expected),r=n(function(t){let r=typeof t;switch(r){case"number":return Number.isNaN(t)?"nan":"number";case"object":if(null===t)return"null";if(Array.isArray(t))return"array";if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}return r}(i.input),i.input);return`Invalid input: expected ${t}, received ${r}`}case"invalid_value":if(1===i.values.length)return`Invalid input: expected ${ew(i.values[0])}`;return`Invalid option: expected one of ${ee(i.values,"|")}`;case"too_big":{let r=i.exact?"exactly ":i.inclusive?"<=":"<",n=t[i.origin]??null;if(n)return`Too big: expected ${i.origin??"value"} to have ${r}${i.maximum.toString()} ${n.unit??"elements"}`;return`Too big: expected ${i.origin??"value"} to be ${r}${i.maximum.toString()}`}case"too_small":{let r=i.exact?"exactly ":i.inclusive?">=":">",n=t[i.origin]??null;if(n)return`Too small: expected ${i.origin} to have ${r}${i.minimum.toString()} ${n.unit}`;return`Too small: expected ${i.origin} to be ${r}${i.minimum.toString()}`}case"invalid_format":if("starts_with"===i.format)return`Invalid string: must start with "${i.prefix}"`;if("ends_with"===i.format)return`Invalid string: must end with "${i.suffix}"`;if("includes"===i.format)return`Invalid string: must include "${i.includes}"`;if("regex"===i.format)return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.format]??i.format}`;case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${ee(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":if(i.options&&Array.isArray(i.options)&&i.options.length>0){let t=i.options.map(t=>`'${t}'`).join(" | ");return`Invalid discriminator value. Expected ${t}`}if(!1===i.inclusive)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}})()}),tU.init(t,r),t.def=r,t.type=r.type,t),{check(...t){let r=this.def;return this.clone(ep(r,{checks:[...r.checks??[],...t.map(t=>"function"==typeof t?{_zod:{check:t,def:{check:"custom"},onattach:[]}}:t)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,r){return eb(this,t,r)},brand(){return this},register(t,r){return t.add(this,r),this},refine(t,r){return this.check(function(t,r={}){return new aD({type:"custom",check:"custom",fn:t,...eS(r)})}(t,r))},superRefine(t,r){return this.check(function(t,r){var i;let n,a;return i=r=>(r.addIssue=t=>{"string"==typeof t?r.issues.push(eN(t,r.value,n._zod.def)):(t.fatal&&(t.continue=!1),t.code??(t.code="custom"),"input"in t||(t.input=r.value),t.inst??(t.inst=n),t.continue??(t.continue=!n._zod.def.abort),r.issues.push(eN(t)))},t(r.value,r)),(a=new tS({check:"custom",...eS(r)}))._zod.check=i,n=a}(t,r))},overwrite(t){return this.check(il(t))},optional(){return aE(this)},exactOptional(){var t;return t=this,new aO({type:"optional",innerType:t})},nullable(){return aq(this)},nullish(){return aE(aq(this))},nonoptional(t){var r;return r=this,new aN({type:"nonoptional",innerType:r,...eS(t)})},array(){return ad(this)},or(t){return ag([this,t])},and(t){return ab(this,t)},transform(t){return aM(this,aT(t))},default(t){var r,i;return r=this,i=t,new aj({type:"default",innerType:r,get defaultValue(){return"function"==typeof i?i():ey(i)}})},prefault(t){var r,i;return r=this,i=t,new aA({type:"prefault",innerType:r,get defaultValue(){return"function"==typeof i?i():ey(i)}})},catch(t){return function(t,r){let i;return new aL({type:"catch",innerType:t,catchValue:"function"==typeof r?r:((i=()=>r)["~constantCatch"]=!0,i)})}(this,t)},pipe(t){return aM(this,t)},readonly(){var t;return t=this,new aU({type:"readonly",innerType:t})},describe(t){let r=this.clone();return r9.add(r,{description:t}),r},meta(...t){if(0===t.length)return r9.get(this);let r=this.clone();return r9.add(r,t[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...r){return 0===r.length?t(this):t(this,...r)},get"~standard"(){return eL(this,"~standard",{...tD(this),jsonSchema:{input:iS(this,"input"),output:iS(this,"output")}},!1)},set"~standard"(value){eL(this,"~standard",value)},parse:function t(r,i){return nS(this,r,i,{callee:t})},parseAsync:async function t(r,i){return await nw(this,r,i,{callee:t})},safeParse(t,r){return nk(this,t,r)},async safeParseAsync(t,r){return nx(this,t,r)},get spa(){return this?.safeParseAsync},set spa(value){eL(this,"spa",value)},validate(t,r){let i=this._zod.bag.validator;if(void 0!==i){if(i(t)!==nf)return!0;if(!0===i.definite&&void 0===r)return!1}return function(t,r,i){let n,a=i?{...i,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=t._zod.bag.fallbackRun;if(o?(a[ng]=!0,n=o({value:r,issues:[]},a)):n=t._zod.run({value:r,issues:[]},a),n instanceof Promise)throw new eJ;return 0===n.issues.length}(this,t,r)},validateAsync(t,r){return ny(this,t,r)},encode:function t(r,i){return nR(this,r,i,{callee:t})},decode:function t(r,i){return n$(this,r,i,{callee:t})},encodeAsync:async function t(r,i){return await nC(this,r,i,{callee:t})},decodeAsync:async function t(r,i){return await nT(this,r,i,{callee:t})},safeEncode(t,r){return nP(this,t,r)},safeDecode(t,r){return nE(this,t,r)},async safeEncodeAsync(t,r){return nO(this,t,r)},async safeDecodeAsync(t,r){return nI(this,t,r)},toJSONSchema(t){return((t,r={})=>i=>{let n=iu({...i,processors:r});return ip(t,n),ih(n,t),ib(n,t)})(this,{})(t)},get description(){return r9.get(this)?.description},get _def(){return this._zod.def}}),nA=eV("_ZodString",(t,r)=>{tV.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iL(t,r,i,n)},ez({format:t=>iq(t).format??null,minLength:t=>iq(t).minimum??null,maxLength:t=>iq(t).maximum??null},{regex(...t){return this.check(function(t,r){return new tI({check:"string_format",format:"regex",...eS(r),pattern:t})}(...t))},includes(...t){return this.check(function(t,r){return new tA({check:"string_format",format:"includes",...eS(r),includes:t})}(...t))},startsWith(...t){return this.check(function(t,r){return new tN({check:"string_format",format:"starts_with",...eS(r),prefix:t})}(...t))},endsWith(...t){return this.check(function(t,r){return new tL({check:"string_format",format:"ends_with",...eS(r),suffix:t})}(...t))},min(...t){return this.check(io(...t))},max(...t){return this.check(ia(...t))},length(...t){return this.check(is(...t))},nonempty(...t){return this.check(io(1,...t))},lowercase(t){return this.check(new tq({check:"string_format",format:"lowercase",...eS(t)}))},uppercase(t){return this.check(new tj({check:"string_format",format:"uppercase",...eS(t)}))},trim(){return this.check(il(t=>t.trim()))},normalize(...t){return this.check(function(t){return il(r=>r.normalize(t))}(...t))},toLowerCase(){return this.check(il(t=>t.toLowerCase()))},toUpperCase(){return this.check(il(t=>t.toUpperCase()))},slugify(){return this.check(il(t=>t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")))}})),nN=eV("ZodString",(t,r)=>{tV.init(t,r),nA.init(t,r)},{email(t){return this.check(r5(nH,t))},url(t){return this.check(r3(nJ,t))},jwt(t){return this.check(new n6({type:"string",format:"jwt",check:"string_format",abort:!1,...eS(t)}))},emoji(t){return this.check(new nB({type:"string",format:"emoji",check:"string_format",abort:!1,...eS(t)}))},guid(t){return this.check(new nD({type:"string",format:"guid",check:"string_format",abort:!1,...eS(t)}))},uuid(t){return this.check(new nV({type:"string",format:"uuid",check:"string_format",abort:!1,...eS(t)}))},uuidv4(t){return this.check(new nV({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...eS(t)}))},uuidv6(t){return this.check(new nV({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...eS(t)}))},uuidv7(t){return this.check(new nV({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...eS(t)}))},nanoid(t){return this.check(new nW({type:"string",format:"nanoid",check:"string_format",abort:!1,...eS(t)}))},cuid(t){return this.check(new nG({type:"string",format:"cuid",check:"string_format",abort:!1,...eS(t)}))},cuid2(t){return this.check(new nK({type:"string",format:"cuid2",check:"string_format",abort:!1,...eS(t)}))},ulid(t){return this.check(new nY({type:"string",format:"ulid",check:"string_format",abort:!1,...eS(t)}))},base64(t){return this.check(new n4({type:"string",format:"base64",check:"string_format",abort:!1,...eS(t)}))},base64url(t){return this.check(new n5({type:"string",format:"base64url",check:"string_format",abort:!1,...eS(t)}))},xid(t){return this.check(new nX({type:"string",format:"xid",check:"string_format",abort:!1,...eS(t)}))},ksuid(t){return this.check(new nQ({type:"string",format:"ksuid",check:"string_format",abort:!1,...eS(t)}))},ipv4(t){return this.check(new n0({type:"string",format:"ipv4",check:"string_format",abort:!1,...eS(t)}))},ipv6(t){return this.check(new n1({type:"string",format:"ipv6",check:"string_format",abort:!1,...eS(t)}))},cidrv4(t){return this.check(new n2({type:"string",format:"cidrv4",check:"string_format",abort:!1,...eS(t)}))},cidrv6(t){return this.check(new n9({type:"string",format:"cidrv6",check:"string_format",abort:!1,...eS(t)}))},e164(t){return this.check(new n3({type:"string",format:"e164",check:"string_format",abort:!1,...eS(t)}))},datetime(t){return this.check(r6(nM,t))},date(t){return this.check(r7(nZ,t))},time(t){return this.check(new nU({type:"string",format:"time",check:"string_format",precision:null,...eS(t)}))},duration(t){return this.check(new nF({type:"string",format:"duration",check:"string_format",...eS(t)}))}});function nL(t){return new nN(r4({type:"string",...eS(t)}))}let nz=eV("ZodStringFormat",(t,r)=>{tJ.init(t,r),nA.init(t,r)}),nM=eV("ZodISODateTime",(t,r)=>{t6.init(t,r),nz.init(t,r)}),nZ=eV("ZodISODate",(t,r)=>{t7.init(t,r),nz.init(t,r)}),nU=eV("ZodISOTime",(t,r)=>{t8.init(t,r),nz.init(t,r)}),nF=eV("ZodISODuration",(t,r)=>{re.init(t,r),nz.init(t,r)}),nH=eV("ZodEmail",(t,r)=>{tG.init(t,r),nz.init(t,r)}),nD=eV("ZodGUID",(t,r)=>{tB.init(t,r),nz.init(t,r)}),nV=eV("ZodUUID",(t,r)=>{tW.init(t,r),nz.init(t,r)}),nJ=eV("ZodURL",(t,r)=>{tQ.init(t,r),nz.init(t,r)}),nB=eV("ZodEmoji",(t,r)=>{t0.init(t,r),nz.init(t,r)}),nW=eV("ZodNanoID",(t,r)=>{t1.init(t,r),nz.init(t,r)}),nG=eV("ZodCUID",(t,r)=>{t2.init(t,r),nz.init(t,r)}),nK=eV("ZodCUID2",(t,r)=>{t9.init(t,r),nz.init(t,r)}),nY=eV("ZodULID",(t,r)=>{t4.init(t,r),nz.init(t,r)}),nX=eV("ZodXID",(t,r)=>{t5.init(t,r),nz.init(t,r)}),nQ=eV("ZodKSUID",(t,r)=>{t3.init(t,r),nz.init(t,r)}),n0=eV("ZodIPv4",(t,r)=>{rt.init(t,r),nz.init(t,r)}),n1=eV("ZodIPv6",(t,r)=>{rn.init(t,r),nz.init(t,r)}),n2=eV("ZodCIDRv4",(t,r)=>{ra.init(t,r),nz.init(t,r)}),n9=eV("ZodCIDRv6",(t,r)=>{ro.init(t,r),nz.init(t,r)}),n4=eV("ZodBase64",(t,r)=>{rc.init(t,r),nz.init(t,r)}),n5=eV("ZodBase64URL",(t,r)=>{rd.init(t,r),nz.init(t,r)}),n3=eV("ZodE164",(t,r)=>{rp.init(t,r),nz.init(t,r)}),n6=eV("ZodJWT",(t,r)=>{rm.init(t,r),nz.init(t,r)}),n7=eV("ZodNumber",(t,r)=>{rh.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iz(t,r,i,n),t.isFinite=!0},ez({minValue:t=>{let{minimum:r,exclusiveMinimum:i}=iq(t);return Math.max(r??-1/0,i??-1/0)},maxValue:t=>{let{maximum:r,exclusiveMaximum:i}=iq(t);return Math.min(r??1/0,i??1/0)},isInt:t=>{let{isInt:r,multipleOf:i}=iq(t);return!!r||!!i?.some(Number.isSafeInteger)},format:t=>iq(t).format??null},{gt(t,r){return this.check(it(t,r))},gte(t,r){return this.check(ir(t,r))},min(t,r){return this.check(ir(t,r))},lt(t,r){return this.check(r8(t,r))},lte(t,r){return this.check(ie(t,r))},max(t,r){return this.check(ie(t,r))},int(t){return this.check(at(t))},safe(t){return this.check(at(t))},positive(t){return this.check(it(0,t))},nonnegative(t){return this.check(ir(0,t))},negative(t){return this.check(r8(0,t))},nonpositive(t){return this.check(ie(0,t))},multipleOf(t,r){return this.check(ii(t,r))},step(t,r){return this.check(ii(t,r))},finite(){return this}}));function n8(t){return new n7(r4({type:"number",checks:[],...eS(t)}))}let ae=eV("ZodNumberFormat",(t,r)=>{rf.init(t,r),n7.init(t,r)});function at(t){return new ae({type:"number",check:"number_format",abort:!1,format:"safeint",...eS(t)})}let ar=eV("ZodBoolean",(t,r)=>{rg.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iM(t,r,i,n)});function ai(t){return new ar({type:"boolean",...eS(t)})}let an=eV("ZodNull",(t,r)=>{ry.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iZ(t,r,i,n)});function aa(t){return new an({type:"null",...eS(t)})}let ao=eV("ZodAny",(t,r)=>{rv.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iF(t,r,i,n)}),as=eV("ZodUnknown",(t,r)=>{r_.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iH(t,r,i,n)});function al(){return new as({type:"unknown"})}let ac=eV("ZodNever",(t,r)=>{rb.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iU(t,r,i,n)}),au=eV("ZodArray",(t,r)=>{nq(),rw.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iW(t,r,i,n),t.element=r.element},{min(t,r){return this.check(io(t,r))},nonempty(t){return this.check(io(1,t))},max(t,r){return this.check(ia(t,r))},length(t,r){return this.check(is(t,r))},unwrap(){return this.element}});function ad(t,r){return new au({type:"array",element:t,...eS(r)})}let ap=eV("ZodObject",(t,r)=>{var i;let n,a;nq(),rT.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iK(t,r,i,n),i="shape",(a=i in(n=Object.getPrototypeOf(t))?void 0:n)&&Object.defineProperty(a,i,{configurable:!0,get(){let t={configurable:!0,writable:!0,enumerable:!1,value:void 0};return Object.defineProperty(this,i,t),t.value=(t=>t._zod.def.shape)(this),Object.defineProperty(this,i,t),t.value},set(t){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!1,value:t})}})},{keyof(){return ax(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(ep(this._zod.def,{catchall:t}))},passthrough(){return this.clone(ep(this._zod.def,{catchall:al()}))},loose(){return this.clone(ep(this._zod.def,{catchall:al()}))},strict(){return this.clone(ep(this._zod.def,{catchall:new ac({type:"never",...eS(void 0)})}))},strip(){return this.clone(ep(this._zod.def,{catchall:void 0}))},extend(t){if(!eg(t))throw Error("Invalid input to extend: expected a plain object");let r=this._zod.def.checks;if(r&&r.length>0){let r=el(this);for(let i of Reflect.ownKeys(t))if(void 0!==Object.getOwnPropertyDescriptor(r,i))throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return eb(this,ep(this._zod.def,{shape:e$(this,t)}))},safeExtend(t){if(!eg(t))throw Error("Invalid input to safeExtend: expected a plain object");return eb(this,ep(this._zod.def,{shape:e$(this,t)}))},merge(t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(this._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r={};return ed(r,this,Reflect.ownKeys(el(this))),ed(r,t,Reflect.ownKeys(el(t))),eb(this,ep(this._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))},pick(t){return function(t,r){let i=t._zod.def,n=i.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let a={};return ed(a,t,eR(t,r)),eb(t,ep(i,{shape:a,checks:[]}))}(this,t)},omit(t){return function(t,r){let i=t._zod.def,n=i.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let a=new Set(eR(t,r)),o={};return ed(o,t,Reflect.ownKeys(el(t)).filter(t=>!a.has(t))),eb(t,ep(i,{shape:o,checks:[]}))}(this,t)},partial(...t){return eC(aP,this,t[0])},exactPartial(...t){return eC(aO,this,t[0],"exactPartial")},required(...t){var r;let i,n;return i=(r=t[0])?new Set(eR(this,r)):void 0,ed(n={},this,Reflect.ownKeys(el(this)),(t,r)=>i&&!i.has(r)?t:new aN({type:"nonoptional",innerType:t})),eb(this,ep(this._zod.def,{shape:n}))}});function am(t,r){return new ap({type:"object",shape:t??{},...eS(r)})}function ah(t,r){return new ap({type:"object",shape:t,catchall:al(),...eS(r)})}let af=eV("ZodUnion",(t,r)=>{rE.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iY(t,r,i,n),t.options=r.options});function ag(t,r){return new af({type:"union",options:t,...eS(r)})}let ay=eV("ZodDiscriminatedUnion",(t,r)=>{af.init(t,r),rO.init(t,r)});function av(t,r,i){return new ay({type:"union",options:r,discriminator:t,...eS(i)})}let a_=eV("ZodIntersection",(t,r)=>{rI.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iX(t,r,i,n)});function ab(t,r){return new a_({type:"intersection",left:t,right:r})}let aS=eV("ZodRecord",(t,r)=>{nq(),rj.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i0(t,r,i,n),t.keyType=r.keyType,t.valueType=r.valueType});function aw(t,r,i){return new aS(r&&r._zod?{type:"record",keyType:t,valueType:r,...eS(i)}:{type:"record",keyType:nL(),valueType:t,...eS(r)})}let ak=eV("ZodEnum",(t,r)=>{rA.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iD(t,r,i,n),t.enum=r.entries,t.options=[...t._zod.values];let i=new Set(Object.keys(r.entries));t.extract=(t,n)=>{let a={};for(let n of t)if(i.has(n))a[n]=r.entries[n];else throw Error(`Key ${n} not found in enum`);return new ak({...r,checks:[],...eS(n),entries:a})},t.exclude=(t,n)=>{let a={...r.entries};for(let r of t)if(i.has(r))delete a[r];else throw Error(`Key ${r} not found in enum`);return new ak({...r,checks:[],...eS(n),entries:a})}});function ax(t,r){return new ak({type:"enum",entries:Array.isArray(t)?Object.fromEntries(t.map(t=>[t,t])):t,...eS(r)})}let aR=eV("ZodLiteral",(t,r)=>{rN.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iV(t,r,i,n),t.values=new Set(r.values),Object.defineProperty(t,"value",{get(){if(r.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return r.values[0]}})});function a$(t,r){return new aR({type:"literal",values:Array.isArray(t)?t:[t],...eS(r)})}let aC=eV("ZodTransform",(t,r)=>{nq(),rL.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iB(t,r,i,n),t._zod.parse=(i,n)=>{if("backward"===n.direction)throw new eB(t.constructor.name);i.addIssue=n=>{"string"==typeof n?i.issues.push(eN(n,i.value,r)):(n.fatal&&(n.continue=!1),n.code??(n.code="custom"),"input"in n||(n.input=i.value),n.inst??(n.inst=t),i.issues.push(eN(n)))};let a=r.transform(i.value,i);return a instanceof Promise?a.then(t=>(i.value=t,i)):(i.value=a,i)}});function aT(t){return new aC({type:"transform",transform:t})}let aP=eV("ZodOptional",(t,r)=>{rM.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>ne(t,r,i,n),t.unwrap=()=>t._zod.def.innerType});function aE(t){return new aP({type:"optional",innerType:t})}let aO=eV("ZodExactOptional",(t,r)=>{rZ.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>ne(t,r,i,n),t.unwrap=()=>t._zod.def.innerType}),aI=eV("ZodNullable",(t,r)=>{rU.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i1(t,r,i,n),t.unwrap=()=>t._zod.def.innerType});function aq(t){return new aI({type:"nullable",innerType:t})}let aj=eV("ZodDefault",(t,r)=>{rF.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i5(t,r,i,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap}),aA=eV("ZodPrefault",(t,r)=>{rD.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i3(t,r,i,n),t.unwrap=()=>t._zod.def.innerType}),aN=eV("ZodNonOptional",(t,r)=>{rV.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i2(t,r,i,n),t.unwrap=()=>t._zod.def.innerType}),aL=eV("ZodCatch",(t,r)=>{rW.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i6(t,r,i,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap}),az=eV("ZodPipe",(t,r)=>{rG.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i7(t,r,i,n),t.in=r.in,t.out=r.out});function aM(t,r){return new az({type:"pipe",in:t,out:r})}let aZ=eV("ZodPreprocess",(t,r)=>{az.init(t,r),rY.init(t,r)}),aU=eV("ZodReadonly",(t,r)=>{rX.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i8(t,r,i,n),t.unwrap=()=>t._zod.def.innerType}),aF=eV("ZodLazy",(t,r)=>{r0.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>nt(t,r,i,n),t.unwrap=()=>t._zod.def.getter()});function aH(t){return new aF({type:"lazy",getter:t})}let aD=eV("ZodCustom",(t,r)=>{r1.init(t,r),nj.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iJ(t,r,i,n)});function aV(t,r){return new aZ({type:"pipe",in:aT(t),out:r})}j||(j={});let aJ="2025-11-25",aB=[aJ,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],aW="io.modelcontextprotocol/protocolVersion",aG="io.modelcontextprotocol/clientInfo",aK="io.modelcontextprotocol/serverInfo",aY="io.modelcontextprotocol/clientCapabilities",aX="io.modelcontextprotocol/subscriptionId",aQ="io.modelcontextprotocol/logLevel",a0=aH(()=>ag([nL(),n8(),ai(),aa(),aw(nL(),a0),ad(a0)])),a1=aw(nL(),a0),a2=ad(a0),a9=ag([nL(),n8().int()]),a4=nL(),a5=am({ttl:n8().optional()}),a3=am({taskId:nL()}),a6=ah({progressToken:a9.optional(),"io.modelcontextprotocol/related-task":a3.optional()}),a7=am({_meta:a6.optional()}),a8=a7.extend({task:a5.optional()}),oe=am({method:nL(),params:a7.loose().optional()}),ot=am({_meta:a6.optional()}),or=am({method:nL(),params:ot.loose().optional()}),oi=ah({get[aK](){return ov.optional().catch(void 0)}}),on=ah({_meta:oi.optional()}),oa=ag([nL(),n8().int()]),oo=am({jsonrpc:a$("2.0"),id:oa,...oe.shape}).strict(),os=am({jsonrpc:a$("2.0"),...or.shape}).strict(),ol=am({jsonrpc:a$("2.0"),id:oa,result:on}).strict(),oc=am({jsonrpc:a$("2.0"),id:oa.optional(),error:am({code:n8().int(),message:nL(),data:al().optional()})}).strict(),ou=ag([oo,os,ol,oc]),od=ag([ol,oc]),op=on.strict(),om=ot.extend({requestId:oa.optional(),reason:nL().optional()}),oh=or.extend({method:a$("notifications/cancelled"),params:om}),of=am({src:nL(),mimeType:nL().optional(),sizes:ad(nL()).optional(),theme:ax(["light","dark"]).optional()}),og=am({icons:ad(of).optional()}),oy=am({name:nL(),title:nL().optional()}),ov=oy.extend({...oy.shape,...og.shape,version:nL(),websiteUrl:nL().optional(),description:nL().optional()}),o_=ab(am({applyDefaults:ai().optional()}),a1),ob=aV(t=>t&&"object"==typeof t&&!Array.isArray(t)&&0===Object.keys(t).length?{form:{}}:t,ab(am({form:o_.optional(),url:a1.optional()}),a1.optional())),oS=ah({list:a1.optional(),cancel:a1.optional(),requests:ah({sampling:ah({createMessage:a1.optional()}).optional(),elicitation:ah({create:a1.optional()}).optional()}).optional()}),ow=ah({list:a1.optional(),cancel:a1.optional(),requests:ah({tools:ah({call:a1.optional()}).optional()}).optional()}),ok=am({experimental:aw(nL(),a1).optional(),sampling:am({context:a1.optional(),tools:a1.optional()}).optional(),elicitation:ob.optional(),roots:am({listChanged:ai().optional()}).optional(),tasks:oS.optional(),extensions:aw(nL(),a1).optional()}),ox=a7.extend({protocolVersion:nL(),capabilities:ok,clientInfo:ov}),oR=oe.extend({method:a$("initialize"),params:ox}),o$=am({experimental:aw(nL(),a1).optional(),logging:a1.optional(),completions:a1.optional(),prompts:am({listChanged:ai().optional()}).optional(),resources:am({subscribe:ai().optional(),listChanged:ai().optional()}).optional(),tools:am({listChanged:ai().optional()}).optional(),tasks:ow.optional(),extensions:aw(nL(),a1).optional()}),oC=on.extend({protocolVersion:nL(),capabilities:o$,serverInfo:ov,instructions:nL().optional()}),oT=or.extend({method:a$("notifications/initialized"),params:ot.optional()}),oP=oe.extend({method:a$("server/discover"),params:a7.optional()}),oE=on.extend({supportedVersions:ad(nL()),capabilities:o$,instructions:nL().optional()}),oO=oe.extend({method:a$("ping"),params:a7.optional()}),oI=am({progress:n8(),total:aE(n8()),message:aE(nL())}),oq=am({...ot.shape,...oI.shape,progressToken:a9}),oj=or.extend({method:a$("notifications/progress"),params:oq}),oA=a7.extend({cursor:a4.optional()}),oN=oe.extend({params:oA.optional()}),oL=on.extend({nextCursor:a4.optional()}),oz=am({uri:nL(),mimeType:aE(nL()),_meta:aw(nL(),al()).optional()}),oM=oz.extend({text:nL()}),oZ=nL().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),oU=oz.extend({blob:oZ}),oF=ax(["user","assistant"]),oH=am({audience:ad(oF).optional(),priority:n8().min(0).max(1).optional(),lastModified:r6(nM,{offset:!0}).optional()}),oD=am({...oy.shape,...og.shape,uri:nL(),description:aE(nL()),mimeType:aE(nL()),size:aE(n8()),annotations:oH.optional(),_meta:aE(ah({}))}),oV=am({...oy.shape,...og.shape,uriTemplate:nL(),description:aE(nL()),mimeType:aE(nL()),annotations:oH.optional(),_meta:aE(ah({}))}),oJ=oN.extend({method:a$("resources/list")}),oB=oL.extend({resources:ad(oD)}),oW=oN.extend({method:a$("resources/templates/list")}),oG=oL.extend({resourceTemplates:ad(oV)}),oK=a7.extend({uri:nL()}),oY=oe.extend({method:a$("resources/read"),params:oK}),oX=on.extend({contents:ad(ag([oM,oU]))}),oQ=or.extend({method:a$("notifications/resources/list_changed"),params:ot.optional()}),o0=oe.extend({method:a$("resources/subscribe"),params:oK}),o1=oe.extend({method:a$("resources/unsubscribe"),params:oK}),o2=am({toolsListChanged:ai().optional(),promptsListChanged:ai().optional(),resourcesListChanged:ai().optional(),resourceSubscriptions:ad(nL()).optional()}),o9=a7.extend({notifications:o2}),o4=oe.extend({method:a$("subscriptions/listen"),params:o9}),o5=ot.extend({notifications:o2}),o3=or.extend({method:a$("notifications/subscriptions/acknowledged"),params:o5}),o6=oi.extend({[aX]:oa}),o7=on.extend({_meta:o6}),o8=ot.extend({uri:nL()}),se=or.extend({method:a$("notifications/resources/updated"),params:o8}),st=am({name:nL(),description:aE(nL()),required:aE(ai())}),sr=am({...oy.shape,...og.shape,description:aE(nL()),arguments:aE(ad(st)),_meta:aE(ah({}))}),si=oN.extend({method:a$("prompts/list")}),sn=oL.extend({prompts:ad(sr)}),sa=a7.extend({name:nL(),arguments:aw(nL(),nL()).optional()}),so=oe.extend({method:a$("prompts/get"),params:sa}),ss=am({type:a$("text"),text:nL(),annotations:oH.optional(),_meta:aw(nL(),al()).optional()}),sl=am({type:a$("image"),data:oZ,mimeType:nL(),annotations:oH.optional(),_meta:aw(nL(),al()).optional()}),sc=am({type:a$("audio"),data:oZ,mimeType:nL(),annotations:oH.optional(),_meta:aw(nL(),al()).optional()}),su=am({type:a$("tool_use"),name:nL(),id:nL(),input:aw(nL(),al()),_meta:aw(nL(),al()).optional()}),sd=am({type:a$("resource"),resource:ag([oM,oU]),annotations:oH.optional(),_meta:aw(nL(),al()).optional()}),sp=oD.extend({type:a$("resource_link")}),sm=ag([ss,sl,sc,sp,sd]),sh=am({role:oF,content:sm}),sf=on.extend({description:nL().optional(),messages:ad(sh)}),sg=or.extend({method:a$("notifications/prompts/list_changed"),params:ot.optional()}),sy=am({title:nL().optional(),readOnlyHint:ai().optional(),destructiveHint:ai().optional(),idempotentHint:ai().optional(),openWorldHint:ai().optional()}),sv=am({taskSupport:ax(["required","optional","forbidden"]).optional()}),s_=am({...oy.shape,...og.shape,description:nL().optional(),inputSchema:am({type:a$("object"),properties:aw(nL(),a0).optional(),required:ad(nL()).optional()}).catchall(al()),outputSchema:ah({$schema:nL().optional()}).optional(),annotations:sy.optional(),execution:sv.optional(),_meta:aw(nL(),al()).optional()}),sb=oN.extend({method:a$("tools/list")}),sS=oL.extend({tools:ad(s_)}),sw=on.extend({content:ad(sm).default([]),structuredContent:al().optional(),isError:ai().optional()}),sk=sw.or(on.extend({toolResult:al()})),sx=a8.extend({name:nL(),arguments:aw(nL(),al()).optional()}),sR=oe.extend({method:a$("tools/call"),params:sx}),s$=or.extend({method:a$("notifications/tools/list_changed"),params:ot.optional()}),sC=am({autoRefresh:ai().default(!0),debounceMs:n8().int().nonnegative().default(300)}),sT=ax(["debug","info","notice","warning","error","critical","alert","emergency"]),sP=a7.extend({level:sT}),sE=oe.extend({method:a$("logging/setLevel"),params:sP}),sO=ot.extend({level:sT,logger:nL().optional(),data:al()}),sI=or.extend({method:a$("notifications/message"),params:sO}),sq=am({name:nL().optional()}),sj=am({hints:ad(sq).optional(),costPriority:n8().min(0).max(1).optional(),speedPriority:n8().min(0).max(1).optional(),intelligencePriority:n8().min(0).max(1).optional()}),sA=am({mode:ax(["auto","required","none"]).optional()}),sN=am({type:a$("tool_result"),toolUseId:nL().describe("The unique identifier for the corresponding tool call."),content:ad(sm),structuredContent:al().optional(),isError:ai().optional(),_meta:aw(nL(),al()).optional()}),sL=av("type",[ss,sl,sc]),sz=av("type",[ss,sl,sc,su,sN]),sM=am({role:oF,content:ag([sz,ad(sz)]),_meta:aw(nL(),al()).optional()}),sZ=a8.extend({messages:ad(sM),modelPreferences:sj.optional(),systemPrompt:nL().optional(),includeContext:ax(["none","thisServer","allServers"]).optional(),temperature:n8().optional(),maxTokens:n8().int(),stopSequences:ad(nL()).optional(),metadata:a1.optional(),tools:ad(s_).optional(),toolChoice:sA.optional()}),sU=oe.extend({method:a$("sampling/createMessage"),params:sZ}),sF=on.extend({model:nL(),stopReason:aE(ax(["endTurn","stopSequence","maxTokens"]).or(nL())),role:oF,content:sL}),sH=on.extend({model:nL(),stopReason:aE(ax(["endTurn","stopSequence","maxTokens","toolUse"]).or(nL())),role:oF,content:ag([sz,ad(sz)])}),sD=am({type:a$("boolean"),title:nL().optional(),description:nL().optional(),default:ai().optional()}),sV=am({type:a$("string"),title:nL().optional(),description:nL().optional(),minLength:n8().optional(),maxLength:n8().optional(),format:ax(["email","uri","date","date-time"]).optional(),default:nL().optional()}),sJ=am({type:ax(["number","integer"]),title:nL().optional(),description:nL().optional(),minimum:n8().optional(),maximum:n8().optional(),default:n8().optional()}),sB=am({type:a$("string"),title:nL().optional(),description:nL().optional(),enum:ad(nL()),default:nL().optional()}),sW=am({type:a$("string"),title:nL().optional(),description:nL().optional(),oneOf:ad(am({const:nL(),title:nL()})),default:nL().optional()}),sG=am({type:a$("string"),title:nL().optional(),description:nL().optional(),enum:ad(nL()),enumNames:ad(nL()).optional(),default:nL().optional()}),sK=ag([sB,sW]),sY=am({type:a$("array"),title:nL().optional(),description:nL().optional(),minItems:n8().optional(),maxItems:n8().optional(),items:am({type:a$("string"),enum:ad(nL())}),default:ad(nL()).optional()}),sX=am({type:a$("array"),title:nL().optional(),description:nL().optional(),minItems:n8().optional(),maxItems:n8().optional(),items:am({anyOf:ad(am({const:nL(),title:nL()}))}),default:ad(nL()).optional()}),sQ=ag([sY,sX]),s0=ag([sG,sK,sQ]),s1=ag([s0,sD,sV,sJ]),s2=a8.extend({mode:a$("form").optional(),message:nL(),requestedSchema:am({type:a$("object"),properties:aw(nL(),s1),required:ad(nL()).optional()}).catchall(al())}),s9=a8.extend({mode:a$("url"),message:nL(),elicitationId:nL(),url:nL().url()}),s4=ag([s2,s9]),s5=oe.extend({method:a$("elicitation/create"),params:s4}),s3=ot.extend({elicitationId:nL()}),s6=or.extend({method:a$("notifications/elicitation/complete"),params:s3}),s7=on.extend({action:ax(["accept","decline","cancel"]),content:aV(t=>null===t?void 0:t,aw(nL(),ag([nL(),n8(),ai(),ad(nL())])).optional())}),s8=am({type:a$("ref/resource"),uri:nL()}),le=am({type:a$("ref/prompt"),name:nL()}),lt=a7.extend({ref:ag([le,s8]),argument:am({name:nL(),value:nL()}),context:am({arguments:aw(nL(),nL()).optional()}).optional()}),lr=oe.extend({method:a$("completion/complete"),params:lt}),li=on.extend({completion:ah({values:ad(nL()).max(100),total:aE(n8().int()),hasMore:aE(ai())})}),ln=am({uri:nL().startsWith("file://"),name:nL().optional(),_meta:aw(nL(),al()).optional()}),la=oe.extend({method:a$("roots/list"),params:a7.optional()}),lo=on.extend({roots:ad(ln)}),ls=or.extend({method:a$("notifications/roots/list_changed"),params:ot.optional()}),ll=ah({ttl:n8().optional(),pollInterval:n8().optional()}),lc=ax(["working","input_required","completed","failed","cancelled"]),lu=am({taskId:nL(),status:lc,ttl:ag([n8(),aa()]),createdAt:nL(),lastUpdatedAt:nL(),pollInterval:aE(n8()),statusMessage:aE(nL())}),ld=on.extend({task:lu}),lp=ot.merge(lu),lm=or.extend({method:a$("notifications/tasks/status"),params:lp}),lh=oe.extend({method:a$("tasks/get"),params:a7.extend({taskId:nL()})}),lf=on.merge(lu),lg=oe.extend({method:a$("tasks/result"),params:a7.extend({taskId:nL()})}),ly=on.loose(),lv=oN.extend({method:a$("tasks/list")}),l_=oL.extend({tasks:ad(lu)}),lb=oe.extend({method:a$("tasks/cancel"),params:a7.extend({taskId:nL()})}),lS=on.merge(lu),lw=ag([oO,oR,oP,lr,sE,so,si,oJ,oW,oY,o0,o1,o4,sR,sb]),lk=ag([oh,oj,oT,ls]),lx=ag([op,sF,sH,s7,lo]),lR=ag([oO,sU,s5,la]),l$=ag([oh,oj,sI,se,oQ,s$,sg,o3,s6]),lC=ag([op,oC,oE,li,sf,sn,oB,oG,oX,sw,sS,o7]),lT=r3(nJ,void 0).superRefine((t,r)=>{if(!URL.canParse(t))return r.addIssue({code:"custom",message:"URL must be parseable",fatal:!0}),eF}).refine(t=>{let r=new URL(t);return"javascript:"!==r.protocol&&"data:"!==r.protocol&&"vbscript:"!==r.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),lP=ah({resource:nL().url(),authorization_servers:ad(lT).optional(),jwks_uri:nL().url().optional(),scopes_supported:ad(nL()).optional(),bearer_methods_supported:ad(nL()).optional(),resource_signing_alg_values_supported:ad(nL()).optional(),resource_name:nL().optional(),resource_documentation:nL().optional(),resource_policy_uri:nL().url().optional(),resource_tos_uri:nL().url().optional(),tls_client_certificate_bound_access_tokens:ai().optional(),authorization_details_types_supported:ad(nL()).optional(),dpop_signing_alg_values_supported:ad(nL()).optional(),dpop_bound_access_tokens_required:ai().optional()}),lE=ah({issuer:nL(),authorization_endpoint:lT,token_endpoint:lT,registration_endpoint:lT.optional(),scopes_supported:ad(nL()).optional(),response_types_supported:ad(nL()),response_modes_supported:ad(nL()).optional(),grant_types_supported:ad(nL()).optional(),token_endpoint_auth_methods_supported:ad(nL()).optional(),token_endpoint_auth_signing_alg_values_supported:ad(nL()).optional(),service_documentation:lT.optional(),revocation_endpoint:lT.optional(),revocation_endpoint_auth_methods_supported:ad(nL()).optional(),revocation_endpoint_auth_signing_alg_values_supported:ad(nL()).optional(),introspection_endpoint:nL().optional(),introspection_endpoint_auth_methods_supported:ad(nL()).optional(),introspection_endpoint_auth_signing_alg_values_supported:ad(nL()).optional(),code_challenge_methods_supported:ad(nL()).optional(),client_id_metadata_document_supported:ai().optional(),authorization_response_iss_parameter_supported:ai().optional().catch(void 0)}),lO=ah({issuer:nL(),authorization_endpoint:lT,token_endpoint:lT,userinfo_endpoint:lT.optional(),jwks_uri:lT,registration_endpoint:lT.optional(),scopes_supported:ad(nL()).optional(),response_types_supported:ad(nL()),response_modes_supported:ad(nL()).optional(),grant_types_supported:ad(nL()).optional(),acr_values_supported:ad(nL()).optional(),subject_types_supported:ad(nL()),id_token_signing_alg_values_supported:ad(nL()),id_token_encryption_alg_values_supported:ad(nL()).optional(),id_token_encryption_enc_values_supported:ad(nL()).optional(),userinfo_signing_alg_values_supported:ad(nL()).optional(),userinfo_encryption_alg_values_supported:ad(nL()).optional(),userinfo_encryption_enc_values_supported:ad(nL()).optional(),request_object_signing_alg_values_supported:ad(nL()).optional(),request_object_encryption_alg_values_supported:ad(nL()).optional(),request_object_encryption_enc_values_supported:ad(nL()).optional(),token_endpoint_auth_methods_supported:ad(nL()).optional(),token_endpoint_auth_signing_alg_values_supported:ad(nL()).optional(),display_values_supported:ad(nL()).optional(),claim_types_supported:ad(nL()).optional(),claims_supported:ad(nL()).optional(),service_documentation:nL().optional(),claims_locales_supported:ad(nL()).optional(),ui_locales_supported:ad(nL()).optional(),claims_parameter_supported:ai().optional(),request_parameter_supported:ai().optional(),request_uri_parameter_supported:ai().optional(),require_request_uri_registration:ai().optional(),op_policy_uri:lT.optional(),op_tos_uri:lT.optional(),client_id_metadata_document_supported:ai().optional(),authorization_response_iss_parameter_supported:ai().optional().catch(void 0)}),lI=am({...lO.shape,...lE.pick({code_challenge_methods_supported:!0}).shape}),lq=am({access_token:nL(),id_token:nL().optional(),token_type:nL(),expires_in:new n7(r4({type:"number",coerce:!0,checks:[],...eS(void 0)})).optional(),scope:nL().optional(),refresh_token:nL().optional()}).strip(),lj=am({issued_token_type:a$("urn:ietf:params:oauth:token-type:id-jag"),access_token:nL(),token_type:nL().optional(),expires_in:n8().optional(),scope:nL().optional()}).strip(),lA=am({error:nL(),error_description:nL().optional(),error_uri:nL().optional()}),lN=lT.optional().or(a$("").transform(()=>void 0)),lL=am({redirect_uris:ad(lT),token_endpoint_auth_method:nL().optional(),grant_types:ad(nL()).optional(),response_types:ad(nL()).optional(),application_type:nL().optional(),client_name:nL().optional(),client_uri:lT.optional(),logo_uri:lN,scope:nL().optional(),contacts:ad(nL()).optional(),tos_uri:lN,policy_uri:nL().optional(),jwks_uri:lT.optional(),jwks:new ao({type:"any"}).optional(),software_id:nL().optional(),software_version:nL().optional(),software_statement:nL().optional()}).strip(),lz=am({client_id:nL(),client_secret:nL().optional(),client_id_issued_at:n8().optional(),client_secret_expires_at:n8().optional()}).strip(),lM=lL.merge(lz),lZ=am({error:nL(),error_description:nL().optional()}).strip(),lU=am({token:nL(),token_type_hint:nL().optional()}).strip(),lF=Symbol.for("mcp.sdk.errorBrands");function lH(t,r){let i=new Set,n=r;for(;"function"==typeof n;){let t=n.mcpBrand;Object.prototype.hasOwnProperty.call(n,"mcpBrand")&&"string"==typeof t&&i.add(t),n=Object.getPrototypeOf(n)}0!==i.size&&Object.defineProperty(t,lF,{value:i,enumerable:!1,configurable:!0})}function lD(t,r){try{if("object"==typeof r&&null!==r&&Object.prototype.hasOwnProperty.call(t,"mcpBrand")&&"string"==typeof t.mcpBrand&&Object.prototype.hasOwnProperty.call(r,lF)){let i=r[lF];if(i&&"function"==typeof i.has&&i.has(t.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(t,r)}(class t extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return lD(this,t)}static isInstance(t){if("function"!=typeof this)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return lD(this,t)}constructor(t,r,i){super(r),this.code=t,this.errorUri=i,this.name="OAuthError",lH(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(r){return new t(r.error,r.error_description??r.error,r.error_uri)}});let lV=(($={}).NotConnected="NOT_CONNECTED",$.AlreadyConnected="ALREADY_CONNECTED",$.NotInitialized="NOT_INITIALIZED",$.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",$.RequestTimeout="REQUEST_TIMEOUT",$.ConnectionClosed="CONNECTION_CLOSED",$.SendFailed="SEND_FAILED",$.InvalidResult="INVALID_RESULT",$.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",$.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",$.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",$.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",$.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",$.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",$.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",$.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",$.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",$.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",$.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",$);var lJ=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](t){return lD(this,t)}static isInstance(t){if("function"!=typeof this)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return lD(this,t)}constructor(t,r,i){super(r),this.code=t,this.data=i,this.name="SdkError",lH(this,new.target)}};(class extends lJ{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(t,r,i){super(t,r,i),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}});let lB={};function lW(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function lG(t,r){let i={};for(let[n,a]of Object.entries(t)){if(void 0===a)continue;let t=void 0===r?void 0:r[n];if(void 0===t){i[n]=a;continue}if(lW(a)&&lW(t)){let r={};for(let[i,o]of Object.entries(a))void 0!==o&&void 0===t[i]&&("elicitation"!==n||"form"!==i||void 0!==t.form||void 0!==t.url)&&(r[i]=o);Object.keys(r).length>0&&(i[n]=r)}}return Object.keys(i).length>0?i:void 0}let lK="2026-07-28",lY=[lK];function lX(t){return t.filter(t=>t>=lK)}function lQ(t){let r=t.structuredContent;return void 0===r||!("object"!=typeof r||null===r||Array.isArray(r))||t.content?.some(t=>"text"===t.type)?t:{...t,content:[...t.content??[],{type:"text",text:JSON.stringify(r)}]}}let l0=["task","inputRequests","requestState"];function l1(t){return null===t||"object"!=typeof t||Array.isArray(t)||void 0!==t.content||l0.some(r=>r in t)?t:{...t,content:[]}}function l2(){let t,r,n,a,o,s,l,c,u,d,p,m,h,f,g,y,v,_,b,S,w,k,x,R,$,C,T,P,E,O,I,q,j,A,N,L,z,M,Z,U,F,H,D,V,J,B,W,G,K,Y,X,Q,ee,et,er,ei,en,ea,eo,es,el,ec,eu,ed,ep,em,eh,ef,eg,ey,ev,e_,eb,eS,ew,ek,ex,eR,e$,eC,eT,eP,eE,eO,eI,eq,ej,eA,eN,eL,ez,eM,eZ,eU,eF,eH,eD,eV,eJ,eB,eW,eG,eK,eY,eX,eQ,e0,e1,e2,e9,e4,e5,e3,e6,e7,e8,te,tt,tr,ti,tn,ta,to,ts,tl,tc,tu,td,tp,tm,th,tf,tg,ty,tv,t_,tb,tS,tw,tk;return i??=(t=aH(()=>ag([nL(),n8(),ai(),aa(),aw(nL(),t),ad(t)])),r=aw(nL(),t),n=ag([nL(),n8().int()]),a=nL(),o=am({ttl:n8().optional()}),s=am({taskId:nL()}),u=(c=am({_meta:(l=ah({progressToken:n.optional(),"io.modelcontextprotocol/related-task":s.optional()})).optional()})).extend({task:o.optional()}),d=am({method:nL(),params:c.loose().optional()}),p=am({_meta:l.optional()}),m=am({method:nL(),params:p.loose().optional()}),h=ah({_meta:l.optional()}),f=ag([nL(),n8().int()]),g=h.strict(),y=p.extend({requestId:f.optional(),reason:nL().optional()}),v=m.extend({method:a$("notifications/cancelled"),params:y}),_=am({src:nL(),mimeType:nL().optional(),sizes:ad(nL()).optional(),theme:ax(["light","dark"]).optional()}),b=am({icons:ad(_).optional()}),w=(S=am({name:nL(),title:nL().optional()})).extend({...S.shape,...b.shape,version:nL(),websiteUrl:nL().optional(),description:nL().optional()}),k=ab(am({applyDefaults:ai().optional()}),r),x=aV(t=>t&&"object"==typeof t&&!Array.isArray(t)&&0===Object.keys(t).length?{form:{}}:t,ab(am({form:k.optional(),url:r.optional()}),r.optional())),R=ah({list:r.optional(),cancel:r.optional(),requests:ah({sampling:ah({createMessage:r.optional()}).optional(),elicitation:ah({create:r.optional()}).optional()}).optional()}),$=ah({list:r.optional(),cancel:r.optional(),requests:ah({tools:ah({call:r.optional()}).optional()}).optional()}),C=am({experimental:aw(nL(),r).optional(),sampling:am({context:r.optional(),tools:r.optional()}).optional(),elicitation:x.optional(),roots:am({listChanged:ai().optional()}).optional(),tasks:R.optional(),extensions:aw(nL(),r).optional()}),T=c.extend({protocolVersion:nL(),capabilities:C,clientInfo:w}),P=d.extend({method:a$("initialize"),params:T}),E=am({experimental:aw(nL(),r).optional(),logging:r.optional(),completions:r.optional(),prompts:am({listChanged:ai().optional()}).optional(),resources:am({subscribe:ai().optional(),listChanged:ai().optional()}).optional(),tools:am({listChanged:ai().optional()}).optional(),tasks:$.optional(),extensions:aw(nL(),r).optional()}),O=h.extend({protocolVersion:nL(),capabilities:E,serverInfo:w,instructions:nL().optional()}),I=m.extend({method:a$("notifications/initialized"),params:p.optional()}),q=d.extend({method:a$("ping"),params:c.optional()}),j=am({progress:n8(),total:aE(n8()),message:aE(nL())}),A=am({...p.shape,...j.shape,progressToken:n}),N=m.extend({method:a$("notifications/progress"),params:A}),L=c.extend({cursor:a.optional()}),z=d.extend({params:L.optional()}),M=h.extend({nextCursor:a.optional()}),U=(Z=am({uri:nL(),mimeType:aE(nL()),_meta:aw(nL(),al()).optional()})).extend({text:nL()}),F=nL().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),H=Z.extend({blob:F}),V=am({audience:ad(D=ax(["user","assistant"])).optional(),priority:n8().min(0).max(1).optional(),lastModified:r6(nM,{offset:!0}).optional()}),J=am({...S.shape,...b.shape,uri:nL(),description:aE(nL()),mimeType:aE(nL()),size:aE(n8()),annotations:V.optional(),_meta:aE(ah({}))}),B=am({...S.shape,...b.shape,uriTemplate:nL(),description:aE(nL()),mimeType:aE(nL()),annotations:V.optional(),_meta:aE(ah({}))}),W=z.extend({method:a$("resources/list")}),G=M.extend({resources:ad(J)}),K=z.extend({method:a$("resources/templates/list")}),Y=M.extend({resourceTemplates:ad(B)}),X=c.extend({uri:nL()}),Q=d.extend({method:a$("resources/read"),params:X}),ee=h.extend({contents:ad(ag([U,H]))}),et=m.extend({method:a$("notifications/resources/list_changed"),params:p.optional()}),er=d.extend({method:a$("resources/subscribe"),params:X}),ei=d.extend({method:a$("resources/unsubscribe"),params:X}),en=p.extend({uri:nL()}),ea=m.extend({method:a$("notifications/resources/updated"),params:en}),eo=am({name:nL(),description:aE(nL()),required:aE(ai())}),es=am({...S.shape,...b.shape,description:aE(nL()),arguments:aE(ad(eo)),_meta:aE(ah({}))}),el=z.extend({method:a$("prompts/list")}),ec=M.extend({prompts:ad(es)}),eu=c.extend({name:nL(),arguments:aw(nL(),nL()).optional()}),ed=d.extend({method:a$("prompts/get"),params:eu}),ep=am({type:a$("text"),text:nL(),annotations:V.optional(),_meta:aw(nL(),al()).optional()}),em=am({type:a$("image"),data:F,mimeType:nL(),annotations:V.optional(),_meta:aw(nL(),al()).optional()}),eh=am({type:a$("audio"),data:F,mimeType:nL(),annotations:V.optional(),_meta:aw(nL(),al()).optional()}),ef=am({type:a$("tool_use"),name:nL(),id:nL(),input:aw(nL(),al()),_meta:aw(nL(),al()).optional()}),eg=am({type:a$("resource"),resource:ag([U,H]),annotations:V.optional(),_meta:aw(nL(),al()).optional()}),e_=am({role:D,content:ev=ag([ep,em,eh,ey=J.extend({type:a$("resource_link")}),eg])}),eb=h.extend({description:nL().optional(),messages:ad(e_)}),eS=m.extend({method:a$("notifications/prompts/list_changed"),params:p.optional()}),ew=am({title:nL().optional(),readOnlyHint:ai().optional(),destructiveHint:ai().optional(),idempotentHint:ai().optional(),openWorldHint:ai().optional()}),ek=am({taskSupport:ax(["required","optional","forbidden"]).optional()}),ex=am({...S.shape,...b.shape,description:nL().optional(),inputSchema:am({type:a$("object"),properties:aw(nL(),t).optional(),required:ad(nL()).optional()}).catchall(al()),outputSchema:am({type:a$("object"),properties:aw(nL(),t).optional(),required:ad(nL()).optional()}).catchall(al()).optional(),annotations:ew.optional(),execution:ek.optional(),_meta:aw(nL(),al()).optional()}),eR=z.extend({method:a$("tools/list")}),e$=M.extend({tools:ad(ex)}),eC=h.extend({content:ad(ev),structuredContent:aw(nL(),al()).optional(),isError:ai().optional()}),eT=u.extend({name:nL(),arguments:aw(nL(),al()).optional()}),eP=d.extend({method:a$("tools/call"),params:eT}),eE=m.extend({method:a$("notifications/tools/list_changed"),params:p.optional()}),eO=ax(["debug","info","notice","warning","error","critical","alert","emergency"]),eI=c.extend({level:eO}),eq=d.extend({method:a$("logging/setLevel"),params:eI}),ej=p.extend({level:eO,logger:nL().optional(),data:al()}),eA=m.extend({method:a$("notifications/message"),params:ej}),eN=am({name:nL().optional()}),eL=am({hints:ad(eN).optional(),costPriority:n8().min(0).max(1).optional(),speedPriority:n8().min(0).max(1).optional(),intelligencePriority:n8().min(0).max(1).optional()}),ez=am({mode:ax(["auto","required","none"]).optional()}),eM=am({type:a$("tool_result"),toolUseId:nL().describe("The unique identifier for the corresponding tool call."),content:ad(ev),structuredContent:am({}).loose().optional(),isError:ai().optional(),_meta:aw(nL(),al()).optional()}),eZ=av("type",[ep,em,eh]),eF=am({role:D,content:ag([eU=av("type",[ep,em,eh,ef,eM]),ad(eU)]),_meta:aw(nL(),al()).optional()}),eH=u.extend({messages:ad(eF),modelPreferences:eL.optional(),systemPrompt:nL().optional(),includeContext:ax(["none","thisServer","allServers"]).optional(),temperature:n8().optional(),maxTokens:n8().int(),stopSequences:ad(nL()).optional(),metadata:r.optional(),tools:ad(ex).optional(),toolChoice:ez.optional()}),eD=d.extend({method:a$("sampling/createMessage"),params:eH}),eV=h.extend({model:nL(),stopReason:aE(ax(["endTurn","stopSequence","maxTokens"]).or(nL())),role:D,content:eZ}),eJ=h.extend({model:nL(),stopReason:aE(ax(["endTurn","stopSequence","maxTokens","toolUse"]).or(nL())),role:D,content:ag([eU,ad(eU)])}),eB=am({type:a$("boolean"),title:nL().optional(),description:nL().optional(),default:ai().optional()}),eW=am({type:a$("string"),title:nL().optional(),description:nL().optional(),minLength:n8().optional(),maxLength:n8().optional(),format:ax(["email","uri","date","date-time"]).optional(),default:nL().optional()}),eG=am({type:ax(["number","integer"]),title:nL().optional(),description:nL().optional(),minimum:n8().optional(),maximum:n8().optional(),default:n8().optional()}),eK=am({type:a$("string"),title:nL().optional(),description:nL().optional(),enum:ad(nL()),default:nL().optional()}),eY=am({type:a$("string"),title:nL().optional(),description:nL().optional(),oneOf:ad(am({const:nL(),title:nL()})),default:nL().optional()}),eX=am({type:a$("string"),title:nL().optional(),description:nL().optional(),enum:ad(nL()),enumNames:ad(nL()).optional(),default:nL().optional()}),eQ=ag([eK,eY]),e0=am({type:a$("array"),title:nL().optional(),description:nL().optional(),minItems:n8().optional(),maxItems:n8().optional(),items:am({type:a$("string"),enum:ad(nL())}),default:ad(nL()).optional()}),e2=ag([e0,e1=am({type:a$("array"),title:nL().optional(),description:nL().optional(),minItems:n8().optional(),maxItems:n8().optional(),items:am({anyOf:ad(am({const:nL(),title:nL()}))}),default:ad(nL()).optional()})]),e9=ag([eX,eQ,e2]),e4=ag([e9,eB,eW,eG]),e5=u.extend({mode:a$("form").optional(),message:nL(),requestedSchema:am({type:a$("object"),properties:aw(nL(),e4),required:ad(nL()).optional()}).catchall(al())}),e6=ag([e5,e3=u.extend({mode:a$("url"),message:nL(),elicitationId:nL(),url:nL().url()})]),e7=d.extend({method:a$("elicitation/create"),params:e6}),e8=p.extend({elicitationId:nL()}),te=m.extend({method:a$("notifications/elicitation/complete"),params:e8}),tt=h.extend({action:ax(["accept","decline","cancel"]),content:aV(t=>null===t?void 0:t,aw(nL(),ag([nL(),n8(),ai(),ad(nL())])).optional())}),tr=am({type:a$("ref/resource"),uri:nL()}),ti=am({type:a$("ref/prompt"),name:nL()}),tn=c.extend({ref:ag([ti,tr]),argument:am({name:nL(),value:nL()}),context:am({arguments:aw(nL(),nL()).optional()}).optional()}),ta=d.extend({method:a$("completion/complete"),params:tn}),to=h.extend({completion:ah({values:ad(nL()).max(100),total:aE(n8().int()),hasMore:aE(ai())})}),ts=am({uri:nL().startsWith("file://"),name:nL().optional(),_meta:aw(nL(),al()).optional()}),tl=d.extend({method:a$("roots/list"),params:c.optional()}),tc=h.extend({roots:ad(ts)}),tu=m.extend({method:a$("notifications/roots/list_changed"),params:p.optional()}),td=ah({ttl:n8().optional(),pollInterval:n8().optional()}),tp=ax(["working","input_required","completed","failed","cancelled"]),tm=am({taskId:nL(),status:tp,ttl:ag([n8(),aa()]),createdAt:nL(),lastUpdatedAt:nL(),pollInterval:aE(n8()),statusMessage:aE(nL())}),th=h.extend({task:tm}),tf=p.merge(tm),tg=m.extend({method:a$("notifications/tasks/status"),params:tf}),ty=d.extend({method:a$("tasks/get"),params:c.extend({taskId:nL()})}),tv=h.merge(tm),t_=d.extend({method:a$("tasks/result"),params:c.extend({taskId:nL()})}),tb=h.loose(),tS=z.extend({method:a$("tasks/list")}),tw=M.extend({tasks:ad(tm)}),tk=d.extend({method:a$("tasks/cancel"),params:c.extend({taskId:nL()})}),{JSONValueSchema:t,JSONObjectSchema:r,ProgressTokenSchema:n,CursorSchema:a,TaskMetadataSchema:o,RelatedTaskMetadataSchema:s,RequestMetaSchema:l,BaseRequestParamsSchema:c,TaskAugmentedRequestParamsSchema:u,RequestSchema:d,NotificationsParamsSchema:p,NotificationSchema:m,ResultSchema:h,RequestIdSchema:f,EmptyResultSchema:g,CancelledNotificationParamsSchema:y,CancelledNotificationSchema:v,IconSchema:_,IconsSchema:b,BaseMetadataSchema:S,ImplementationSchema:w,ClientTasksCapabilitySchema:R,ServerTasksCapabilitySchema:$,ClientCapabilitiesSchema:C,InitializeRequestParamsSchema:T,InitializeRequestSchema:P,ServerCapabilitiesSchema:E,InitializeResultSchema:O,InitializedNotificationSchema:I,PingRequestSchema:q,ProgressSchema:j,ProgressNotificationParamsSchema:A,ProgressNotificationSchema:N,PaginatedRequestParamsSchema:L,PaginatedRequestSchema:z,PaginatedResultSchema:M,ResourceContentsSchema:Z,TextResourceContentsSchema:U,BlobResourceContentsSchema:H,RoleSchema:D,AnnotationsSchema:V,ResourceSchema:J,ResourceTemplateSchema:B,ListResourcesRequestSchema:W,ListResourcesResultSchema:G,ListResourceTemplatesRequestSchema:K,ListResourceTemplatesResultSchema:Y,ResourceRequestParamsSchema:X,ReadResourceRequestParamsSchema:X,ReadResourceRequestSchema:Q,ReadResourceResultSchema:ee,ResourceListChangedNotificationSchema:et,SubscribeRequestParamsSchema:X,SubscribeRequestSchema:er,UnsubscribeRequestParamsSchema:X,UnsubscribeRequestSchema:ei,ResourceUpdatedNotificationParamsSchema:en,ResourceUpdatedNotificationSchema:ea,PromptArgumentSchema:eo,PromptSchema:es,ListPromptsRequestSchema:el,ListPromptsResultSchema:ec,GetPromptRequestParamsSchema:eu,GetPromptRequestSchema:ed,TextContentSchema:ep,ImageContentSchema:em,AudioContentSchema:eh,ToolUseContentSchema:ef,EmbeddedResourceSchema:eg,ResourceLinkSchema:ey,ContentBlockSchema:ev,PromptMessageSchema:e_,GetPromptResultSchema:eb,PromptListChangedNotificationSchema:eS,ToolAnnotationsSchema:ew,ToolExecutionSchema:ek,ToolSchema:ex,ListToolsRequestSchema:eR,ListToolsResultSchema:e$,CallToolResultSchema:eC,CallToolRequestParamsSchema:eT,CallToolRequestSchema:eP,ToolListChangedNotificationSchema:eE,LoggingLevelSchema:eO,SetLevelRequestParamsSchema:eI,SetLevelRequestSchema:eq,LoggingMessageNotificationParamsSchema:ej,LoggingMessageNotificationSchema:eA,ModelHintSchema:eN,ModelPreferencesSchema:eL,ToolChoiceSchema:ez,ToolResultContentSchema:eM,SamplingContentSchema:eZ,SamplingMessageContentBlockSchema:eU,SamplingMessageSchema:eF,CreateMessageRequestParamsSchema:eH,CreateMessageRequestSchema:eD,CreateMessageResultSchema:eV,CreateMessageResultWithToolsSchema:eJ,BooleanSchemaSchema:eB,StringSchemaSchema:eW,NumberSchemaSchema:eG,UntitledSingleSelectEnumSchemaSchema:eK,TitledSingleSelectEnumSchemaSchema:eY,LegacyTitledEnumSchemaSchema:eX,SingleSelectEnumSchemaSchema:eQ,UntitledMultiSelectEnumSchemaSchema:e0,TitledMultiSelectEnumSchemaSchema:e1,MultiSelectEnumSchemaSchema:e2,EnumSchemaSchema:e9,PrimitiveSchemaDefinitionSchema:e4,ElicitRequestFormParamsSchema:e5,ElicitRequestURLParamsSchema:e3,ElicitRequestParamsSchema:e6,ElicitRequestSchema:e7,ElicitationCompleteNotificationParamsSchema:e8,ElicitationCompleteNotificationSchema:te,ElicitResultSchema:tt,ResourceTemplateReferenceSchema:tr,PromptReferenceSchema:ti,CompleteRequestParamsSchema:tn,CompleteRequestSchema:ta,CompleteResultSchema:to,RootSchema:ts,ListRootsRequestSchema:tl,ListRootsResultSchema:tc,RootsListChangedNotificationSchema:tu,TaskCreationParamsSchema:td,TaskStatusSchema:tp,TaskSchema:tm,CreateTaskResultSchema:th,TaskStatusNotificationParamsSchema:tf,TaskStatusNotificationSchema:tg,GetTaskRequestSchema:ty,GetTaskResultSchema:tv,GetTaskPayloadRequestSchema:t_,GetTaskPayloadResultSchema:tb,ListTasksRequestSchema:tS,ListTasksResultSchema:tw,CancelTaskRequestSchema:tk,CancelTaskResultSchema:h.merge(tm),ClientRequestSchema:ag([q,P,ta,eq,ed,el,W,K,Q,er,ei,eP,eR,ty,t_,tS,tk]),ClientNotificationSchema:ag([v,N,I,tu,tg]),ClientResultSchema:ag([g,eV,eJ,tt,tc,tv,tw,th]),ServerRequestSchema:ag([q,eD,e7,tl,ty,t_,tS,tk]),ServerNotificationSchema:ag([v,N,eA,ea,et,eE,eS,tg,te]),ServerResultSchema:ag([g,O,to,eb,ec,G,Y,ee,eC,e$,tv,tw,th]),CallToolResultWireSchema:al().superRefine((t,r)=>{if(!("object"!=typeof t||null===t||Array.isArray(t))&&void 0===t.content){for(let i of l0)if(i in t)return void r.addIssue({code:"custom",message:`content is required when the body carries '${i}' — another result family cannot default into an empty tools/call success`})}}).transform(l1).pipe(eC)})}function l9(t){return"object"!==t.type}let l4=new Set(["const","enum","default","examples"]),l5=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function l3(t){return void 0!==t&&!("string"==typeof t&&t.startsWith("#"))}let l6={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},l7={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},l8={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};function ce(){if(n)return n;let t=l2();return n={requestSchemas:{ping:t.PingRequestSchema,initialize:t.InitializeRequestSchema,"completion/complete":t.CompleteRequestSchema,"logging/setLevel":t.SetLevelRequestSchema,"prompts/get":t.GetPromptRequestSchema,"prompts/list":t.ListPromptsRequestSchema,"resources/list":t.ListResourcesRequestSchema,"resources/templates/list":t.ListResourceTemplatesRequestSchema,"resources/read":t.ReadResourceRequestSchema,"resources/subscribe":t.SubscribeRequestSchema,"resources/unsubscribe":t.UnsubscribeRequestSchema,"tools/call":t.CallToolRequestSchema,"tools/list":t.ListToolsRequestSchema,"tasks/get":t.GetTaskRequestSchema,"tasks/result":t.GetTaskPayloadRequestSchema,"tasks/list":t.ListTasksRequestSchema,"tasks/cancel":t.CancelTaskRequestSchema,"sampling/createMessage":t.CreateMessageRequestSchema,"elicitation/create":t.ElicitRequestSchema,"roots/list":t.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":t.CancelledNotificationSchema,"notifications/progress":t.ProgressNotificationSchema,"notifications/initialized":t.InitializedNotificationSchema,"notifications/roots/list_changed":t.RootsListChangedNotificationSchema,"notifications/tasks/status":t.TaskStatusNotificationSchema,"notifications/message":t.LoggingMessageNotificationSchema,"notifications/resources/updated":t.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":t.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":t.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":t.PromptListChangedNotificationSchema,"notifications/elicitation/complete":t.ElicitationCompleteNotificationSchema},resultSchemas:{ping:t.EmptyResultSchema,initialize:t.InitializeResultSchema,"completion/complete":t.CompleteResultSchema,"logging/setLevel":t.EmptyResultSchema,"prompts/get":t.GetPromptResultSchema,"prompts/list":t.ListPromptsResultSchema,"resources/list":t.ListResourcesResultSchema,"resources/templates/list":t.ListResourceTemplatesResultSchema,"resources/read":t.ReadResourceResultSchema,"resources/subscribe":t.EmptyResultSchema,"resources/unsubscribe":t.EmptyResultSchema,"tools/call":t.CallToolResultWireSchema,"tools/list":t.ListToolsResultSchema,"sampling/createMessage":t.CreateMessageResultWithToolsSchema,"elicitation/create":t.ElicitResultSchema,"roots/list":t.ListRootsResultSchema}}}function ct(t){return Object.prototype.hasOwnProperty.call(l6,t)}function cr(t){return Object.prototype.hasOwnProperty.call(l7,t)}function ci(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function cn(t,r){if(void 0===t)return{ok:!1,reason:"not-in-era"};let i=t.safeParse(r);return i.success?{ok:!0,value:i.data}:{ok:!1,reason:"invalid",message:String(i.error)}}Object.keys(l6),Object.keys(l7);let ca={ok:!1,reason:"not-in-era"};function co(t){return ci(t)&&ci(t.outputSchema)&&l9(t.outputSchema)}let cs={era:"2025-11-25",hasRequestMethod:ct,hasNotificationMethod:cr,validateRequest:(t,r)=>cn(ct(t)?ce().requestSchemas[t]:void 0,r),validateResult:(t,r)=>cn(Object.prototype.hasOwnProperty.call(l8,t)?ce().resultSchemas[t]:void 0,r),validateNotification:(t,r)=>cn(cr(t)?ce().notificationSchemas[t]:void 0,r),hasInputRequestMethod:()=>!1,validateInputRequest:()=>ca,validateInputResponse:()=>ca,samplingResultVariant:(t,r)=>{let i=l2();return cn(t?i.CreateMessageResultWithToolsSchema:i.CreateMessageResultSchema,r)},outboundEnvelope:t=>void 0,validateEnvelopeMeta:t=>[],projectCallToolResult(t,r){let i=lQ(t),n=i.structuredContent;if(void 0===n)return i;let a="object"!=typeof n||null===n||Array.isArray(n),o=void 0!==r&&l9(r);return a||o?{...i,structuredContent:{result:n}}:i},decodeResult(t,r){if(ci(r)&&"resultType"in r){let t={...r};return delete t.resultType,{kind:"complete",result:t}}return{kind:"complete",result:r}},encodeResult(t,r){if("tools/list"!==t)return r;let i=r.tools;return Array.isArray(i)&&i.some(t=>co(t))?{...r,tools:i.map(t=>co(t)?{...t,outputSchema:function(t){var r;let i="string"==typeof t.$schema?t.$schema:void 0;if(l3(t.$id))return{...void 0!==i&&{$schema:i},type:"object",properties:{result:t},required:["result"]};let n="string"==typeof(r=t.$schema)&&K.has(r.replace(/#$/,""))&&!0!==t.$recursiveAnchor,a=(t,r)=>{if(Array.isArray(t))return t.map(t=>a(t,!1));if(null===t||"object"!=typeof t||!r&&l3(t.$id))return t;let i={},o=!1;for(let[s,l]of Object.entries(t))r?i[s]=a(l,!1):("$ref"===s||"$dynamicRef"===s)&&"string"==typeof l?i[s]="#"===l?"#/properties/result":l.startsWith("#/")?`#/properties/result${l.slice(1)}`:l:"$recursiveRef"===s&&"#"===l&&n?o=!0:l4.has(s)?i[s]=l:l5.has(s)?i[s]=a(l,!0):i[s]=a(l,!1);return o&&("$ref"in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:"#/properties/result"}]:i.$ref="#/properties/result"),i};return{...void 0!==i&&{$schema:i},type:"object",properties:{result:a(t,!1)},required:["result"]}}(t.outputSchema)}:t)}:r},encodeErrorCode:t=>-32002===t?-32602:t,checkInboundEnvelope:t=>void 0};function cl(){return a??=function(){let t=aH(()=>ag([nL(),n8(),ai(),aa(),aw(nL(),t),ad(t)])),r=aw(nL(),t),i=ag([nL(),n8().int()]),n=nL(),a=ag([nL(),n8().int()]),o=ax(["user","assistant"]),s=ax(["debug","info","notice","warning","error","critical","alert","emergency"]),l=nL().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),c=am({ttl:n8().optional()}),u=am({taskId:nL()}),d=ah({progressToken:i.optional(),"io.modelcontextprotocol/related-task":u.optional()}),p=am({_meta:d.optional()}),m=p.extend({task:c.optional()}),h=am({_meta:d.optional()}),f=am({method:nL(),params:h.loose().optional()}),g=am({src:nL(),mimeType:nL().optional(),sizes:ad(nL()).optional(),theme:ax(["light","dark"]).optional()}),y=am({icons:ad(g).optional()}),v=am({name:nL(),title:nL().optional()}),_=v.extend({...v.shape,...y.shape,version:nL(),websiteUrl:nL().optional(),description:nL().optional()}),b=ab(am({applyDefaults:ai().optional()}),r),S=aV(t=>t&&"object"==typeof t&&!Array.isArray(t)&&0===Object.keys(t).length?{form:{}}:t,ab(am({form:b.optional(),url:r.optional()}),r.optional())),w=ah({list:r.optional(),cancel:r.optional(),requests:ah({sampling:ah({createMessage:r.optional()}).optional(),elicitation:ah({create:r.optional()}).optional()}).optional()}),k=ah({list:r.optional(),cancel:r.optional(),requests:ah({tools:ah({call:r.optional()}).optional()}).optional()}),x=am({experimental:aw(nL(),r).optional(),sampling:am({context:r.optional(),tools:r.optional()}).optional(),elicitation:S.optional(),roots:am({listChanged:ai().optional()}).optional(),tasks:w.optional(),extensions:aw(nL(),r).optional()}),R=am({experimental:aw(nL(),r).optional(),logging:r.optional(),completions:r.optional(),prompts:am({listChanged:ai().optional()}).optional(),resources:am({subscribe:ai().optional(),listChanged:ai().optional()}).optional(),tools:am({listChanged:ai().optional()}).optional(),tasks:k.optional(),extensions:aw(nL(),r).optional()}),$=am({progress:n8(),total:aE(n8()),message:aE(nL())}),C=am({...h.shape,...$.shape,progressToken:i}),T=f.extend({method:a$("notifications/progress"),params:C}),P=h.extend({level:s,logger:nL().optional(),data:al()}),E=f.extend({method:a$("notifications/message"),params:P}),O=am({uri:nL(),mimeType:aE(nL()),_meta:aw(nL(),al()).optional()}),I=O.extend({text:nL()}),q=O.extend({blob:l}),j=am({audience:ad(o).optional(),priority:n8().min(0).max(1).optional(),lastModified:r6(nM,{offset:!0}).optional()}),A=am({...v.shape,...y.shape,uri:nL(),description:aE(nL()),mimeType:aE(nL()),size:aE(n8()),annotations:j.optional(),_meta:aE(ah({}))}),N=am({...v.shape,...y.shape,uriTemplate:nL(),description:aE(nL()),mimeType:aE(nL()),annotations:j.optional(),_meta:aE(ah({}))}),L=f.extend({method:a$("notifications/resources/list_changed"),params:h.optional()}),z=h.extend({uri:nL()}),M=f.extend({method:a$("notifications/resources/updated"),params:z}),Z=am({name:nL(),description:aE(nL()),required:aE(ai())}),U=am({...v.shape,...y.shape,description:aE(nL()),arguments:aE(ad(Z)),_meta:aE(ah({}))}),F=f.extend({method:a$("notifications/prompts/list_changed"),params:h.optional()}),H=am({type:a$("text"),text:nL(),annotations:j.optional(),_meta:aw(nL(),al()).optional()}),D=am({type:a$("image"),data:l,mimeType:nL(),annotations:j.optional(),_meta:aw(nL(),al()).optional()}),V=am({type:a$("audio"),data:l,mimeType:nL(),annotations:j.optional(),_meta:aw(nL(),al()).optional()}),J=am({type:a$("tool_use"),name:nL(),id:nL(),input:aw(nL(),al()),_meta:aw(nL(),al()).optional()}),B=am({type:a$("resource"),resource:ag([I,q]),annotations:j.optional(),_meta:aw(nL(),al()).optional()}),W=A.extend({type:a$("resource_link")}),G=ag([H,D,V,W,B]),K=am({role:o,content:G}),Y=am({title:nL().optional(),readOnlyHint:ai().optional(),destructiveHint:ai().optional(),idempotentHint:ai().optional(),openWorldHint:ai().optional()}),X=f.extend({method:a$("notifications/tools/list_changed"),params:h.optional()}),Q=am({name:nL().optional()}),ee=am({hints:ad(Q).optional(),costPriority:n8().min(0).max(1).optional(),speedPriority:n8().min(0).max(1).optional(),intelligencePriority:n8().min(0).max(1).optional()}),et=am({mode:ax(["auto","required","none"]).optional()}),er=am({type:a$("boolean"),title:nL().optional(),description:nL().optional(),default:ai().optional()}),ei=am({type:a$("string"),title:nL().optional(),description:nL().optional(),minLength:n8().optional(),maxLength:n8().optional(),format:ax(["email","uri","date","date-time"]).optional(),default:nL().optional()}),en=am({type:ax(["number","integer"]),title:nL().optional(),description:nL().optional(),minimum:n8().optional(),maximum:n8().optional(),default:n8().optional()}),ea=am({type:a$("string"),title:nL().optional(),description:nL().optional(),enum:ad(nL()),default:nL().optional()}),eo=am({type:a$("string"),title:nL().optional(),description:nL().optional(),oneOf:ad(am({const:nL(),title:nL()})),default:nL().optional()}),es=am({type:a$("string"),title:nL().optional(),description:nL().optional(),enum:ad(nL()),enumNames:ad(nL()).optional(),default:nL().optional()}),el=ag([ea,eo]),ec=am({type:a$("array"),title:nL().optional(),description:nL().optional(),minItems:n8().optional(),maxItems:n8().optional(),items:am({type:a$("string"),enum:ad(nL())}),default:ad(nL()).optional()}),eu=am({type:a$("array"),title:nL().optional(),description:nL().optional(),minItems:n8().optional(),maxItems:n8().optional(),items:am({anyOf:ad(am({const:nL(),title:nL()}))}),default:ad(nL()).optional()}),ed=ag([ec,eu]),ep=ag([es,el,ed]),em=ag([ep,er,ei,en]),eh=m.extend({mode:a$("form").optional(),message:nL(),requestedSchema:am({type:a$("object"),properties:aw(nL(),em),required:ad(nL()).optional()}).catchall(al())}),ef=am({type:a$("ref/resource"),uri:nL()}),eg=am({type:a$("ref/prompt"),name:nL()}),ey=am({uri:nL().startsWith("file://"),name:nL().optional(),_meta:aw(nL(),al()).optional()}),ev=x.shape,e_=am({experimental:ev.experimental,sampling:ev.sampling,elicitation:ev.elicitation,roots:ev.roots,extensions:ev.extensions}),eb=R.shape,eS=am({experimental:eb.experimental,logging:eb.logging,completions:eb.completions,prompts:eb.prompts,resources:eb.resources,tools:eb.tools,extensions:eb.extensions}),ew=ah({progressToken:i.optional(),[aW]:nL(),[aG]:_.optional(),[aY]:e_,[aQ]:s.optional()}),ek=am({...v.shape,...y.shape,description:nL().optional(),inputSchema:ah({$schema:nL().optional(),type:a$("object")}),outputSchema:ah({$schema:nL().optional()}).optional(),annotations:Y.optional(),_meta:aw(nL(),al()).optional()}),ex=am({type:a$("tool_result"),toolUseId:nL(),content:ad(G),structuredContent:al().optional(),isError:ai().optional(),_meta:aw(nL(),al()).optional()}),eR=ag([H,D,V,J,ex]),e$=am({role:o,content:ag([eR,ad(eR)]),_meta:aw(nL(),al()).optional()}),eC=nL(),eT=ah({[aK]:_.optional().catch(void 0)}),eP=eT.optional();function eE(t){return ah({_meta:eP,resultType:eC.default("complete"),...t})}let eO=eE({}),eI=eE({nextCursor:n.optional()}),eq=eE({content:ad(G),structuredContent:al().optional(),isError:ai().optional()}),ej=eE({ttlMs:n8().int().min(0),cacheScope:ax(["public","private"]),tools:ad(ek),nextCursor:n.optional()}),eA=eE({ttlMs:n8().int().min(0),cacheScope:ax(["public","private"]),prompts:ad(U),nextCursor:n.optional()}),eN=eE({description:nL().optional(),messages:ad(K)}),eL=eE({ttlMs:n8().int().min(0),cacheScope:ax(["public","private"]),resources:ad(A),nextCursor:n.optional()}),ez=eE({ttlMs:n8().int().min(0),cacheScope:ax(["public","private"]),resourceTemplates:ad(N),nextCursor:n.optional()}),eM=eE({ttlMs:n8().int().min(0),cacheScope:ax(["public","private"]),contents:ad(ag([I,q]))}),eZ=eE({completion:am({values:ad(nL()).max(100),total:n8().int().optional(),hasMore:ai().optional()}).loose()}),eU=eE({ttlMs:n8().int().min(0),cacheScope:ax(["public","private"])}),eF=eE({ttlMs:n8().int().min(0).catch(0),cacheScope:ax(["public","private"]).catch("private"),supportedVersions:ad(nL()),capabilities:eS,instructions:nL().optional()}),eH=am({messages:ad(e$),modelPreferences:ee.optional(),systemPrompt:nL().optional(),includeContext:ax(["none","thisServer","allServers"]).optional(),temperature:n8().optional(),maxTokens:n8().int(),stopSequences:ad(nL()).optional(),metadata:r.optional(),tools:ad(ek).optional(),toolChoice:et.optional()}),eD=am({method:a$("sampling/createMessage"),params:eH}),eV=am({method:a$("roots/list"),params:am({_meta:aw(nL(),al()).optional()}).optional()}),eJ=am({...e$.shape,model:nL(),stopReason:nL().optional()}),eB=am({roots:ad(ey)}),eW=am({action:ax(["accept","decline","cancel"]),content:aw(nL(),ag([nL(),n8(),ai(),ad(nL())])).optional()}),eG=am({mode:a$("url"),message:nL(),url:nL().url()}),eK=ag([eh,eG]),eY=am({method:a$("elicitation/create"),params:eK}),eX=ag([eD,eV,eY]),eQ=ag([eJ,eB,eW]),e0=aw(nL(),eX),e1=aw(nL(),eQ),e2=eE({inputRequests:e0.optional(),requestState:nL().optional()}),e9={inputResponses:e1.optional(),requestState:nL().optional()},e4=am({_meta:ew,...e9}),e5=ah({progressToken:i.optional()});function e3(t,r){return am({method:a$(t),params:am({_meta:ew,...r})})}function e6(t,r){return am({method:a$(t),params:am({_meta:e5.optional(),...r}).optional()})}let e7={name:nL(),arguments:aw(nL(),al()).optional(),...e9},e8={cursor:n.optional()},te=e3("tools/call",e7),tt=e3("tools/list",e8),tr=e3("prompts/list",e8),ti=e3("prompts/get",{name:nL(),arguments:aw(nL(),nL()).optional(),...e9}),tn=e3("resources/list",e8),ta=e3("resources/templates/list",e8),to=e3("resources/read",{uri:nL(),...e9}),ts={ref:ag([eg,ef]),argument:am({name:nL(),value:nL()}),context:am({arguments:aw(nL(),nL()).optional()}).optional()},tl=e3("completion/complete",ts),tc=e3("server/discover",{}),tu=am({toolsListChanged:ai().optional(),promptsListChanged:ai().optional(),resourcesListChanged:ai().optional(),resourceSubscriptions:ad(nL()).optional()}),td={notifications:tu},tp=e3("subscriptions/listen",td),tm=eT.extend({"io.modelcontextprotocol/subscriptionId":a}),th=ah({_meta:tm,resultType:eC.default("complete")}),tf={"tools/call":e6("tools/call",e7),"tools/list":e6("tools/list",e8),"prompts/get":e6("prompts/get",{name:nL(),arguments:aw(nL(),nL()).optional()}),"prompts/list":e6("prompts/list",e8),"resources/list":e6("resources/list",e8),"resources/templates/list":e6("resources/templates/list",e8),"resources/read":e6("resources/read",{uri:nL()}),"completion/complete":e6("completion/complete",ts),"server/discover":e6("server/discover",{}),"subscriptions/listen":e6("subscriptions/listen",td)};function tg(t){return ah({_meta:eP,...t})}let ty={"tools/call":tg({content:ad(G),structuredContent:al().optional(),isError:ai().optional()}),"tools/list":tg({ttlMs:n8().int().min(0),cacheScope:ax(["public","private"]),tools:ad(ek),nextCursor:n.optional()}),"prompts/get":tg({description:nL().optional(),messages:ad(K)}),"prompts/list":tg({ttlMs:n8().int().min(0),cacheScope:ax(["public","private"]),prompts:ad(U),nextCursor:n.optional()}),"resources/list":tg({ttlMs:n8().int().min(0),cacheScope:ax(["public","private"]),resources:ad(A),nextCursor:n.optional()}),"resources/templates/list":tg({ttlMs:n8().int().min(0),cacheScope:ax(["public","private"]),resourceTemplates:ad(N),nextCursor:n.optional()}),"resources/read":tg({ttlMs:n8().int().min(0),cacheScope:ax(["public","private"]),contents:ad(ag([I,q]))}),"completion/complete":tg({completion:am({values:ad(nL()).max(100),total:n8().int().optional(),hasMore:ai().optional()}).loose()}),"server/discover":tg({ttlMs:n8().int().min(0).catch(0),cacheScope:ax(["public","private"]).catch("private"),supportedVersions:ad(nL()),capabilities:eS,instructions:nL().optional()}),"subscriptions/listen":tg({})},tv=ah({"io.modelcontextprotocol/subscriptionId":a.optional()}),t_=am({method:a$("notifications/subscriptions/acknowledged"),params:am({_meta:tv.optional(),notifications:tu})}),tb=am({_meta:tv.optional(),requestId:a,reason:nL().optional()}),tS=am({method:a$("notifications/cancelled"),params:tb}),tw=t=>am({jsonrpc:a$("2.0"),id:ag([nL(),n8().int()]),result:t}).strict();return{JSONValueSchema:t,JSONObjectSchema:r,ProgressTokenSchema:i,CursorSchema:n,RequestIdSchema:a,RoleSchema:o,LoggingLevelSchema:s,TaskMetadataSchema:c,RelatedTaskMetadataSchema:u,RequestMetaSchema:d,BaseRequestParamsSchema:p,TaskAugmentedRequestParamsSchema:m,NotificationsParamsSchema:h,NotificationSchema:f,IconSchema:g,IconsSchema:y,BaseMetadataSchema:v,ImplementationSchema:_,ClientTasksCapabilitySchema:w,ServerTasksCapabilitySchema:k,ClientCapabilitiesSchema:x,ServerCapabilitiesSchema:R,ProgressSchema:$,ProgressNotificationParamsSchema:C,ProgressNotificationSchema:T,LoggingMessageNotificationParamsSchema:P,LoggingMessageNotificationSchema:E,ResourceContentsSchema:O,TextResourceContentsSchema:I,BlobResourceContentsSchema:q,AnnotationsSchema:j,ResourceSchema:A,ResourceTemplateSchema:N,ResourceListChangedNotificationSchema:L,ResourceUpdatedNotificationParamsSchema:z,ResourceUpdatedNotificationSchema:M,PromptArgumentSchema:Z,PromptSchema:U,PromptListChangedNotificationSchema:F,TextContentSchema:H,ImageContentSchema:D,AudioContentSchema:V,ToolUseContentSchema:J,EmbeddedResourceSchema:B,ResourceLinkSchema:W,ContentBlockSchema:G,PromptMessageSchema:K,ToolAnnotationsSchema:Y,ToolListChangedNotificationSchema:X,ModelHintSchema:Q,ModelPreferencesSchema:ee,ToolChoiceSchema:et,BooleanSchemaSchema:er,StringSchemaSchema:ei,NumberSchemaSchema:en,UntitledSingleSelectEnumSchemaSchema:ea,TitledSingleSelectEnumSchemaSchema:eo,LegacyTitledEnumSchemaSchema:es,SingleSelectEnumSchemaSchema:el,UntitledMultiSelectEnumSchemaSchema:ec,TitledMultiSelectEnumSchemaSchema:eu,MultiSelectEnumSchemaSchema:ed,EnumSchemaSchema:ep,PrimitiveSchemaDefinitionSchema:em,ElicitRequestFormParamsSchema:eh,ResourceTemplateReferenceSchema:ef,PromptReferenceSchema:eg,RootSchema:ey,ClientCapabilities2026Schema:e_,ServerCapabilities2026Schema:eS,RequestMetaEnvelopeSchema:ew,ToolSchema:ek,ToolResultContentSchema:ex,SamplingMessageContentBlockSchema:eR,SamplingMessageSchema:e$,ResultTypeSchema:eC,ResultMetaSchema:eT,ResultSchema:eO,PaginatedResultSchema:eI,CallToolResultSchema:eq,ListToolsResultSchema:ej,ListPromptsResultSchema:eA,GetPromptResultSchema:eN,ListResourcesResultSchema:eL,ListResourceTemplatesResultSchema:ez,ReadResourceResultSchema:eM,CompleteResultSchema:eZ,CacheableResultSchema:eU,DiscoverResultSchema:eF,CreateMessageRequestParamsSchema:eH,CreateMessageRequestSchema:eD,ListRootsRequestSchema:eV,CreateMessageResultSchema:eJ,ListRootsResultSchema:eB,ElicitResultSchema:eW,ElicitRequestURLParamsSchema:eG,ElicitRequestParamsSchema:eK,ElicitRequestSchema:eY,InputRequestSchema:eX,InputResponseSchema:eQ,InputRequestsSchema:e0,InputResponsesSchema:e1,InputRequiredResultSchema:e2,InputResponseRequestParamsSchema:e4,CallToolRequestSchema:te,ListToolsRequestSchema:tt,ListPromptsRequestSchema:tr,GetPromptRequestSchema:ti,ListResourcesRequestSchema:tn,ListResourceTemplatesRequestSchema:ta,ReadResourceRequestSchema:to,CompleteRequestSchema:tl,DiscoverRequestSchema:tc,SubscriptionFilterSchema:tu,SubscriptionsListenRequestSchema:tp,SubscriptionsListenResultMetaSchema:tm,SubscriptionsListenResultSchema:th,dispatchRequestSchemas:tf,dispatchResultSchemas:ty,NotificationMetaSchema:tv,SubscriptionsAcknowledgedNotificationSchema:t_,CancelledNotificationParamsSchema:tb,CancelledNotificationSchema:tS,notificationSchemas2026:{"notifications/cancelled":tS,"notifications/progress":T,"notifications/message":E,"notifications/resources/updated":M,"notifications/resources/list_changed":L,"notifications/tools/list_changed":X,"notifications/prompts/list_changed":F,"notifications/subscriptions/acknowledged":t_},JSONRPCResultResponseSchema:tw(eO),CallToolResultResponseSchema:tw(ag([eq,e2])),ListToolsResultResponseSchema:tw(ej),ListPromptsResultResponseSchema:tw(eA),GetPromptResultResponseSchema:tw(ag([eN,e2])),ListResourcesResultResponseSchema:tw(eL),ListResourceTemplatesResultResponseSchema:tw(ez),ReadResourceResultResponseSchema:tw(ag([eM,e2])),CompleteResultResponseSchema:tw(eZ),DiscoverResultResponseSchema:tw(eF)}}()}let cc=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"],cu=Symbol("modelcontextprotocol.resultCacheHintFallback");function cd(t,r){if(void 0===r)return t;let i=t[cu];if(void 0===i)return{...t,[cu]:r};let n={},a=i.ttlMs??r.ttlMs;void 0!==a&&(n.ttlMs=a);let o=i.cacheScope??r.cacheScope;return void 0!==o&&(n.cacheScope=o),{...t,[cu]:n}}function cp(t){return"number"==typeof t&&Number.isSafeInteger(t)&&t>=0}function cm(t){return"public"===t||"private"===t}function ch(t,r){if(void 0!==t.ttlMs&&!cp(t.ttlMs))throw RangeError(`Invalid cache hint for ${r}: ttlMs must be a non-negative safe integer (got ${String(t.ttlMs)})`);if(void 0!==t.cacheScope&&!cm(t.cacheScope))throw RangeError(`Invalid cache hint for ${r}: cacheScope must be 'public' or 'private' (got ${String(t.cacheScope)})`)}let cf=((C={})[C.ParseError=-32700]="ParseError",C[C.InvalidRequest=-32600]="InvalidRequest",C[C.MethodNotFound=-32601]="MethodNotFound",C[C.InvalidParams=-32602]="InvalidParams",C[C.InternalError=-32603]="InternalError",C[C.ResourceNotFound=-32002]="ResourceNotFound",C[C.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",C[C.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",C[C.UrlElicitationRequired=-32042]="UrlElicitationRequired",C);var cg=class t extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return lD(this,t)}static isInstance(t){if("function"!=typeof this)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return lD(this,t)}constructor(t,r,i){super(r),this.code=t,this.data=i,this.name="ProtocolError",lH(this,new.target)}static fromError(r,i,n){return r===cf.UrlElicitationRequired&&n&&n.elicitations?new cv(n.elicitations,i):r===cf.UnsupportedProtocolVersion&&n&&Array.isArray(n.supported)&&"string"==typeof n.requested?new c_({supported:n.supported,requested:n.requested},i):(r===cf.InvalidParams||r===cf.ResourceNotFound)&&"string"==typeof n?.uri&&(r===cf.ResourceNotFound||1===Object.keys(n).length)?new cy(n.uri,i):r===cf.MissingRequiredClientCapability&&n&&null!==n.requiredCapabilities&&"object"==typeof n.requiredCapabilities&&!Array.isArray(n.requiredCapabilities)?new cb({requiredCapabilities:n.requiredCapabilities},i):new t(r,i,n)}},cy=class extends cg{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(t,r=`Resource not found: ${t}`){super(cf.InvalidParams,r,{uri:t})}get uri(){return this.data.uri}},cv=class extends cg{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(cf.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}},c_=class extends cg{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(t,r=`Unsupported protocol version: ${t.requested}`){super(cf.UnsupportedProtocolVersion,r,t)}get supported(){return this.data.supported}get requested(){return this.data.requested}},cb=class extends cg{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(t,r=`Missing required client capabilities: ${Object.keys(t.requiredCapabilities).join(", ")}`){super(cf.MissingRequiredClientCapability,r,t)}get requiredCapabilities(){return this.data.requiredCapabilities}};let cS=["tools/call","prompts/get","resources/read"],cw=["elicitation/create","sampling/createMessage","roots/list"];function ck(){if(o)return o;let t=cl();return o={request:{"elicitation/create":am({method:a$("elicitation/create"),params:t.ElicitRequestParamsSchema}),"sampling/createMessage":am({method:a$("sampling/createMessage"),params:t.CreateMessageRequestParamsSchema}),"roots/list":am({method:a$("roots/list"),params:ah({}).optional()})},response:{"elicitation/create":t.ElicitResultSchema,"sampling/createMessage":t.CreateMessageResultSchema,"roots/list":t.ListRootsResultSchema}}}function cx(t){return cw.includes(t)}function cR(t){return cx(t)?ck().request[t]:void 0}let c$={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},cC={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function cT(t){return Object.prototype.hasOwnProperty.call(c$,t)}function cP(t){return Object.prototype.hasOwnProperty.call(cC,t)}function cE(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function cO(t,r){if(void 0===t)return{ok:!1,reason:"not-in-era"};let i=t.safeParse(r);return i.success?{ok:!0,value:i.data}:{ok:!1,reason:"invalid",message:String(i.error)}}Object.keys(c$),Object.keys(cC);let cI={ok:!1,reason:"not-in-era"},cq=[aW,aY],cj={era:"2026-07-28",hasRequestMethod:cT,hasNotificationMethod:cP,hasInputRequestMethod:t=>void 0!==cR(t),validateRequest:(t,r)=>cO(cT(t)?cl().dispatchRequestSchemas[t]:void 0,r),validateResult:(t,r)=>cO(Object.prototype.hasOwnProperty.call(c$,t)?cl().dispatchResultSchemas[t]:void 0,r),validateNotification:(t,r)=>cO(cP(t)?cl().notificationSchemas2026[t]:void 0,r),validateInputRequest:(t,r)=>cO(cR(t),r),validateInputResponse:(t,r)=>cO(cx(t)?ck().response[t]:void 0,r),samplingResultVariant:()=>cI,outboundEnvelope:t=>({[aW]:t.protocolVersion,[aG]:t.clientInfo,[aY]:t.clientCapabilities,...void 0!==t.logLevel&&{[aQ]:t.logLevel}}),validateEnvelopeMeta(t){let r=[];for(let i of cq)i in t||r.push({key:i,problem:"missing"});let i=cl().RequestMetaEnvelopeSchema.safeParse(t);if(!i.success)for(let t of i.error.issues){let i=t.path.map(String),n=i.length>0?i.join("."):"_meta";1===i.length&&r.some(t=>t.key===n&&"missing"===t.problem)||r.push({key:n,problem:t.message})}return r},projectCallToolResult:t=>lQ(t),inputRequestSchema:cR,decodeResult(t,r){if(!cE(r))return{kind:"invalid",error:new lJ(lV.InvalidResult,`Invalid result for ${t}: not an object`,{method:t})};let i=r.resultType;if(void 0===i)return{kind:"invalid",error:new lJ(lV.InvalidResult,`Invalid result for ${t}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:t,violation:"missing-resultType"})};if("string"!=typeof i)return{kind:"invalid",error:new lJ(lV.InvalidResult,`Invalid result for ${t}: non-string resultType`,{method:t,resultType:i})};if("input_required"===i){let i=r.inputRequests,n=cE(i)?i:{},a=r.requestState;return 0===Object.keys(n).length&&"string"!=typeof a?{kind:"invalid",error:new lJ(lV.InvalidResult,`Invalid result for ${t}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:t,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:n,..."string"==typeof a&&{requestState:a}}}if("complete"!==i)return{kind:"invalid",error:new lJ(lV.UnsupportedResultType,`Unsupported result type '${i}' for ${t}`,{resultType:i,method:t})};let n=cA(),a=Object.hasOwn(n,t)?n[t]:void 0;if(void 0!==a){let i=a.safeParse(r);if(!i.success)return{kind:"invalid",error:new lJ(lV.InvalidResult,`Invalid result for ${t}: ${i.error}`,{method:t})}}let o={...r};return delete o.resultType,{kind:"complete",result:o}},encodeResult:(t,r,i)=>(function(t,r){if(void 0===r)return t;let i=t._meta;return void 0===i?{...t,_meta:{[aK]:r}}:null===i||"object"!=typeof i||Array.isArray(i)||void 0!==i[aK]?t:{...t,_meta:{...i,[aK]:r}}})(function(t,r){var i,n;let a=r[cu];if("complete"!==r.resultType||!cc.includes(t)){let t;return void 0===a?r:(t={...r},delete t[cu],t)}let o=cp(r.ttlMs)?r.ttlMs:void 0!==(i=a)&&cp(i.ttlMs)?i.ttlMs:0,s=cm(r.cacheScope)?r.cacheScope:void 0!==(n=a)&&cm(n.cacheScope)?n.cacheScope:"private",l={...r,ttlMs:o,cacheScope:s};return delete l[cu],l}(t,function(t,r){let i=r.resultType;if(void 0===i)return{...r,resultType:"complete"};if("complete"===i||cS.includes(t))return r;throw new cg(cf.InternalError,`Handler for ${t} returned resultType '${String(i)}', but results of ${t} only support 'complete' on protocol revision 2026-07-28`)}(t,function(t,r){let i=r,n=!1,a=()=>(n||(i={...i},n=!0),i),o=r.tools;"tools/list"===t&&Array.isArray(o)&&o.some(t=>cE(t)&&"execution"in t)&&(a().tools=o.map(t=>{if(!cE(t)||!("execution"in t))return t;let r={...t};return delete r.execution,r}));let s=r.capabilities;if(cE(s)&&"tasks"in s){let t={...s};delete t.tasks,a().capabilities=t}return i}(t,r))),i),encodeErrorCode:t=>-32002===t?-32602:t,checkInboundEnvelope(t){if(void 0===t.envelope)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let r=cl().RequestMetaEnvelopeSchema.safeParse(t.envelope);if(!r.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${r.error.issues.map(t=>t.message).join("; ")}`}};function cA(){if(s)return s;let t=cl();return s={"tools/call":t.CallToolResultSchema,"tools/list":t.ListToolsResultSchema,"prompts/get":t.GetPromptResultSchema,"prompts/list":t.ListPromptsResultSchema,"resources/list":t.ListResourcesResultSchema,"resources/templates/list":t.ListResourceTemplatesResultSchema,"resources/read":t.ReadResourceResultSchema,"completion/complete":t.CompleteResultSchema,"server/discover":t.DiscoverResultSchema}}let cN="2026-07-28";function cL(t){return void 0!==t&&t>=lK?cj:cs}function cz(t){return void 0!==t.revision?cL(t.revision).era:"modern"===t.era?cj.era:cs.era}function cM(t){return cU.some(r=>r.hasRequestMethod(t))}function cZ(t){return cU.some(r=>r.hasNotificationMethod(t))}let cU=[cs,cj];function cF(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function cH(t){if(!cF(t))return;let r=t._meta;return cF(r)?r:void 0}function cD(t){let r=cH(t);return void 0!==r&&aW in r}function cV(t){let r=cH(t)?.[aW];return"string"==typeof r?r:void 0}function cJ(t){return cL(cN).validateEnvelopeMeta(t)}var cB=((t,r)=>{let i={};for(var n in t)D(i,n,{get:t[n],enumerable:!0});return r&&D(i,Symbol.toStringTag,{value:"Module"}),i})({AnnotationsSchema:()=>oH,AudioContentSchema:()=>sc,BaseMetadataSchema:()=>oy,BaseRequestParamsSchema:()=>a7,BlobResourceContentsSchema:()=>oU,BooleanSchemaSchema:()=>sD,CallToolRequestParamsSchema:()=>sx,CallToolRequestSchema:()=>sR,CallToolResultSchema:()=>sw,CancelTaskRequestSchema:()=>lb,CancelTaskResultSchema:()=>lS,CancelledNotificationParamsSchema:()=>om,CancelledNotificationSchema:()=>oh,ClientCapabilitiesSchema:()=>ok,ClientNotificationSchema:()=>lk,ClientRequestSchema:()=>lw,ClientResultSchema:()=>lx,ClientTasksCapabilitySchema:()=>oS,CompatibilityCallToolResultSchema:()=>sk,CompleteRequestParamsSchema:()=>lt,CompleteRequestSchema:()=>lr,CompleteResultSchema:()=>li,ContentBlockSchema:()=>sm,CreateMessageRequestParamsSchema:()=>sZ,CreateMessageRequestSchema:()=>sU,CreateMessageResultSchema:()=>sF,CreateMessageResultWithToolsSchema:()=>sH,CreateTaskResultSchema:()=>ld,CursorSchema:()=>a4,DiscoverRequestSchema:()=>oP,DiscoverResultSchema:()=>oE,ElicitRequestFormParamsSchema:()=>s2,ElicitRequestParamsSchema:()=>s4,ElicitRequestSchema:()=>s5,ElicitRequestURLParamsSchema:()=>s9,ElicitResultSchema:()=>s7,ElicitationCompleteNotificationParamsSchema:()=>s3,ElicitationCompleteNotificationSchema:()=>s6,EmbeddedResourceSchema:()=>sd,EmptyResultSchema:()=>op,EnumSchemaSchema:()=>s0,GetPromptRequestParamsSchema:()=>sa,GetPromptRequestSchema:()=>so,GetPromptResultSchema:()=>sf,GetTaskPayloadRequestSchema:()=>lg,GetTaskPayloadResultSchema:()=>ly,GetTaskRequestSchema:()=>lh,GetTaskResultSchema:()=>lf,IconSchema:()=>of,IconsSchema:()=>og,ImageContentSchema:()=>sl,ImplementationSchema:()=>ov,InitializeRequestParamsSchema:()=>ox,InitializeRequestSchema:()=>oR,InitializeResultSchema:()=>oC,InitializedNotificationSchema:()=>oT,JSONArraySchema:()=>a2,JSONObjectSchema:()=>a1,JSONRPCErrorResponseSchema:()=>oc,JSONRPCMessageSchema:()=>ou,JSONRPCNotificationSchema:()=>os,JSONRPCRequestSchema:()=>oo,JSONRPCResponseSchema:()=>od,JSONRPCResultResponseSchema:()=>ol,JSONValueSchema:()=>a0,LegacyTitledEnumSchemaSchema:()=>sG,ListChangedOptionsBaseSchema:()=>sC,ListPromptsRequestSchema:()=>si,ListPromptsResultSchema:()=>sn,ListResourceTemplatesRequestSchema:()=>oW,ListResourceTemplatesResultSchema:()=>oG,ListResourcesRequestSchema:()=>oJ,ListResourcesResultSchema:()=>oB,ListRootsRequestSchema:()=>la,ListRootsResultSchema:()=>lo,ListTasksRequestSchema:()=>lv,ListTasksResultSchema:()=>l_,ListToolsRequestSchema:()=>sb,ListToolsResultSchema:()=>sS,LoggingLevelSchema:()=>sT,LoggingMessageNotificationParamsSchema:()=>sO,LoggingMessageNotificationSchema:()=>sI,ModelHintSchema:()=>sq,ModelPreferencesSchema:()=>sj,MultiSelectEnumSchemaSchema:()=>sQ,NotificationSchema:()=>or,NotificationsParamsSchema:()=>ot,NumberSchemaSchema:()=>sJ,PaginatedRequestParamsSchema:()=>oA,PaginatedRequestSchema:()=>oN,PaginatedResultSchema:()=>oL,PingRequestSchema:()=>oO,PrimitiveSchemaDefinitionSchema:()=>s1,ProgressNotificationParamsSchema:()=>oq,ProgressNotificationSchema:()=>oj,ProgressSchema:()=>oI,ProgressTokenSchema:()=>a9,PromptArgumentSchema:()=>st,PromptListChangedNotificationSchema:()=>sg,PromptMessageSchema:()=>sh,PromptReferenceSchema:()=>le,PromptSchema:()=>sr,ReadResourceRequestParamsSchema:()=>oK,ReadResourceRequestSchema:()=>oY,ReadResourceResultSchema:()=>oX,RelatedTaskMetadataSchema:()=>a3,RequestIdSchema:()=>oa,RequestMetaSchema:()=>a6,RequestSchema:()=>oe,ResourceContentsSchema:()=>oz,ResourceLinkSchema:()=>sp,ResourceListChangedNotificationSchema:()=>oQ,ResourceRequestParamsSchema:()=>oK,ResourceSchema:()=>oD,ResourceTemplateReferenceSchema:()=>s8,ResourceTemplateSchema:()=>oV,ResourceUpdatedNotificationParamsSchema:()=>o8,ResourceUpdatedNotificationSchema:()=>se,ResultMetaObjectSchema:()=>oi,ResultSchema:()=>on,RoleSchema:()=>oF,RootSchema:()=>ln,RootsListChangedNotificationSchema:()=>ls,SamplingContentSchema:()=>sL,SamplingMessageContentBlockSchema:()=>sz,SamplingMessageSchema:()=>sM,ServerCapabilitiesSchema:()=>o$,ServerNotificationSchema:()=>l$,ServerRequestSchema:()=>lR,ServerResultSchema:()=>lC,ServerTasksCapabilitySchema:()=>ow,SetLevelRequestParamsSchema:()=>sP,SetLevelRequestSchema:()=>sE,SingleSelectEnumSchemaSchema:()=>sK,StringSchemaSchema:()=>sV,SubscribeRequestParamsSchema:()=>oK,SubscribeRequestSchema:()=>o0,SubscriptionFilterSchema:()=>o2,SubscriptionsAcknowledgedNotificationParamsSchema:()=>o5,SubscriptionsAcknowledgedNotificationSchema:()=>o3,SubscriptionsListenRequestParamsSchema:()=>o9,SubscriptionsListenRequestSchema:()=>o4,SubscriptionsListenResultMetaSchema:()=>o6,SubscriptionsListenResultSchema:()=>o7,TaskAugmentedRequestParamsSchema:()=>a8,TaskCreationParamsSchema:()=>ll,TaskMetadataSchema:()=>a5,TaskSchema:()=>lu,TaskStatusNotificationParamsSchema:()=>lp,TaskStatusNotificationSchema:()=>lm,TaskStatusSchema:()=>lc,TextContentSchema:()=>ss,TextResourceContentsSchema:()=>oM,TitledMultiSelectEnumSchemaSchema:()=>sX,TitledSingleSelectEnumSchemaSchema:()=>sW,ToolAnnotationsSchema:()=>sy,ToolChoiceSchema:()=>sA,ToolExecutionSchema:()=>sv,ToolListChangedNotificationSchema:()=>s$,ToolResultContentSchema:()=>sN,ToolSchema:()=>s_,ToolUseContentSchema:()=>su,UnsubscribeRequestParamsSchema:()=>oK,UnsubscribeRequestSchema:()=>o1,UntitledMultiSelectEnumSchemaSchema:()=>sY,UntitledSingleSelectEnumSchemaSchema:()=>sB});let cW=t=>oo.safeParse(t).success,cG=t=>os.safeParse(t).success,cK=t=>ol.safeParse(t).success,cY=t=>oc.safeParse(t).success,cX=t=>"object"==typeof t&&null!==t&&!Array.isArray(t)&&"input_required"===t.resultType,cQ="x-mcp-header",c0=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,c1=new Set(["string","integer","boolean","number"]);function c2(t){let r=[],i=new Map,n=(t,a,o)=>{if(null===t||"object"!=typeof t)return;if(cQ in t){if(!o||0===a.length)return`${c5(a)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let n=t[cQ];if("string"!=typeof n||0===n.length)return`${c5(a)}: x-mcp-header MUST be a non-empty string`;if(!c0.test(n))return`${c5(a)}: x-mcp-header '${n}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let s="string"==typeof t.type?t.type:void 0;if(void 0===s||!c1.has(s))return`${c5(a)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${s??"<none>"}`;let l=n.toLowerCase(),c=i.get(l);if(void 0!==c)return`x-mcp-header '${n}' is not case-insensitively unique (also declared as '${c}')`;i.set(l,n),r.push({path:a,headerName:n,type:s})}let s=t.properties;if(null!==s&&"object"==typeof s)for(let[t,r]of Object.entries(s)){let i=n(r,[...a,t],o);if(void 0!==i)return i}for(let r of c9){let i=t[r];if(void 0!==i)for(let t of Array.isArray(i)?i:null!==i&&"object"==typeof i&&c4.has(r)?Object.values(i):[i]){let i=n(t,[...a,`<${r}>`],!1);if(void 0!==i)return i}}},a=n(t,[],!0);return void 0===a?{valid:!0,declarations:r}:{valid:!1,reason:a}}let c9=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],c4=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function c5(t){return 0===t.length?"<root>":t.join(".")}let c3=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,c6=/^-?\d+(\.\d+)?$/;function c7(t){if(!(t.startsWith("=?base64?")&&t.endsWith("?=")))return t;let r=t.slice(9,t.length-2);if(c3.test(r))try{let t=atob(r),i=new Uint8Array(t.length);for(let r=0;r<t.length;r++)i[r]=t.codePointAt(r);return new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return}}function c8(t,r,i){return{kind:"reject",rung:"param-header-validation",cell:t,httpStatus:400,code:ue,message:`Bad Request: the request headers and body disagree: ${i}`,data:{mismatch:{header:r,body:i}},settled:!0}}let ue=-32020;cf.InvalidRequest,cf.UnsupportedProtocolVersion,cf.InvalidParams,cf.MethodNotFound,cf.InvalidParams,cf.MissingRequiredClientCapability;let ut={[cf.ParseError]:400,[cf.InvalidRequest]:400,[cf.MethodNotFound]:404,[cf.UnsupportedProtocolVersion]:400,[cf.MissingRequiredClientCapability]:400,[ue]:400};function ur(t,r,i,n,a){return{kind:"reject",rung:t,cell:r,httpStatus:i,code:n.code,message:n.message,...void 0!==n.data&&{data:n.data},settled:a}}function ui(t,r,i,n="era-classification"){return ur(n,t,400,new cg(ue,`Bad Request: the request headers and body disagree: ${i}`,{mismatch:{header:r,body:i}}),!0)}let un={"tools/call":"name","prompts/get":"name","resources/read":"uri"};function ua(t){let r=0;for(;r<t.length;){let i=t.codePointAt(r);if(9!==i&&32!==i)break;r+=1}let i=t.length;for(;i>r;){let r=t.codePointAt(i-1);if(9!==r&&32!==r)break;i-=1}return 0===r&&i===t.length?t:t.slice(r,i)}function uo(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function us(t){return void 0===t?{era:"modern"}:{era:t>=lK?"modern":"legacy",revision:t}}function ul(t){return new Set(t.flatMap(t=>Object.keys(t.shape)))}function uc(t){if(null==t)return!1;let r=typeof t;return("object"===r||"function"===r)&&"~standard"in t&&"function"==typeof t["~standard"]?.validate}let uu=!1,ud="draft-2020-12";function up(t,r="input"){let i,n=t["~standard"];if(n.jsonSchema)i=n.jsonSchema[r]({target:ud});else if("zod"===n.vendor){if(!("_zod"in t))throw Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");uu||(uu=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),i=ni(t,{target:ud,io:r})}else throw Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if("output"===r)return void 0!==i.type||!function t(r){if("properties"in r||"patternProperties"in r||"additionalProperties"in r||"required"in r)return!0;for(let i of["oneOf","anyOf","allOf"]){let n=r[i];if(Array.isArray(n)&&n.length>0)return n.every(r=>null!==r&&"object"==typeof r&&("object"===r.type||t(r)))}return!1}(i)?i:{type:"object",...i};if(void 0!==i.type&&"object"!==i.type)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(i.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...i}}async function um(t,r){let i=await t["~standard"].validate(r);return i.issues&&i.issues.length>0?{success:!1,error:i.issues.map(t=>t.path?.length?`${t.path.map(t=>String("object"==typeof t?t.key:t)).join(".")}: ${t.message}`:t.message).join(", ")}:{success:!0,data:i.value}}let uh=/\\\.\\d\{(\d+)\}/;function uf(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}let ug=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function uy(t){return ug.has(t)||t.startsWith("x-")}let uv=new Set(["$schema",...Object.keys(s2.shape.requestedSchema.shape)]),u_={string:ul([sV,sB,sW,sG]),number:ul([sJ]),integer:ul([sJ]),boolean:ul([sD]),array:ul([sY,sX])},ub=new Set(sV.shape.format.unwrap().options);Object.assign(function(t){let r=void 0!==t.inputRequests&&Object.keys(t.inputRequests).length>0,i="string"==typeof t.requestState;if(!r&&!i)throw TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...void 0!==t.inputRequests&&{inputRequests:t.inputRequests},...void 0!==t.requestState&&{requestState:t.requestState}}},{elicit(t){try{return{method:"elicitation/create",params:function(t){var r;if(!uc(t.requestedSchema))return{...t,mode:"form",requestedSchema:t.requestedSchema};let i=t.requestedSchema["~standard"].vendor,n=function(t,r){let i={},n=[];for(let[a,o]of Object.entries(t))"properties"===a&&uf(o)?i[a]=Object.fromEntries(Object.entries(o).map(([t,i])=>[t,function(t,r,i,n){if(!uf(t))return t;let a="string"==typeof t.type&&Object.hasOwn(u_,t.type)?u_[t.type]:void 0;if(void 0===a)return t;let o={};for(let[l,c]of Object.entries(t))if(a.has(l)||uy(l))o[l]=c;else if("pattern"===l&&"string"===t.type&&"string"==typeof t.format)if(ub.has(t.format)){var s;"string"==typeof c&&(s=t.format,"zod"!==i||(function(t,r){let i;switch(t){case"email":i=[r5(nH,void 0)];break;case"uri":i=[r3(nJ,void 0)];break;case"date":i=[r7(nZ,void 0)];break;case"date-time":let n,a;n=uh.exec(r),a=[void 0,-1,0],n&&a.push(Number(n[1])),i=[!1,!0].flatMap(t=>[!1,!0].flatMap(r=>a.map(i=>r6(nM,{local:t,offset:r,precision:i}))))}return new Set(i.map(t=>{let r;return r=ni(t,{target:ud,io:"input"}),"string"==typeof r.pattern?r.pattern:void 0}).filter(t=>void 0!==t))})(s,c).has(c))||n.push(`${r}.${l}`)}else o[l]=c;else n.push(`${r}.${l}`);return o}(i,`properties.${t}`,r,n)])):uv.has(a)?i[a]=o:uy(a)||n.push(a);if(n.length>0)throw new cg(cf.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return i}(function(t){try{return up(t,"input")}catch(r){let t=r instanceof Error?r.message:String(r);throw new cg(cf.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${t}`)}}(t.requestedSchema),i),a=(r=s2.shape.requestedSchema,nk(r,n));if(!a.success)throw new cg(cf.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${function(t,r){if(!uf(t.properties))return r;let i=Object.entries(t.properties).filter(([,t])=>!nk(s1,t).success).map(([t])=>`properties.${t}`);return i.length>0?i.join(", "):r}(n,a.error.message)}`);let o=function t(r,i,n=""){return Array.isArray(r)&&Array.isArray(i)?r.flatMap((r,a)=>t(r,i[a],`${n}[${a}]`)):uf(r)&&uf(i)?Object.entries(r).flatMap(([r,a])=>{let o=n?`${n}.${r}`:r;return Object.prototype.hasOwnProperty.call(i,r)?t(a,i[r],o):uy(r)?[]:[o]}):[]}(n,a.data);if(o.length>0)throw new cg(cf.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);let s=(a.data.required??[]).filter(t=>!Object.prototype.hasOwnProperty.call(a.data.properties,t));if(s.length>0)throw new cg(cf.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...t,mode:"form",requestedSchema:a.data}}(t)}}catch(t){throw t instanceof cg?TypeError(t.message,{cause:t}):t}},elicitUrl:t=>({method:"elicitation/create",params:{...t,mode:"url"}}),createMessage:t=>({method:"sampling/createMessage",params:t}),listRoots:()=>({method:"roots/list"})});let uS={},uw={};function uk(t,r){let i=t.slice(0,-6);uS[i]=r,uw[i]=t=>r.safeParse(t).success}for(let t of["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"])uk(t,cB[t]);for(let[t,r]of Object.entries({IdJagTokenExchangeResponseSchema:lj,OAuthClientInformationFullSchema:lM,OAuthClientInformationSchema:lz,OAuthClientMetadataSchema:lL,OAuthClientRegistrationErrorSchema:lZ,OAuthErrorResponseSchema:lA,OAuthMetadataSchema:lE,OAuthProtectedResourceMetadataSchema:lP,OAuthTokenRevocationRequestSchema:lU,OAuthTokensSchema:lq,OpenIdProviderDiscoveryMetadataSchema:lI,OpenIdProviderMetadataSchema:lO}))uk(t,r);let ux=Object.freeze(uS);Object.freeze(uw);let uR=[aW,aG,aY,aQ],u$=["inputResponses","requestState"];function uC(t,r){let i=t.params;if(!uI(i))return{message:t,lifted:{}};let n=i._meta,a=uI(n)?uR.filter(t=>t in n):[],o="request"===r?u$.filter(t=>t in i):[];if(0===a.length&&0===o.length)return{message:t,lifted:{}};let s={},l={...i};if(a.length>0&&uI(n)){let t={},r={...n};for(let i of a)t[i]=n[i],delete r[i];s.envelope=t,Object.keys(r).length>0?l._meta=r:delete l._meta}for(let t of o)"inputResponses"===t&&(s.inputResponses=l[t]),"requestState"===t&&(s.requestState=l[t]),delete l[t];return{message:{...t,params:l},lifted:s}}function uT(t,r){let i=t.validateResult(r,void 0);if(i.ok||"not-in-era"!==i.reason)return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(i){let n=t.validateResult(r,i);return n.ok?{value:n.value}:{issues:[{message:"invalid"===n.reason?n.message:`not-in-era: ${r}`}]}}}}}let uP=(T=void 0,()=>T);function uE(t,r){return{...t,mcpReq:{...t.mcpReq,requestState:()=>r}}}var uO=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{l=(t,r)=>{t._negotiatedProtocolVersion=r}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(t){this._options=t,this._supportedProtocolVersions=t?.supportedProtocolVersions??aB,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(t){}_outboundMetaEnvelope(){}_envelopeOutbound(t){let r=this._outboundMetaEnvelope();if(void 0===r)return t;let i=t.params??{};return{...t,params:{...i,_meta:{...r,...i._meta}}}}_resolveNonCompleteResult(t,r){return Promise.reject(new lJ(lV.UnsupportedResultType,`Unsupported result type '${t.kind}' for ${r.request.method}`,{resultType:t.kind,method:r.request.method}))}_getRequestHandler(t){return this._requestHandlers.get(t)}async _oncancel(t){t.params.requestId&&this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,i,n,a=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:i,resetTimeoutOnProgress:a,onTimeout:n})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let i=Date.now()-r.startTime;if(r.maxTotalTimeout&&i>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),new lJ(lV.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:i});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{try{r?.()}finally{this._onclose()}};let i=this.transport?.onerror;this._transport.onerror=t=>{i?.(t),this._onerror(t)};let n=this._transport?.onmessage;this._transport.onmessage=(t,r)=>{n?.(t,r),cK(t)||cY(t)?this._onresponse(t):cW(t)?this._onrequest(t,r):cG(t)?this._onnotification(t,r):this._onerror(Error(`Unknown message type: ${JSON.stringify(t)}`))},t.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let t=this._responseHandlers;for(let t of(this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._timeoutInfo.values()))clearTimeout(t.timeoutId);this._timeoutInfo.clear();let r=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let i=new lJ(lV.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let r of t.values())r(i);for(let t of r.values())t.abort(i)}}_onerror(t){this.onerror?.(t)}_onnotification(t,r){let{message:i}=uC(t,"notification"),n=this._negotiatedWireCodec();if(r?.classification===void 0&&"drop"===this._shouldDropInbound(t))return;if(r?.classification!==void 0){let t=cz(r.classification);if(t!==n.era)return void this._onerror(Error(`Era mismatch on inbound notification '${i.method}': classified as ${t} but this instance serves ${n.era}`))}if(cZ(i.method)&&!n.hasNotificationMethod(i.method))return;let a=this._notificationHandlers.get(i.method),o=this.fallbackNotificationHandler;(void 0!==a||void 0!==o)&&Promise.resolve().then(()=>void 0===a?o(i):a(i,n)).catch(t=>this._onerror(Error(`Uncaught error in notification handler: ${t}`)))}_onrequest(t,r){var i;let{message:n,lifted:a}=uC(t,"request"),o=this._negotiatedWireCodec();if(r?.classification===void 0&&"drop"===this._shouldDropInbound(t))return void this._onerror(Error(`Dropped inbound request '${t.method}': not servable on this connection's protocol era`));let s=this._transport,l=(t,r,i)=>{let a={jsonrpc:"2.0",id:n.id,error:{code:t,message:r,...void 0!==i&&{data:i}}};s?.send(a).catch(t=>this._onerror(Error(`Failed to send an error response: ${t}`)))};if(r?.classification!==void 0){let t=cz(r.classification);if(t!==o.era){this._onerror(Error(`Era mismatch on inbound request '${n.method}': classified as ${t} but this instance serves ${o.era}`));let i=r.classification.revision??t;l(cf.UnsupportedProtocolVersion,`Unsupported protocol version: ${i}`,{supported:this._supportedProtocolVersions,requested:i});return}}if(cM(n.method)&&!o.hasRequestMethod(n.method))return void l(cf.MethodNotFound,"Method not found");let c=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(void 0===c)return void l(cf.MethodNotFound,"Method not found");let u=o.checkInboundEnvelope(a);if(void 0!==u)return void l(cf.InvalidParams,u);let d=(t,r)=>this._notificationViaCodec(this._resolveOutboundCodec(t.method),t,{...r,relatedRequestId:n.id}),p=(t,r,i)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(t.method),t,r,{...i,relatedRequestId:n.id}),m=new AbortController;this._requestHandlerAbortControllers.set(n.id,m);let h=void 0===a.inputResponses?void 0:function(t){let r={},i=[];if(!uq(t))return{accepted:r,droppedKeys:i};for(let[n,a]of Object.entries(t)){if(!uq(a)||"method"in a||"result"in a){i.push(n);continue}r[n]=a}return{accepted:r,droppedKeys:i}}(a.inputResponses),f={sessionId:s?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...void 0!==a.envelope&&{envelope:a.envelope},...void 0!==h&&{inputResponses:h.accepted},...void 0!==h&&h.droppedKeys.length>0&&{droppedInputResponseKeys:h.droppedKeys},requestState:void 0===a.requestState?uP:(i=a.requestState,()=>i),signal:m.signal,send:(t,r,i)=>{let n=this._resolveOutboundCodec(t.method);if(this._assertOutboundRequestInEra(n,t.method),uc(r))return p(t,r,i);let a=uT(n,t.method);if(void 0===a)throw TypeError(`'${t.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return p(t,a,r)},notify:d},http:r?.authInfo?{authInfo:r.authInfo}:void 0},g=this.buildContext(f,r);Promise.resolve().then(()=>c(n,g)).then(async t=>{let r;if(m.signal.aborted)return;try{r=o.encodeResult(n.method,t,this._outboundServerInfo())}catch(t){this._onerror(Error(`Failed to encode result for ${n.method}: ${t}`)),l(cf.InternalError,"Internal error");return}let i={result:r,jsonrpc:"2.0",id:n.id};await s?.send(i)},async t=>{if(m.signal.aborted)return;let r=Number.isSafeInteger(t.code)?t.code:cf.InternalError,i={jsonrpc:"2.0",id:n.id,error:{code:o.encodeErrorCode(r),message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};await s?.send(i)}).catch(t=>this._onerror(Error(`Failed to send response: ${t}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===m&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(t){let{progressToken:r,...i}=t.params,n=Number(r),a=this._progressHandlers.get(n);if(!a)return void this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));let o=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(t){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),o(t);return}a(i)}_onresponse(t){let r=Number(t.id),i=this._responseHandlers.get(r);void 0===i?this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`)):(this._responseHandlers.delete(r),this._cleanupTimeout(r),this._progressHandlers.delete(r),i(cK(t)?t:cg.fromError(t.error.code,t.error.message,t.error.data)))}get transport(){return this._transport}async close(){await this._transport?.close()}request(t,r,i){let n=this._resolveOutboundCodec(t.method);if(this._assertOutboundRequestInEra(n,t.method),uc(r))return this._requestWithSchemaViaCodec(n,t,r,i);let a=uT(n,t.method);if(void 0===a)throw TypeError(`'${t.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(n,t,a,r)}_negotiatedWireCodec(){return cL(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(t){if(void 0===this._negotiatedProtocolVersion){let r=function(t){switch(t){case"initialize":case"notifications/initialized":return cL(void 0);case"server/discover":return cL(cN);default:return}}(t);if(r)return r}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(t,r){if(cM(r)&&!t.hasRequestMethod(r))throw new lJ(lV.MethodNotSupportedByProtocolVersion,`Method '${r}' is not supported by the negotiated protocol version (wire era ${t.era})`,{method:r,era:t.era})}_requestWithSchema(t,r,i){let n=this._resolveOutboundCodec(t.method);return this._assertOutboundRequestInEra(n,t.method),this._requestWithSchemaViaCodec(n,t,r,i)}_requestWithSchemaViaCodec(t,r,i,n){let a,o,{relatedRequestId:s,resumptionToken:l,onresumptiontoken:c,headers:u}=n??{},d=Date.now();return new Promise((p,m)=>{let h=t=>{m(t)};if(!this._transport)return void h(Error("Not connected"));if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(r.method)}catch(t){h(t);return}if(n?.signal?.aborted){let t=n.signal.reason;throw t instanceof lJ?t:new lJ(lV.RequestTimeout,String(t))}let f=t.era===cN&&!0===this._transport.hasPerRequestStream?new AbortController:void 0,g=this._requestMessageId++;o=g;let y={...r,jsonrpc:"2.0",id:g};n?.onprogress&&(this._progressHandlers.set(g,n.onprogress),y.params={...r.params,_meta:{...r.params?._meta,progressToken:g}});let v=this._envelopeOutbound(y),_=!1,b=t=>{_||(this._progressHandlers.delete(g),void 0===f?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(t)}}),{relatedRequestId:s,resumptionToken:l,onresumptiontoken:c}).catch(t=>this._onerror(Error(`Failed to send cancellation: ${t}`))):f.abort(),m(t instanceof lJ?t:new lJ(lV.RequestTimeout,String(t))))};this._responseHandlers.set(g,a=>{let o;if(!n?.signal?.aborted){if(_=!0,a instanceof Error)return m(a);try{o=t.decodeResult(r.method,a.result)}catch(t){return m(t instanceof Error?t:Error(String(t)))}if("invalid"===o.kind)return m(o.error);if("input_required"===o.kind){var s;return n?.allowInputRequired===!0?p({resultType:"input_required",inputRequests:(s=o).inputRequests,...void 0!==s.requestState&&{requestState:s.requestState}}):p(this._resolveNonCompleteResult(o,{codec:t,request:r,resultSchema:i,options:n,flowStartedAt:d,retry:(n,a)=>this._requestWithSchemaViaCodec(t,void 0===n?{method:r.method}:{method:r.method,params:n},i,a)}))}um(i,o.result).then(t=>{t.success?p(t.data):m(new lJ(lV.InvalidResult,`Invalid result for ${r.method}: ${t.error}`))},m)}}),a=()=>b(n?.signal?.reason),n?.signal?.addEventListener("abort",a,{once:!0});let S=n?.timeout??6e4;this._setupTimeout(g,S,n?.maxTotalTimeout,()=>b(new lJ(lV.RequestTimeout,"Request timed out",{timeout:S})),n?.resetTimeoutOnProgress??!1),this._transport.send(v,{relatedRequestId:s,resumptionToken:l,onresumptiontoken:c,headers:u,requestSignal:f?.signal}).catch(t=>{this._progressHandlers.delete(g),m(t)})}).finally(()=>{a&&n?.signal?.removeEventListener("abort",a),void 0!==o&&(this._responseHandlers.delete(o),this._cleanupTimeout(o))})}async notification(t,r){return this._notificationViaCodec(this._resolveOutboundCodec(t.method),t,r)}async _notificationViaCodec(t,r,i){if(!this._transport)throw new lJ(lV.NotConnected,"Not connected");if(cZ(r.method)&&!t.hasNotificationMethod(r.method))throw new lJ(lV.MethodNotSupportedByProtocolVersion,`Notification '${r.method}' is not supported by the negotiated protocol version (wire era ${t.era})`,{method:r.method,era:t.era});this.assertNotificationCapability(r.method);let n=this._envelopeOutbound({jsonrpc:"2.0",...r});if((this._options?.debouncedNotificationMethods??[]).includes(r.method)&&!r.params&&!i?.relatedRequestId){if(this._pendingDebouncedNotifications.has(r.method))return;this._pendingDebouncedNotifications.add(r.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(r.method),this._transport&&this._transport?.send(n,i).catch(t=>this._onerror(t))});return}await this._transport.send(n,i)}setRequestHandler(t,r,i){let n;if(this.assertRequestHandlerCapability(t),"function"==typeof r){if(!cM(t))throw TypeError(`'${t}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);n=(i,n)=>{let a=this._negotiatedWireCodec(),o=a.validateRequest(t,i);if(o.ok||"not-in-era"!==o.reason||(o=a.validateInputRequest(t,i)),!o.ok){if("not-in-era"===o.reason)throw new cg(cf.InternalError,`No wire schema for ${t} in the resolved era`);throw Error(o.message)}return Promise.resolve(r(o.value,n))}}else if(i)n=async(n,a)=>{let o=await um(r.params,{...n.params});if(!o.success)throw new cg(cf.InvalidParams,`Invalid params for ${t}: ${o.error}`);return i(o.data,a)};else throw TypeError("setRequestHandler: handler is required");this._requestHandlers.set(t,this._wrapHandler(t,n))}_wrapHandler(t,r){return r}_outboundServerInfo(){}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r,i){if("function"==typeof r){if(!cZ(t))throw TypeError(`'${t}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(t,(i,n)=>{let a=n.validateNotification(t,i);if(!a.ok){if("not-in-era"===a.reason)throw new cg(cf.InternalError,`No wire schema for ${t} in the resolved era`);throw Error(a.message)}return Promise.resolve(r(a.value))});return}if(!i)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(t,async n=>{let a=await um(r.params,{...n.params});if(!a.success)throw new cg(cf.InvalidParams,`Invalid params for notification ${t}: ${a.error}`);await i(a.data,n)})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}};function uI(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function uq(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}var uj=((t,r,i,n)=>{if(r&&"object"==typeof r||"function"==typeof r)for(var a,o=J(r),s=0,l=o.length;s<l;s++)a=o[s],W.call(t,a)||a===i||D(t,a,{get:(t=>r[t]).bind(null,a),enumerable:!(n=V(r,a))||n.enumerable});return t})(D(null!=(k=(S=t=>{var r=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,i=/\\([\u000b\u0020-\u00ff])/g,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function a(t){this.parameters=Object.create(null),this.type=t}t.parse=function(t){if(!t)throw TypeError("argument string is required");var o,s,l,c="object"==typeof t?function(t){var r;if("function"==typeof t.getHeader?r=t.getHeader("content-type"):"object"==typeof t.headers&&(r=t.headers&&t.headers["content-type"]),"string"!=typeof r)throw TypeError("content-type header is missing from object");return r}(t):t;if("string"!=typeof c)throw TypeError("argument string is required to be a string");var u=c.indexOf(";"),d=-1!==u?c.slice(0,u).trim():c.trim();if(!n.test(d))throw TypeError("invalid media type");var p=new a(d.toLowerCase());if(-1!==u){for(r.lastIndex=u;s=r.exec(c);){if(s.index!==u)throw TypeError("invalid parameter format");u+=s[0].length,o=s[1].toLowerCase(),34===(l=s[2]).charCodeAt(0)&&-1!==(l=l.slice(1,-1)).indexOf("\\")&&(l=l.replace(i,"$1")),p.parameters[o]=l}if(u!==c.length)throw TypeError("invalid parameter format")}return p}},()=>(w||S((w={exports:{}}).exports,w),w.exports))())?H(B(k)):{},"default",{value:k,enumerable:!0}),k);function uA(t){if(t)try{return uj.parse(t).type}catch{let r=(t.split(";",1)[0]??"").trim().toLowerCase();if(""===r||t.slice(r.length).includes(","))return;return r}}function uN(t){return"application/json"===t||"application/json"===uA(t)}let uL=/^[A-Za-z0-9._-]{1,128}$/;function uz(t){let r=function(t){let r=[];if(0===t.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&r.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&r.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&r.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&r.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!uL.test(t)){let i=[...t].filter(t=>!/[A-Za-z0-9._-]/.test(t)).filter((t,r,i)=>i.indexOf(t)===r);return r.push(`Tool name contains invalid characters: ${i.map(t=>`"${t}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:r}}return{isValid:!0,warnings:r}}(t);var i=r.warnings;if(i.length>0){for(let r of(console.warn(`Tool name validation warning for "${t}":`),i))console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}return r.isValid}var uM=class t{static isTemplate(t){return/\{[^}\s]+\}/.test(t)}static validateLength(t,r,i){if(t.length>r)throw Error(`${i} exceeds maximum length of ${r} characters (got ${t.length})`)}template;parts;get variableNames(){return this.parts.flatMap(t=>"string"==typeof t?[]:t.names)}constructor(r){t.validateLength(r,1e6,"Template"),this.template=r,this.parts=this.parse(r)}toString(){return this.template}parse(r){let i=[],n="",a=0,o=0;for(;a<r.length;)if("{"===r[a]){n&&(i.push(n),n="");let s=r.indexOf("}",a);if(-1===s)throw Error("Unclosed template expression");if(++o>1e4)throw Error("Template contains too many expressions (max 10000)");let l=r.slice(a+1,s),c=this.getOperator(l),u=l.includes("*"),d=this.getNames(l),p=d[0];for(let r of d)t.validateLength(r,1e6,"Variable name");i.push({name:p,operator:c,names:d,exploded:u}),a=s+1}else n+=r[a],a++;return n&&i.push(n),i}getOperator(t){return["+","#",".","/","?","&"].find(r=>t.startsWith(r))||""}getNames(t){let r=this.getOperator(t);return t.slice(r.length).split(",").map(t=>t.replace("*","").trim()).filter(t=>t.length>0)}encodeValue(r,i){return(t.validateLength(r,1e6,"Variable value"),"+"===i||"#"===i)?encodeURI(r):encodeURIComponent(r)}expandPart(t,r){if("?"===t.operator||"&"===t.operator){let i=t.names.map(i=>{let n=r[i];return void 0===n?"":`${i}=${Array.isArray(n)?n.map(r=>this.encodeValue(r,t.operator)).join(","):this.encodeValue(n.toString(),t.operator)}`}).filter(t=>t.length>0);return 0===i.length?"":("?"===t.operator?"?":"&")+i.join("&")}if(t.names.length>1){let i=t.names.map(t=>r[t]).filter(t=>void 0!==t);return 0===i.length?"":i.map(t=>Array.isArray(t)?t[0]:t).join(",")}let i=r[t.name];if(void 0===i)return"";let n=(Array.isArray(i)?i:[i]).map(r=>this.encodeValue(r,t.operator));switch(t.operator){case"":case"+":default:return n.join(",");case"#":return"#"+n.join(",");case".":return"."+n.join(".");case"/":return"/"+n.join("/")}}expand(t){let r="",i=!1;for(let n of this.parts){if("string"==typeof n){r+=n;continue}let a=this.expandPart(n,t);a&&(r+=("?"===n.operator||"&"===n.operator)&&i?a.replace("?","&"):a,("?"===n.operator||"&"===n.operator)&&(i=!0))}return r}escapeRegExp(t){return t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(r){let i,n=[];for(let i of r.names)t.validateLength(i,1e6,"Variable name");if("?"===r.operator||"&"===r.operator){for(let t=0;t<r.names.length;t++){let i=r.names[t],a=0===t?"\\"+r.operator:"&";n.push({pattern:a+this.escapeRegExp(i)+"=([^&]+)",name:i})}return n}let a=r.name;switch(r.operator){case"":i=r.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":i="(.+)";break;case".":i=String.raw`\.([^/,]+)`;break;case"/":i="/"+(r.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:i="([^/]+)"}return n.push({pattern:i,name:a}),n}match(r){t.validateLength(r,1e6,"URI");let i="^",n=[];for(let t of this.parts)if("string"==typeof t)i+=this.escapeRegExp(t);else for(let{pattern:r,name:a}of this.partToRegExp(t))i+=r,n.push({name:a,exploded:t.exploded});i+="$",t.validateLength(i,1e6,"Generated regex pattern");let a=new RegExp(i),o=r.match(a);if(!o)return null;let s={};for(let[t,r]of n.entries()){let{name:i,exploded:n}=r,a=o[t+1];s[i.replace("*","")]=n&&a.includes(",")?a.split(","):a}return s}};function uZ(t){if(void 0!==t){if(function(t){if("object"!=typeof t||null===t||uc(t))return!1;let r=Object.getPrototypeOf(t);return(r===Object.prototype||null===r)&&Object.values(t).every(t=>"object"==typeof t&&null!==t&&"_zod"in t)}(t))return am(t);if("object"==typeof t&&null!==t&&!uc(t)&&Object.values(t).some(t=>"object"==typeof t&&null!==t&&!("_zod"in t)&&"_def"in t&&"string"==typeof t._def?.typeName))throw TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!uc(t))throw TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return t}}function uU(){l2(),cl(),ce(),ck(),cA()}function uF(t,r){let i=typeof t;if(i!==typeof r)return!1;if(Array.isArray(t)){if(!Array.isArray(r))return!1;let i=t.length;if(i!==r.length)return!1;for(let n=0;n<i;n++)if(!uF(t[n],r[n]))return!1;return!0}if("object"===i){if(!t||!r)return t===r;let i=Object.keys(t),n=Object.keys(r);if(i.length!==n.length)return!1;for(let n of i)if(!uF(t[n],r[n]))return!1;return!0}return t===r}function uH(t){return encodeURI(t.replace(/~/g,"~0").replace(/\//g,"~1"))}let uD={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},uV={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},uJ={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},uB="undefined"!=typeof self&&self.location&&"null"!==self.location.origin?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function uW(t,r=Object.create(null),i=uB,n=""){if(t&&"object"==typeof t&&!Array.isArray(t)){let a=t.$id||t.id;if(a){let o=new URL(a,i.href);o.hash.length>1?r[o.href]=t:(o.hash="",""===n?i=o:uW(t,r,i))}}else if(!0!==t&&!1!==t)return r;let a=i.href+(n?"#"+n:"");if(void 0!==r[a])throw Error(`Duplicate schema URI "${a}".`);if(r[a]=t,!0===t||!1===t)return r;if(void 0===t.__absolute_uri__&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:a}),t.$ref&&void 0===t.__absolute_ref__){let r=new URL(t.$ref,i.href);r.hash=r.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:r.href})}if(t.$recursiveRef&&void 0===t.__absolute_recursive_ref__){let r=new URL(t.$recursiveRef,i.href);r.hash=r.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:r.href})}for(let a in t.$anchor&&(r[new URL("#"+t.$anchor,i.href).href]=t),t){if(uJ[a])continue;let o=`${n}/${uH(a)}`,s=t[a];if(Array.isArray(s)){if(uD[a]){let t=s.length;for(let n=0;n<t;n++)uW(s[n],r,i,`${o}/${n}`)}}else if(uV[a])for(let t in s)uW(s[t],r,i,`${o}/${uH(t)}`);else uW(s,r,i,o)}return r}let uG=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,uK=[0,31,28,31,30,31,30,31,31,30,31,30,31],uY=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;function uX(t){return t.test.bind(t)}let uQ={date:u0,time:u1.bind(void 0,!1),"date-time":function(t){let r=t.split(u2);return 2==r.length&&u0(r[0])&&u1(!0,r[1])},duration:t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t)),uri:function(t){return u9.test(t)&&u4.test(t)},"uri-reference":uX(/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i),"uri-template":uX(/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i),url:uX(/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu),email:t=>{if('"'===t[0])return!1;let[r,i,...n]=t.split("@");return!(!r||!i||0!==n.length||r.length>64||i.length>253||"."===r[0]||r.endsWith(".")||r.includes(".."))&&!!/^[a-z0-9.-]+$/i.test(i)&&!!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(r)&&i.split(".").every(t=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(t))},hostname:uX(/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i),ipv4:uX(/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/),ipv6:uX(/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i),regex:function(t){if(u5.test(t))return!1;try{return RegExp(t,"u"),!0}catch(t){return!1}},uuid:uX(/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i),"json-pointer":uX(/^(?:\/(?:[^~/]|~0|~1)*)*$/),"json-pointer-uri-fragment":uX(/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i),"relative-json-pointer":uX(/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/)};function u0(t){var r;let i=t.match(uG);if(!i)return!1;let n=+i[1],a=+i[2],o=+i[3];return a>=1&&a<=12&&o>=1&&o<=(2==a&&(r=n)%4==0&&(r%100!=0||r%400==0)?29:uK[a])}function u1(t,r){let i=r.match(uY);if(!i)return!1;let n=+i[1],a=+i[2],o=+i[3],s=!!i[5];return(n<=23&&a<=59&&o<=59||23==n&&59==a&&60==o)&&(!t||s)}let u2=/t|\s/i,u9=/\/|:/,u4=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,u5=/[^\\]\\Z/;var u3=class{schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",i=!0){this.schema=t,this.draft=r,this.shortCircuit=i,this.lookup=uW(t)}validate(t){return function t(r,i,n="2019-09",a=uW(i),o=!0,s=null,l="#",c="#",u=Object.create(null)){let d;if(!0===i)return{valid:!0,errors:[]};if(!1===i)return{valid:!1,errors:[{instanceLocation:l,keyword:"false",keywordLocation:l,error:"False boolean schema."}]};let p=typeof r;switch(p){case"boolean":case"number":case"string":d=p;break;case"object":d=null===r?"null":Array.isArray(r)?"array":"object";break;default:throw Error(`Instances of "${p}" type are not supported.`)}let{$ref:m,$recursiveRef:h,$recursiveAnchor:f,type:g,const:y,enum:v,required:_,not:b,anyOf:S,allOf:w,oneOf:k,if:x,then:R,else:$,format:C,properties:T,patternProperties:P,additionalProperties:E,unevaluatedProperties:O,minProperties:I,maxProperties:q,propertyNames:j,dependentRequired:A,dependentSchemas:N,dependencies:L,prefixItems:z,items:M,additionalItems:Z,unevaluatedItems:U,contains:F,minContains:H,maxContains:D,minItems:V,maxItems:J,uniqueItems:B,minimum:W,maximum:G,exclusiveMinimum:K,exclusiveMaximum:Y,multipleOf:X,minLength:Q,maxLength:ee,pattern:et,__absolute_ref__:er,__absolute_recursive_ref__:ei}=i,en=[];if(!0===f&&null===s&&(s=i),"#"===h){let d=null===s?a[ei]:s,p=`${c}/$recursiveRef`,m=t(r,null===s?i:s,n,a,o,d,l,p,u);m.valid||en.push({instanceLocation:l,keyword:"$recursiveRef",keywordLocation:p,error:"A subschema had errors."},...m.errors)}if(void 0!==m){let i=a[er||m];if(void 0===i){let t=`Unresolved $ref "${m}".`;throw er&&er!==m&&(t+=` Absolute URI "${er}".`),Error(t+=`
|
|
56
56
|
Known schemas:
|
|
57
|
-
- ${Object.keys(a).join("\n- ")}`)}let d=`${c}/$ref`,p=t(r,i,n,a,o,s,l,d,u);if(p.valid||en.push({instanceLocation:l,keyword:"$ref",keywordLocation:d,error:"A subschema had errors."},...p.errors),"4"===n||"7"===n)return{valid:0===en.length,errors:en}}if(Array.isArray(g)){let t=g.length,i=!1;for(let n=0;n<t;n++)if(d===g[n]||"integer"===g[n]&&"number"===d&&r%1==0&&r==r){i=!0;break}i||en.push({instanceLocation:l,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${g.join('", "')}".`})}else"integer"===g?("number"!==d||r%1||r!=r)&&en.push({instanceLocation:l,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${g}".`}):void 0!==g&&d!==g&&en.push({instanceLocation:l,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${g}".`});if(void 0!==y&&("object"===d||"array"===d?uH(r,y)||en.push({instanceLocation:l,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):r!==y&&en.push({instanceLocation:l,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),void 0!==v&&("object"===d||"array"===d?v.some(t=>uH(r,t))||en.push({instanceLocation:l,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(t=>r===t)||en.push({instanceLocation:l,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),void 0!==b){let i=`${c}/not`;t(r,b,n,a,o,s,l,i).valid&&en.push({instanceLocation:l,keyword:"not",keywordLocation:i,error:'Instance matched "not" schema.'})}let ea=[];if(void 0!==S){let i=`${c}/anyOf`,d=en.length,p=!1;for(let c=0;c<S.length;c++){let d=S[c],m=Object.create(u),h=t(r,d,n,a,o,!0===f?s:null,l,`${i}/${c}`,m);en.push(...h.errors),p=p||h.valid,h.valid&&ea.push(m)}p?en.length=d:en.splice(d,0,{instanceLocation:l,keyword:"anyOf",keywordLocation:i,error:"Instance does not match any subschemas."})}if(void 0!==w){let i=`${c}/allOf`,d=en.length,p=!0;for(let c=0;c<w.length;c++){let d=w[c],m=Object.create(u),h=t(r,d,n,a,o,!0===f?s:null,l,`${i}/${c}`,m);en.push(...h.errors),p=p&&h.valid,h.valid&&ea.push(m)}p?en.length=d:en.splice(d,0,{instanceLocation:l,keyword:"allOf",keywordLocation:i,error:"Instance does not match every subschema."})}if(void 0!==x){let i=`${c}/oneOf`,d=en.length,p=x.filter((c,d)=>{let p=Object.create(u),m=t(r,c,n,a,o,!0===f?s:null,l,`${i}/${d}`,p);return en.push(...m.errors),m.valid&&ea.push(p),m.valid}).length;1===p?en.length=d:en.splice(d,0,{instanceLocation:l,keyword:"oneOf",keywordLocation:i,error:`Instance does not match exactly one subschema (${p} matches).`})}if(("object"===d||"array"===d)&&Object.assign(u,...ea),void 0!==k){let i=`${c}/if`;if(t(r,k,n,a,o,s,l,i,u).valid){if(void 0!==R){let d=t(r,R,n,a,o,s,l,`${c}/then`,u);d.valid||en.push({instanceLocation:l,keyword:"if",keywordLocation:i,error:'Instance does not match "then" schema.'},...d.errors)}}else if(void 0!==$){let d=t(r,$,n,a,o,s,l,`${c}/else`,u);d.valid||en.push({instanceLocation:l,keyword:"if",keywordLocation:i,error:'Instance does not match "else" schema.'},...d.errors)}}if("object"===d){if(void 0!==_)for(let t of _)t in r||en.push({instanceLocation:l,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${t}".`});let i=Object.keys(r);if(void 0!==I&&i.length<I&&en.push({instanceLocation:l,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${I} properties.`}),void 0!==q&&i.length>q&&en.push({instanceLocation:l,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${q} properties.`}),void 0!==j){let i=`${c}/propertyNames`;for(let c in r){let r=`${l}/${uJ(c)}`,u=t(c,j,n,a,o,s,r,i);u.valid||en.push({instanceLocation:l,keyword:"propertyNames",keywordLocation:i,error:`Property name "${c}" does not match schema.`},...u.errors)}}if(void 0!==z){let t=`${c}/dependantRequired`;for(let i in z)if(i in r)for(let n of z[i])n in r||en.push({instanceLocation:l,keyword:"dependentRequired",keywordLocation:t,error:`Instance has "${i}" but does not have "${n}".`})}if(void 0!==N)for(let i in N){let d=`${c}/dependentSchemas`;if(i in r){let c=t(r,N[i],n,a,o,s,l,`${d}/${uJ(i)}`,u);c.valid||en.push({instanceLocation:l,keyword:"dependentSchemas",keywordLocation:d,error:`Instance has "${i}" but does not match dependant schema.`},...c.errors)}}if(void 0!==A){let i=`${c}/dependencies`;for(let c in A)if(c in r){let u=A[c];if(Array.isArray(u))for(let t of u)t in r||en.push({instanceLocation:l,keyword:"dependencies",keywordLocation:i,error:`Instance has "${c}" but does not have "${t}".`});else{let d=t(r,u,n,a,o,s,l,`${i}/${uJ(c)}`);d.valid||en.push({instanceLocation:l,keyword:"dependencies",keywordLocation:i,error:`Instance has "${c}" but does not match dependant schema.`},...d.errors)}}}let d=Object.create(null),p=!1;if(void 0!==T){let i=`${c}/properties`;for(let c in T){if(!(c in r))continue;let m=`${l}/${uJ(c)}`,h=t(r[c],T[c],n,a,o,s,m,`${i}/${uJ(c)}`);if(h.valid)u[c]=d[c]=!0;else if(p=o,en.push({instanceLocation:l,keyword:"properties",keywordLocation:i,error:`Property "${c}" does not match schema.`},...h.errors),p)break}}if(!p&&void 0!==O){let i=`${c}/patternProperties`;for(let c in O){let m=RegExp(c,"u"),h=O[c];for(let f in r){if(!m.test(f))continue;let g=`${l}/${uJ(f)}`,y=t(r[f],h,n,a,o,s,g,`${i}/${uJ(c)}`);y.valid?u[f]=d[f]=!0:(p=o,en.push({instanceLocation:l,keyword:"patternProperties",keywordLocation:i,error:`Property "${f}" matches pattern "${c}" but does not match associated schema.`},...y.errors))}}}if(p||void 0===P){if(!p&&void 0!==E){let i=`${c}/unevaluatedProperties`;for(let c in r)if(!u[c]){let d=`${l}/${uJ(c)}`,p=t(r[c],E,n,a,o,s,d,i);p.valid?u[c]=!0:en.push({instanceLocation:l,keyword:"unevaluatedProperties",keywordLocation:i,error:`Property "${c}" does not match unevaluated properties schema.`},...p.errors)}}}else{let i=`${c}/additionalProperties`;for(let c in r){if(d[c])continue;let m=`${l}/${uJ(c)}`,h=t(r[c],P,n,a,o,s,m,i);h.valid?u[c]=!0:(p=o,en.push({instanceLocation:l,keyword:"additionalProperties",keywordLocation:i,error:`Property "${c}" does not match additional properties schema.`},...h.errors))}}}else if("array"===d){void 0!==V&&r.length>V&&en.push({instanceLocation:l,keyword:"maxItems",keywordLocation:`${c}/maxItems`,error:`Array has too many items (${r.length} > ${V}).`}),void 0!==D&&r.length<D&&en.push({instanceLocation:l,keyword:"minItems",keywordLocation:`${c}/minItems`,error:`Array has too few items (${r.length} < ${D}).`});let i=r.length,d=0,p=!1;if(void 0!==L){let m=`${c}/prefixItems`,h=Math.min(L.length,i);for(;d<h;d++){let i=t(r[d],L[d],n,a,o,s,`${l}/${d}`,`${m}/${d}`);if(u[d]=!0,!i.valid&&(p=o,en.push({instanceLocation:l,keyword:"prefixItems",keywordLocation:m,error:"Items did not match schema."},...i.errors),p))break}}if(void 0!==M){let m=`${c}/items`;if(Array.isArray(M)){let c=Math.min(M.length,i);for(;d<c;d++){let i=t(r[d],M[d],n,a,o,s,`${l}/${d}`,`${m}/${d}`);if(u[d]=!0,!i.valid&&(p=o,en.push({instanceLocation:l,keyword:"items",keywordLocation:m,error:"Items did not match schema."},...i.errors),p))break}}else for(;d<i;d++){let i=t(r[d],M,n,a,o,s,`${l}/${d}`,m);if(u[d]=!0,!i.valid&&(p=o,en.push({instanceLocation:l,keyword:"items",keywordLocation:m,error:"Items did not match schema."},...i.errors),p))break}if(!p&&void 0!==Z){let m=`${c}/additionalItems`;for(;d<i;d++){let i=t(r[d],Z,n,a,o,s,`${l}/${d}`,m);u[d]=!0,i.valid||(p=o,en.push({instanceLocation:l,keyword:"additionalItems",keywordLocation:m,error:"Items did not match additional items schema."},...i.errors))}}}if(void 0!==F)if(0===i&&void 0===H)en.push({instanceLocation:l,keyword:"contains",keywordLocation:`${c}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(void 0!==H&&i<H)en.push({instanceLocation:l,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array has less items (${i}) than minContains (${H}).`});else{let d=`${c}/contains`,p=en.length,m=0;for(let c=0;c<i;c++){let i=t(r[c],F,n,a,o,s,`${l}/${c}`,d);i.valid?(u[c]=!0,m++):en.push(...i.errors)}m>=(H||0)&&(en.length=p),void 0===H&&void 0===J&&0===m?en.splice(p,0,{instanceLocation:l,keyword:"contains",keywordLocation:d,error:"Array does not contain item matching schema."}):void 0!==H&&m<H?en.push({instanceLocation:l,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array must contain at least ${H} items matching schema. Only ${m} items were found.`}):void 0!==J&&m>J&&en.push({instanceLocation:l,keyword:"maxContains",keywordLocation:`${c}/maxContains`,error:`Array may contain at most ${J} items matching schema. ${m} items were found.`})}if(!p&&void 0!==U){let p=`${c}/unevaluatedItems`;for(;d<i;d++){if(u[d])continue;let i=t(r[d],U,n,a,o,s,`${l}/${d}`,p);u[d]=!0,i.valid||en.push({instanceLocation:l,keyword:"unevaluatedItems",keywordLocation:p,error:"Items did not match unevaluated items schema."},...i.errors)}}if(B)for(let t=0;t<i;t++){let n=r[t],a="object"==typeof n&&null!==n;for(let o=0;o<i;o++){if(t===o)continue;let i=r[o];(n===i||a&&"object"==typeof i&&null!==i&&uH(n,i))&&(en.push({instanceLocation:l,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${t} and ${o}.`}),t=Number.MAX_SAFE_INTEGER,o=Number.MAX_SAFE_INTEGER)}}}else if("number"===d){if("4"===n?(void 0!==W&&(!0===K&&r<=W||r<W)&&en.push({instanceLocation:l,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${r} is less than ${K?"or equal to ":""} ${W}.`}),void 0!==G&&(!0===Y&&r>=G||r>G)&&en.push({instanceLocation:l,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${r} is greater than ${Y?"or equal to ":""} ${G}.`})):(void 0!==W&&r<W&&en.push({instanceLocation:l,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${r} is less than ${W}.`}),void 0!==G&&r>G&&en.push({instanceLocation:l,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${r} is greater than ${G}.`}),void 0!==K&&r<=K&&en.push({instanceLocation:l,keyword:"exclusiveMinimum",keywordLocation:`${c}/exclusiveMinimum`,error:`${r} is less than ${K}.`}),void 0!==Y&&r>=Y&&en.push({instanceLocation:l,keyword:"exclusiveMaximum",keywordLocation:`${c}/exclusiveMaximum`,error:`${r} is greater than or equal to ${Y}.`})),void 0!==X){let t=r%X;Math.abs(0-t)>=11920929e-14&&Math.abs(X-t)>=11920929e-14&&en.push({instanceLocation:l,keyword:"multipleOf",keywordLocation:`${c}/multipleOf`,error:`${r} is not a multiple of ${X}.`})}}else if("string"===d){let t=void 0===Q&&void 0===ee?0:function(t){let r,i=0,n=t.length,a=0;for(;a<n;)i++,(r=t.charCodeAt(a++))>=55296&&r<=56319&&a<n&&(64512&(r=t.charCodeAt(a)))==56320&&a++;return i}(r);void 0!==Q&&t<Q&&en.push({instanceLocation:l,keyword:"minLength",keywordLocation:`${c}/minLength`,error:`String is too short (${t} < ${Q}).`}),void 0!==ee&&t>ee&&en.push({instanceLocation:l,keyword:"maxLength",keywordLocation:`${c}/maxLength`,error:`String is too long (${t} > ${ee}).`}),void 0===et||RegExp(et,"u").test(r)||en.push({instanceLocation:l,keyword:"pattern",keywordLocation:`${c}/pattern`,error:"String does not match pattern."}),void 0!==C&&u0[C]&&!u0[C](r)&&en.push({instanceLocation:l,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${C}".`})}return{valid:0===en.length,errors:en}}(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),uG(t,this.lookup)}},u7=class{shortcircuit;draft;constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft}_draftFor(t){let r=function(t,r){if(!("$schema"in t)||"string"!=typeof t.$schema)return"2020-12";let i=t.$schema.replace(/#$/,"");if(K.has(i))return"2020-12";if(Y.has(i))return"2019-09";if(X.has(i)||Q.has(i))return"draft-7";throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${t.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${r}`)}(t,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return"draft-7"===r?"7":r}getValidator(t){let r=new u6(t,this.draft??this._draftFor(t),this.shortcircuit);return t=>{let i=r.validate(t);return i.valid?{valid:!0,data:t,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:i.errors.map(t=>`${t.instanceLocation}: ${t.error}`).join("; ")}}}};uF();let u8=Symbol.for("mcp.completable");function de(t){return!!t&&"object"==typeof t&&u8 in t}let dt=0x80000000-1;function dr(t,r){if(!Number.isFinite(t)||t<1)return;let i=setInterval(r,Math.min(t,dt));return i.unref?.(),i}var di=class{_listeners=new Set;constructor(t){this.onerror=t}publish(t){for(let r of this._listeners)try{r(t)}catch(t){this.onerror?.(t instanceof Error?t:Error(String(t)))}}subscribe(t){this._listeners.add(t);let r=!0;return()=>{r&&(r=!1,this._listeners.delete(t))}}get listenerCount(){return this._listeners.size}};function dn(t,r,i){return Response.json({jsonrpc:"2.0",error:{code:r,message:i},id:t},{status:200})}function da(t,r){return{method:t.method,params:{...t.params,_meta:{...t.params?._meta,[aQ]:r}}}}function ds(t,r,i){if(null===i||"object"!=typeof i||"string"!=typeof i.method)throw new cy(cg.InternalError,`Handler for ${t} returned an invalid input request '${r}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let n=function(t){switch(t.method){case"elicitation/create":if(t.params?.mode==="url")return{elicitation:{url:{}}};return{elicitation:{form:{}}};case"sampling/createMessage":{let r=t.params;if(void 0!==r&&(void 0!==r.tools||void 0!==r.toolChoice))return{sampling:{tools:{}}};return{sampling:{}}}case"roots/list":return{roots:{}};default:return}}(i);if(void 0===n)throw new cy(cg.InternalError,`Handler for ${t} returned an input request '${r}' of kind '${i.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:i,required:n}}function dl(t,r){if("tools/call"===t)return{content:[{type:"text",text:r}],isError:!0};throw new cy(cg.InternalError,r)}var dc=class{constructor(t){this._host=t}async fulfill(t,r,i,n,a){let{maxRounds:o,roundTimeoutMs:s}=this._host,l=n.mcpReq.signal,c=a,u=0;for(;;){let a;if((u+=1)>o)return dl(t,`Multi-round-trip request '${t}' still required input after ${o} rounds (inputRequired.maxRounds)`);let d=c.inputRequests,p=null!=d&&Object.keys(d).length>0,m="string"==typeof c.requestState?c.requestState:void 0;if(!p&&void 0===m)throw new cy(cg.InternalError,`Handler for ${t} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(p){let r=this._host.resolvedClientCapabilities(n),i=[];for(let[n,a]of Object.entries(d)){let{embedded:o,required:s}=ds(t,n,a);if("roots/list"!==o.method&&void 0===o.params)throw new cy(cg.InternalError,`Handler for ${t} returned an input request '${n}' of kind '${o.method}' without params`);if(void 0!==lK(s,r))return dl(t,`Cannot request input '${n}' (${o.method}): the client on this 2025-era connection did not declare the required capability${void 0===r?" (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)":""}`);i.push([n,o])}let o=function(t){let r=new AbortController,i=()=>r.abort(t?.reason);return t?.addEventListener("abort",i,{once:!0}),t?.aborted&&r.abort(t.reason),{signal:r.signal,abort:t=>r.abort(t),dispose:()=>t?.removeEventListener("abort",i)}}(l);try{let t={relatedRequestId:n.mcpReq.id,timeout:s,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:o.signal},r=await Promise.all(i.map(async([r,i])=>{try{return[r,await this._dispatchLeg(i,t)]}catch(t){throw o.abort(t),t}}));a=Object.fromEntries(r)}catch(r){if(l.aborted)throw r;return dl(t,`Fulfilling input required by '${t}' failed: ${r instanceof Error?r.message:String(r)}`)}finally{o.dispose()}}else await function(t,r){return new Promise((t,i)=>{if(r?.aborted)return void i(r.reason instanceof lB?r.reason:new lB(lV.RequestTimeout,String(r.reason)));let n=setTimeout(()=>{r?.removeEventListener("abort",a),t()},250),a=()=>{clearTimeout(n),i(r?.reason instanceof lB?r.reason:new lB(lV.RequestTimeout,String(r?.reason)))};r?.addEventListener("abort",a,{once:!0})})}(0,l);let h={...n,mcpReq:{...n.mcpReq,inputResponses:a,droppedInputResponseKeys:void 0,requestState:function(t){return()=>t}(m)}};if(void 0!==m){let r=await this._host.verifyRequestState(m,h,t);void 0!==r&&(h=uE(h,r))}let f=await r(i,h);if(!cQ(f))return f;c=f}}async _dispatchLeg(t,r){switch(t.method){case"elicitation/create":{let i=t.params;return"url"===i.mode&&void 0===i.elicitationId&&(i={...i,elicitationId:function(){let t=globalThis.crypto;if(t?.randomUUID!==void 0)return t.randomUUID();let r=new Uint8Array(16);t.getRandomValues(r),r[6]=15&r[6]|64,r[8]=63&r[8]|128;let i=[...r].map(t=>t.toString(16).padStart(2,"0")).join("");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}()}),await this._host.sendElicitation(i,r)}case"sampling/createMessage":return await this._host.sendSampling(t.params,r);case"roots/list":return await this._host.listRoots(t.params,r)}}};let du=new Set(["tools/call","prompts/get","resources/read"]);var dd=class extends uI{_clientCapabilities;_clientVersion;static{c=(t,r)=>{void 0!==r.clientCapabilities&&(t._clientCapabilities=r.clientCapabilities),void 0!==r.clientInfo&&(t._clientVersion=r.clientInfo)},u=(t,r)=>{let i=r.filter(r=>!t._supportedProtocolVersions.includes(r));i.length>0&&(t._supportedProtocolVersions=[...t._supportedProtocolVersions,...i]),t.setRequestHandler("server/discover",()=>t._ondiscover())},d=t=>t._serverInfo}_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_legacyInputRequiredShim(){return this._legacyShim??=new dc({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:t=>this._inputRequestCapabilityView(t),verifyRequestState:(t,r,i)=>this._verifyRequestState(t,r,i),sendElicitation:(t,r)=>this._sendElicitationLeg(t,r,{validateAcceptedContent:!1}),sendSampling:(t,r)=>this.createMessage(t,r),listRoots:(t,r)=>this.listRoots(t,r)})}oninitialized;constructor(t,r){if(super(r),this._serverInfo=t,this._capabilities=r?.capabilities?{...r.capabilities}:{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new u7,this._requestStateVerify=r?.requestState?.verify,this._inputRequiredServing=function(t){if(t?.maxRounds!==void 0&&(!Number.isInteger(t.maxRounds)||t.maxRounds<1))throw RangeError(`inputRequired.maxRounds must be a positive integer (got ${t.maxRounds})`);if(t?.roundTimeoutMs!==void 0&&(!Number.isFinite(t.roundTimeoutMs)||t.roundTimeoutMs<=0))throw RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${t.roundTimeoutMs})`);return{maxRounds:t?.maxRounds??8,roundTimeoutMs:t?.roundTimeoutMs??6e5,legacyShim:t?.legacyShim??!0}}(r?.inputRequired),r?.cacheHints!==void 0){for(let[t,i]of Object.entries(r.cacheHints))void 0!==i&&cf(i,`cacheHints['${t}']`);this._cacheHints=r.cacheHints}this.setRequestHandler("initialize",t=>this._oninitialize(t)),this.setNotificationHandler("notifications/initialized",()=>this.oninitialized?.()),lQ(this._supportedProtocolVersions).length>0&&this.setRequestHandler("server/discover",()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}_registerLoggingHandler(){this.setRequestHandler("logging/setLevel",async(t,r)=>{let i=r.sessionId||r.http?.req?.headers.get("mcp-session-id")||void 0,{level:n}=t.params,a=nk(sO,n);return a.success&&this._loggingLevels.set(i,a.data),{}})}buildContext(t,r){let i=t.http||r?.request||r?.closeSSEStream||r?.closeStandaloneSSEStream;return{...t,mcpReq:{...t.mcpReq,log:(r,i,n)=>{let a;if(!this._capabilities.logging)return Promise.resolve();if(this._servedModernEra()){if(void 0===(a=t.mcpReq.envelope?.[a0]))return Promise.resolve()}else a=this._loggingLevels.get(t.sessionId)??this._loggingLevels.get(void 0);return void 0!==a&&this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(a)?Promise.resolve():t.mcpReq.notify({method:"notifications/message",params:{level:r,data:i,logger:n}})},elicitInput:(t,r)=>this.elicitInput(t,r),requestSampling:(t,r)=>this.createMessage(t,r)},http:i?{...t.http,req:r?.request,closeSSE:r?.closeSSEStream,closeStandaloneSSE:r?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(sO.options.map((t,r)=>[t,r]));isMessageIgnored=(t,r)=>{let i=this._loggingLevels.get(r);return!!i&&this.LOG_LEVEL_SEVERITY.get(t)<this.LOG_LEVEL_SEVERITY.get(i)};registerCapabilities(t){if(this.transport)throw new lB(lV.AlreadyConnected,"Cannot register capabilities after connecting to transport");let r=!!this._capabilities.logging;this._capabilities=function(t,r){let i={...t};for(let t in r){let n=r[t];if(void 0===n)continue;let a=i[t];i[t]=uq(a)&&uq(n)?{...a,...n}:n}return i}(this._capabilities,t),!r&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(t,r){if("tools/call"!==t){let i=this._cacheHints?.[t],n=du.has(t);return void 0!==i||n?async(a,o)=>{let s=n?await this._invokeInputRequiredCapableHandler(t,r,a,o):await r(a,o);if(cQ(s)){if(!n)throw new cy(cg.InternalError,`Handler for ${t} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return s}return void 0===i?s:cp(s,i)}:async(i,n)=>{let a=await r(i,n);if(cQ(a))throw new cy(cg.InternalError,`Handler for ${t} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return a}}return async(t,i)=>{let n=cL(this._negotiatedProtocolVersion),a=n.validateRequest("tools/call",t);if(!a.ok)throw new cy("not-in-era"===a.reason?cg.InternalError:cg.InvalidParams,"not-in-era"===a.reason?"No wire schema for tools/call in the resolved era":`Invalid tools/call request: ${a.message}`);let o=await this._invokeInputRequiredCapableHandler("tools/call",r,t,i);if(cQ(o))return o;let s=l2(o),l=n.validateResult("tools/call",s);if(!l.ok)throw new cy("not-in-era"===l.reason?cg.InternalError:cg.InvalidParams,"not-in-era"===l.reason?"No wire schema for tools/call in the resolved era":`Invalid tools/call result: ${l.message}`);return l.value}}_servedModernEra(){return void 0!==this._negotiatedProtocolVersion&&this._negotiatedProtocolVersion>=lY}async _invokeInputRequiredCapableHandler(t,r,i,n){let a,o=this._servedModernEra(),s=n.mcpReq.requestState();if(void 0!==s&&"string"!=typeof s)throw new cy(cg.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"});let l=n;if("string"==typeof s){let r=await this._verifyRequestState(s,n,t);void 0!==r&&(l=uE(n,r))}try{a=await r(i,l)}catch(t){if(t instanceof cy&&t.code===cg.UrlElicitationRequired){if(!o)throw t;throw new cy(cg.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`)}throw t}if(!cQ(a))return a;if(!o){if(!this._inputRequiredServing.legacyShim)throw new cy(cg.InternalError,`Handler for ${t} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??aB}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(t,r,i,l,a)}let c=a.inputRequests,u=null!=c&&Object.keys(c).length>0,d="string"==typeof a.requestState;if(!u&&!d)throw new cy(cg.InternalError,`Handler for ${t} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(u){let r=this._inputRequestCapabilityView(n);for(let[i,n]of Object.entries(c)){let{embedded:a,required:o}=ds(t,i,n),s=lK(o,r);if(void 0!==s)throw new cS({requiredCapabilities:s},`Cannot request input '${i}' (${a.method}): the request's client capabilities do not declare the required capability`)}}return a}async _verifyRequestState(t,r,i){if(void 0!==this._requestStateVerify)try{return await this._requestStateVerify(t,r)}catch(t){throw this.onerror?.(Error(`requestState verification rejected ${i}: ${t instanceof Error?t.message:String(t)}`)),new cy(cg.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"})}}_inputRequestCapabilityView(t){return this._servedModernEra()?t.mcpReq.envelope?.[aX]:this._clientCapabilities}_assertPushApiInServedEra(t){if(this._servedModernEra())throw new lB(lV.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${t}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:t,era:"2026-07-28"})}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new lB(lV.CapabilityNotSupported,`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new lB(lV.CapabilityNotSupported,`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new lB(lV.CapabilityNotSupported,`Client does not support listing roots (required for ${t})`)}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new lB(lV.CapabilityNotSupported,`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new lB(lV.CapabilityNotSupported,`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new lB(lV.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new lB(lV.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new lB(lV.CapabilityNotSupported,`Client does not support URL elicitation (required for ${t})`)}}assertRequestHandlerCapability(t){switch(t){case"completion/complete":if(!this._capabilities.completions)throw new lB(lV.CapabilityNotSupported,`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new lB(lV.CapabilityNotSupported,`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new lB(lV.CapabilityNotSupported,`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new lB(lV.CapabilityNotSupported,`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new lB(lV.CapabilityNotSupported,`Server does not support tools (required for ${t})`)}}async _oninitialize(t){let r=t.params.protocolVersion;this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo;let i=this._supportedProtocolVersions.filter(t=>!(t>=lY)),n=i.includes(r)?r:i[0]??aB;return this._negotiatedProtocolVersion=n,this.transport?.setProtocolVersion?.(n),{protocolVersion:n,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:lQ(this._supportedProtocolVersions),capabilities:{...this.getCapabilities()},...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(t,r){return this._wireCodec().projectCallToolResult(t,r)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra("ping"),this.request({method:"ping"})}async createMessage(t,r){if(this._assertPushApiInServedEra("sampling/createMessage"),(t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new lB(lV.CapabilityNotSupported,"Client does not support sampling tools capability.");if(t.messages.length>0){let r=t.messages.at(-1),i=Array.isArray(r.content)?r.content:[r.content],n=i.some(t=>"tool_result"===t.type),a=t.messages.length>1?t.messages.at(-2):void 0,o=a?Array.isArray(a.content)?a.content:[a.content]:[],s=o.some(t=>"tool_use"===t.type);if(n){if(i.some(t=>"tool_result"!==t.type))throw new cy(cg.InvalidParams,"The last message must contain only tool_result content if any is present");if(!s)throw new cy(cg.InvalidParams,"tool_result blocks are not matching any tool_use from the previous message")}if(s){let t=new Set(o.filter(t=>"tool_use"===t.type).map(t=>t.id)),r=new Set(i.filter(t=>"tool_result"===t.type).map(t=>t.toolUseId));if(t.size!==r.size||![...t].every(t=>r.has(t)))throw new cy(cg.InvalidParams,"ids of tool_result blocks and tool_use blocks from previous message do not match")}}let i=!!(t.tools||t.toolChoice),n=await this.request({method:"sampling/createMessage",params:t},r),a=this._wireCodec().samplingResultVariant(i,n);if(!a.ok)throw new lB(lV.InvalidResult,`Invalid sampling/createMessage result: ${"invalid"===a.reason?a.message:a.reason}`);return a.value}async elicitInput(t,r){switch(this._assertPushApiInServedEra("elicitation/create"),t.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw new lB(lV.CapabilityNotSupported,"Client does not support url elicitation.");break;case"form":if(!this._clientCapabilities?.elicitation?.form)throw new lB(lV.CapabilityNotSupported,"Client does not support form elicitation.")}return this._sendElicitationLeg(t,r)}async _sendElicitationLeg(t,r,i){let n=t.mode??"form",a=i?.validateAcceptedContent??!0;switch(n){case"url":return this.request({method:"elicitation/create",params:t},r);case"form":{let i="form"===t.mode?t:{...t,mode:"form"},n=await this.request({method:"elicitation/create",params:i},r);if(a&&"accept"===n.action&&n.content&&i.requestedSchema)try{let t=this._jsonSchemaValidator.getValidator(i.requestedSchema)(n.content);if(!t.valid)throw new cy(cg.InvalidParams,`Elicitation response content does not match requested schema: ${t.errorMessage}`)}catch(t){if(t instanceof cy)throw t;throw new cy(cg.InternalError,`Error validating elicitation response: ${t instanceof Error?t.message:String(t)}`)}return n}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new lB(lV.CapabilityNotSupported,"Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this._assertPushApiInServedEra("roots/list"),this.request({method:"roots/list",params:t},r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}},dp=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(t){let r=this._registeredTools[t];if(void 0!==r&&r.enabled){if(Object.hasOwn(this._toolInputSchemaJson,t))return this._toolInputSchemaJson[t];if(void 0===r.inputSchema)return df;try{let i=um(r.inputSchema,"input");return this._toolInputSchemaJson[t]=i,i}catch{return}}}constructor(t,r){this.server=new dd(t,r),r?.capabilities?.tools&&this.setToolRequestHandlers(),r?.capabilities?.resources&&this.setResourceRequestHandlers(),r?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler("tools/list"),this.server.assertCanSetRequestHandler("tools/call"),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler("tools/list",()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let i={name:t,title:r.title,description:r.description,inputSchema:r.inputSchema?um(r.inputSchema,"input"):df,annotations:r.annotations,icons:r.icons,execution:r.execution,_meta:r._meta};return r.outputSchema&&(i.outputSchema=um(r.outputSchema,"output")),i})})),this.server.setRequestHandler("tools/call",async(t,r)=>{let i=this._registeredTools[t.params.name];if(!i)throw new cy(cg.InvalidParams,`Tool ${t.params.name} not found`);if(!i.enabled)throw new cy(cg.InvalidParams,`Tool ${t.params.name} disabled`);try{let n=await this.validateToolInput(i,t.params.arguments,t.params.name),a=await this.executeToolHandler(i,n,r);if(await this.validateToolOutput(i,a,t.params.name),cQ(a))return a;return this.server.projectCallToolResult(a,i.outputSchemaJson)}catch(t){if(t instanceof cy&&t.code===cg.UrlElicitationRequired)throw t;return this.createToolError(t instanceof Error?t.message:String(t))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,i){if(!t.inputSchema)return;let n=await uh(t.inputSchema,r??{});if(!n.success)throw new cy(cg.InvalidParams,`Input validation error: Invalid arguments for tool ${i}: ${n.error}`);return n.data}async validateToolOutput(t,r,i){if(!t.outputSchema||cQ(r)||r.isError)return;if(void 0===r.structuredContent)throw new cy(cg.InvalidParams,`Output validation error: Tool ${i} has an output schema but no structured content was provided`);let n=await uh(t.outputSchema,r.structuredContent);if(!n.success)throw new cy(cg.InvalidParams,`Output validation error: Invalid structured content for tool ${i}: ${n.error}`)}async executeToolHandler(t,r,i){return t.executor(r,i)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler("completion/complete"),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler("completion/complete",async t=>{switch(t.params.ref.type){case"ref/prompt":if("ref/prompt"!==t.params.ref.type)throw TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`);return this.handlePromptCompletion(t,t.params.ref);case"ref/resource":if("ref/resource"!==t.params.ref.type)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`);return this.handleResourceCompletion(t,t.params.ref);default:throw new cy(cg.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let i=this._registeredPrompts[r.name];if(!i)throw new cy(cg.InvalidParams,`Prompt ${r.name} not found`);if(!i.enabled)throw new cy(cg.InvalidParams,`Prompt ${r.name} disabled`);if(!i.argsSchema)return d_;let n=dS(db(i.argsSchema)?.[t.params.argument.name]);if(!de(n))return d_;let a=n[u8]?.complete;return a?dv(await a(t.params.argument.value,t.params.context)):d_}async handleResourceCompletion(t,r){let i=Object.values(this._registeredResourceTemplates).find(t=>t.resourceTemplate.uriTemplate.toString()===r.uri);if(!i){if(this._registeredResources[r.uri])return d_;throw new cy(cg.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let n=i.resourceTemplate.completeCallback(t.params.argument.name);return n?dv(await n(t.params.argument.value,t.params.context)):d_}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler("resources/list"),this.server.assertCanSetRequestHandler("resources/templates/list"),this.server.assertCanSetRequestHandler("resources/read"),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler("resources/list",async(t,r)=>{let i=Object.entries(this._registeredResources).filter(([t,r])=>r.enabled).map(([t,r])=>({uri:t,name:r.name,...r.metadata})),n=[];for(let t of Object.values(this._registeredResourceTemplates))if(t.resourceTemplate.listCallback)for(let i of(await t.resourceTemplate.listCallback(r)).resources)n.push({...t.metadata,...i});return{resources:[...i,...n]}}),this.server.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler("resources/read",async(t,r)=>{let i;try{i=new URL(t.params.uri)}catch{throw new cy(cg.InvalidParams,`Resource URI ${t.params.uri} is invalid`,{uri:t.params.uri,reason:"invalid_uri"})}let n=this._registeredResources[i.toString()];if(n){if(!n.enabled)throw new cy(cg.InvalidParams,`Resource ${i} disabled`);return cp(await n.readCallback(i,r),n.cacheHint)}for(let t of Object.values(this._registeredResourceTemplates)){let n=t.resourceTemplate.uriTemplate.match(i.toString());if(n)return cp(await t.readCallback(i,n,r),t.cacheHint)}throw new cv(t.params.uri)}),this._resourceHandlersInitialized=!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler("prompts/list"),this.server.assertCanSetRequestHandler("prompts/get"),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler("prompts/list",()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>{let i,n,a;return{name:t,title:r.title,description:r.description,arguments:r.argsSchema?(n=(i=um(r.argsSchema,"input")).properties||{},a=i.required||[],Object.entries(n).map(([t,r])=>({name:t,description:r?.description,required:a.includes(t)}))):void 0,icons:r.icons,_meta:r._meta}})})),this.server.setRequestHandler("prompts/get",async(t,r)=>{let i=this._registeredPrompts[t.params.name];if(!i)throw new cy(cg.InvalidParams,`Prompt ${t.params.name} not found`);if(!i.enabled)throw new cy(cg.InvalidParams,`Prompt ${t.params.name} disabled`);return i.handler(t.params.arguments,r)}),this._promptHandlersInitialized=!0)}registerResource(t,r,i,n){let a=i.cacheHint,o=i;if(void 0!==a){cf(a,`resource ${t}`);let r={...i};delete r.cacheHint,o=r}if("string"==typeof r){if(this._registeredResources[r])throw Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,i.title,r,o,n);return void 0!==a&&(s.cacheHint=a),this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}{if(this._registeredResourceTemplates[t])throw Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,i.title,r,o,n);return void 0!==a&&(s.cacheHint=a),this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(t,r,i,n,a){let o={name:t,title:r,metadata:n,readCallback:a,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:t=>{void 0!==t.uri&&t.uri!==i&&(delete this._registeredResources[i],t.uri&&(this._registeredResources[t.uri]=o)),void 0!==t.name&&(o.name=t.name),void 0!==t.title&&(o.title=t.title),void 0!==t.metadata&&(o.metadata=t.metadata),void 0!==t.callback&&(o.readCallback=t.callback),void 0!==t.enabled&&(o.enabled=t.enabled),this.sendResourceListChanged()}};return this._registeredResources[i]=o,o}_createRegisteredResourceTemplate(t,r,i,n,a){let o={resourceTemplate:i,title:r,metadata:n,readCallback:a,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:r=>{void 0!==r.name&&r.name!==t&&(delete this._registeredResourceTemplates[t],r.name&&(this._registeredResourceTemplates[r.name]=o)),void 0!==r.title&&(o.title=r.title),void 0!==r.template&&(o.resourceTemplate=r.template),void 0!==r.metadata&&(o.metadata=r.metadata),void 0!==r.callback&&(o.readCallback=r.callback),void 0!==r.enabled&&(o.enabled=r.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=o;let s=i.uriTemplate.variableNames;return Array.isArray(s)&&s.some(t=>!!i.completeCallback(t))&&this.setCompletionRequestHandler(),o}_createRegisteredPrompt(t,r,i,n,a,o,s){let l=n,c=a,u={title:r,description:i,argsSchema:n,icons:o,_meta:s,handler:dy(t,n,a),enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:r=>{void 0!==r.name&&r.name!==t&&(delete this._registeredPrompts[t],r.name&&(this._registeredPrompts[r.name]=u)),void 0!==r.title&&(u.title=r.title),void 0!==r.description&&(u.description=r.description),void 0!==r.icons&&(u.icons=r.icons),void 0!==r._meta&&(u._meta=r._meta);let i=!1;void 0!==r.argsSchema&&(u.argsSchema=r.argsSchema,l=r.argsSchema,i=!0),void 0!==r.callback&&(c=r.callback,i=!0),i&&(u.handler=dy(t,l,c)),void 0!==r.enabled&&(u.enabled=r.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[t]=u,n){let t=db(n);t&&Object.values(t).some(t=>de(dS(t)))&&this.setCompletionRequestHandler()}return u}_createRegisteredTool(t,r,i,n,a,o,s,l,c,u){if(uM(t),void 0!==n)try{let r=um(n,"input");this._toolInputSchemaJson[t]=r;let i=c9(r);i.valid||console.warn(`[mcp-sdk] tool '${t}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${i.reason}`)}catch{}let d=u,p={title:r,description:i,inputSchema:n,outputSchema:a,outputSchemaJson:dg(a),annotations:o,icons:s,execution:l,_meta:c,handler:u,executor:dh(n,u),enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:r=>{void 0!==r.name&&r.name!==t&&("string"==typeof r.name&&uM(r.name),delete this._registeredTools[t],delete this._toolInputSchemaJson[t],r.name&&(delete this._toolInputSchemaJson[r.name],this._registeredTools[r.name]=p,t=r.name)),void 0!==r.title&&(p.title=r.title),void 0!==r.description&&(p.description=r.description);let i=!1;void 0!==r.paramsSchema&&(p.inputSchema=r.paramsSchema,delete this._toolInputSchemaJson[t],i=!0),void 0!==r.callback&&(p.handler=r.callback,d=r.callback,i=!0),i&&(p.executor=dh(p.inputSchema,d)),void 0!==r.outputSchema&&(p.outputSchema=r.outputSchema,p.outputSchemaJson=dg(r.outputSchema)),void 0!==r.annotations&&(p.annotations=r.annotations),void 0!==r.icons&&(p.icons=r.icons),void 0!==r._meta&&(p._meta=r._meta),void 0!==r.enabled&&(p.enabled=r.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}registerTool(t,r,i){if(this._registeredTools[t])throw Error(`Tool ${t} is already registered`);let{title:n,description:a,inputSchema:o,outputSchema:s,annotations:l,icons:c,_meta:u}=r;return this._createRegisteredTool(t,n,a,uU(o),uU(s),l,c,void 0,u,i)}registerPrompt(t,r,i){if(this._registeredPrompts[t])throw Error(`Prompt ${t} is already registered`);let{title:n,description:a,argsSchema:o,icons:s,_meta:l}=r,c=this._createRegisteredPrompt(t,n,a,uU(o),i,s,l);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),c}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},dm=class{_uriTemplate;constructor(t,r){this._callbacks=r,this._uriTemplate="string"==typeof t?new uZ(t):t}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(t){return this._callbacks.complete?.[t]}};function dh(t,r){return t?async(t,i)=>r(t,i):async(t,i)=>r(i)}let df={type:"object",properties:{}};function dg(t){if(void 0!==t)try{return um(t,"output")}catch{return}}function dy(t,r,i){return r?async(n,a)=>{let o=await uh(r,n);if(!o.success)throw new cy(cg.InvalidParams,`Invalid arguments for prompt ${t}: ${o.error}`);return i(o.data,a)}:async(t,r)=>i(r)}function dv(t){return{completion:{values:t.map(String).slice(0,100),total:t.length,hasMore:t.length>100}}}let d_={completion:{values:[],hasMore:!1}};function db(t){if(t.shape&&"object"==typeof t.shape)return t.shape}function dS(t){return t?.type!=="optional"?t:t.def?.innerType??t}var dw=class{onclose;onerror;onmessage;_classification;_responseMode;_started=!1;_used=!1;_closed=!1;_terminalDelivered=!1;_dispatchWindowOpen=!1;_requestId;_deferredResponse;_sse;_abortCleanup;_keepAliveMs;constructor(t){this._classification=t.classification,this._responseMode=t.responseMode??"auto",this._keepAliveMs=t.keepAliveMs??15e3}async start(){if(this._started)throw Error("PerRequestHTTPServerTransport is already started");this._started=!0}async handleMessage(t,r){if(this._used)throw Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request");if(!this._started||void 0===this.onmessage)throw Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message");if(this._closed)throw Error("PerRequestHTTPServerTransport is closed");this._used=!0;let i=r?.request?.signal;if(i?.aborted)throw await this.close(),new lB(lV.ConnectionClosed,"The request was aborted before it could be handled");let n={classification:this._classification,...r?.request!==void 0&&{request:r.request},...r?.authInfo!==void 0&&{authInfo:r.authInfo}};if(cG(t)){let r,a;this._requestId=t.id;let o=new Promise((t,i)=>{r=t,a=i});if(this._deferredResponse={promise:o,resolve:r,reject:a,settled:!1},void 0!==i){let t=()=>void this.close();i.addEventListener("abort",t,{once:!0}),this._abortCleanup=()=>i.removeEventListener("abort",t)}this._dispatchWindowOpen=!0;try{this.onmessage(t,n)}finally{this._dispatchWindowOpen=!1}return"sse"!==this._responseMode||this._closed||this._deferredResponse.settled||this.upgradeToSse(),o}return this.onmessage(t,n),new Response(null,{status:202})}async send(t,r){if(this._closed)return;let i=cY(t)||cX(t),n=i?t.id:r?.relatedRequestId;if(void 0===this._requestId||void 0===n||n!==this._requestId){i&&this.onerror?.(Error(`Received a response for an unknown request id: ${String(t.id)}`));return}if(i){if(this._terminalDelivered)return;this._terminalDelivered=!0;let r=cX(t)?t.error.code:void 0,i=void 0!==r&&(this._dispatchWindowOpen||r===cg.MissingRequiredClientCapability)?ur[r]:void 0;if(void 0!==i&&void 0===this._sse){this.settleResponse(Response.json(t,{status:i,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>void this.close());return}if(void 0!==this._sse||"sse"===this._responseMode){void 0===this._sse&&this.upgradeToSse(),this.writeMessageFrame(t),this.finalizeStream();return}this.settleResponse(Response.json(t,{status:200,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>void this.close());return}"json"!==this._responseMode&&(void 0===this._sse&&this.upgradeToSse(),this.writeMessageFrame(t))}writeCommentFrame(t){if(this._closed||void 0===this._sse||this._sse.closed)return;let r=t.split("\n").map(t=>`: ${t}`).join("\n");this.writeFrame(`${r}
|
|
57
|
+
- ${Object.keys(a).join("\n- ")}`)}let d=`${c}/$ref`,p=t(r,i,n,a,o,s,l,d,u);if(p.valid||en.push({instanceLocation:l,keyword:"$ref",keywordLocation:d,error:"A subschema had errors."},...p.errors),"4"===n||"7"===n)return{valid:0===en.length,errors:en}}if(Array.isArray(g)){let t=g.length,i=!1;for(let n=0;n<t;n++)if(d===g[n]||"integer"===g[n]&&"number"===d&&r%1==0&&r==r){i=!0;break}i||en.push({instanceLocation:l,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${g.join('", "')}".`})}else"integer"===g?("number"!==d||r%1||r!=r)&&en.push({instanceLocation:l,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${g}".`}):void 0!==g&&d!==g&&en.push({instanceLocation:l,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${g}".`});if(void 0!==y&&("object"===d||"array"===d?uF(r,y)||en.push({instanceLocation:l,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):r!==y&&en.push({instanceLocation:l,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),void 0!==v&&("object"===d||"array"===d?v.some(t=>uF(r,t))||en.push({instanceLocation:l,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(t=>r===t)||en.push({instanceLocation:l,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),void 0!==b){let i=`${c}/not`;t(r,b,n,a,o,s,l,i).valid&&en.push({instanceLocation:l,keyword:"not",keywordLocation:i,error:'Instance matched "not" schema.'})}let ea=[];if(void 0!==S){let i=`${c}/anyOf`,d=en.length,p=!1;for(let c=0;c<S.length;c++){let d=S[c],m=Object.create(u),h=t(r,d,n,a,o,!0===f?s:null,l,`${i}/${c}`,m);en.push(...h.errors),p=p||h.valid,h.valid&&ea.push(m)}p?en.length=d:en.splice(d,0,{instanceLocation:l,keyword:"anyOf",keywordLocation:i,error:"Instance does not match any subschemas."})}if(void 0!==w){let i=`${c}/allOf`,d=en.length,p=!0;for(let c=0;c<w.length;c++){let d=w[c],m=Object.create(u),h=t(r,d,n,a,o,!0===f?s:null,l,`${i}/${c}`,m);en.push(...h.errors),p=p&&h.valid,h.valid&&ea.push(m)}p?en.length=d:en.splice(d,0,{instanceLocation:l,keyword:"allOf",keywordLocation:i,error:"Instance does not match every subschema."})}if(void 0!==k){let i=`${c}/oneOf`,d=en.length,p=k.filter((c,d)=>{let p=Object.create(u),m=t(r,c,n,a,o,!0===f?s:null,l,`${i}/${d}`,p);return en.push(...m.errors),m.valid&&ea.push(p),m.valid}).length;1===p?en.length=d:en.splice(d,0,{instanceLocation:l,keyword:"oneOf",keywordLocation:i,error:`Instance does not match exactly one subschema (${p} matches).`})}if(("object"===d||"array"===d)&&Object.assign(u,...ea),void 0!==x){let i=`${c}/if`;if(t(r,x,n,a,o,s,l,i,u).valid){if(void 0!==R){let d=t(r,R,n,a,o,s,l,`${c}/then`,u);d.valid||en.push({instanceLocation:l,keyword:"if",keywordLocation:i,error:'Instance does not match "then" schema.'},...d.errors)}}else if(void 0!==$){let d=t(r,$,n,a,o,s,l,`${c}/else`,u);d.valid||en.push({instanceLocation:l,keyword:"if",keywordLocation:i,error:'Instance does not match "else" schema.'},...d.errors)}}if("object"===d){if(void 0!==_)for(let t of _)t in r||en.push({instanceLocation:l,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${t}".`});let i=Object.keys(r);if(void 0!==I&&i.length<I&&en.push({instanceLocation:l,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${I} properties.`}),void 0!==q&&i.length>q&&en.push({instanceLocation:l,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${q} properties.`}),void 0!==j){let i=`${c}/propertyNames`;for(let c in r){let r=`${l}/${uH(c)}`,u=t(c,j,n,a,o,s,r,i);u.valid||en.push({instanceLocation:l,keyword:"propertyNames",keywordLocation:i,error:`Property name "${c}" does not match schema.`},...u.errors)}}if(void 0!==A){let t=`${c}/dependantRequired`;for(let i in A)if(i in r)for(let n of A[i])n in r||en.push({instanceLocation:l,keyword:"dependentRequired",keywordLocation:t,error:`Instance has "${i}" but does not have "${n}".`})}if(void 0!==N)for(let i in N){let d=`${c}/dependentSchemas`;if(i in r){let c=t(r,N[i],n,a,o,s,l,`${d}/${uH(i)}`,u);c.valid||en.push({instanceLocation:l,keyword:"dependentSchemas",keywordLocation:d,error:`Instance has "${i}" but does not match dependant schema.`},...c.errors)}}if(void 0!==L){let i=`${c}/dependencies`;for(let c in L)if(c in r){let u=L[c];if(Array.isArray(u))for(let t of u)t in r||en.push({instanceLocation:l,keyword:"dependencies",keywordLocation:i,error:`Instance has "${c}" but does not have "${t}".`});else{let d=t(r,u,n,a,o,s,l,`${i}/${uH(c)}`);d.valid||en.push({instanceLocation:l,keyword:"dependencies",keywordLocation:i,error:`Instance has "${c}" but does not match dependant schema.`},...d.errors)}}}let d=Object.create(null),p=!1;if(void 0!==T){let i=`${c}/properties`;for(let c in T){if(!(c in r))continue;let m=`${l}/${uH(c)}`,h=t(r[c],T[c],n,a,o,s,m,`${i}/${uH(c)}`);if(h.valid)u[c]=d[c]=!0;else if(p=o,en.push({instanceLocation:l,keyword:"properties",keywordLocation:i,error:`Property "${c}" does not match schema.`},...h.errors),p)break}}if(!p&&void 0!==P){let i=`${c}/patternProperties`;for(let c in P){let m=RegExp(c,"u"),h=P[c];for(let f in r){if(!m.test(f))continue;let g=`${l}/${uH(f)}`,y=t(r[f],h,n,a,o,s,g,`${i}/${uH(c)}`);y.valid?u[f]=d[f]=!0:(p=o,en.push({instanceLocation:l,keyword:"patternProperties",keywordLocation:i,error:`Property "${f}" matches pattern "${c}" but does not match associated schema.`},...y.errors))}}}if(p||void 0===E){if(!p&&void 0!==O){let i=`${c}/unevaluatedProperties`;for(let c in r)if(!u[c]){let d=`${l}/${uH(c)}`,p=t(r[c],O,n,a,o,s,d,i);p.valid?u[c]=!0:en.push({instanceLocation:l,keyword:"unevaluatedProperties",keywordLocation:i,error:`Property "${c}" does not match unevaluated properties schema.`},...p.errors)}}}else{let i=`${c}/additionalProperties`;for(let c in r){if(d[c])continue;let m=`${l}/${uH(c)}`,h=t(r[c],E,n,a,o,s,m,i);h.valid?u[c]=!0:(p=o,en.push({instanceLocation:l,keyword:"additionalProperties",keywordLocation:i,error:`Property "${c}" does not match additional properties schema.`},...h.errors))}}}else if("array"===d){void 0!==J&&r.length>J&&en.push({instanceLocation:l,keyword:"maxItems",keywordLocation:`${c}/maxItems`,error:`Array has too many items (${r.length} > ${J}).`}),void 0!==V&&r.length<V&&en.push({instanceLocation:l,keyword:"minItems",keywordLocation:`${c}/minItems`,error:`Array has too few items (${r.length} < ${V}).`});let i=r.length,d=0,p=!1;if(void 0!==z){let m=`${c}/prefixItems`,h=Math.min(z.length,i);for(;d<h;d++){let i=t(r[d],z[d],n,a,o,s,`${l}/${d}`,`${m}/${d}`);if(u[d]=!0,!i.valid&&(p=o,en.push({instanceLocation:l,keyword:"prefixItems",keywordLocation:m,error:"Items did not match schema."},...i.errors),p))break}}if(void 0!==M){let m=`${c}/items`;if(Array.isArray(M)){let c=Math.min(M.length,i);for(;d<c;d++){let i=t(r[d],M[d],n,a,o,s,`${l}/${d}`,`${m}/${d}`);if(u[d]=!0,!i.valid&&(p=o,en.push({instanceLocation:l,keyword:"items",keywordLocation:m,error:"Items did not match schema."},...i.errors),p))break}}else for(;d<i;d++){let i=t(r[d],M,n,a,o,s,`${l}/${d}`,m);if(u[d]=!0,!i.valid&&(p=o,en.push({instanceLocation:l,keyword:"items",keywordLocation:m,error:"Items did not match schema."},...i.errors),p))break}if(!p&&void 0!==Z){let m=`${c}/additionalItems`;for(;d<i;d++){let i=t(r[d],Z,n,a,o,s,`${l}/${d}`,m);u[d]=!0,i.valid||(p=o,en.push({instanceLocation:l,keyword:"additionalItems",keywordLocation:m,error:"Items did not match additional items schema."},...i.errors))}}}if(void 0!==F)if(0===i&&void 0===H)en.push({instanceLocation:l,keyword:"contains",keywordLocation:`${c}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(void 0!==H&&i<H)en.push({instanceLocation:l,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array has less items (${i}) than minContains (${H}).`});else{let d=`${c}/contains`,p=en.length,m=0;for(let c=0;c<i;c++){let i=t(r[c],F,n,a,o,s,`${l}/${c}`,d);i.valid?(u[c]=!0,m++):en.push(...i.errors)}m>=(H||0)&&(en.length=p),void 0===H&&void 0===D&&0===m?en.splice(p,0,{instanceLocation:l,keyword:"contains",keywordLocation:d,error:"Array does not contain item matching schema."}):void 0!==H&&m<H?en.push({instanceLocation:l,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array must contain at least ${H} items matching schema. Only ${m} items were found.`}):void 0!==D&&m>D&&en.push({instanceLocation:l,keyword:"maxContains",keywordLocation:`${c}/maxContains`,error:`Array may contain at most ${D} items matching schema. ${m} items were found.`})}if(!p&&void 0!==U){let p=`${c}/unevaluatedItems`;for(;d<i;d++){if(u[d])continue;let i=t(r[d],U,n,a,o,s,`${l}/${d}`,p);u[d]=!0,i.valid||en.push({instanceLocation:l,keyword:"unevaluatedItems",keywordLocation:p,error:"Items did not match unevaluated items schema."},...i.errors)}}if(B)for(let t=0;t<i;t++){let n=r[t],a="object"==typeof n&&null!==n;for(let o=0;o<i;o++){if(t===o)continue;let i=r[o];(n===i||a&&"object"==typeof i&&null!==i&&uF(n,i))&&(en.push({instanceLocation:l,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${t} and ${o}.`}),t=Number.MAX_SAFE_INTEGER,o=Number.MAX_SAFE_INTEGER)}}}else if("number"===d){if("4"===n?(void 0!==W&&(!0===K&&r<=W||r<W)&&en.push({instanceLocation:l,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${r} is less than ${K?"or equal to ":""} ${W}.`}),void 0!==G&&(!0===Y&&r>=G||r>G)&&en.push({instanceLocation:l,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${r} is greater than ${Y?"or equal to ":""} ${G}.`})):(void 0!==W&&r<W&&en.push({instanceLocation:l,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${r} is less than ${W}.`}),void 0!==G&&r>G&&en.push({instanceLocation:l,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${r} is greater than ${G}.`}),void 0!==K&&r<=K&&en.push({instanceLocation:l,keyword:"exclusiveMinimum",keywordLocation:`${c}/exclusiveMinimum`,error:`${r} is less than ${K}.`}),void 0!==Y&&r>=Y&&en.push({instanceLocation:l,keyword:"exclusiveMaximum",keywordLocation:`${c}/exclusiveMaximum`,error:`${r} is greater than or equal to ${Y}.`})),void 0!==X){let t=r%X;Math.abs(0-t)>=11920929e-14&&Math.abs(X-t)>=11920929e-14&&en.push({instanceLocation:l,keyword:"multipleOf",keywordLocation:`${c}/multipleOf`,error:`${r} is not a multiple of ${X}.`})}}else if("string"===d){let t=void 0===Q&&void 0===ee?0:function(t){let r,i=0,n=t.length,a=0;for(;a<n;)i++,(r=t.charCodeAt(a++))>=55296&&r<=56319&&a<n&&(64512&(r=t.charCodeAt(a)))==56320&&a++;return i}(r);void 0!==Q&&t<Q&&en.push({instanceLocation:l,keyword:"minLength",keywordLocation:`${c}/minLength`,error:`String is too short (${t} < ${Q}).`}),void 0!==ee&&t>ee&&en.push({instanceLocation:l,keyword:"maxLength",keywordLocation:`${c}/maxLength`,error:`String is too long (${t} > ${ee}).`}),void 0===et||RegExp(et,"u").test(r)||en.push({instanceLocation:l,keyword:"pattern",keywordLocation:`${c}/pattern`,error:"String does not match pattern."}),void 0!==C&&uQ[C]&&!uQ[C](r)&&en.push({instanceLocation:l,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${C}".`})}return{valid:0===en.length,errors:en}}(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),uW(t,this.lookup)}},u6=class{shortcircuit;draft;constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft}_draftFor(t){let r=function(t,r){if(!("$schema"in t)||"string"!=typeof t.$schema)return"2020-12";let i=t.$schema.replace(/#$/,"");if(G.has(i))return"2020-12";if(K.has(i))return"2019-09";if(Y.has(i)||X.has(i))return"draft-7";throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${t.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${r}`)}(t,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return"draft-7"===r?"7":r}getValidator(t){let r=new u3(t,this.draft??this._draftFor(t),this.shortcircuit);return t=>{let i=r.validate(t);return i.valid?{valid:!0,data:t,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:i.errors.map(t=>`${t.instanceLocation}: ${t.error}`).join("; ")}}}};uU();let u7=Symbol.for("mcp.completable");function u8(t){return!!t&&"object"==typeof t&&u7 in t}let de=0x80000000-1;function dt(t,r){if(!Number.isFinite(t)||t<1)return;let i=setInterval(r,Math.min(t,de));return i.unref?.(),i}var dr=class{_listeners=new Set;constructor(t){this.onerror=t}publish(t){for(let r of this._listeners)try{r(t)}catch(t){this.onerror?.(t instanceof Error?t:Error(String(t)))}}subscribe(t){this._listeners.add(t);let r=!0;return()=>{r&&(r=!1,this._listeners.delete(t))}}get listenerCount(){return this._listeners.size}};function di(t,r,i){return Response.json({jsonrpc:"2.0",error:{code:r,message:i},id:t},{status:200})}function dn(t,r){return{method:t.method,params:{...t.params,_meta:{...t.params?._meta,[aX]:r}}}}function da(t,r,i){if(null===i||"object"!=typeof i||"string"!=typeof i.method)throw new cg(cf.InternalError,`Handler for ${t} returned an invalid input request '${r}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);let n=function(t){switch(t.method){case"elicitation/create":if(t.params?.mode==="url")return{elicitation:{url:{}}};return{elicitation:{form:{}}};case"sampling/createMessage":{let r=t.params;if(void 0!==r&&(void 0!==r.tools||void 0!==r.toolChoice))return{sampling:{tools:{}}};return{sampling:{}}}case"roots/list":return{roots:{}};default:return}}(i);if(void 0===n)throw new cg(cf.InternalError,`Handler for ${t} returned an input request '${r}' of kind '${i.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:i,required:n}}function ds(t,r){if("tools/call"===t)return{content:[{type:"text",text:r}],isError:!0};throw new cg(cf.InternalError,r)}var dl=class{constructor(t){this._host=t}async fulfill(t,r,i,n,a){let{maxRounds:o,roundTimeoutMs:s}=this._host,l=n.mcpReq.signal,c=a,u=0;for(;;){let a;if((u+=1)>o)return ds(t,`Multi-round-trip request '${t}' still required input after ${o} rounds (inputRequired.maxRounds)`);let d=c.inputRequests,p=null!=d&&Object.keys(d).length>0,m="string"==typeof c.requestState?c.requestState:void 0;if(!p&&void 0===m)throw new cg(cf.InternalError,`Handler for ${t} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(p){let r=this._host.resolvedClientCapabilities(n),i=[];for(let[n,a]of Object.entries(d)){let{embedded:o,required:s}=da(t,n,a);if("roots/list"!==o.method&&void 0===o.params)throw new cg(cf.InternalError,`Handler for ${t} returned an input request '${n}' of kind '${o.method}' without params`);if(void 0!==lG(s,r))return ds(t,`Cannot request input '${n}' (${o.method}): the client on this 2025-era connection did not declare the required capability${void 0===r?" (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)":""}`);i.push([n,o])}let o=function(t){let r=new AbortController,i=()=>r.abort(t?.reason);return t?.addEventListener("abort",i,{once:!0}),t?.aborted&&r.abort(t.reason),{signal:r.signal,abort:t=>r.abort(t),dispose:()=>t?.removeEventListener("abort",i)}}(l);try{let t={relatedRequestId:n.mcpReq.id,timeout:s,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:o.signal},r=await Promise.all(i.map(async([r,i])=>{try{return[r,await this._dispatchLeg(i,t)]}catch(t){throw o.abort(t),t}}));a=Object.fromEntries(r)}catch(r){if(l.aborted)throw r;return ds(t,`Fulfilling input required by '${t}' failed: ${r instanceof Error?r.message:String(r)}`)}finally{o.dispose()}}else await function(t,r){return new Promise((t,i)=>{if(r?.aborted)return void i(r.reason instanceof lJ?r.reason:new lJ(lV.RequestTimeout,String(r.reason)));let n=setTimeout(()=>{r?.removeEventListener("abort",a),t()},250),a=()=>{clearTimeout(n),i(r?.reason instanceof lJ?r.reason:new lJ(lV.RequestTimeout,String(r?.reason)))};r?.addEventListener("abort",a,{once:!0})})}(0,l);let h={...n,mcpReq:{...n.mcpReq,inputResponses:a,droppedInputResponseKeys:void 0,requestState:function(t){return()=>t}(m)}};if(void 0!==m){let r=await this._host.verifyRequestState(m,h,t);void 0!==r&&(h=uE(h,r))}let f=await r(i,h);if(!cX(f))return f;c=f}}async _dispatchLeg(t,r){switch(t.method){case"elicitation/create":{let i=t.params;return"url"===i.mode&&void 0===i.elicitationId&&(i={...i,elicitationId:function(){let t=globalThis.crypto;if(t?.randomUUID!==void 0)return t.randomUUID();let r=new Uint8Array(16);t.getRandomValues(r),r[6]=15&r[6]|64,r[8]=63&r[8]|128;let i=[...r].map(t=>t.toString(16).padStart(2,"0")).join("");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}()}),await this._host.sendElicitation(i,r)}case"sampling/createMessage":return await this._host.sendSampling(t.params,r);case"roots/list":return await this._host.listRoots(t.params,r)}}};let dc=new Set(["tools/call","prompts/get","resources/read"]);var du=class extends uO{_clientCapabilities;_clientVersion;static{c=(t,r)=>{void 0!==r.clientCapabilities&&(t._clientCapabilities=r.clientCapabilities),void 0!==r.clientInfo&&(t._clientVersion=r.clientInfo)},u=(t,r)=>{let i=r.filter(r=>!t._supportedProtocolVersions.includes(r));i.length>0&&(t._supportedProtocolVersions=[...t._supportedProtocolVersions,...i]),t.setRequestHandler("server/discover",()=>t._ondiscover())},d=t=>t._serverInfo}_capabilities;_instructions;_jsonSchemaValidator;_cacheHints;_requestStateVerify;_inputRequiredServing;_legacyShim;_legacyInputRequiredShim(){return this._legacyShim??=new dl({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:t=>this._inputRequestCapabilityView(t),verifyRequestState:(t,r,i)=>this._verifyRequestState(t,r,i),sendElicitation:(t,r)=>this._sendElicitationLeg(t,r,{validateAcceptedContent:!1}),sendSampling:(t,r)=>this.createMessage(t,r),listRoots:(t,r)=>this.listRoots(t,r)})}oninitialized;constructor(t,r){if(super(r),this._serverInfo=t,this._capabilities=r?.capabilities?{...r.capabilities}:{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new u6,this._requestStateVerify=r?.requestState?.verify,this._inputRequiredServing=function(t){if(t?.maxRounds!==void 0&&(!Number.isInteger(t.maxRounds)||t.maxRounds<1))throw RangeError(`inputRequired.maxRounds must be a positive integer (got ${t.maxRounds})`);if(t?.roundTimeoutMs!==void 0&&(!Number.isFinite(t.roundTimeoutMs)||t.roundTimeoutMs<=0))throw RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${t.roundTimeoutMs})`);return{maxRounds:t?.maxRounds??8,roundTimeoutMs:t?.roundTimeoutMs??6e5,legacyShim:t?.legacyShim??!0}}(r?.inputRequired),r?.cacheHints!==void 0){for(let[t,i]of Object.entries(r.cacheHints))void 0!==i&&ch(i,`cacheHints['${t}']`);this._cacheHints=r.cacheHints}this.setRequestHandler("initialize",t=>this._oninitialize(t)),this.setNotificationHandler("notifications/initialized",()=>this.oninitialized?.()),lX(this._supportedProtocolVersions).length>0&&this.setRequestHandler("server/discover",()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}_registerLoggingHandler(){this.setRequestHandler("logging/setLevel",async(t,r)=>{let i=r.sessionId||r.http?.req?.headers.get("mcp-session-id")||void 0,{level:n}=t.params,a=nk(sT,n);return a.success&&this._loggingLevels.set(i,a.data),{}})}buildContext(t,r){let i=t.http||r?.request||r?.closeSSEStream||r?.closeStandaloneSSEStream;return{...t,mcpReq:{...t.mcpReq,log:(r,i,n)=>{let a;if(!this._capabilities.logging)return Promise.resolve();if(this._servedModernEra()){if(void 0===(a=t.mcpReq.envelope?.[aQ]))return Promise.resolve()}else a=this._loggingLevels.get(t.sessionId)??this._loggingLevels.get(void 0);return void 0!==a&&this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(a)?Promise.resolve():t.mcpReq.notify({method:"notifications/message",params:{level:r,data:i,logger:n}})},elicitInput:(t,r)=>this.elicitInput(t,r),requestSampling:(t,r)=>this.createMessage(t,r)},http:i?{...t.http,req:r?.request,closeSSE:r?.closeSSEStream,closeStandaloneSSE:r?.closeStandaloneSSEStream}:void 0}}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(sT.options.map((t,r)=>[t,r]));isMessageIgnored=(t,r)=>{let i=this._loggingLevels.get(r);return!!i&&this.LOG_LEVEL_SEVERITY.get(t)<this.LOG_LEVEL_SEVERITY.get(i)};registerCapabilities(t){if(this.transport)throw new lJ(lV.AlreadyConnected,"Cannot register capabilities after connecting to transport");let r=!!this._capabilities.logging;this._capabilities=function(t,r){let i={...t};for(let t in r){let n=r[t];if(void 0===n)continue;let a=i[t];i[t]=uI(a)&&uI(n)?{...a,...n}:n}return i}(this._capabilities,t),!r&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(t,r){if("tools/call"!==t){let i=this._cacheHints?.[t],n=dc.has(t);return void 0!==i||n?async(a,o)=>{let s=n?await this._invokeInputRequiredCapableHandler(t,r,a,o):await r(a,o);if(cX(s)){if(!n)throw new cg(cf.InternalError,`Handler for ${t} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return s}return void 0===i?s:cd(s,i)}:async(i,n)=>{let a=await r(i,n);if(cX(a))throw new cg(cf.InternalError,`Handler for ${t} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return a}}return async(t,i)=>{let n=cL(this._negotiatedProtocolVersion),a=n.validateRequest("tools/call",t);if(!a.ok)throw new cg("not-in-era"===a.reason?cf.InternalError:cf.InvalidParams,"not-in-era"===a.reason?"No wire schema for tools/call in the resolved era":`Invalid tools/call request: ${a.message}`);let o=await this._invokeInputRequiredCapableHandler("tools/call",r,t,i);if(cX(o))return o;let s=l1(o),l=n.validateResult("tools/call",s);if(!l.ok)throw new cg("not-in-era"===l.reason?cf.InternalError:cf.InvalidParams,"not-in-era"===l.reason?"No wire schema for tools/call in the resolved era":`Invalid tools/call result: ${l.message}`);return l.value}}_servedModernEra(){return void 0!==this._negotiatedProtocolVersion&&this._negotiatedProtocolVersion>=lK}async _invokeInputRequiredCapableHandler(t,r,i,n){let a,o=this._servedModernEra(),s=n.mcpReq.requestState();if(void 0!==s&&"string"!=typeof s)throw new cg(cf.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"});let l=n;if("string"==typeof s){let r=await this._verifyRequestState(s,n,t);void 0!==r&&(l=uE(n,r))}try{a=await r(i,l)}catch(t){if(t instanceof cg&&t.code===cf.UrlElicitationRequired){if(!o)throw t;throw new cg(cf.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`)}throw t}if(!cX(a))return a;if(!o){if(!this._inputRequiredServing.legacyShim)throw new cg(cf.InternalError,`Handler for ${t} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??aJ}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(t,r,i,l,a)}let c=a.inputRequests,u=null!=c&&Object.keys(c).length>0,d="string"==typeof a.requestState;if(!u&&!d)throw new cg(cf.InternalError,`Handler for ${t} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(u){let r=this._inputRequestCapabilityView(n);for(let[i,n]of Object.entries(c)){let{embedded:a,required:o}=da(t,i,n),s=lG(o,r);if(void 0!==s)throw new cb({requiredCapabilities:s},`Cannot request input '${i}' (${a.method}): the request's client capabilities do not declare the required capability`)}}return a}async _verifyRequestState(t,r,i){if(void 0!==this._requestStateVerify)try{return await this._requestStateVerify(t,r)}catch(t){throw this.onerror?.(Error(`requestState verification rejected ${i}: ${t instanceof Error?t.message:String(t)}`)),new cg(cf.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"})}}_inputRequestCapabilityView(t){return this._servedModernEra()?t.mcpReq.envelope?.[aY]:this._clientCapabilities}_assertPushApiInServedEra(t){if(this._servedModernEra())throw new lJ(lV.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${t}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:t,era:"2026-07-28"})}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new lJ(lV.CapabilityNotSupported,`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new lJ(lV.CapabilityNotSupported,`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new lJ(lV.CapabilityNotSupported,`Client does not support listing roots (required for ${t})`)}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new lJ(lV.CapabilityNotSupported,`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new lJ(lV.CapabilityNotSupported,`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new lJ(lV.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new lJ(lV.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new lJ(lV.CapabilityNotSupported,`Client does not support URL elicitation (required for ${t})`)}}assertRequestHandlerCapability(t){switch(t){case"completion/complete":if(!this._capabilities.completions)throw new lJ(lV.CapabilityNotSupported,`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new lJ(lV.CapabilityNotSupported,`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new lJ(lV.CapabilityNotSupported,`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new lJ(lV.CapabilityNotSupported,`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new lJ(lV.CapabilityNotSupported,`Server does not support tools (required for ${t})`)}}async _oninitialize(t){let r=t.params.protocolVersion;this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo;let i=this._supportedProtocolVersions.filter(t=>!(t>=lK)),n=i.includes(r)?r:i[0]??aJ;return this._negotiatedProtocolVersion=n,this.transport?.setProtocolVersion?.(n),{protocolVersion:n,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:lX(this._supportedProtocolVersions),capabilities:{...this.getCapabilities()},...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(t,r){return this._wireCodec().projectCallToolResult(t,r)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra("ping"),this.request({method:"ping"})}async createMessage(t,r){if(this._assertPushApiInServedEra("sampling/createMessage"),(t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new lJ(lV.CapabilityNotSupported,"Client does not support sampling tools capability.");if(t.messages.length>0){let r=t.messages.at(-1),i=Array.isArray(r.content)?r.content:[r.content],n=i.some(t=>"tool_result"===t.type),a=t.messages.length>1?t.messages.at(-2):void 0,o=a?Array.isArray(a.content)?a.content:[a.content]:[],s=o.some(t=>"tool_use"===t.type);if(n){if(i.some(t=>"tool_result"!==t.type))throw new cg(cf.InvalidParams,"The last message must contain only tool_result content if any is present");if(!s)throw new cg(cf.InvalidParams,"tool_result blocks are not matching any tool_use from the previous message")}if(s){let t=new Set(o.filter(t=>"tool_use"===t.type).map(t=>t.id)),r=new Set(i.filter(t=>"tool_result"===t.type).map(t=>t.toolUseId));if(t.size!==r.size||![...t].every(t=>r.has(t)))throw new cg(cf.InvalidParams,"ids of tool_result blocks and tool_use blocks from previous message do not match")}}let i=!!(t.tools||t.toolChoice),n=await this.request({method:"sampling/createMessage",params:t},r),a=this._wireCodec().samplingResultVariant(i,n);if(!a.ok)throw new lJ(lV.InvalidResult,`Invalid sampling/createMessage result: ${"invalid"===a.reason?a.message:a.reason}`);return a.value}async elicitInput(t,r){switch(this._assertPushApiInServedEra("elicitation/create"),t.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw new lJ(lV.CapabilityNotSupported,"Client does not support url elicitation.");break;case"form":if(!this._clientCapabilities?.elicitation?.form)throw new lJ(lV.CapabilityNotSupported,"Client does not support form elicitation.")}return this._sendElicitationLeg(t,r)}async _sendElicitationLeg(t,r,i){let n=t.mode??"form",a=i?.validateAcceptedContent??!0;switch(n){case"url":return this.request({method:"elicitation/create",params:t},r);case"form":{let i="form"===t.mode?t:{...t,mode:"form"},n=await this.request({method:"elicitation/create",params:i},r);if(a&&"accept"===n.action&&n.content&&i.requestedSchema)try{let t=this._jsonSchemaValidator.getValidator(i.requestedSchema)(n.content);if(!t.valid)throw new cg(cf.InvalidParams,`Elicitation response content does not match requested schema: ${t.errorMessage}`)}catch(t){if(t instanceof cg)throw t;throw new cg(cf.InternalError,`Error validating elicitation response: ${t instanceof Error?t.message:String(t)}`)}return n}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new lJ(lV.CapabilityNotSupported,"Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this._assertPushApiInServedEra("roots/list"),this.request({method:"roots/list",params:t},r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}},dd=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_toolInputSchemaJson={};toolInputSchemaJson(t){let r=this._registeredTools[t];if(void 0!==r&&r.enabled){if(Object.hasOwn(this._toolInputSchemaJson,t))return this._toolInputSchemaJson[t];if(void 0===r.inputSchema)return dh;try{let i=up(r.inputSchema,"input");return this._toolInputSchemaJson[t]=i,i}catch{return}}}constructor(t,r){this.server=new du(t,r),r?.capabilities?.tools&&this.setToolRequestHandlers(),r?.capabilities?.resources&&this.setResourceRequestHandlers(),r?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler("tools/list"),this.server.assertCanSetRequestHandler("tools/call"),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler("tools/list",()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let i={name:t,title:r.title,description:r.description,inputSchema:r.inputSchema?up(r.inputSchema,"input"):dh,annotations:r.annotations,icons:r.icons,execution:r.execution,_meta:r._meta};return r.outputSchema&&(i.outputSchema=up(r.outputSchema,"output")),i})})),this.server.setRequestHandler("tools/call",async(t,r)=>{let i=this._registeredTools[t.params.name];if(!i)throw new cg(cf.InvalidParams,`Tool ${t.params.name} not found`);if(!i.enabled)throw new cg(cf.InvalidParams,`Tool ${t.params.name} disabled`);try{let n=await this.validateToolInput(i,t.params.arguments,t.params.name),a=await this.executeToolHandler(i,n,r);if(await this.validateToolOutput(i,a,t.params.name),cX(a))return a;return this.server.projectCallToolResult(a,i.outputSchemaJson)}catch(t){if(t instanceof cg&&t.code===cf.UrlElicitationRequired)throw t;return this.createToolError(t instanceof Error?t.message:String(t))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,i){if(!t.inputSchema)return;let n=await um(t.inputSchema,r??{});if(!n.success)throw new cg(cf.InvalidParams,`Input validation error: Invalid arguments for tool ${i}: ${n.error}`);return n.data}async validateToolOutput(t,r,i){if(!t.outputSchema||cX(r)||r.isError)return;if(void 0===r.structuredContent)throw new cg(cf.InvalidParams,`Output validation error: Tool ${i} has an output schema but no structured content was provided`);let n=await um(t.outputSchema,r.structuredContent);if(!n.success)throw new cg(cf.InvalidParams,`Output validation error: Invalid structured content for tool ${i}: ${n.error}`)}async executeToolHandler(t,r,i){return t.executor(r,i)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler("completion/complete"),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler("completion/complete",async t=>{switch(t.params.ref.type){case"ref/prompt":if("ref/prompt"!==t.params.ref.type)throw TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`);return this.handlePromptCompletion(t,t.params.ref);case"ref/resource":if("ref/resource"!==t.params.ref.type)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`);return this.handleResourceCompletion(t,t.params.ref);default:throw new cg(cf.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let i=this._registeredPrompts[r.name];if(!i)throw new cg(cf.InvalidParams,`Prompt ${r.name} not found`);if(!i.enabled)throw new cg(cf.InvalidParams,`Prompt ${r.name} disabled`);if(!i.argsSchema)return dv;let n=db(d_(i.argsSchema)?.[t.params.argument.name]);if(!u8(n))return dv;let a=n[u7]?.complete;return a?dy(await a(t.params.argument.value,t.params.context)):dv}async handleResourceCompletion(t,r){let i=Object.values(this._registeredResourceTemplates).find(t=>t.resourceTemplate.uriTemplate.toString()===r.uri);if(!i){if(this._registeredResources[r.uri])return dv;throw new cg(cf.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let n=i.resourceTemplate.completeCallback(t.params.argument.name);return n?dy(await n(t.params.argument.value,t.params.context)):dv}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler("resources/list"),this.server.assertCanSetRequestHandler("resources/templates/list"),this.server.assertCanSetRequestHandler("resources/read"),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler("resources/list",async(t,r)=>{let i=Object.entries(this._registeredResources).filter(([t,r])=>r.enabled).map(([t,r])=>({uri:t,name:r.name,...r.metadata})),n=[];for(let t of Object.values(this._registeredResourceTemplates))if(t.resourceTemplate.listCallback)for(let i of(await t.resourceTemplate.listCallback(r)).resources)n.push({...t.metadata,...i});return{resources:[...i,...n]}}),this.server.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler("resources/read",async(t,r)=>{let i;try{i=new URL(t.params.uri)}catch{throw new cg(cf.InvalidParams,`Resource URI ${t.params.uri} is invalid`,{uri:t.params.uri,reason:"invalid_uri"})}let n=this._registeredResources[i.toString()];if(n){if(!n.enabled)throw new cg(cf.InvalidParams,`Resource ${i} disabled`);return cd(await n.readCallback(i,r),n.cacheHint)}for(let t of Object.values(this._registeredResourceTemplates)){let n=t.resourceTemplate.uriTemplate.match(i.toString());if(n)return cd(await t.readCallback(i,n,r),t.cacheHint)}throw new cy(t.params.uri)}),this._resourceHandlersInitialized=!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler("prompts/list"),this.server.assertCanSetRequestHandler("prompts/get"),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler("prompts/list",()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>{let i,n,a;return{name:t,title:r.title,description:r.description,arguments:r.argsSchema?(n=(i=up(r.argsSchema,"input")).properties||{},a=i.required||[],Object.entries(n).map(([t,r])=>({name:t,description:r?.description,required:a.includes(t)}))):void 0,icons:r.icons,_meta:r._meta}})})),this.server.setRequestHandler("prompts/get",async(t,r)=>{let i=this._registeredPrompts[t.params.name];if(!i)throw new cg(cf.InvalidParams,`Prompt ${t.params.name} not found`);if(!i.enabled)throw new cg(cf.InvalidParams,`Prompt ${t.params.name} disabled`);return i.handler(t.params.arguments,r)}),this._promptHandlersInitialized=!0)}registerResource(t,r,i,n){let a=i.cacheHint,o=i;if(void 0!==a){ch(a,`resource ${t}`);let r={...i};delete r.cacheHint,o=r}if("string"==typeof r){if(this._registeredResources[r])throw Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,i.title,r,o,n);return void 0!==a&&(s.cacheHint=a),this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}{if(this._registeredResourceTemplates[t])throw Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,i.title,r,o,n);return void 0!==a&&(s.cacheHint=a),this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(t,r,i,n,a){let o={name:t,title:r,metadata:n,readCallback:a,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:t=>{void 0!==t.uri&&t.uri!==i&&(delete this._registeredResources[i],t.uri&&(this._registeredResources[t.uri]=o)),void 0!==t.name&&(o.name=t.name),void 0!==t.title&&(o.title=t.title),void 0!==t.metadata&&(o.metadata=t.metadata),void 0!==t.callback&&(o.readCallback=t.callback),void 0!==t.enabled&&(o.enabled=t.enabled),this.sendResourceListChanged()}};return this._registeredResources[i]=o,o}_createRegisteredResourceTemplate(t,r,i,n,a){let o={resourceTemplate:i,title:r,metadata:n,readCallback:a,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:r=>{void 0!==r.name&&r.name!==t&&(delete this._registeredResourceTemplates[t],r.name&&(this._registeredResourceTemplates[r.name]=o)),void 0!==r.title&&(o.title=r.title),void 0!==r.template&&(o.resourceTemplate=r.template),void 0!==r.metadata&&(o.metadata=r.metadata),void 0!==r.callback&&(o.readCallback=r.callback),void 0!==r.enabled&&(o.enabled=r.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=o;let s=i.uriTemplate.variableNames;return Array.isArray(s)&&s.some(t=>!!i.completeCallback(t))&&this.setCompletionRequestHandler(),o}_createRegisteredPrompt(t,r,i,n,a,o,s){let l=n,c=a,u={title:r,description:i,argsSchema:n,icons:o,_meta:s,handler:dg(t,n,a),enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:r=>{void 0!==r.name&&r.name!==t&&(delete this._registeredPrompts[t],r.name&&(this._registeredPrompts[r.name]=u)),void 0!==r.title&&(u.title=r.title),void 0!==r.description&&(u.description=r.description),void 0!==r.icons&&(u.icons=r.icons),void 0!==r._meta&&(u._meta=r._meta);let i=!1;void 0!==r.argsSchema&&(u.argsSchema=r.argsSchema,l=r.argsSchema,i=!0),void 0!==r.callback&&(c=r.callback,i=!0),i&&(u.handler=dg(t,l,c)),void 0!==r.enabled&&(u.enabled=r.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[t]=u,n){let t=d_(n);t&&Object.values(t).some(t=>u8(db(t)))&&this.setCompletionRequestHandler()}return u}_createRegisteredTool(t,r,i,n,a,o,s,l,c,u){if(uz(t),void 0!==n)try{let r=up(n,"input");this._toolInputSchemaJson[t]=r;let i=c2(r);i.valid||console.warn(`[mcp-sdk] tool '${t}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${i.reason}`)}catch{}let d=u,p={title:r,description:i,inputSchema:n,outputSchema:a,outputSchemaJson:df(a),annotations:o,icons:s,execution:l,_meta:c,handler:u,executor:dm(n,u),enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:r=>{void 0!==r.name&&r.name!==t&&("string"==typeof r.name&&uz(r.name),delete this._registeredTools[t],delete this._toolInputSchemaJson[t],r.name&&(delete this._toolInputSchemaJson[r.name],this._registeredTools[r.name]=p,t=r.name)),void 0!==r.title&&(p.title=r.title),void 0!==r.description&&(p.description=r.description);let i=!1;void 0!==r.paramsSchema&&(p.inputSchema=r.paramsSchema,delete this._toolInputSchemaJson[t],i=!0),void 0!==r.callback&&(p.handler=r.callback,d=r.callback,i=!0),i&&(p.executor=dm(p.inputSchema,d)),void 0!==r.outputSchema&&(p.outputSchema=r.outputSchema,p.outputSchemaJson=df(r.outputSchema)),void 0!==r.annotations&&(p.annotations=r.annotations),void 0!==r.icons&&(p.icons=r.icons),void 0!==r._meta&&(p._meta=r._meta),void 0!==r.enabled&&(p.enabled=r.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}registerTool(t,r,i){if(this._registeredTools[t])throw Error(`Tool ${t} is already registered`);let{title:n,description:a,inputSchema:o,outputSchema:s,annotations:l,icons:c,_meta:u}=r;return this._createRegisteredTool(t,n,a,uZ(o),uZ(s),l,c,void 0,u,i)}registerPrompt(t,r,i){if(this._registeredPrompts[t])throw Error(`Prompt ${t} is already registered`);let{title:n,description:a,argsSchema:o,icons:s,_meta:l}=r,c=this._createRegisteredPrompt(t,n,a,uZ(o),i,s,l);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),c}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},dp=class{_uriTemplate;constructor(t,r){this._callbacks=r,this._uriTemplate="string"==typeof t?new uM(t):t}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(t){return this._callbacks.complete?.[t]}};function dm(t,r){return t?async(t,i)=>r(t,i):async(t,i)=>r(i)}let dh={type:"object",properties:{}};function df(t){if(void 0!==t)try{return up(t,"output")}catch{return}}function dg(t,r,i){return r?async(n,a)=>{let o=await um(r,n);if(!o.success)throw new cg(cf.InvalidParams,`Invalid arguments for prompt ${t}: ${o.error}`);return i(o.data,a)}:async(t,r)=>i(r)}function dy(t){return{completion:{values:t.map(String).slice(0,100),total:t.length,hasMore:t.length>100}}}let dv={completion:{values:[],hasMore:!1}};function d_(t){if(t.shape&&"object"==typeof t.shape)return t.shape}function db(t){return t?.type!=="optional"?t:t.def?.innerType??t}var dS=class{onclose;onerror;onmessage;_classification;_responseMode;_started=!1;_used=!1;_closed=!1;_terminalDelivered=!1;_dispatchWindowOpen=!1;_requestId;_deferredResponse;_sse;_abortCleanup;_keepAliveMs;constructor(t){this._classification=t.classification,this._responseMode=t.responseMode??"auto",this._keepAliveMs=t.keepAliveMs??15e3}async start(){if(this._started)throw Error("PerRequestHTTPServerTransport is already started");this._started=!0}async handleMessage(t,r){if(this._used)throw Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request");if(!this._started||void 0===this.onmessage)throw Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message");if(this._closed)throw Error("PerRequestHTTPServerTransport is closed");this._used=!0;let i=r?.request?.signal;if(i?.aborted)throw await this.close(),new lJ(lV.ConnectionClosed,"The request was aborted before it could be handled");let n={classification:this._classification,...r?.request!==void 0&&{request:r.request},...r?.authInfo!==void 0&&{authInfo:r.authInfo}};if(cW(t)){let r,a;this._requestId=t.id;let o=new Promise((t,i)=>{r=t,a=i});if(this._deferredResponse={promise:o,resolve:r,reject:a,settled:!1},void 0!==i){let t=()=>void this.close();i.addEventListener("abort",t,{once:!0}),this._abortCleanup=()=>i.removeEventListener("abort",t)}this._dispatchWindowOpen=!0;try{this.onmessage(t,n)}finally{this._dispatchWindowOpen=!1}return"sse"!==this._responseMode||this._closed||this._deferredResponse.settled||this.upgradeToSse(),o}return this.onmessage(t,n),new Response(null,{status:202})}async send(t,r){if(this._closed)return;let i=cK(t)||cY(t),n=i?t.id:r?.relatedRequestId;if(void 0===this._requestId||void 0===n||n!==this._requestId){i&&this.onerror?.(Error(`Received a response for an unknown request id: ${String(t.id)}`));return}if(i){if(this._terminalDelivered)return;this._terminalDelivered=!0;let r=cY(t)?t.error.code:void 0,i=void 0!==r&&(this._dispatchWindowOpen||r===cf.MissingRequiredClientCapability)?ut[r]:void 0;if(void 0!==i&&void 0===this._sse){this.settleResponse(Response.json(t,{status:i,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>void this.close());return}if(void 0!==this._sse||"sse"===this._responseMode){void 0===this._sse&&this.upgradeToSse(),this.writeMessageFrame(t),this.finalizeStream();return}this.settleResponse(Response.json(t,{status:200,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>void this.close());return}"json"!==this._responseMode&&(void 0===this._sse&&this.upgradeToSse(),this.writeMessageFrame(t))}writeCommentFrame(t){if(this._closed||void 0===this._sse||this._sse.closed)return;let r=t.split("\n").map(t=>`: ${t}`).join("\n");this.writeFrame(`${r}
|
|
58
58
|
|
|
59
|
-
`)}async close(){if(!this._closed){if(this._closed=!0,this._abortCleanup?.(),this._abortCleanup=void 0,this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),void 0!==this._sse&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}void 0===this._deferredResponse||this._deferredResponse.settled||(this._deferredResponse.settled=!0,this._deferredResponse.reject(new
|
|
59
|
+
`)}async close(){if(!this._closed){if(this._closed=!0,this._abortCleanup?.(),this._abortCleanup=void 0,this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),void 0!==this._sse&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}void 0===this._deferredResponse||this._deferredResponse.settled||(this._deferredResponse.settled=!0,this._deferredResponse.reject(new lJ(lV.ConnectionClosed,"Connection closed before a response was produced"))),this.onclose?.()}}settleResponse(t){void 0===this._deferredResponse||this._deferredResponse.settled||(this._deferredResponse.settled=!0,this._deferredResponse.resolve(t))}upgradeToSse(){let t,r=new ReadableStream({start:r=>{t=r},cancel:()=>{this.close()}});this._sse={controller:t,encoder:new TextEncoder,closed:!1},this._sse.keepAliveTimer=dt(this._keepAliveMs,()=>this.writeCommentFrame("keepalive")),this.settleResponse(new Response(r,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}))}finalizeStream(){if(this._sse?.keepAliveTimer!==void 0&&clearInterval(this._sse.keepAliveTimer),void 0!==this._sse&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}queueMicrotask(()=>void this.close())}writeMessageFrame(t){this.writeFrame(`event: message
|
|
60
60
|
data: ${JSON.stringify(t)}
|
|
61
61
|
|
|
62
|
-
`)}writeFrame(t){if(void 0!==this._sse&&!this._sse.closed)try{this._sse.controller.enqueue(this._sse.encoder.encode(t))}catch(t){this.onerror?.(Error(`Failed to write to the response stream: ${t}`))}}};async function
|
|
62
|
+
`)}writeFrame(t){if(void 0!==this._sse&&!this._sse.closed)try{this._sse.controller.enqueue(this._sse.encoder.encode(t))}catch(t){this.onerror?.(Error(`Failed to write to the response stream: ${t}`))}}};async function dw(t,r,i){let n=new dS({classification:i.classification,...void 0!==i.responseMode&&{responseMode:i.responseMode},...void 0!==i.keepAliveMs&&{keepAliveMs:i.keepAliveMs}});return await t.connect(n),n.handleMessage(r,{...void 0!==i.request&&{request:i.request},...void 0!==i.authInfo&&{authInfo:i.authInfo}})}var dk=class{sessionIdGenerator;_started=!1;_closed=!1;_streamMapping=new Map;_requestToStreamMapping=new Map;_requestResponseMap=new Map;_initialized=!1;_enableJsonResponse=!1;_standaloneSseStreamId="_GET_stream";_eventStore;_onsessioninitialized;_onsessionclosed;_allowedHosts;_allowedOrigins;_enableDnsRebindingProtection;_retryInterval;_supportedProtocolVersions;_keepAliveMs;sessionId;onclose;onerror;onmessage;constructor(t={}){this.sessionIdGenerator=t.sessionIdGenerator,this._enableJsonResponse=t.enableJsonResponse??!1,this._eventStore=t.eventStore,this._onsessioninitialized=t.onsessioninitialized,this._onsessionclosed=t.onsessionclosed,this._allowedHosts=t.allowedHosts,this._allowedOrigins=t.allowedOrigins,this._enableDnsRebindingProtection=t.enableDnsRebindingProtection??!1,this._retryInterval=t.retryInterval,this._supportedProtocolVersions=t.supportedProtocolVersions??aB,this._keepAliveMs=t.keepAliveMs??15e3}startKeepAlive(t,r){if(this._closed)return;let i=dt(this._keepAliveMs,()=>{try{t.enqueue(r.encode(": keepalive\n\n"))}catch{void 0!==i&&clearInterval(i)}});return i}async start(){if(this._started)throw Error("Transport already started");this._started=!0}setSupportedProtocolVersions(t){this._supportedProtocolVersions=t}createJsonErrorResponse(t,r,i,n){let a={code:r,message:i};return n?.data!==void 0&&(a.data=n.data),Response.json({jsonrpc:"2.0",error:a,id:null},{status:t,headers:{"Content-Type":"application/json",...n?.headers}})}validateRequestHeaders(t){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let r=t.headers.get("host");if(!r||!this._allowedHosts.includes(r)){let t=`Invalid Host header: ${r}`;return this.onerror?.(Error(t)),this.createJsonErrorResponse(403,-32e3,t)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let r=t.headers.get("origin");if(r&&!this._allowedOrigins.includes(r)){let t=`Invalid Origin header: ${r}`;return this.onerror?.(Error(t)),this.createJsonErrorResponse(403,-32e3,t)}}}}async handleRequest(t,r){if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let i=this.validateRequestHeaders(t);if(i)return i;switch(t.method){case"POST":return this.handlePostRequest(t,r);case"GET":return this.handleGetRequest(t);case"DELETE":return this.handleDeleteRequest(t);default:return this.handleUnsupportedRequest()}}supportsEmptySSEData(t){return this._supportedProtocolVersions.includes(t)&&t>="2025-11-25"}async writePrimingEvent(t,r,i,n){if(!this._eventStore||!this.supportsEmptySSEData(n))return;let a=await this._eventStore.storeEvent(i,{}),o=`id: ${a}
|
|
63
63
|
data:
|
|
64
64
|
|
|
65
65
|
`;void 0!==this._retryInterval&&(o=`id: ${a}
|
|
@@ -70,19 +70,17 @@ data:
|
|
|
70
70
|
`;return n&&(a+=`id: ${n}
|
|
71
71
|
`),a+=`data: ${JSON.stringify(i)}
|
|
72
72
|
|
|
73
|
-
`,t.enqueue(r.encode(a)),!0}catch(t){return this.onerror?.(t),!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(t,r){try{let i,n,a,o,s=t.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(!uA(t.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(r?.parsedBody===void 0)try{i=await t.json()}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else i=r.parsedBody;try{n=Array.isArray(i)?i.map(t=>od.parse(t)):[od.parse(i)]}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let l=n.some(t=>o$.safeParse(t).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(n.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 r=this.validateSession(t);if(r)return r;let i=this.validateProtocolVersion(t);if(i)return i}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!n.some(t=>cG(t))){for(let i of n)this.onmessage?.(i,{authInfo:r?.authInfo,request:t});return new Response(null,{status:202})}let c=crypto.randomUUID(),u=n.find(t=>o$.safeParse(t).success),d=u?u.params.protocolVersion:t.headers.get("mcp-protocol-version")??"2025-03-26";if(this._enableJsonResponse)return new Promise(i=>{for(let t of(this._streamMapping.set(c,{resolveJson:i,cleanup:()=>{this._streamMapping.delete(c)}}),n))cG(t)&&this._requestToStreamMapping.set(t.id,c);for(let i of n)this.onmessage?.(i,{authInfo:r?.authInfo,request:t})});let p=new TextEncoder,m=new ReadableStream({start:t=>{a=t},cancel:()=>{void 0!==o&&clearInterval(o),this._streamMapping.get(c)?.controller===a&&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 t of(void 0!==this.sessionId&&(h["mcp-session-id"]=this.sessionId),n))cG(t)&&(this._streamMapping.set(c,{controller:a,encoder:p,cleanup:()=>{void 0!==o&&clearInterval(o),this._streamMapping.delete(c);try{a.close()}catch{}}}),this._requestToStreamMapping.set(t.id,c));for(let i of(await this.writePrimingEvent(a,p,c,d),n)){let n,a;cG(i)&&this._eventStore&&this.supportsEmptySSEData(d)&&(n=()=>{this.closeSSEStream(i.id)},a=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(i,{authInfo:r?.authInfo,request:t,closeSSEStream:n,closeStandaloneSSEStream:a})}return this._streamMapping.get(c)?.controller===a&&(o=this.startKeepAlive(a,p)),new Response(m,{status:200,headers:h})}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(t)})}}async handleDeleteRequest(t){let r=this.validateSession(t);if(r)return r;let i=this.validateProtocolVersion(t);if(i)return i;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(t){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 r=t.headers.get("mcp-session-id");return r?r!==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(t){let r=t.headers.get("mcp-protocol-version");if(null!==r&&!this._supportedProtocolVersions.includes(r)){let t=`Bad Request: Unsupported protocol version: ${r} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(Error(t)),this.createJsonErrorResponse(400,-32e3,t)}}async close(){if(!this._closed){for(let{cleanup:t}of(this._closed=!0,this._streamMapping.values()))t();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(t){let r=this._requestToStreamMapping.get(t);if(!r)return;let i=this._streamMapping.get(r);i&&i.cleanup()}closeStandaloneSSEStream(){let t=this._streamMapping.get(this._standaloneSseStreamId);t&&t.cleanup()}async send(t,r){let i=r?.relatedRequestId;if((cY(t)||cX(t))&&(i=t.id),void 0===i){let r;if(cY(t)||cX(t))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");this._eventStore&&(r=await this._eventStore.storeEvent(this._standaloneSseStreamId,t));let i=this._streamMapping.get(this._standaloneSseStreamId);if(void 0===i)return;i.controller&&i.encoder&&(void 0===r||!i.replayedEventIds?.has(r))&&this.writeSSEEvent(i.controller,i.encoder,t,r);return}let n=this._requestToStreamMapping.get(i);if(!n)throw Error(`No connection established for request ID: ${String(i)}`);let a=this._streamMapping.get(n);if(!this._enableJsonResponse){let r;this._eventStore&&(r=await this._eventStore.storeEvent(n,t),a=this._streamMapping.get(n)),a?.controller&&a?.encoder&&(void 0===r||!a.replayedEventIds?.has(r))&&this.writeSSEEvent(a.controller,a.encoder,t,r)}if(cY(t)||cX(t)){this._requestResponseMap.set(i,t);let r=[...this._requestToStreamMapping.entries()].filter(([t,r])=>r===n).map(([t])=>t);if(r.every(t=>this._requestResponseMap.has(t))){if(!a){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(i)}`);if(!this._eventStore){for(let t of(this.onerror?.(Error(`Response for request ID ${String(i)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)),r))this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t);return}for(let t of r)this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t);return}if(this._enableJsonResponse&&a.resolveJson){let t={"Content-Type":"application/json"};void 0!==this.sessionId&&(t["mcp-session-id"]=this.sessionId);let i=r.map(t=>this._requestResponseMap.get(t));1===i.length?a.resolveJson(Response.json(i[0],{status:200,headers:t})):a.resolveJson(Response.json(i,{status:200,headers:t})),a.cleanup()}else a.cleanup();for(let t of r)this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t)}}}};function dR(t){if(null===t||"object"!=typeof t||Array.isArray(t))return null;let{method:r,id:i}=t;return"string"!=typeof r?null:"string"==typeof i||"number"==typeof i?i:null}function d$(t,r,i,n,a=null){return Response.json({jsonrpc:"2.0",error:{code:r,message:i,...void 0!==n&&{data:n}},id:a},{status:t})}function dC(t,r=null){return d$(t.httpStatus,t.code,t.message,t.data,r)}function dT(t){return t instanceof Error?t:Error(String(t))}function dO(t=null){return d$(500,-32603,"Internal server error",void 0,t)}async function dP(t,r,i=!0){let n,a=t.method.toUpperCase(),o=r,s=t,l=!1;if("POST"===a){if(void 0===o){let r;i&&(s=t.clone());try{r=await t.text()}catch{return{step:"unreadable-body"}}try{n=0===r.length?void 0:JSON.parse(r)}catch{l=!0}l||void 0===n||(o=n)}else n=o;if(l||void 0===n)return{step:"no-json-body",forwardRequest:s}}return{step:"classified",outcome:function(t){if("POST"!==(t={...t,...void 0!==t.protocolVersionHeader&&{protocolVersionHeader:uo(t.protocolVersionHeader)},...void 0!==t.mcpMethodHeader&&{mcpMethodHeader:uo(t.mcpMethodHeader)},...void 0!==t.mcpNameHeader&&{mcpNameHeader:uo(t.mcpNameHeader)}}).httpMethod.toUpperCase())return{kind:"legacy",reason:"http-method"};let r=t.body;if(Array.isArray(r)){if(0===r.length)return ui("jsonrpc-shape","empty-batch",400,new cy(cg.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let t of r){if(cD(us(t)?t.params:void 0))return ui("jsonrpc-shape","batch-with-modern-element",400,new cy(cg.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(cG(t)||cK(t)||cY(t)||cX(t)))return ui("jsonrpc-shape","batch-with-invalid-element",400,new cy(cg.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}return cY(r)||cX(r)?{kind:"legacy",reason:"response"}:us(r)&&cG(r)?function(t,r){let i=r.params,n=r.method,a=t.protocolVersionHeader,o=void 0!==a&&a>=lY;if("initialize"===n&&!function(t){if(!cD(t))return!1;let r=cV(t);if(void 0===r||!(r>=lY))return!1;let i=cJ(t);return void 0!==i&&0===cB(i).length}(i)){if(o)return un("initialize-with-modern-header",a,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let t=us(i)&&"string"==typeof i.protocolVersion?i.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...void 0!==t&&{requestedVersion:t}}}if(cD(i)){let o=cJ(i),s=(void 0===o?[]:cB(o))[0];if(void 0!==s)return ui("envelope","envelope-invalid",400,new cy(cg.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${s.key}: ${s.problem}`,{envelope:s}),!0);let l=cV(i);return void 0!==a&&void 0!==l&&a!==l?un("header-body-version-mismatch",a,`the body envelope names protocol version ${l} but the MCP-Protocol-Version header names ${a}`):void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?un("method-header-mismatch",t.mcpMethodHeader,`the body names method ${n} but the Mcp-Method header names ${t.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:r,classification:ul(l)}}if(o){let t=cJ(i),r=cB(t??{}).filter(t=>"missing"===t.problem).map(t=>t.key),n=void 0===t?["_meta"]:r.length>0?r:[aG];return ui("envelope","modern-header-without-claim",400,new cy(cg.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${a}, but the request is missing the required per-request envelope key(s): ${n.join(", ")}`,{envelope:{missing:n}}),!0)}return{kind:"legacy",reason:"no-claim",...void 0!==a&&{requestedVersion:a}}}(t,r):us(r)&&cK(r)?function(t,r){let i=r.params,n=r.method,a=t.protocolVersionHeader,o=void 0!==a&&a>=lY;if(cD(i)){let o=cV(i);if(void 0===o){let t=cJ(i),r=(void 0===t?[]:cB(t)).find(t=>t.key===aG)??{key:aG,problem:"expected a protocol version string"};return ui("envelope","notification-envelope-invalid",400,new cy(cg.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${r.key}: ${r.problem}`,{envelope:r}),!0)}if(void 0!==a&&a!==o)return un("notification-header-body-version-mismatch",a,`the notification envelope names protocol version ${o} but the MCP-Protocol-Version header names ${a}`);let s=ul(o);return"modern"===s.era&&void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?un("notification-method-header-mismatch",t.mcpMethodHeader,`the notification body names method ${n} but the Mcp-Method header names ${t.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:r,classification:s}}return o?void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?un("notification-method-header-mismatch",t.mcpMethodHeader,`the notification body names method ${n} but the Mcp-Method header names ${t.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:r,classification:{era:"modern",revision:a}}:{kind:"legacy",reason:"notification",...void 0!==a&&{requestedVersion:a}}}(t,r):ui("jsonrpc-shape","invalid-json-rpc-body",400,new cy(cg.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}({httpMethod:a,protocolVersionHeader:t.headers.get("mcp-protocol-version")??void 0,mcpMethodHeader:t.headers.get("mcp-method")??void 0,mcpNameHeader:t.headers.get("mcp-name")??void 0,...void 0!==n&&{body:n}}),body:n,parsedBody:o,forwardRequest:s}}let dE=Symbol("Let zodToJsonSchema decide on which parser to use"),dI={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"};(O=z||(z={})).assertEqual=t=>{},O.assertIs=function(t){},O.assertNever=function(t){throw Error()},O.arrayToEnum=t=>{let r={};for(let i of t)r[i]=i;return r},O.getValidEnumValues=t=>{let r=O.objectKeys(t).filter(r=>"number"!=typeof t[t[r]]),i={};for(let n of r)i[n]=t[n];return O.objectValues(i)},O.objectValues=t=>O.objectKeys(t).map(function(r){return t[r]}),O.objectKeys="function"==typeof Object.keys?t=>Object.keys(t):t=>{let r=[];for(let i in t)Object.prototype.hasOwnProperty.call(t,i)&&r.push(i);return r},O.find=(t,r)=>{for(let i of t)if(r(i))return i},O.isInteger="function"==typeof Number.isInteger?t=>Number.isInteger(t):t=>"number"==typeof t&&Number.isFinite(t)&&Math.floor(t)===t,O.joinValues=function(t,r=" | "){return t.map(t=>"string"==typeof t?`'${t}'`:t).join(r)},O.jsonStringifyReplacer=(t,r)=>"bigint"==typeof r?r.toString():r,(N||(N={})).mergeShapes=(t,r)=>({...t,...r});let dq=z.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),dj=t=>{switch(typeof t){case"undefined":return dq.undefined;case"string":return dq.string;case"number":return Number.isNaN(t)?dq.nan:dq.number;case"boolean":return dq.boolean;case"function":return dq.function;case"bigint":return dq.bigint;case"symbol":return dq.symbol;case"object":if(Array.isArray(t))return dq.array;if(null===t)return dq.null;if(t.then&&"function"==typeof t.then&&t.catch&&"function"==typeof t.catch)return dq.promise;if("undefined"!=typeof Map&&t instanceof Map)return dq.map;if("undefined"!=typeof Set&&t instanceof Set)return dq.set;if("undefined"!=typeof Date&&t instanceof Date)return dq.date;return dq.object;default:return dq.unknown}},dz=z.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 dN extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=t=>{this.issues=[...this.issues,t]},this.addIssues=(t=[])=>{this.issues=[...this.issues,...t]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(t){return t.message},i={_errors:[]},n=t=>{for(let a of t.issues)if("invalid_union"===a.code)a.unionErrors.map(n);else if("invalid_return_type"===a.code)n(a.returnTypeError);else if("invalid_arguments"===a.code)n(a.argumentsError);else if(0===a.path.length)i._errors.push(r(a));else{let t=i,n=0;for(;n<a.path.length;){let i=a.path[n];n===a.path.length-1?(t[i]=t[i]||{_errors:[]},t[i]._errors.push(r(a))):t[i]=t[i]||{_errors:[]},t=t[i],n++}}};return n(this),i}static assert(t){if(!(t instanceof dN))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,z.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(t=t=>t.message){let r=Object.create(null),i=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(t(n))}else i.push(t(n));return{formErrors:i,fieldErrors:r}}get formErrors(){return this.flatten()}}dN.create=t=>new dN(t);let dA=(t,r)=>{let i;switch(t.code){case dz.invalid_type:i=t.received===dq.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case dz.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(t.expected,z.jsonStringifyReplacer)}`;break;case dz.unrecognized_keys:i=`Unrecognized key(s) in object: ${z.joinValues(t.keys,", ")}`;break;case dz.invalid_union:i="Invalid input";break;case dz.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${z.joinValues(t.options)}`;break;case dz.invalid_enum_value:i=`Invalid enum value. Expected ${z.joinValues(t.options)}, received '${t.received}'`;break;case dz.invalid_arguments:i="Invalid function arguments";break;case dz.invalid_return_type:i="Invalid function return type";break;case dz.invalid_date:i="Invalid date";break;case dz.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(i=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(i=`${i} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?i=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?i=`Invalid input: must end with "${t.validation.endsWith}"`:z.assertNever(t.validation):i="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case dz.too_small:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:"number"===t.type||"bigint"===t.type?`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:"date"===t.type?`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:"Invalid input";break;case dz.too_big:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"bigint"===t.type?`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"date"===t.type?`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:"Invalid input";break;case dz.custom:i="Invalid input";break;case dz.invalid_intersection_types:i="Intersection results could not be merged";break;case dz.not_multiple_of:i=`Number must be a multiple of ${t.multipleOf}`;break;case dz.not_finite:i="Number must be finite";break;default:i=r.defaultError,z.assertNever(t)}return{message:i}};(P=A||(A={})).errToObj=t=>"string"==typeof t?{message:t}:t||{},P.toString=t=>"string"==typeof t?t:t?.message;let dL=t=>{let{data:r,path:i,errorMaps:n,issueData:a}=t,o=[...i,...a.path||[]],s={...a,path:o};if(void 0!==a.message)return{...a,path:o,message:a.message};let l="";for(let t of n.filter(t=>!!t).slice().reverse())l=t(s,{data:r,defaultError:l}).message;return{...a,path:o,message:l}};function dM(t,r){let i=dL({issueData:r,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,dA,void 0].filter(t=>!!t)});t.common.issues.push(i)}class dZ{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(t,r){let i=[];for(let n of r){if("aborted"===n.status)return dU;"dirty"===n.status&&t.dirty(),i.push(n.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,r){let i=[];for(let t of r){let r=await t.key,n=await t.value;i.push({key:r,value:n})}return dZ.mergeObjectSync(t,i)}static mergeObjectSync(t,r){let i={};for(let n of r){let{key:r,value:a}=n;if("aborted"===r.status||"aborted"===a.status)return dU;"dirty"===r.status&&t.dirty(),"dirty"===a.status&&t.dirty(),"__proto__"!==r.value&&(void 0!==a.value||n.alwaysSet)&&(i[r.value]=a.value)}return{status:t.value,value:i}}}let dU=Object.freeze({status:"aborted"}),dF=t=>({status:"dirty",value:t}),dH=t=>({status:"valid",value:t}),dJ=t=>"undefined"!=typeof Promise&&t instanceof Promise;class dD{constructor(t,r,i,n){this._cachedPath=[],this.parent=t,this.data=r,this._path=i,this._key=n}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 dV=(t,r)=>{if("valid"===r.status)return{success:!0,data:r.value};if(!t.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new dN(t.common.issues);return this._error=r,this._error}}};function dB(t){if(!t)return{};let{errorMap:r,invalid_type_error:i,required_error:n,description:a}=t;if(r&&(i||n))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return r?{errorMap:r,description:a}:{errorMap:(r,a)=>{let{message:o}=t;return"invalid_enum_value"===r.code?{message:o??a.defaultError}:void 0===a.data?{message:o??n??a.defaultError}:"invalid_type"!==r.code?{message:a.defaultError}:{message:o??i??a.defaultError}},description:a}}class dW{get description(){return this._def.description}_getType(t){return dj(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:dj(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new dZ,ctx:{common:t.parent.common,data:t.data,parsedType:dj(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(dJ(r))throw Error("Synchronous parse encountered promise.");return r}_parseAsync(t){return Promise.resolve(this._parse(t))}parse(t,r){let i=this.safeParse(t,r);if(i.success)return i.data;throw i.error}safeParse(t,r){let i={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:dj(t)},n=this._parseSync({data:t,path:i.path,parent:i});return dV(i,n)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:dj(t)};if(!this["~standard"].async)try{let i=this._parseSync({data:t,path:[],parent:r});return"valid"===i.status?{value:i.value}:{issues:r.common.issues}}catch(t){t?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(t=>"valid"===t.status?{value:t.value}:{issues:r.common.issues})}async parseAsync(t,r){let i=await this.safeParseAsync(t,r);if(i.success)return i.data;throw i.error}async safeParseAsync(t,r){let i={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:dj(t)},n=this._parse({data:t,path:i.path,parent:i});return dV(i,await (dJ(n)?n:Promise.resolve(n)))}refine(t,r){return this._refinement((i,n)=>{let a=t(i),o=()=>n.addIssue({code:dz.custom,..."string"==typeof r||void 0===r?{message:r}:"function"==typeof r?r(i):r});return"undefined"!=typeof Promise&&a instanceof Promise?a.then(t=>!!t||(o(),!1)):!!a||(o(),!1)})}refinement(t,r){return this._refinement((i,n)=>!!t(i)||(n.addIssue("function"==typeof r?r(i,n):r),!1))}_refinement(t){return new pE({schema:this,typeName:L.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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:t=>this["~validate"](t)}}optional(){return pI.create(this,this._def)}nullable(){return pq.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ph.create(this)}promise(){return pP.create(this,this._def)}or(t){return pg.create([this,t],this._def)}and(t){return p_.create(this,t,this._def)}transform(t){return new pE({...dB(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:t}})}default(t){return new pj({...dB(this._def),innerType:this,defaultValue:"function"==typeof t?t:()=>t,typeName:L.ZodDefault})}brand(){return new pA({typeName:L.ZodBranded,type:this,...dB(this._def)})}catch(t){return new pz({...dB(this._def),innerType:this,catchValue:"function"==typeof t?t:()=>t,typeName:L.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return pL.create(this,t)}readonly(){return pM.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let dG=/^c[^\s-]{8,}$/i,dK=/^[0-9a-z]+$/,dY=/^[0-9A-HJKMNP-TV-Z]{26}$/i,dX=/^[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,dQ=/^[a-z0-9_-]{21}$/i,d0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,d1=/^[-+]?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)?)??$/,d2=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,d9=/^(?:(?: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])$/,d4=/^(?:(?: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])$/,d5=/^(([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]))$/,d3=/^(([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])$/,d6=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,d7=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,d8="((\\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])))",pe=RegExp(`^${d8}$`);function pt(t){let r="[0-5]\\d";t.precision?r=`${r}\\.\\d{${t.precision}}`:null==t.precision&&(r=`${r}(\\.\\d+)?`);let i=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${r})${i}`}class pr extends dW{_parse(t){var r,i,n,a;let o;if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==dq.string){let r=this._getOrReturnCtx(t);return dM(r,{code:dz.invalid_type,expected:dq.string,received:r.parsedType}),dU}let s=new dZ;for(let l of this._def.checks)if("min"===l.kind)t.data.length<l.value&&(dM(o=this._getOrReturnCtx(t,o),{code:dz.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),s.dirty());else if("max"===l.kind)t.data.length>l.value&&(dM(o=this._getOrReturnCtx(t,o),{code:dz.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),s.dirty());else if("length"===l.kind){let r=t.data.length>l.value,i=t.data.length<l.value;(r||i)&&(o=this._getOrReturnCtx(t,o),r?dM(o,{code:dz.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):i&&dM(o,{code:dz.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),s.dirty())}else if("email"===l.kind)d2.test(t.data)||(dM(o=this._getOrReturnCtx(t,o),{validation:"email",code:dz.invalid_string,message:l.message}),s.dirty());else if("emoji"===l.kind)p||(p=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),p.test(t.data)||(dM(o=this._getOrReturnCtx(t,o),{validation:"emoji",code:dz.invalid_string,message:l.message}),s.dirty());else if("uuid"===l.kind)dX.test(t.data)||(dM(o=this._getOrReturnCtx(t,o),{validation:"uuid",code:dz.invalid_string,message:l.message}),s.dirty());else if("nanoid"===l.kind)dQ.test(t.data)||(dM(o=this._getOrReturnCtx(t,o),{validation:"nanoid",code:dz.invalid_string,message:l.message}),s.dirty());else if("cuid"===l.kind)dG.test(t.data)||(dM(o=this._getOrReturnCtx(t,o),{validation:"cuid",code:dz.invalid_string,message:l.message}),s.dirty());else if("cuid2"===l.kind)dK.test(t.data)||(dM(o=this._getOrReturnCtx(t,o),{validation:"cuid2",code:dz.invalid_string,message:l.message}),s.dirty());else if("ulid"===l.kind)dY.test(t.data)||(dM(o=this._getOrReturnCtx(t,o),{validation:"ulid",code:dz.invalid_string,message:l.message}),s.dirty());else if("url"===l.kind)try{new URL(t.data)}catch{dM(o=this._getOrReturnCtx(t,o),{validation:"url",code:dz.invalid_string,message:l.message}),s.dirty()}else"regex"===l.kind?(l.regex.lastIndex=0,l.regex.test(t.data)||(dM(o=this._getOrReturnCtx(t,o),{validation:"regex",code:dz.invalid_string,message:l.message}),s.dirty())):"trim"===l.kind?t.data=t.data.trim():"includes"===l.kind?t.data.includes(l.value,l.position)||(dM(o=this._getOrReturnCtx(t,o),{code:dz.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),s.dirty()):"toLowerCase"===l.kind?t.data=t.data.toLowerCase():"toUpperCase"===l.kind?t.data=t.data.toUpperCase():"startsWith"===l.kind?t.data.startsWith(l.value)||(dM(o=this._getOrReturnCtx(t,o),{code:dz.invalid_string,validation:{startsWith:l.value},message:l.message}),s.dirty()):"endsWith"===l.kind?t.data.endsWith(l.value)||(dM(o=this._getOrReturnCtx(t,o),{code:dz.invalid_string,validation:{endsWith:l.value},message:l.message}),s.dirty()):"datetime"===l.kind?(function(t){let r=`${d8}T${pt(t)}`,i=[];return i.push(t.local?"Z?":"Z"),t.offset&&i.push("([+-]\\d{2}:?\\d{2})"),r=`${r}(${i.join("|")})`,RegExp(`^${r}$`)})(l).test(t.data)||(dM(o=this._getOrReturnCtx(t,o),{code:dz.invalid_string,validation:"datetime",message:l.message}),s.dirty()):"date"===l.kind?pe.test(t.data)||(dM(o=this._getOrReturnCtx(t,o),{code:dz.invalid_string,validation:"date",message:l.message}),s.dirty()):"time"===l.kind?RegExp(`^${pt(l)}$`).test(t.data)||(dM(o=this._getOrReturnCtx(t,o),{code:dz.invalid_string,validation:"time",message:l.message}),s.dirty()):"duration"===l.kind?d1.test(t.data)||(dM(o=this._getOrReturnCtx(t,o),{validation:"duration",code:dz.invalid_string,message:l.message}),s.dirty()):"ip"===l.kind?(r=t.data,!(("v4"===(i=l.version)||!i)&&d9.test(r)||("v6"===i||!i)&&d5.test(r))&&1&&(dM(o=this._getOrReturnCtx(t,o),{validation:"ip",code:dz.invalid_string,message:l.message}),s.dirty())):"jwt"===l.kind?!function(t,r){if(!d0.test(t))return!1;try{let[i]=t.split(".");if(!i)return!1;let n=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),a=JSON.parse(atob(n));if("object"!=typeof a||null===a||"typ"in a&&a?.typ!=="JWT"||!a.alg||r&&a.alg!==r)return!1;return!0}catch{return!1}}(t.data,l.alg)&&(dM(o=this._getOrReturnCtx(t,o),{validation:"jwt",code:dz.invalid_string,message:l.message}),s.dirty()):"cidr"===l.kind?(n=t.data,!(("v4"===(a=l.version)||!a)&&d4.test(n)||("v6"===a||!a)&&d3.test(n))&&1&&(dM(o=this._getOrReturnCtx(t,o),{validation:"cidr",code:dz.invalid_string,message:l.message}),s.dirty())):"base64"===l.kind?d6.test(t.data)||(dM(o=this._getOrReturnCtx(t,o),{validation:"base64",code:dz.invalid_string,message:l.message}),s.dirty()):"base64url"===l.kind?d7.test(t.data)||(dM(o=this._getOrReturnCtx(t,o),{validation:"base64url",code:dz.invalid_string,message:l.message}),s.dirty()):z.assertNever(l);return{status:s.value,value:t.data}}_regex(t,r,i){return this.refinement(r=>t.test(r),{validation:r,code:dz.invalid_string,...A.errToObj(i)})}_addCheck(t){return new pr({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...A.errToObj(t)})}url(t){return this._addCheck({kind:"url",...A.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...A.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...A.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...A.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...A.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...A.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...A.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...A.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...A.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...A.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...A.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...A.errToObj(t)})}datetime(t){return"string"==typeof t?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:void 0===t?.precision?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...A.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return"string"==typeof t?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:void 0===t?.precision?null:t?.precision,...A.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...A.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...A.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...A.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...A.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...A.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...A.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...A.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...A.errToObj(r)})}nonempty(t){return this.min(1,A.errToObj(t))}trim(){return new pr({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new pr({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new pr({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>"datetime"===t.kind)}get isDate(){return!!this._def.checks.find(t=>"date"===t.kind)}get isTime(){return!!this._def.checks.find(t=>"time"===t.kind)}get isDuration(){return!!this._def.checks.find(t=>"duration"===t.kind)}get isEmail(){return!!this._def.checks.find(t=>"email"===t.kind)}get isURL(){return!!this._def.checks.find(t=>"url"===t.kind)}get isEmoji(){return!!this._def.checks.find(t=>"emoji"===t.kind)}get isUUID(){return!!this._def.checks.find(t=>"uuid"===t.kind)}get isNANOID(){return!!this._def.checks.find(t=>"nanoid"===t.kind)}get isCUID(){return!!this._def.checks.find(t=>"cuid"===t.kind)}get isCUID2(){return!!this._def.checks.find(t=>"cuid2"===t.kind)}get isULID(){return!!this._def.checks.find(t=>"ulid"===t.kind)}get isIP(){return!!this._def.checks.find(t=>"ip"===t.kind)}get isCIDR(){return!!this._def.checks.find(t=>"cidr"===t.kind)}get isBase64(){return!!this._def.checks.find(t=>"base64"===t.kind)}get isBase64url(){return!!this._def.checks.find(t=>"base64url"===t.kind)}get minLength(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}}pr.create=t=>new pr({checks:[],typeName:L.ZodString,coerce:t?.coerce??!1,...dB(t)});class pi extends dW{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){let r;if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==dq.number){let r=this._getOrReturnCtx(t);return dM(r,{code:dz.invalid_type,expected:dq.number,received:r.parsedType}),dU}let i=new dZ;for(let n of this._def.checks)"int"===n.kind?z.isInteger(t.data)||(dM(r=this._getOrReturnCtx(t,r),{code:dz.invalid_type,expected:"integer",received:"float",message:n.message}),i.dirty()):"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(dM(r=this._getOrReturnCtx(t,r),{code:dz.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),i.dirty()):"max"===n.kind?(n.inclusive?t.data>n.value:t.data>=n.value)&&(dM(r=this._getOrReturnCtx(t,r),{code:dz.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),i.dirty()):"multipleOf"===n.kind?0!==function(t,r){let i=(t.toString().split(".")[1]||"").length,n=(r.toString().split(".")[1]||"").length,a=i>n?i:n;return Number.parseInt(t.toFixed(a).replace(".",""))%Number.parseInt(r.toFixed(a).replace(".",""))/10**a}(t.data,n.value)&&(dM(r=this._getOrReturnCtx(t,r),{code:dz.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):"finite"===n.kind?Number.isFinite(t.data)||(dM(r=this._getOrReturnCtx(t,r),{code:dz.not_finite,message:n.message}),i.dirty()):z.assertNever(n);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,A.toString(r))}gt(t,r){return this.setLimit("min",t,!1,A.toString(r))}lte(t,r){return this.setLimit("max",t,!0,A.toString(r))}lt(t,r){return this.setLimit("max",t,!1,A.toString(r))}setLimit(t,r,i,n){return new pi({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:A.toString(n)}]})}_addCheck(t){return new pi({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:A.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:A.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:A.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:A.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:A.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:A.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:A.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:A.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:A.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>"int"===t.kind||"multipleOf"===t.kind&&z.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let i of this._def.checks)if("finite"===i.kind||"int"===i.kind||"multipleOf"===i.kind)return!0;else"min"===i.kind?(null===r||i.value>r)&&(r=i.value):"max"===i.kind&&(null===t||i.value<t)&&(t=i.value);return Number.isFinite(r)&&Number.isFinite(t)}}pi.create=t=>new pi({checks:[],typeName:L.ZodNumber,coerce:t?.coerce||!1,...dB(t)});class pn extends dW{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){let r;if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==dq.bigint)return this._getInvalidInput(t);let i=new dZ;for(let n of this._def.checks)"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(dM(r=this._getOrReturnCtx(t,r),{code:dz.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),i.dirty()):"max"===n.kind?(n.inclusive?t.data>n.value:t.data>=n.value)&&(dM(r=this._getOrReturnCtx(t,r),{code:dz.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),i.dirty()):"multipleOf"===n.kind?t.data%n.value!==BigInt(0)&&(dM(r=this._getOrReturnCtx(t,r),{code:dz.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):z.assertNever(n);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return dM(r,{code:dz.invalid_type,expected:dq.bigint,received:r.parsedType}),dU}gte(t,r){return this.setLimit("min",t,!0,A.toString(r))}gt(t,r){return this.setLimit("min",t,!1,A.toString(r))}lte(t,r){return this.setLimit("max",t,!0,A.toString(r))}lt(t,r){return this.setLimit("max",t,!1,A.toString(r))}setLimit(t,r,i,n){return new pn({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:A.toString(n)}]})}_addCheck(t){return new pn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:A.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:A.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:A.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:A.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:A.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}}pn.create=t=>new pn({checks:[],typeName:L.ZodBigInt,coerce:t?.coerce??!1,...dB(t)});class pa extends dW{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==dq.boolean){let r=this._getOrReturnCtx(t);return dM(r,{code:dz.invalid_type,expected:dq.boolean,received:r.parsedType}),dU}return dH(t.data)}}pa.create=t=>new pa({typeName:L.ZodBoolean,coerce:t?.coerce||!1,...dB(t)});class po extends dW{_parse(t){let r;if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==dq.date){let r=this._getOrReturnCtx(t);return dM(r,{code:dz.invalid_type,expected:dq.date,received:r.parsedType}),dU}if(Number.isNaN(t.data.getTime()))return dM(this._getOrReturnCtx(t),{code:dz.invalid_date}),dU;let i=new dZ;for(let n of this._def.checks)"min"===n.kind?t.data.getTime()<n.value&&(dM(r=this._getOrReturnCtx(t,r),{code:dz.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),i.dirty()):"max"===n.kind?t.data.getTime()>n.value&&(dM(r=this._getOrReturnCtx(t,r),{code:dz.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):z.assertNever(n);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new po({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:A.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:A.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return null!=t?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return null!=t?new Date(t):null}}po.create=t=>new po({checks:[],coerce:t?.coerce||!1,typeName:L.ZodDate,...dB(t)});class ps extends dW{_parse(t){if(this._getType(t)!==dq.symbol){let r=this._getOrReturnCtx(t);return dM(r,{code:dz.invalid_type,expected:dq.symbol,received:r.parsedType}),dU}return dH(t.data)}}ps.create=t=>new ps({typeName:L.ZodSymbol,...dB(t)});class pl extends dW{_parse(t){if(this._getType(t)!==dq.undefined){let r=this._getOrReturnCtx(t);return dM(r,{code:dz.invalid_type,expected:dq.undefined,received:r.parsedType}),dU}return dH(t.data)}}pl.create=t=>new pl({typeName:L.ZodUndefined,...dB(t)});class pc extends dW{_parse(t){if(this._getType(t)!==dq.null){let r=this._getOrReturnCtx(t);return dM(r,{code:dz.invalid_type,expected:dq.null,received:r.parsedType}),dU}return dH(t.data)}}pc.create=t=>new pc({typeName:L.ZodNull,...dB(t)});class pu extends dW{constructor(){super(...arguments),this._any=!0}_parse(t){return dH(t.data)}}pu.create=t=>new pu({typeName:L.ZodAny,...dB(t)});class pd extends dW{constructor(){super(...arguments),this._unknown=!0}_parse(t){return dH(t.data)}}pd.create=t=>new pd({typeName:L.ZodUnknown,...dB(t)});class pp extends dW{_parse(t){let r=this._getOrReturnCtx(t);return dM(r,{code:dz.invalid_type,expected:dq.never,received:r.parsedType}),dU}}pp.create=t=>new pp({typeName:L.ZodNever,...dB(t)});class pm extends dW{_parse(t){if(this._getType(t)!==dq.undefined){let r=this._getOrReturnCtx(t);return dM(r,{code:dz.invalid_type,expected:dq.void,received:r.parsedType}),dU}return dH(t.data)}}pm.create=t=>new pm({typeName:L.ZodVoid,...dB(t)});class ph extends dW{_parse(t){let{ctx:r,status:i}=this._processInputParams(t),n=this._def;if(r.parsedType!==dq.array)return dM(r,{code:dz.invalid_type,expected:dq.array,received:r.parsedType}),dU;if(null!==n.exactLength){let t=r.data.length>n.exactLength.value,a=r.data.length<n.exactLength.value;(t||a)&&(dM(r,{code:t?dz.too_big:dz.too_small,minimum:a?n.exactLength.value:void 0,maximum:t?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),i.dirty())}if(null!==n.minLength&&r.data.length<n.minLength.value&&(dM(r,{code:dz.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),i.dirty()),null!==n.maxLength&&r.data.length>n.maxLength.value&&(dM(r,{code:dz.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),i.dirty()),r.common.async)return Promise.all([...r.data].map((t,i)=>n.type._parseAsync(new dD(r,t,r.path,i)))).then(t=>dZ.mergeArray(i,t));let a=[...r.data].map((t,i)=>n.type._parseSync(new dD(r,t,r.path,i)));return dZ.mergeArray(i,a)}get element(){return this._def.type}min(t,r){return new ph({...this._def,minLength:{value:t,message:A.toString(r)}})}max(t,r){return new ph({...this._def,maxLength:{value:t,message:A.toString(r)}})}length(t,r){return new ph({...this._def,exactLength:{value:t,message:A.toString(r)}})}nonempty(t){return this.min(1,t)}}ph.create=(t,r)=>new ph({type:t,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...dB(r)});class pf extends dW{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let t=this._def.shape(),r=z.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==dq.object){let r=this._getOrReturnCtx(t);return dM(r,{code:dz.invalid_type,expected:dq.object,received:r.parsedType}),dU}let{status:r,ctx:i}=this._processInputParams(t),{shape:n,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof pp&&"strip"===this._def.unknownKeys))for(let t in i.data)a.includes(t)||o.push(t);let s=[];for(let t of a){let r=n[t],a=i.data[t];s.push({key:{status:"valid",value:t},value:r._parse(new dD(i,a,i.path,t)),alwaysSet:t in i.data})}if(this._def.catchall instanceof pp){let t=this._def.unknownKeys;if("passthrough"===t)for(let t of o)s.push({key:{status:"valid",value:t},value:{status:"valid",value:i.data[t]}});else if("strict"===t)o.length>0&&(dM(i,{code:dz.unrecognized_keys,keys:o}),r.dirty());else if("strip"===t);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let t=this._def.catchall;for(let r of o){let n=i.data[r];s.push({key:{status:"valid",value:r},value:t._parse(new dD(i,n,i.path,r)),alwaysSet:r in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let t=[];for(let r of s){let i=await r.key,n=await r.value;t.push({key:i,value:n,alwaysSet:r.alwaysSet})}return t}).then(t=>dZ.mergeObjectSync(r,t)):dZ.mergeObjectSync(r,s)}get shape(){return this._def.shape()}strict(t){return A.errToObj,new pf({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(r,i)=>{let n=this._def.errorMap?.(r,i).message??i.defaultError;return"unrecognized_keys"===r.code?{message:A.errToObj(t).message??n}:{message:n}}}:{}})}strip(){return new pf({...this._def,unknownKeys:"strip"})}passthrough(){return new pf({...this._def,unknownKeys:"passthrough"})}extend(t){return new pf({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new pf({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:L.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new pf({...this._def,catchall:t})}pick(t){let r={};for(let i of z.objectKeys(t))t[i]&&this.shape[i]&&(r[i]=this.shape[i]);return new pf({...this._def,shape:()=>r})}omit(t){let r={};for(let i of z.objectKeys(this.shape))t[i]||(r[i]=this.shape[i]);return new pf({...this._def,shape:()=>r})}deepPartial(){return function t(r){if(r instanceof pf){let i={};for(let n in r.shape){let a=r.shape[n];i[n]=pI.create(t(a))}return new pf({...r._def,shape:()=>i})}if(r instanceof ph)return new ph({...r._def,type:t(r.element)});if(r instanceof pI)return pI.create(t(r.unwrap()));if(r instanceof pq)return pq.create(t(r.unwrap()));if(r instanceof pb)return pb.create(r.items.map(r=>t(r)));else return r}(this)}partial(t){let r={};for(let i of z.objectKeys(this.shape)){let n=this.shape[i];t&&!t[i]?r[i]=n:r[i]=n.optional()}return new pf({...this._def,shape:()=>r})}required(t){let r={};for(let i of z.objectKeys(this.shape))if(t&&!t[i])r[i]=this.shape[i];else{let t=this.shape[i];for(;t instanceof pI;)t=t._def.innerType;r[i]=t}return new pf({...this._def,shape:()=>r})}keyof(){return pC(z.objectKeys(this.shape))}}pf.create=(t,r)=>new pf({shape:()=>t,unknownKeys:"strip",catchall:pp.create(),typeName:L.ZodObject,...dB(r)}),pf.strictCreate=(t,r)=>new pf({shape:()=>t,unknownKeys:"strict",catchall:pp.create(),typeName:L.ZodObject,...dB(r)}),pf.lazycreate=(t,r)=>new pf({shape:t,unknownKeys:"strip",catchall:pp.create(),typeName:L.ZodObject,...dB(r)});class pg extends dW{_parse(t){let{ctx:r}=this._processInputParams(t),i=this._def.options;if(r.common.async)return Promise.all(i.map(async t=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await t._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(function(t){for(let r of t)if("valid"===r.result.status)return r.result;for(let i of t)if("dirty"===i.result.status)return r.common.issues.push(...i.ctx.common.issues),i.result;let i=t.map(t=>new dN(t.ctx.common.issues));return dM(r,{code:dz.invalid_union,unionErrors:i}),dU});{let t,n=[];for(let a of i){let i={...r,common:{...r.common,issues:[]},parent:null},o=a._parseSync({data:r.data,path:r.path,parent:i});if("valid"===o.status)return o;"dirty"!==o.status||t||(t={result:o,ctx:i}),i.common.issues.length&&n.push(i.common.issues)}if(t)return r.common.issues.push(...t.ctx.common.issues),t.result;let a=n.map(t=>new dN(t));return dM(r,{code:dz.invalid_union,unionErrors:a}),dU}}get options(){return this._def.options}}pg.create=(t,r)=>new pg({options:t,typeName:L.ZodUnion,...dB(r)});let py=t=>{if(t instanceof pR)return py(t.schema);if(t instanceof pE)return py(t.innerType());if(t instanceof p$)return[t.value];if(t instanceof pT)return t.options;if(t instanceof pO)return z.objectValues(t.enum);else if(t instanceof pj)return py(t._def.innerType);else if(t instanceof pl)return[void 0];else if(t instanceof pc)return[null];else if(t instanceof pI)return[void 0,...py(t.unwrap())];else if(t instanceof pq)return[null,...py(t.unwrap())];else if(t instanceof pA)return py(t.unwrap());else if(t instanceof pM)return py(t.unwrap());else if(t instanceof pz)return py(t._def.innerType);else return[]};class pv extends dW{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==dq.object)return dM(r,{code:dz.invalid_type,expected:dq.object,received:r.parsedType}),dU;let i=this.discriminator,n=r.data[i],a=this.optionsMap.get(n);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(dM(r,{code:dz.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),dU)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,i){let n=new Map;for(let i of r){let r=py(i.shape[t]);if(!r.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of r){if(n.has(a))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);n.set(a,i)}}return new pv({typeName:L.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:n,...dB(i)})}}class p_ extends dW{_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=(t,n)=>{if("aborted"===t.status||"aborted"===n.status)return dU;let a=function t(r,i){let n=dj(r),a=dj(i);if(r===i)return{valid:!0,data:r};if(n===dq.object&&a===dq.object){let n=z.objectKeys(i),a=z.objectKeys(r).filter(t=>-1!==n.indexOf(t)),o={...r,...i};for(let n of a){let a=t(r[n],i[n]);if(!a.valid)return{valid:!1};o[n]=a.data}return{valid:!0,data:o}}if(n===dq.array&&a===dq.array){if(r.length!==i.length)return{valid:!1};let n=[];for(let a=0;a<r.length;a++){let o=t(r[a],i[a]);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}if(n===dq.date&&a===dq.date&&+r==+i)return{valid:!0,data:r};return{valid:!1}}(t.value,n.value);return a.valid?(("dirty"===t.status||"dirty"===n.status)&&r.dirty(),{status:r.value,value:a.data}):(dM(i,{code:dz.invalid_intersection_types}),dU)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([t,r])=>n(t,r)):n(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}p_.create=(t,r,i)=>new p_({left:t,right:r,typeName:L.ZodIntersection,...dB(i)});class pb extends dW{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==dq.array)return dM(i,{code:dz.invalid_type,expected:dq.array,received:i.parsedType}),dU;if(i.data.length<this._def.items.length)return dM(i,{code:dz.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),dU;!this._def.rest&&i.data.length>this._def.items.length&&(dM(i,{code:dz.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let n=[...i.data].map((t,r)=>{let n=this._def.items[r]||this._def.rest;return n?n._parse(new dD(i,t,i.path,r)):null}).filter(t=>!!t);return i.common.async?Promise.all(n).then(t=>dZ.mergeArray(r,t)):dZ.mergeArray(r,n)}get items(){return this._def.items}rest(t){return new pb({...this._def,rest:t})}}pb.create=(t,r)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new pb({items:t,typeName:L.ZodTuple,rest:null,...dB(r)})};class pS extends dW{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==dq.object)return dM(i,{code:dz.invalid_type,expected:dq.object,received:i.parsedType}),dU;let n=[],a=this._def.keyType,o=this._def.valueType;for(let t in i.data)n.push({key:a._parse(new dD(i,t,i.path,t)),value:o._parse(new dD(i,i.data[t],i.path,t)),alwaysSet:t in i.data});return i.common.async?dZ.mergeObjectAsync(r,n):dZ.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(t,r,i){return new pS(r instanceof dW?{keyType:t,valueType:r,typeName:L.ZodRecord,...dB(i)}:{keyType:pr.create(),valueType:t,typeName:L.ZodRecord,...dB(r)})}}class pw extends dW{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==dq.map)return dM(i,{code:dz.invalid_type,expected:dq.map,received:i.parsedType}),dU;let n=this._def.keyType,a=this._def.valueType,o=[...i.data.entries()].map(([t,r],o)=>({key:n._parse(new dD(i,t,i.path,[o,"key"])),value:a._parse(new dD(i,r,i.path,[o,"value"]))}));if(i.common.async){let t=new Map;return Promise.resolve().then(async()=>{for(let i of o){let n=await i.key,a=await i.value;if("aborted"===n.status||"aborted"===a.status)return dU;("dirty"===n.status||"dirty"===a.status)&&r.dirty(),t.set(n.value,a.value)}return{status:r.value,value:t}})}{let t=new Map;for(let i of o){let n=i.key,a=i.value;if("aborted"===n.status||"aborted"===a.status)return dU;("dirty"===n.status||"dirty"===a.status)&&r.dirty(),t.set(n.value,a.value)}return{status:r.value,value:t}}}}pw.create=(t,r,i)=>new pw({valueType:r,keyType:t,typeName:L.ZodMap,...dB(i)});class px extends dW{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==dq.set)return dM(i,{code:dz.invalid_type,expected:dq.set,received:i.parsedType}),dU;let n=this._def;null!==n.minSize&&i.data.size<n.minSize.value&&(dM(i,{code:dz.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),null!==n.maxSize&&i.data.size>n.maxSize.value&&(dM(i,{code:dz.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let a=this._def.valueType;function o(t){let i=new Set;for(let n of t){if("aborted"===n.status)return dU;"dirty"===n.status&&r.dirty(),i.add(n.value)}return{status:r.value,value:i}}let s=[...i.data.values()].map((t,r)=>a._parse(new dD(i,t,i.path,r)));return i.common.async?Promise.all(s).then(t=>o(t)):o(s)}min(t,r){return new px({...this._def,minSize:{value:t,message:A.toString(r)}})}max(t,r){return new px({...this._def,maxSize:{value:t,message:A.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}px.create=(t,r)=>new px({valueType:t,minSize:null,maxSize:null,typeName:L.ZodSet,...dB(r)});class pk extends dW{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==dq.function)return dM(r,{code:dz.invalid_type,expected:dq.function,received:r.parsedType}),dU;function i(t,i){return dL({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,dA,dA].filter(t=>!!t),issueData:{code:dz.invalid_arguments,argumentsError:i}})}function n(t,i){return dL({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,dA,dA].filter(t=>!!t),issueData:{code:dz.invalid_return_type,returnTypeError:i}})}let a={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof pP){let t=this;return dH(async function(...r){let s=new dN([]),l=await t._def.args.parseAsync(r,a).catch(t=>{throw s.addIssue(i(r,t)),s}),c=await Reflect.apply(o,this,l);return await t._def.returns._def.type.parseAsync(c,a).catch(t=>{throw s.addIssue(n(c,t)),s})})}{let t=this;return dH(function(...r){let s=t._def.args.safeParse(r,a);if(!s.success)throw new dN([i(r,s.error)]);let l=Reflect.apply(o,this,s.data),c=t._def.returns.safeParse(l,a);if(!c.success)throw new dN([n(l,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new pk({...this._def,args:pb.create(t).rest(pd.create())})}returns(t){return new pk({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,i){return new pk({args:t||pb.create([]).rest(pd.create()),returns:r||pd.create(),typeName:L.ZodFunction,...dB(i)})}}class pR extends dW{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}pR.create=(t,r)=>new pR({getter:t,typeName:L.ZodLazy,...dB(r)});class p$ extends dW{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return dM(r,{received:r.data,code:dz.invalid_literal,expected:this._def.value}),dU}return{status:"valid",value:t.data}}get value(){return this._def.value}}function pC(t,r){return new pT({values:t,typeName:L.ZodEnum,...dB(r)})}p$.create=(t,r)=>new p$({value:t,typeName:L.ZodLiteral,...dB(r)});class pT extends dW{_parse(t){if("string"!=typeof t.data){let r=this._getOrReturnCtx(t),i=this._def.values;return dM(r,{expected:z.joinValues(i),received:r.parsedType,code:dz.invalid_type}),dU}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),i=this._def.values;return dM(r,{received:r.data,code:dz.invalid_enum_value,options:i}),dU}return dH(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return pT.create(t,{...this._def,...r})}exclude(t,r=this._def){return pT.create(this.options.filter(r=>!t.includes(r)),{...this._def,...r})}}pT.create=pC;class pO extends dW{_parse(t){let r=z.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==dq.string&&i.parsedType!==dq.number){let t=z.objectValues(r);return dM(i,{expected:z.joinValues(t),received:i.parsedType,code:dz.invalid_type}),dU}if(this._cache||(this._cache=new Set(z.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let t=z.objectValues(r);return dM(i,{received:i.data,code:dz.invalid_enum_value,options:t}),dU}return dH(t.data)}get enum(){return this._def.values}}pO.create=(t,r)=>new pO({values:t,typeName:L.ZodNativeEnum,...dB(r)});class pP extends dW{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);return r.parsedType!==dq.promise&&!1===r.common.async?(dM(r,{code:dz.invalid_type,expected:dq.promise,received:r.parsedType}),dU):dH((r.parsedType===dq.promise?r.data:Promise.resolve(r.data)).then(t=>this._def.type.parseAsync(t,{path:r.path,errorMap:r.common.contextualErrorMap})))}}pP.create=(t,r)=>new pP({type:t,typeName:L.ZodPromise,...dB(r)});class pE extends dW{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=this._def.effect||null,a={addIssue:t=>{dM(i,t),t.fatal?r.abort():r.dirty()},get path(){return i.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===n.type){let t=n.transform(i.data,a);if(i.common.async)return Promise.resolve(t).then(async t=>{if("aborted"===r.value)return dU;let n=await this._def.schema._parseAsync({data:t,path:i.path,parent:i});return"aborted"===n.status?dU:"dirty"===n.status||"dirty"===r.value?dF(n.value):n});{if("aborted"===r.value)return dU;let n=this._def.schema._parseSync({data:t,path:i.path,parent:i});return"aborted"===n.status?dU:"dirty"===n.status||"dirty"===r.value?dF(n.value):n}}if("refinement"===n.type){let t=t=>{let r=n.refinement(t,a);if(i.common.async)return Promise.resolve(r);if(r instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return t};if(!1!==i.common.async)return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(i=>"aborted"===i.status?dU:("dirty"===i.status&&r.dirty(),t(i.value).then(()=>({status:r.value,value:i.value}))));{let n=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===n.status?dU:("dirty"===n.status&&r.dirty(),t(n.value),{status:r.value,value:n.value})}}if("transform"===n.type)if(!1!==i.common.async)return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(t=>"valid"!==t.status?dU:Promise.resolve(n.transform(t.value,a)).then(t=>({status:r.value,value:t})));else{let t=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if("valid"!==t.status)return dU;let o=n.transform(t.value,a);if(o instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}z.assertNever(n)}}pE.create=(t,r,i)=>new pE({schema:t,typeName:L.ZodEffects,effect:r,...dB(i)}),pE.createWithPreprocess=(t,r,i)=>new pE({schema:r,effect:{type:"preprocess",transform:t},typeName:L.ZodEffects,...dB(i)});class pI extends dW{_parse(t){return this._getType(t)===dq.undefined?dH(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}pI.create=(t,r)=>new pI({innerType:t,typeName:L.ZodOptional,...dB(r)});class pq extends dW{_parse(t){return this._getType(t)===dq.null?dH(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}pq.create=(t,r)=>new pq({innerType:t,typeName:L.ZodNullable,...dB(r)});class pj extends dW{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return r.parsedType===dq.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}pj.create=(t,r)=>new pj({innerType:t,typeName:L.ZodDefault,defaultValue:"function"==typeof r.default?r.default:()=>r.default,...dB(r)});class pz extends dW{_parse(t){let{ctx:r}=this._processInputParams(t),i={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return dJ(n)?n.then(t=>({status:"valid",value:"valid"===t.status?t.value:this._def.catchValue({get error(){return new dN(i.common.issues)},input:i.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new dN(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}pz.create=(t,r)=>new pz({innerType:t,typeName:L.ZodCatch,catchValue:"function"==typeof r.catch?r.catch:()=>r.catch,...dB(r)});class pN extends dW{_parse(t){if(this._getType(t)!==dq.nan){let r=this._getOrReturnCtx(t);return dM(r,{code:dz.invalid_type,expected:dq.nan,received:r.parsedType}),dU}return{status:"valid",value:t.data}}}pN.create=t=>new pN({typeName:L.ZodNaN,...dB(t)}),Symbol("zod_brand");class pA extends dW{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return this._def.type._parse({data:i,path:r.path,parent:r})}unwrap(){return this._def.type}}class pL extends dW{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{let t=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return"aborted"===t.status?dU:"dirty"===t.status?(r.dirty(),dF(t.value)):this._def.out._parseAsync({data:t.value,path:i.path,parent:i})})();{let t=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===t.status?dU:"dirty"===t.status?(r.dirty(),{status:"dirty",value:t.value}):this._def.out._parseSync({data:t.value,path:i.path,parent:i})}}static create(t,r){return new pL({in:t,out:r,typeName:L.ZodPipeline})}}class pM extends dW{_parse(t){let r=this._def.innerType._parse(t),i=t=>("valid"===t.status&&(t.value=Object.freeze(t.value)),t);return dJ(r)?r.then(t=>i(t)):i(r)}unwrap(){return this._def.innerType}}pM.create=(t,r)=>new pM({innerType:t,typeName:L.ZodReadonly,...dB(r)}),pf.lazycreate,(E=L||(L={})).ZodString="ZodString",E.ZodNumber="ZodNumber",E.ZodNaN="ZodNaN",E.ZodBigInt="ZodBigInt",E.ZodBoolean="ZodBoolean",E.ZodDate="ZodDate",E.ZodSymbol="ZodSymbol",E.ZodUndefined="ZodUndefined",E.ZodNull="ZodNull",E.ZodAny="ZodAny",E.ZodUnknown="ZodUnknown",E.ZodNever="ZodNever",E.ZodVoid="ZodVoid",E.ZodArray="ZodArray",E.ZodObject="ZodObject",E.ZodUnion="ZodUnion",E.ZodDiscriminatedUnion="ZodDiscriminatedUnion",E.ZodIntersection="ZodIntersection",E.ZodTuple="ZodTuple",E.ZodRecord="ZodRecord",E.ZodMap="ZodMap",E.ZodSet="ZodSet",E.ZodFunction="ZodFunction",E.ZodLazy="ZodLazy",E.ZodLiteral="ZodLiteral",E.ZodEnum="ZodEnum",E.ZodEffects="ZodEffects",E.ZodNativeEnum="ZodNativeEnum",E.ZodOptional="ZodOptional",E.ZodNullable="ZodNullable",E.ZodDefault="ZodDefault",E.ZodCatch="ZodCatch",E.ZodPromise="ZodPromise",E.ZodBranded="ZodBranded",E.ZodPipeline="ZodPipeline",E.ZodReadonly="ZodReadonly",pr.create,pi.create,pN.create,pn.create,pa.create,po.create,ps.create,pl.create,pc.create,pu.create,pd.create,pp.create,pm.create,ph.create,pf.create,pf.strictCreate,pg.create,pv.create,p_.create,pb.create,pS.create,pw.create,px.create,pk.create,pR.create,p$.create,pT.create,pO.create,pP.create,pE.create,pI.create,pq.create,pE.createWithPreprocess,pL.create;let pZ=(t,r)=>{let i=0;for(;i<t.length&&i<r.length&&t[i]===r[i];i++);return[(t.length-i).toString(),...r.slice(i)].join("/")};function pU(t){if("openAi"!==t.target)return{};let r=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===t.$refStrategy?pZ(r,t.currentPath):r.join("/")}}function pF(t,r,i,n){n?.errorMessages&&i&&(t.errorMessage={...t.errorMessage,[r]:i})}function pH(t,r,i,n,a){t[r]=i,pF(t,r,n,a)}function pJ(t,r){return mt(t.type._def,r)}let pD=/^[cC][^\s-]{8,}$/,pV=/^[0-9a-z]+$/,pB=/^[0-9A-HJKMNP-TV-Z]{26}$/,pW=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,pG=()=>(void 0===k&&(k=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),k),pK=/^(?:(?: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])$/,pY=/^(([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])$/,pX=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pQ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,p0=/^[a-zA-Z0-9_-]{21}$/,p1=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function p2(t,r){let i={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":pH(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,n.value):n.value,n.message,r);break;case"max":pH(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,n.value):n.value,n.message,r);break;case"email":switch(r.emailStrategy){case"format:email":p5(i,"email",n.message,r);break;case"format:idn-email":p5(i,"idn-email",n.message,r);break;case"pattern:zod":p3(i,pW,n.message,r)}break;case"url":p5(i,"uri",n.message,r);break;case"uuid":p5(i,"uuid",n.message,r);break;case"regex":p3(i,n.regex,n.message,r);break;case"cuid":p3(i,pD,n.message,r);break;case"cuid2":p3(i,pV,n.message,r);break;case"startsWith":p3(i,RegExp(`^${p9(n.value,r)}`),n.message,r);break;case"endsWith":p3(i,RegExp(`${p9(n.value,r)}$`),n.message,r);break;case"datetime":p5(i,"date-time",n.message,r);break;case"date":p5(i,"date",n.message,r);break;case"time":p5(i,"time",n.message,r);break;case"duration":p5(i,"duration",n.message,r);break;case"length":pH(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,n.value):n.value,n.message,r),pH(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,n.value):n.value,n.message,r);break;case"includes":p3(i,RegExp(p9(n.value,r)),n.message,r);break;case"ip":"v6"!==n.version&&p5(i,"ipv4",n.message,r),"v4"!==n.version&&p5(i,"ipv6",n.message,r);break;case"base64url":p3(i,pQ,n.message,r);break;case"jwt":p3(i,p1,n.message,r);break;case"cidr":"v6"!==n.version&&p3(i,pK,n.message,r),"v4"!==n.version&&p3(i,pY,n.message,r);break;case"emoji":p3(i,pG(),n.message,r);break;case"ulid":p3(i,pB,n.message,r);break;case"base64":switch(r.base64Strategy){case"format:binary":p5(i,"binary",n.message,r);break;case"contentEncoding:base64":pH(i,"contentEncoding","base64",n.message,r);break;case"pattern:zod":p3(i,pX,n.message,r)}break;case"nanoid":p3(i,p0,n.message,r)}return i}function p9(t,r){return"escape"===r.patternStrategy?function(t){let r="";for(let i=0;i<t.length;i++)p4.has(t[i])||(r+="\\"),r+=t[i];return r}(t):t}let p4=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function p5(t,r,i,n){t.format||t.anyOf?.some(t=>t.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,0===Object.keys(t.errorMessage).length&&delete t.errorMessage)),t.anyOf.push({format:r,...i&&n.errorMessages&&{errorMessage:{format:i}}})):pH(t,"format",r,i,n)}function p3(t,r,i,n){t.pattern||t.allOf?.some(t=>t.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,0===Object.keys(t.errorMessage).length&&delete t.errorMessage)),t.allOf.push({pattern:p6(r,n),...i&&n.errorMessages&&{errorMessage:{pattern:i}}})):pH(t,"pattern",p6(r,n),i,n)}function p6(t,r){if(!r.applyRegexFlags||!t.flags)return t.source;let i={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=i.i?t.source.toLowerCase():t.source,a="",o=!1,s=!1,l=!1;for(let t=0;t<n.length;t++){if(o){a+=n[t],o=!1;continue}if(i.i){if(s){if(n[t].match(/[a-z]/)){l?(a+=n[t],a+=`${n[t-2]}-${n[t]}`.toUpperCase(),l=!1):"-"===n[t+1]&&n[t+2]?.match(/[a-z]/)?(a+=n[t],l=!0):a+=`${n[t]}${n[t].toUpperCase()}`;continue}}else if(n[t].match(/[a-z]/)){a+=`[${n[t]}${n[t].toUpperCase()}]`;continue}}if(i.m){if("^"===n[t]){a+=`(^|(?<=[\r
|
|
73
|
+
`,t.enqueue(r.encode(a)),!0}catch(t){return this.onerror?.(t),!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(t,r){try{let i,n,a,o,s=t.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(!uN(t.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(r?.parsedBody===void 0)try{i=await t.json()}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else i=r.parsedBody;try{n=Array.isArray(i)?i.map(t=>ou.parse(t)):[ou.parse(i)]}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let l=n.some(t=>oR.safeParse(t).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(n.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 r=this.validateSession(t);if(r)return r;let i=this.validateProtocolVersion(t);if(i)return i}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!n.some(t=>cW(t))){for(let i of n)this.onmessage?.(i,{authInfo:r?.authInfo,request:t});return new Response(null,{status:202})}let c=crypto.randomUUID(),u=n.find(t=>oR.safeParse(t).success),d=u?u.params.protocolVersion:t.headers.get("mcp-protocol-version")??"2025-03-26";if(this._enableJsonResponse)return new Promise(i=>{for(let t of(this._streamMapping.set(c,{resolveJson:i,cleanup:()=>{this._streamMapping.delete(c)}}),n))cW(t)&&this._requestToStreamMapping.set(t.id,c);for(let i of n)this.onmessage?.(i,{authInfo:r?.authInfo,request:t})});let p=new TextEncoder,m=new ReadableStream({start:t=>{a=t},cancel:()=>{void 0!==o&&clearInterval(o),this._streamMapping.get(c)?.controller===a&&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 t of(void 0!==this.sessionId&&(h["mcp-session-id"]=this.sessionId),n))cW(t)&&(this._streamMapping.set(c,{controller:a,encoder:p,cleanup:()=>{void 0!==o&&clearInterval(o),this._streamMapping.delete(c);try{a.close()}catch{}}}),this._requestToStreamMapping.set(t.id,c));for(let i of(await this.writePrimingEvent(a,p,c,d),n)){let n,a;cW(i)&&this._eventStore&&this.supportsEmptySSEData(d)&&(n=()=>{this.closeSSEStream(i.id)},a=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(i,{authInfo:r?.authInfo,request:t,closeSSEStream:n,closeStandaloneSSEStream:a})}return this._streamMapping.get(c)?.controller===a&&(o=this.startKeepAlive(a,p)),new Response(m,{status:200,headers:h})}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(t)})}}async handleDeleteRequest(t){let r=this.validateSession(t);if(r)return r;let i=this.validateProtocolVersion(t);if(i)return i;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(t){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 r=t.headers.get("mcp-session-id");return r?r!==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(t){let r=t.headers.get("mcp-protocol-version");if(null!==r&&!this._supportedProtocolVersions.includes(r)){let t=`Bad Request: Unsupported protocol version: ${r} (supported versions: ${this._supportedProtocolVersions.join(", ")})`;return this.onerror?.(Error(t)),this.createJsonErrorResponse(400,-32e3,t)}}async close(){if(!this._closed){for(let{cleanup:t}of(this._closed=!0,this._streamMapping.values()))t();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}}closeSSEStream(t){let r=this._requestToStreamMapping.get(t);if(!r)return;let i=this._streamMapping.get(r);i&&i.cleanup()}closeStandaloneSSEStream(){let t=this._streamMapping.get(this._standaloneSseStreamId);t&&t.cleanup()}async send(t,r){let i=r?.relatedRequestId;if((cK(t)||cY(t))&&(i=t.id),void 0===i){let r;if(cK(t)||cY(t))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");this._eventStore&&(r=await this._eventStore.storeEvent(this._standaloneSseStreamId,t));let i=this._streamMapping.get(this._standaloneSseStreamId);if(void 0===i)return;i.controller&&i.encoder&&(void 0===r||!i.replayedEventIds?.has(r))&&this.writeSSEEvent(i.controller,i.encoder,t,r);return}let n=this._requestToStreamMapping.get(i);if(!n)throw Error(`No connection established for request ID: ${String(i)}`);let a=this._streamMapping.get(n);if(!this._enableJsonResponse){let r;this._eventStore&&(r=await this._eventStore.storeEvent(n,t),a=this._streamMapping.get(n)),a?.controller&&a?.encoder&&(void 0===r||!a.replayedEventIds?.has(r))&&this.writeSSEEvent(a.controller,a.encoder,t,r)}if(cK(t)||cY(t)){this._requestResponseMap.set(i,t);let r=[...this._requestToStreamMapping.entries()].filter(([t,r])=>r===n).map(([t])=>t);if(r.every(t=>this._requestResponseMap.has(t))){if(!a){if(this._enableJsonResponse)throw Error(`No connection established for request ID: ${String(i)}`);if(!this._eventStore){for(let t of(this.onerror?.(Error(`Response for request ID ${String(i)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)),r))this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t);return}for(let t of r)this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t);return}if(this._enableJsonResponse&&a.resolveJson){let t={"Content-Type":"application/json"};void 0!==this.sessionId&&(t["mcp-session-id"]=this.sessionId);let i=r.map(t=>this._requestResponseMap.get(t));1===i.length?a.resolveJson(Response.json(i[0],{status:200,headers:t})):a.resolveJson(Response.json(i,{status:200,headers:t})),a.cleanup()}else a.cleanup();for(let t of r)this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t)}}}};function dx(t){if(null===t||"object"!=typeof t||Array.isArray(t))return null;let{method:r,id:i}=t;return"string"!=typeof r?null:"string"==typeof i||"number"==typeof i?i:null}function dR(t,r,i,n,a=null){return Response.json({jsonrpc:"2.0",error:{code:r,message:i,...void 0!==n&&{data:n}},id:a},{status:t})}function d$(t,r=null){return dR(t.httpStatus,t.code,t.message,t.data,r)}function dC(t){return t instanceof Error?t:Error(String(t))}function dT(t=null){return dR(500,-32603,"Internal server error",void 0,t)}async function dP(t,r,i=!0){let n,a=t.method.toUpperCase(),o=r,s=t,l=!1;if("POST"===a){if(void 0===o){let r;i&&(s=t.clone());try{r=await t.text()}catch{return{step:"unreadable-body"}}try{n=0===r.length?void 0:JSON.parse(r)}catch{l=!0}l||void 0===n||(o=n)}else n=o;if(l||void 0===n)return{step:"no-json-body",forwardRequest:s}}return{step:"classified",outcome:function(t){if("POST"!==(t={...t,...void 0!==t.protocolVersionHeader&&{protocolVersionHeader:ua(t.protocolVersionHeader)},...void 0!==t.mcpMethodHeader&&{mcpMethodHeader:ua(t.mcpMethodHeader)},...void 0!==t.mcpNameHeader&&{mcpNameHeader:ua(t.mcpNameHeader)}}).httpMethod.toUpperCase())return{kind:"legacy",reason:"http-method"};let r=t.body;if(Array.isArray(r)){if(0===r.length)return ur("jsonrpc-shape","empty-batch",400,new cg(cf.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let t of r){if(cD(uo(t)?t.params:void 0))return ur("jsonrpc-shape","batch-with-modern-element",400,new cg(cf.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(cW(t)||cG(t)||cK(t)||cY(t)))return ur("jsonrpc-shape","batch-with-invalid-element",400,new cg(cf.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}return cK(r)||cY(r)?{kind:"legacy",reason:"response"}:uo(r)&&cW(r)?function(t,r){let i=r.params,n=r.method,a=t.protocolVersionHeader,o=void 0!==a&&a>=lK;if("initialize"===n&&!function(t){if(!cD(t))return!1;let r=cV(t);if(void 0===r||!(r>=lK))return!1;let i=cH(t);return void 0!==i&&0===cJ(i).length}(i)){if(o)return ui("initialize-with-modern-header",a,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let t=uo(i)&&"string"==typeof i.protocolVersion?i.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...void 0!==t&&{requestedVersion:t}}}if(cD(i)){let o=cH(i),s=(void 0===o?[]:cJ(o))[0];if(void 0!==s)return ur("envelope","envelope-invalid",400,new cg(cf.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${s.key}: ${s.problem}`,{envelope:s}),!0);let l=cV(i);return void 0!==a&&void 0!==l&&a!==l?ui("header-body-version-mismatch",a,`the body envelope names protocol version ${l} but the MCP-Protocol-Version header names ${a}`):void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?ui("method-header-mismatch",t.mcpMethodHeader,`the body names method ${n} but the Mcp-Method header names ${t.mcpMethodHeader}`):{kind:"modern",messageKind:"request",message:r,classification:us(l)}}if(o){let t=cH(i),r=cJ(t??{}).filter(t=>"missing"===t.problem).map(t=>t.key),n=void 0===t?["_meta"]:r.length>0?r:[aW];return ur("envelope","modern-header-without-claim",400,new cg(cf.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${a}, but the request is missing the required per-request envelope key(s): ${n.join(", ")}`,{envelope:{missing:n}}),!0)}return{kind:"legacy",reason:"no-claim",...void 0!==a&&{requestedVersion:a}}}(t,r):uo(r)&&cG(r)?function(t,r){let i=r.params,n=r.method,a=t.protocolVersionHeader,o=void 0!==a&&a>=lK;if(cD(i)){let o=cV(i);if(void 0===o){let t=cH(i),r=(void 0===t?[]:cJ(t)).find(t=>t.key===aW)??{key:aW,problem:"expected a protocol version string"};return ur("envelope","notification-envelope-invalid",400,new cg(cf.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${r.key}: ${r.problem}`,{envelope:r}),!0)}if(void 0!==a&&a!==o)return ui("notification-header-body-version-mismatch",a,`the notification envelope names protocol version ${o} but the MCP-Protocol-Version header names ${a}`);let s=us(o);return"modern"===s.era&&void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?ui("notification-method-header-mismatch",t.mcpMethodHeader,`the notification body names method ${n} but the Mcp-Method header names ${t.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:r,classification:s}}return o?void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?ui("notification-method-header-mismatch",t.mcpMethodHeader,`the notification body names method ${n} but the Mcp-Method header names ${t.mcpMethodHeader}`):{kind:"modern",messageKind:"notification",message:r,classification:{era:"modern",revision:a}}:{kind:"legacy",reason:"notification",...void 0!==a&&{requestedVersion:a}}}(t,r):ur("jsonrpc-shape","invalid-json-rpc-body",400,new cg(cf.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}({httpMethod:a,protocolVersionHeader:t.headers.get("mcp-protocol-version")??void 0,mcpMethodHeader:t.headers.get("mcp-method")??void 0,mcpNameHeader:t.headers.get("mcp-name")??void 0,...void 0!==n&&{body:n}}),body:n,parsedBody:o,forwardRequest:s}}let dE=Symbol("Let zodToJsonSchema decide on which parser to use"),dO={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"};(P=A||(A={})).assertEqual=t=>{},P.assertIs=function(t){},P.assertNever=function(t){throw Error()},P.arrayToEnum=t=>{let r={};for(let i of t)r[i]=i;return r},P.getValidEnumValues=t=>{let r=P.objectKeys(t).filter(r=>"number"!=typeof t[t[r]]),i={};for(let n of r)i[n]=t[n];return P.objectValues(i)},P.objectValues=t=>P.objectKeys(t).map(function(r){return t[r]}),P.objectKeys="function"==typeof Object.keys?t=>Object.keys(t):t=>{let r=[];for(let i in t)Object.prototype.hasOwnProperty.call(t,i)&&r.push(i);return r},P.find=(t,r)=>{for(let i of t)if(r(i))return i},P.isInteger="function"==typeof Number.isInteger?t=>Number.isInteger(t):t=>"number"==typeof t&&Number.isFinite(t)&&Math.floor(t)===t,P.joinValues=function(t,r=" | "){return t.map(t=>"string"==typeof t?`'${t}'`:t).join(r)},P.jsonStringifyReplacer=(t,r)=>"bigint"==typeof r?r.toString():r,(N||(N={})).mergeShapes=(t,r)=>({...t,...r});let dI=A.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),dq=t=>{switch(typeof t){case"undefined":return dI.undefined;case"string":return dI.string;case"number":return Number.isNaN(t)?dI.nan:dI.number;case"boolean":return dI.boolean;case"function":return dI.function;case"bigint":return dI.bigint;case"symbol":return dI.symbol;case"object":if(Array.isArray(t))return dI.array;if(null===t)return dI.null;if(t.then&&"function"==typeof t.then&&t.catch&&"function"==typeof t.catch)return dI.promise;if("undefined"!=typeof Map&&t instanceof Map)return dI.map;if("undefined"!=typeof Set&&t instanceof Set)return dI.set;if("undefined"!=typeof Date&&t instanceof Date)return dI.date;return dI.object;default:return dI.unknown}},dj=A.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 dA extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=t=>{this.issues=[...this.issues,t]},this.addIssues=(t=[])=>{this.issues=[...this.issues,...t]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(t){return t.message},i={_errors:[]},n=t=>{for(let a of t.issues)if("invalid_union"===a.code)a.unionErrors.map(n);else if("invalid_return_type"===a.code)n(a.returnTypeError);else if("invalid_arguments"===a.code)n(a.argumentsError);else if(0===a.path.length)i._errors.push(r(a));else{let t=i,n=0;for(;n<a.path.length;){let i=a.path[n],o=n===a.path.length-1;if("_errors"===i){o&&t._errors.push(r(a)),n++;continue}Object.prototype.hasOwnProperty.call(t,i)||("__proto__"===i?Object.defineProperty(t,i,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):t[i]={_errors:[]}),t=t[i],o&&t._errors.push(r(a)),n++}}};return n(this),i}static assert(t){if(!(t instanceof dA))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,A.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(t=t=>t.message){let r=Object.create(null),i=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];r[i]=r[i]||[],r[i].push(t(n))}else i.push(t(n));return{formErrors:i,fieldErrors:r}}get formErrors(){return this.flatten()}}dA.create=t=>new dA(t);let dN=(t,r)=>{let i;switch(t.code){case dj.invalid_type:i=t.received===dI.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case dj.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(t.expected,A.jsonStringifyReplacer)}`;break;case dj.unrecognized_keys:i=`Unrecognized key(s) in object: ${A.joinValues(t.keys,", ")}`;break;case dj.invalid_union:i="Invalid input";break;case dj.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${A.joinValues(t.options)}`;break;case dj.invalid_enum_value:i=`Invalid enum value. Expected ${A.joinValues(t.options)}, received '${t.received}'`;break;case dj.invalid_arguments:i="Invalid function arguments";break;case dj.invalid_return_type:i="Invalid function return type";break;case dj.invalid_date:i="Invalid date";break;case dj.invalid_string:"object"==typeof t.validation?"includes"in t.validation?(i=`Invalid input: must include "${t.validation.includes}"`,"number"==typeof t.validation.position&&(i=`${i} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?i=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?i=`Invalid input: must end with "${t.validation.endsWith}"`:A.assertNever(t.validation):i="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case dj.too_small:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:"number"===t.type||"bigint"===t.type?`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:"date"===t.type?`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:"Invalid input";break;case dj.too_big:i="array"===t.type?`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:"string"===t.type?`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:"number"===t.type?`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"bigint"===t.type?`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:"date"===t.type?`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:"Invalid input";break;case dj.custom:i="Invalid input";break;case dj.invalid_intersection_types:i="Intersection results could not be merged";break;case dj.not_multiple_of:i=`Number must be a multiple of ${t.multipleOf}`;break;case dj.not_finite:i="Number must be finite";break;default:i=r.defaultError,A.assertNever(t)}return{message:i}};(E=L||(L={})).errToObj=t=>"string"==typeof t?{message:t}:t||{},E.toString=t=>"string"==typeof t?t:t?.message;let dL=t=>{let{data:r,path:i,errorMaps:n,issueData:a}=t,o=[...i,...a.path||[]],s={...a,path:o};if(void 0!==a.message)return{...a,path:o,message:a.message};let l="";for(let t of n.filter(t=>!!t).slice().reverse())l=t(s,{data:r,defaultError:l}).message;return{...a,path:o,message:l}};function dz(t,r){let i=dL({issueData:r,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,dN,void 0].filter(t=>!!t)});t.common.issues.push(i)}class dM{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(t,r){let i=[];for(let n of r){if("aborted"===n.status)return dZ;"dirty"===n.status&&t.dirty(),i.push(n.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,r){let i=[];for(let t of r){let r=await t.key,n=await t.value;i.push({key:r,value:n})}return dM.mergeObjectSync(t,i)}static mergeObjectSync(t,r){let i={};for(let n of r){let{key:r,value:a}=n;if("aborted"===r.status||"aborted"===a.status)return dZ;"dirty"===r.status&&t.dirty(),"dirty"===a.status&&t.dirty(),"__proto__"!==r.value&&(void 0!==a.value||n.alwaysSet)&&(i[r.value]=a.value)}return{status:t.value,value:i}}}let dZ=Object.freeze({status:"aborted"}),dU=t=>({status:"dirty",value:t}),dF=t=>({status:"valid",value:t}),dH=t=>"undefined"!=typeof Promise&&t instanceof Promise;class dD{constructor(t,r,i,n){this._cachedPath=[],this.parent=t,this.data=r,this._path=i,this._key=n}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 dV=(t,r)=>{if("valid"===r.status)return{success:!0,data:r.value};if(!t.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new dA(t.common.issues);return this._error=r,this._error}}};function dJ(t){if(!t)return{};let{errorMap:r,invalid_type_error:i,required_error:n,description:a}=t;if(r&&(i||n))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return r?{errorMap:r,description:a}:{errorMap:(r,a)=>{let{message:o}=t;return"invalid_enum_value"===r.code?{message:o??a.defaultError}:void 0===a.data?{message:o??n??a.defaultError}:"invalid_type"!==r.code?{message:a.defaultError}:{message:o??i??a.defaultError}},description:a}}class dB{get description(){return this._def.description}_getType(t){return dq(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:dq(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new dM,ctx:{common:t.parent.common,data:t.data,parsedType:dq(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(dH(r))throw Error("Synchronous parse encountered promise.");return r}_parseAsync(t){return Promise.resolve(this._parse(t))}parse(t,r){let i=this.safeParse(t,r);if(i.success)return i.data;throw i.error}safeParse(t,r){let i={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:dq(t)},n=this._parseSync({data:t,path:i.path,parent:i});return dV(i,n)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:dq(t)};if(!this["~standard"].async)try{let i=this._parseSync({data:t,path:[],parent:r});return"valid"===i.status?{value:i.value}:{issues:r.common.issues}}catch(t){t?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(t=>"valid"===t.status?{value:t.value}:{issues:r.common.issues})}async parseAsync(t,r){let i=await this.safeParseAsync(t,r);if(i.success)return i.data;throw i.error}async safeParseAsync(t,r){let i={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:dq(t)},n=this._parse({data:t,path:i.path,parent:i});return dV(i,await (dH(n)?n:Promise.resolve(n)))}refine(t,r){return this._refinement((i,n)=>{let a=t(i),o=()=>n.addIssue({code:dj.custom,..."string"==typeof r||void 0===r?{message:r}:"function"==typeof r?r(i):r});return"undefined"!=typeof Promise&&a instanceof Promise?a.then(t=>!!t||(o(),!1)):!!a||(o(),!1)})}refinement(t,r){return this._refinement((i,n)=>!!t(i)||(n.addIssue("function"==typeof r?r(i,n):r),!1))}_refinement(t){return new pE({schema:this,typeName:z.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,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:t=>this["~validate"](t)}}optional(){return pO.create(this,this._def)}nullable(){return pI.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pm.create(this)}promise(){return pP.create(this,this._def)}or(t){return pf.create([this,t],this._def)}and(t){return pv.create(this,t,this._def)}transform(t){return new pE({...dJ(this._def),schema:this,typeName:z.ZodEffects,effect:{type:"transform",transform:t}})}default(t){return new pq({...dJ(this._def),innerType:this,defaultValue:"function"==typeof t?t:()=>t,typeName:z.ZodDefault})}brand(){return new pN({typeName:z.ZodBranded,type:this,...dJ(this._def)})}catch(t){return new pj({...dJ(this._def),innerType:this,catchValue:"function"==typeof t?t:()=>t,typeName:z.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return pL.create(this,t)}readonly(){return pz.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let dW=/^c[^\s-]{8,}$/i,dG=/^[0-9a-z]+$/,dK=/^[0-9A-HJKMNP-TV-Z]{26}$/i,dY=/^[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,dX=/^[a-z0-9_-]{21}$/i,dQ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,d0=/^[-+]?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)?)??$/,d1=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,d2=/^(?:(?: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])$/,d9=/^(?:(?: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])$/,d4=/^(([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]))$/,d5=/^(([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])$/,d3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,d6=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,d7="((\\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])))",d8=RegExp(`^${d7}$`);function pe(t){let r="[0-5]\\d";t.precision?r=`${r}\\.\\d{${t.precision}}`:null==t.precision&&(r=`${r}(\\.\\d+)?`);let i=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${r})${i}`}class pt extends dB{_parse(t){var r,i,n,a;let o;if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==dI.string){let r=this._getOrReturnCtx(t);return dz(r,{code:dj.invalid_type,expected:dI.string,received:r.parsedType}),dZ}let s=new dM;for(let l of this._def.checks)if("min"===l.kind)t.data.length<l.value&&(dz(o=this._getOrReturnCtx(t,o),{code:dj.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),s.dirty());else if("max"===l.kind)t.data.length>l.value&&(dz(o=this._getOrReturnCtx(t,o),{code:dj.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!1,message:l.message}),s.dirty());else if("length"===l.kind){let r=t.data.length>l.value,i=t.data.length<l.value;(r||i)&&(o=this._getOrReturnCtx(t,o),r?dz(o,{code:dj.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):i&&dz(o,{code:dj.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),s.dirty())}else if("email"===l.kind)d1.test(t.data)||(dz(o=this._getOrReturnCtx(t,o),{validation:"email",code:dj.invalid_string,message:l.message}),s.dirty());else if("emoji"===l.kind)p||(p=RegExp("^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$","u")),p.test(t.data)||(dz(o=this._getOrReturnCtx(t,o),{validation:"emoji",code:dj.invalid_string,message:l.message}),s.dirty());else if("uuid"===l.kind)dY.test(t.data)||(dz(o=this._getOrReturnCtx(t,o),{validation:"uuid",code:dj.invalid_string,message:l.message}),s.dirty());else if("nanoid"===l.kind)dX.test(t.data)||(dz(o=this._getOrReturnCtx(t,o),{validation:"nanoid",code:dj.invalid_string,message:l.message}),s.dirty());else if("cuid"===l.kind)dW.test(t.data)||(dz(o=this._getOrReturnCtx(t,o),{validation:"cuid",code:dj.invalid_string,message:l.message}),s.dirty());else if("cuid2"===l.kind)dG.test(t.data)||(dz(o=this._getOrReturnCtx(t,o),{validation:"cuid2",code:dj.invalid_string,message:l.message}),s.dirty());else if("ulid"===l.kind)dK.test(t.data)||(dz(o=this._getOrReturnCtx(t,o),{validation:"ulid",code:dj.invalid_string,message:l.message}),s.dirty());else if("url"===l.kind)try{new URL(t.data)}catch{dz(o=this._getOrReturnCtx(t,o),{validation:"url",code:dj.invalid_string,message:l.message}),s.dirty()}else"regex"===l.kind?(l.regex.lastIndex=0,l.regex.test(t.data)||(dz(o=this._getOrReturnCtx(t,o),{validation:"regex",code:dj.invalid_string,message:l.message}),s.dirty())):"trim"===l.kind?t.data=t.data.trim():"includes"===l.kind?t.data.includes(l.value,l.position)||(dz(o=this._getOrReturnCtx(t,o),{code:dj.invalid_string,validation:{includes:l.value,position:l.position},message:l.message}),s.dirty()):"toLowerCase"===l.kind?t.data=t.data.toLowerCase():"toUpperCase"===l.kind?t.data=t.data.toUpperCase():"startsWith"===l.kind?t.data.startsWith(l.value)||(dz(o=this._getOrReturnCtx(t,o),{code:dj.invalid_string,validation:{startsWith:l.value},message:l.message}),s.dirty()):"endsWith"===l.kind?t.data.endsWith(l.value)||(dz(o=this._getOrReturnCtx(t,o),{code:dj.invalid_string,validation:{endsWith:l.value},message:l.message}),s.dirty()):"datetime"===l.kind?(function(t){let r=`${d7}T${pe(t)}`,i=[];return i.push(t.local?"Z?":"Z"),t.offset&&i.push("([+-]\\d{2}:?\\d{2})"),r=`${r}(${i.join("|")})`,RegExp(`^${r}$`)})(l).test(t.data)||(dz(o=this._getOrReturnCtx(t,o),{code:dj.invalid_string,validation:"datetime",message:l.message}),s.dirty()):"date"===l.kind?d8.test(t.data)||(dz(o=this._getOrReturnCtx(t,o),{code:dj.invalid_string,validation:"date",message:l.message}),s.dirty()):"time"===l.kind?RegExp(`^${pe(l)}$`).test(t.data)||(dz(o=this._getOrReturnCtx(t,o),{code:dj.invalid_string,validation:"time",message:l.message}),s.dirty()):"duration"===l.kind?d0.test(t.data)||(dz(o=this._getOrReturnCtx(t,o),{validation:"duration",code:dj.invalid_string,message:l.message}),s.dirty()):"ip"===l.kind?(r=t.data,!(("v4"===(i=l.version)||!i)&&d2.test(r)||("v6"===i||!i)&&d4.test(r))&&1&&(dz(o=this._getOrReturnCtx(t,o),{validation:"ip",code:dj.invalid_string,message:l.message}),s.dirty())):"jwt"===l.kind?!function(t,r){if(!dQ.test(t))return!1;try{let[i]=t.split(".");if(!i)return!1;let n=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),a=JSON.parse(atob(n));if("object"!=typeof a||null===a||"typ"in a&&a?.typ!=="JWT"||!a.alg||r&&a.alg!==r)return!1;return!0}catch{return!1}}(t.data,l.alg)&&(dz(o=this._getOrReturnCtx(t,o),{validation:"jwt",code:dj.invalid_string,message:l.message}),s.dirty()):"cidr"===l.kind?(n=t.data,!(("v4"===(a=l.version)||!a)&&d9.test(n)||("v6"===a||!a)&&d5.test(n))&&1&&(dz(o=this._getOrReturnCtx(t,o),{validation:"cidr",code:dj.invalid_string,message:l.message}),s.dirty())):"base64"===l.kind?d3.test(t.data)||(dz(o=this._getOrReturnCtx(t,o),{validation:"base64",code:dj.invalid_string,message:l.message}),s.dirty()):"base64url"===l.kind?d6.test(t.data)||(dz(o=this._getOrReturnCtx(t,o),{validation:"base64url",code:dj.invalid_string,message:l.message}),s.dirty()):A.assertNever(l);return{status:s.value,value:t.data}}_regex(t,r,i){return this.refinement(r=>t.test(r),{validation:r,code:dj.invalid_string,...L.errToObj(i)})}_addCheck(t){return new pt({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...L.errToObj(t)})}url(t){return this._addCheck({kind:"url",...L.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...L.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...L.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...L.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...L.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...L.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...L.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...L.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...L.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...L.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...L.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...L.errToObj(t)})}datetime(t){return"string"==typeof t?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:void 0===t?.precision?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...L.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return"string"==typeof t?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:void 0===t?.precision?null:t?.precision,...L.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...L.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...L.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...L.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...L.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...L.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...L.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...L.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...L.errToObj(r)})}nonempty(t){return this.min(1,L.errToObj(t))}trim(){return new pt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new pt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new pt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>"datetime"===t.kind)}get isDate(){return!!this._def.checks.find(t=>"date"===t.kind)}get isTime(){return!!this._def.checks.find(t=>"time"===t.kind)}get isDuration(){return!!this._def.checks.find(t=>"duration"===t.kind)}get isEmail(){return!!this._def.checks.find(t=>"email"===t.kind)}get isURL(){return!!this._def.checks.find(t=>"url"===t.kind)}get isEmoji(){return!!this._def.checks.find(t=>"emoji"===t.kind)}get isUUID(){return!!this._def.checks.find(t=>"uuid"===t.kind)}get isNANOID(){return!!this._def.checks.find(t=>"nanoid"===t.kind)}get isCUID(){return!!this._def.checks.find(t=>"cuid"===t.kind)}get isCUID2(){return!!this._def.checks.find(t=>"cuid2"===t.kind)}get isULID(){return!!this._def.checks.find(t=>"ulid"===t.kind)}get isIP(){return!!this._def.checks.find(t=>"ip"===t.kind)}get isCIDR(){return!!this._def.checks.find(t=>"cidr"===t.kind)}get isBase64(){return!!this._def.checks.find(t=>"base64"===t.kind)}get isBase64url(){return!!this._def.checks.find(t=>"base64url"===t.kind)}get minLength(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}}pt.create=t=>new pt({checks:[],typeName:z.ZodString,coerce:t?.coerce??!1,...dJ(t)});class pr extends dB{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){let r;if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==dI.number){let r=this._getOrReturnCtx(t);return dz(r,{code:dj.invalid_type,expected:dI.number,received:r.parsedType}),dZ}let i=new dM;for(let n of this._def.checks)"int"===n.kind?A.isInteger(t.data)||(dz(r=this._getOrReturnCtx(t,r),{code:dj.invalid_type,expected:"integer",received:"float",message:n.message}),i.dirty()):"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(dz(r=this._getOrReturnCtx(t,r),{code:dj.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),i.dirty()):"max"===n.kind?(n.inclusive?t.data>n.value:t.data>=n.value)&&(dz(r=this._getOrReturnCtx(t,r),{code:dj.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),i.dirty()):"multipleOf"===n.kind?0!==function(t,r){let i=(t.toString().split(".")[1]||"").length,n=(r.toString().split(".")[1]||"").length,a=i>n?i:n;return Number.parseInt(t.toFixed(a).replace(".",""))%Number.parseInt(r.toFixed(a).replace(".",""))/10**a}(t.data,n.value)&&(dz(r=this._getOrReturnCtx(t,r),{code:dj.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):"finite"===n.kind?Number.isFinite(t.data)||(dz(r=this._getOrReturnCtx(t,r),{code:dj.not_finite,message:n.message}),i.dirty()):A.assertNever(n);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,L.toString(r))}gt(t,r){return this.setLimit("min",t,!1,L.toString(r))}lte(t,r){return this.setLimit("max",t,!0,L.toString(r))}lt(t,r){return this.setLimit("max",t,!1,L.toString(r))}setLimit(t,r,i,n){return new pr({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:L.toString(n)}]})}_addCheck(t){return new pr({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:L.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:L.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:L.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>"int"===t.kind||"multipleOf"===t.kind&&A.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let i of this._def.checks)if("finite"===i.kind||"int"===i.kind||"multipleOf"===i.kind)return!0;else"min"===i.kind?(null===r||i.value>r)&&(r=i.value):"max"===i.kind&&(null===t||i.value<t)&&(t=i.value);return Number.isFinite(r)&&Number.isFinite(t)}}pr.create=t=>new pr({checks:[],typeName:z.ZodNumber,coerce:t?.coerce||!1,...dJ(t)});class pi extends dB{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){let r;if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==dI.bigint)return this._getInvalidInput(t);let i=new dM;for(let n of this._def.checks)"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(dz(r=this._getOrReturnCtx(t,r),{code:dj.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),i.dirty()):"max"===n.kind?(n.inclusive?t.data>n.value:t.data>=n.value)&&(dz(r=this._getOrReturnCtx(t,r),{code:dj.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),i.dirty()):"multipleOf"===n.kind?t.data%n.value!==BigInt(0)&&(dz(r=this._getOrReturnCtx(t,r),{code:dj.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):A.assertNever(n);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return dz(r,{code:dj.invalid_type,expected:dI.bigint,received:r.parsedType}),dZ}gte(t,r){return this.setLimit("min",t,!0,L.toString(r))}gt(t,r){return this.setLimit("min",t,!1,L.toString(r))}lte(t,r){return this.setLimit("max",t,!0,L.toString(r))}lt(t,r){return this.setLimit("max",t,!1,L.toString(r))}setLimit(t,r,i,n){return new pi({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:L.toString(n)}]})}_addCheck(t){return new pi({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:L.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:L.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return t}}pi.create=t=>new pi({checks:[],typeName:z.ZodBigInt,coerce:t?.coerce??!1,...dJ(t)});class pn extends dB{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==dI.boolean){let r=this._getOrReturnCtx(t);return dz(r,{code:dj.invalid_type,expected:dI.boolean,received:r.parsedType}),dZ}return dF(t.data)}}pn.create=t=>new pn({typeName:z.ZodBoolean,coerce:t?.coerce||!1,...dJ(t)});class pa extends dB{_parse(t){let r;if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==dI.date){let r=this._getOrReturnCtx(t);return dz(r,{code:dj.invalid_type,expected:dI.date,received:r.parsedType}),dZ}if(Number.isNaN(t.data.getTime()))return dz(this._getOrReturnCtx(t),{code:dj.invalid_date}),dZ;let i=new dM;for(let n of this._def.checks)"min"===n.kind?t.data.getTime()<n.value&&(dz(r=this._getOrReturnCtx(t,r),{code:dj.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),i.dirty()):"max"===n.kind?t.data.getTime()>n.value&&(dz(r=this._getOrReturnCtx(t,r),{code:dj.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):A.assertNever(n);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new pa({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:L.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:L.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)"min"===r.kind&&(null===t||r.value>t)&&(t=r.value);return null!=t?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)"max"===r.kind&&(null===t||r.value<t)&&(t=r.value);return null!=t?new Date(t):null}}pa.create=t=>new pa({checks:[],coerce:t?.coerce||!1,typeName:z.ZodDate,...dJ(t)});class po extends dB{_parse(t){if(this._getType(t)!==dI.symbol){let r=this._getOrReturnCtx(t);return dz(r,{code:dj.invalid_type,expected:dI.symbol,received:r.parsedType}),dZ}return dF(t.data)}}po.create=t=>new po({typeName:z.ZodSymbol,...dJ(t)});class ps extends dB{_parse(t){if(this._getType(t)!==dI.undefined){let r=this._getOrReturnCtx(t);return dz(r,{code:dj.invalid_type,expected:dI.undefined,received:r.parsedType}),dZ}return dF(t.data)}}ps.create=t=>new ps({typeName:z.ZodUndefined,...dJ(t)});class pl extends dB{_parse(t){if(this._getType(t)!==dI.null){let r=this._getOrReturnCtx(t);return dz(r,{code:dj.invalid_type,expected:dI.null,received:r.parsedType}),dZ}return dF(t.data)}}pl.create=t=>new pl({typeName:z.ZodNull,...dJ(t)});class pc extends dB{constructor(){super(...arguments),this._any=!0}_parse(t){return dF(t.data)}}pc.create=t=>new pc({typeName:z.ZodAny,...dJ(t)});class pu extends dB{constructor(){super(...arguments),this._unknown=!0}_parse(t){return dF(t.data)}}pu.create=t=>new pu({typeName:z.ZodUnknown,...dJ(t)});class pd extends dB{_parse(t){let r=this._getOrReturnCtx(t);return dz(r,{code:dj.invalid_type,expected:dI.never,received:r.parsedType}),dZ}}pd.create=t=>new pd({typeName:z.ZodNever,...dJ(t)});class pp extends dB{_parse(t){if(this._getType(t)!==dI.undefined){let r=this._getOrReturnCtx(t);return dz(r,{code:dj.invalid_type,expected:dI.void,received:r.parsedType}),dZ}return dF(t.data)}}pp.create=t=>new pp({typeName:z.ZodVoid,...dJ(t)});class pm extends dB{_parse(t){let{ctx:r,status:i}=this._processInputParams(t),n=this._def;if(r.parsedType!==dI.array)return dz(r,{code:dj.invalid_type,expected:dI.array,received:r.parsedType}),dZ;if(null!==n.exactLength){let t=r.data.length>n.exactLength.value,a=r.data.length<n.exactLength.value;(t||a)&&(dz(r,{code:t?dj.too_big:dj.too_small,minimum:a?n.exactLength.value:void 0,maximum:t?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),i.dirty())}if(null!==n.minLength&&r.data.length<n.minLength.value&&(dz(r,{code:dj.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),i.dirty()),null!==n.maxLength&&r.data.length>n.maxLength.value&&(dz(r,{code:dj.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),i.dirty()),r.common.async)return Promise.all([...r.data].map((t,i)=>n.type._parseAsync(new dD(r,t,r.path,i)))).then(t=>dM.mergeArray(i,t));let a=[...r.data].map((t,i)=>n.type._parseSync(new dD(r,t,r.path,i)));return dM.mergeArray(i,a)}get element(){return this._def.type}min(t,r){return new pm({...this._def,minLength:{value:t,message:L.toString(r)}})}max(t,r){return new pm({...this._def,maxLength:{value:t,message:L.toString(r)}})}length(t,r){return new pm({...this._def,exactLength:{value:t,message:L.toString(r)}})}nonempty(t){return this.min(1,t)}}pm.create=(t,r)=>new pm({type:t,minLength:null,maxLength:null,exactLength:null,typeName:z.ZodArray,...dJ(r)});class ph extends dB{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let t=this._def.shape(),r=A.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==dI.object){let r=this._getOrReturnCtx(t);return dz(r,{code:dj.invalid_type,expected:dI.object,received:r.parsedType}),dZ}let{status:r,ctx:i}=this._processInputParams(t),{shape:n,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof pd&&"strip"===this._def.unknownKeys))for(let t in i.data)a.includes(t)||o.push(t);let s=[];for(let t of a){let r=n[t],a=i.data[t];s.push({key:{status:"valid",value:t},value:r._parse(new dD(i,a,i.path,t)),alwaysSet:t in i.data})}if(this._def.catchall instanceof pd){let t=this._def.unknownKeys;if("passthrough"===t)for(let t of o)s.push({key:{status:"valid",value:t},value:{status:"valid",value:i.data[t]}});else if("strict"===t)o.length>0&&(dz(i,{code:dj.unrecognized_keys,keys:o}),r.dirty());else if("strip"===t);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let t=this._def.catchall;for(let r of o){let n=i.data[r];s.push({key:{status:"valid",value:r},value:t._parse(new dD(i,n,i.path,r)),alwaysSet:r in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let t=[];for(let r of s){let i=await r.key,n=await r.value;t.push({key:i,value:n,alwaysSet:r.alwaysSet})}return t}).then(t=>dM.mergeObjectSync(r,t)):dM.mergeObjectSync(r,s)}get shape(){return this._def.shape()}strict(t){return L.errToObj,new ph({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(r,i)=>{let n=this._def.errorMap?.(r,i).message??i.defaultError;return"unrecognized_keys"===r.code?{message:L.errToObj(t).message??n}:{message:n}}}:{}})}strip(){return new ph({...this._def,unknownKeys:"strip"})}passthrough(){return new ph({...this._def,unknownKeys:"passthrough"})}extend(t){return new ph({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new ph({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:z.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new ph({...this._def,catchall:t})}pick(t){let r={};for(let i of A.objectKeys(t))t[i]&&this.shape[i]&&(r[i]=this.shape[i]);return new ph({...this._def,shape:()=>r})}omit(t){let r={};for(let i of A.objectKeys(this.shape))t[i]||(r[i]=this.shape[i]);return new ph({...this._def,shape:()=>r})}deepPartial(){return function t(r){if(r instanceof ph){let i={};for(let n in r.shape){let a=r.shape[n];i[n]=pO.create(t(a))}return new ph({...r._def,shape:()=>i})}if(r instanceof pm)return new pm({...r._def,type:t(r.element)});if(r instanceof pO)return pO.create(t(r.unwrap()));if(r instanceof pI)return pI.create(t(r.unwrap()));if(r instanceof p_)return p_.create(r.items.map(r=>t(r)));else return r}(this)}partial(t){let r={};for(let i of A.objectKeys(this.shape)){let n=this.shape[i];t&&!t[i]?r[i]=n:r[i]=n.optional()}return new ph({...this._def,shape:()=>r})}required(t){let r={};for(let i of A.objectKeys(this.shape))if(t&&!t[i])r[i]=this.shape[i];else{let t=this.shape[i];for(;t instanceof pO;)t=t._def.innerType;r[i]=t}return new ph({...this._def,shape:()=>r})}keyof(){return p$(A.objectKeys(this.shape))}}ph.create=(t,r)=>new ph({shape:()=>t,unknownKeys:"strip",catchall:pd.create(),typeName:z.ZodObject,...dJ(r)}),ph.strictCreate=(t,r)=>new ph({shape:()=>t,unknownKeys:"strict",catchall:pd.create(),typeName:z.ZodObject,...dJ(r)}),ph.lazycreate=(t,r)=>new ph({shape:t,unknownKeys:"strip",catchall:pd.create(),typeName:z.ZodObject,...dJ(r)});class pf extends dB{_parse(t){let{ctx:r}=this._processInputParams(t),i=this._def.options;if(r.common.async)return Promise.all(i.map(async t=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await t._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(function(t){for(let r of t)if("valid"===r.result.status)return r.result;for(let i of t)if("dirty"===i.result.status)return r.common.issues.push(...i.ctx.common.issues),i.result;let i=t.map(t=>new dA(t.ctx.common.issues));return dz(r,{code:dj.invalid_union,unionErrors:i}),dZ});{let t,n=[];for(let a of i){let i={...r,common:{...r.common,issues:[]},parent:null},o=a._parseSync({data:r.data,path:r.path,parent:i});if("valid"===o.status)return o;"dirty"!==o.status||t||(t={result:o,ctx:i}),i.common.issues.length&&n.push(i.common.issues)}if(t)return r.common.issues.push(...t.ctx.common.issues),t.result;let a=n.map(t=>new dA(t));return dz(r,{code:dj.invalid_union,unionErrors:a}),dZ}}get options(){return this._def.options}}pf.create=(t,r)=>new pf({options:t,typeName:z.ZodUnion,...dJ(r)});let pg=t=>{if(t instanceof px)return pg(t.schema);if(t instanceof pE)return pg(t.innerType());if(t instanceof pR)return[t.value];if(t instanceof pC)return t.options;if(t instanceof pT)return A.objectValues(t.enum);else if(t instanceof pq)return pg(t._def.innerType);else if(t instanceof ps)return[void 0];else if(t instanceof pl)return[null];else if(t instanceof pO)return[void 0,...pg(t.unwrap())];else if(t instanceof pI)return[null,...pg(t.unwrap())];else if(t instanceof pN)return pg(t.unwrap());else if(t instanceof pz)return pg(t.unwrap());else if(t instanceof pj)return pg(t._def.innerType);else return[]};class py extends dB{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==dI.object)return dz(r,{code:dj.invalid_type,expected:dI.object,received:r.parsedType}),dZ;let i=this.discriminator,n=r.data[i],a=this.optionsMap.get(n);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(dz(r,{code:dj.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),dZ)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,i){let n=new Map;for(let i of r){let r=pg(i.shape[t]);if(!r.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of r){if(n.has(a))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);n.set(a,i)}}return new py({typeName:z.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:n,...dJ(i)})}}class pv extends dB{_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=(t,n)=>{if("aborted"===t.status||"aborted"===n.status)return dZ;let a=function t(r,i){let n=dq(r),a=dq(i);if(r===i)return{valid:!0,data:r};if(n===dI.object&&a===dI.object){let n=A.objectKeys(i),a=A.objectKeys(r).filter(t=>-1!==n.indexOf(t)),o={...r,...i};for(let n of(Object.prototype.hasOwnProperty.call(o,"__proto__")&&delete o.__proto__,a)){if("__proto__"===n)continue;let a=t(r[n],i[n]);if(!a.valid)return{valid:!1};o[n]=a.data}return{valid:!0,data:o}}if(n===dI.array&&a===dI.array){if(r.length!==i.length)return{valid:!1};let n=[];for(let a=0;a<r.length;a++){let o=t(r[a],i[a]);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}if(n===dI.date&&a===dI.date&&+r==+i)return{valid:!0,data:r};return{valid:!1}}(t.value,n.value);return a.valid?(("dirty"===t.status||"dirty"===n.status)&&r.dirty(),{status:r.value,value:a.data}):(dz(i,{code:dj.invalid_intersection_types}),dZ)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([t,r])=>n(t,r)):n(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}pv.create=(t,r,i)=>new pv({left:t,right:r,typeName:z.ZodIntersection,...dJ(i)});class p_ extends dB{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==dI.array)return dz(i,{code:dj.invalid_type,expected:dI.array,received:i.parsedType}),dZ;if(i.data.length<this._def.items.length)return dz(i,{code:dj.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),dZ;!this._def.rest&&i.data.length>this._def.items.length&&(dz(i,{code:dj.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let n=[...i.data].map((t,r)=>{let n=this._def.items[r]||this._def.rest;return n?n._parse(new dD(i,t,i.path,r)):null}).filter(t=>!!t);return i.common.async?Promise.all(n).then(t=>dM.mergeArray(r,t)):dM.mergeArray(r,n)}get items(){return this._def.items}rest(t){return new p_({...this._def,rest:t})}}p_.create=(t,r)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new p_({items:t,typeName:z.ZodTuple,rest:null,...dJ(r)})};class pb extends dB{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==dI.object)return dz(i,{code:dj.invalid_type,expected:dI.object,received:i.parsedType}),dZ;let n=[],a=this._def.keyType,o=this._def.valueType;for(let t in i.data)n.push({key:a._parse(new dD(i,t,i.path,t)),value:o._parse(new dD(i,i.data[t],i.path,t)),alwaysSet:t in i.data});return i.common.async?dM.mergeObjectAsync(r,n):dM.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(t,r,i){return new pb(r instanceof dB?{keyType:t,valueType:r,typeName:z.ZodRecord,...dJ(i)}:{keyType:pt.create(),valueType:t,typeName:z.ZodRecord,...dJ(r)})}}class pS extends dB{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==dI.map)return dz(i,{code:dj.invalid_type,expected:dI.map,received:i.parsedType}),dZ;let n=this._def.keyType,a=this._def.valueType,o=[...i.data.entries()].map(([t,r],o)=>({key:n._parse(new dD(i,t,i.path,[o,"key"])),value:a._parse(new dD(i,r,i.path,[o,"value"]))}));if(i.common.async){let t=new Map;return Promise.resolve().then(async()=>{for(let i of o){let n=await i.key,a=await i.value;if("aborted"===n.status||"aborted"===a.status)return dZ;("dirty"===n.status||"dirty"===a.status)&&r.dirty(),t.set(n.value,a.value)}return{status:r.value,value:t}})}{let t=new Map;for(let i of o){let n=i.key,a=i.value;if("aborted"===n.status||"aborted"===a.status)return dZ;("dirty"===n.status||"dirty"===a.status)&&r.dirty(),t.set(n.value,a.value)}return{status:r.value,value:t}}}}pS.create=(t,r,i)=>new pS({valueType:r,keyType:t,typeName:z.ZodMap,...dJ(i)});class pw extends dB{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==dI.set)return dz(i,{code:dj.invalid_type,expected:dI.set,received:i.parsedType}),dZ;let n=this._def;null!==n.minSize&&i.data.size<n.minSize.value&&(dz(i,{code:dj.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),null!==n.maxSize&&i.data.size>n.maxSize.value&&(dz(i,{code:dj.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let a=this._def.valueType;function o(t){let i=new Set;for(let n of t){if("aborted"===n.status)return dZ;"dirty"===n.status&&r.dirty(),i.add(n.value)}return{status:r.value,value:i}}let s=[...i.data.values()].map((t,r)=>a._parse(new dD(i,t,i.path,r)));return i.common.async?Promise.all(s).then(t=>o(t)):o(s)}min(t,r){return new pw({...this._def,minSize:{value:t,message:L.toString(r)}})}max(t,r){return new pw({...this._def,maxSize:{value:t,message:L.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}pw.create=(t,r)=>new pw({valueType:t,minSize:null,maxSize:null,typeName:z.ZodSet,...dJ(r)});class pk extends dB{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==dI.function)return dz(r,{code:dj.invalid_type,expected:dI.function,received:r.parsedType}),dZ;function i(t,i){return dL({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,dN,dN].filter(t=>!!t),issueData:{code:dj.invalid_arguments,argumentsError:i}})}function n(t,i){return dL({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,dN,dN].filter(t=>!!t),issueData:{code:dj.invalid_return_type,returnTypeError:i}})}let a={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof pP){let t=this;return dF(async function(...r){let s=new dA([]),l=await t._def.args.parseAsync(r,a).catch(t=>{throw s.addIssue(i(r,t)),s}),c=await Reflect.apply(o,this,l);return await t._def.returns._def.type.parseAsync(c,a).catch(t=>{throw s.addIssue(n(c,t)),s})})}{let t=this;return dF(function(...r){let s=t._def.args.safeParse(r,a);if(!s.success)throw new dA([i(r,s.error)]);let l=Reflect.apply(o,this,s.data),c=t._def.returns.safeParse(l,a);if(!c.success)throw new dA([n(l,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new pk({...this._def,args:p_.create(t).rest(pu.create())})}returns(t){return new pk({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,i){return new pk({args:t||p_.create([]).rest(pu.create()),returns:r||pu.create(),typeName:z.ZodFunction,...dJ(i)})}}class px extends dB{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}px.create=(t,r)=>new px({getter:t,typeName:z.ZodLazy,...dJ(r)});class pR extends dB{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return dz(r,{received:r.data,code:dj.invalid_literal,expected:this._def.value}),dZ}return{status:"valid",value:t.data}}get value(){return this._def.value}}function p$(t,r){return new pC({values:t,typeName:z.ZodEnum,...dJ(r)})}pR.create=(t,r)=>new pR({value:t,typeName:z.ZodLiteral,...dJ(r)});class pC extends dB{_parse(t){if("string"!=typeof t.data){let r=this._getOrReturnCtx(t),i=this._def.values;return dz(r,{expected:A.joinValues(i),received:r.parsedType,code:dj.invalid_type}),dZ}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),i=this._def.values;return dz(r,{received:r.data,code:dj.invalid_enum_value,options:i}),dZ}return dF(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return pC.create(t,{...this._def,...r})}exclude(t,r=this._def){return pC.create(this.options.filter(r=>!t.includes(r)),{...this._def,...r})}}pC.create=p$;class pT extends dB{_parse(t){let r=A.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==dI.string&&i.parsedType!==dI.number){let t=A.objectValues(r);return dz(i,{expected:A.joinValues(t),received:i.parsedType,code:dj.invalid_type}),dZ}if(this._cache||(this._cache=new Set(A.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let t=A.objectValues(r);return dz(i,{received:i.data,code:dj.invalid_enum_value,options:t}),dZ}return dF(t.data)}get enum(){return this._def.values}}pT.create=(t,r)=>new pT({values:t,typeName:z.ZodNativeEnum,...dJ(r)});class pP extends dB{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);return r.parsedType!==dI.promise&&!1===r.common.async?(dz(r,{code:dj.invalid_type,expected:dI.promise,received:r.parsedType}),dZ):dF((r.parsedType===dI.promise?r.data:Promise.resolve(r.data)).then(t=>this._def.type.parseAsync(t,{path:r.path,errorMap:r.common.contextualErrorMap})))}}pP.create=(t,r)=>new pP({type:t,typeName:z.ZodPromise,...dJ(r)});class pE extends dB{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=this._def.effect||null,a={addIssue:t=>{dz(i,t),t.fatal?r.abort():r.dirty()},get path(){return i.path}};if(a.addIssue=a.addIssue.bind(a),"preprocess"===n.type){let t=n.transform(i.data,a);if(i.common.async)return Promise.resolve(t).then(async t=>{if("aborted"===r.value)return dZ;let n=await this._def.schema._parseAsync({data:t,path:i.path,parent:i});return"aborted"===n.status?dZ:"dirty"===n.status||"dirty"===r.value?dU(n.value):n});{if("aborted"===r.value)return dZ;let n=this._def.schema._parseSync({data:t,path:i.path,parent:i});return"aborted"===n.status?dZ:"dirty"===n.status||"dirty"===r.value?dU(n.value):n}}if("refinement"===n.type){let t=t=>{let r=n.refinement(t,a);if(i.common.async)return Promise.resolve(r);if(r instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return t};if(!1!==i.common.async)return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(i=>"aborted"===i.status?dZ:("dirty"===i.status&&r.dirty(),t(i.value).then(()=>({status:r.value,value:i.value}))));{let n=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===n.status?dZ:("dirty"===n.status&&r.dirty(),t(n.value),{status:r.value,value:n.value})}}if("transform"===n.type)if(!1!==i.common.async)return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(t=>"valid"!==t.status?dZ:Promise.resolve(n.transform(t.value,a)).then(t=>({status:r.value,value:t})));else{let t=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if("valid"!==t.status)return dZ;let o=n.transform(t.value,a);if(o instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}A.assertNever(n)}}pE.create=(t,r,i)=>new pE({schema:t,typeName:z.ZodEffects,effect:r,...dJ(i)}),pE.createWithPreprocess=(t,r,i)=>new pE({schema:r,effect:{type:"preprocess",transform:t},typeName:z.ZodEffects,...dJ(i)});class pO extends dB{_parse(t){return this._getType(t)===dI.undefined?dF(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}pO.create=(t,r)=>new pO({innerType:t,typeName:z.ZodOptional,...dJ(r)});class pI extends dB{_parse(t){return this._getType(t)===dI.null?dF(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}pI.create=(t,r)=>new pI({innerType:t,typeName:z.ZodNullable,...dJ(r)});class pq extends dB{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return r.parsedType===dI.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}pq.create=(t,r)=>new pq({innerType:t,typeName:z.ZodDefault,defaultValue:"function"==typeof r.default?r.default:()=>r.default,...dJ(r)});class pj extends dB{_parse(t){let{ctx:r}=this._processInputParams(t),i={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return dH(n)?n.then(t=>({status:"valid",value:"valid"===t.status?t.value:this._def.catchValue({get error(){return new dA(i.common.issues)},input:i.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new dA(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}pj.create=(t,r)=>new pj({innerType:t,typeName:z.ZodCatch,catchValue:"function"==typeof r.catch?r.catch:()=>r.catch,...dJ(r)});class pA extends dB{_parse(t){if(this._getType(t)!==dI.nan){let r=this._getOrReturnCtx(t);return dz(r,{code:dj.invalid_type,expected:dI.nan,received:r.parsedType}),dZ}return{status:"valid",value:t.data}}}pA.create=t=>new pA({typeName:z.ZodNaN,...dJ(t)}),Symbol("zod_brand");class pN extends dB{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return this._def.type._parse({data:i,path:r.path,parent:r})}unwrap(){return this._def.type}}class pL extends dB{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{let t=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return"aborted"===t.status?dZ:"dirty"===t.status?(r.dirty(),dU(t.value)):this._def.out._parseAsync({data:t.value,path:i.path,parent:i})})();{let t=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return"aborted"===t.status?dZ:"dirty"===t.status?(r.dirty(),{status:"dirty",value:t.value}):this._def.out._parseSync({data:t.value,path:i.path,parent:i})}}static create(t,r){return new pL({in:t,out:r,typeName:z.ZodPipeline})}}class pz extends dB{_parse(t){let r=this._def.innerType._parse(t),i=t=>("valid"===t.status&&(t.value=Object.freeze(t.value)),t);return dH(r)?r.then(t=>i(t)):i(r)}unwrap(){return this._def.innerType}}pz.create=(t,r)=>new pz({innerType:t,typeName:z.ZodReadonly,...dJ(r)}),ph.lazycreate,(O=z||(z={})).ZodString="ZodString",O.ZodNumber="ZodNumber",O.ZodNaN="ZodNaN",O.ZodBigInt="ZodBigInt",O.ZodBoolean="ZodBoolean",O.ZodDate="ZodDate",O.ZodSymbol="ZodSymbol",O.ZodUndefined="ZodUndefined",O.ZodNull="ZodNull",O.ZodAny="ZodAny",O.ZodUnknown="ZodUnknown",O.ZodNever="ZodNever",O.ZodVoid="ZodVoid",O.ZodArray="ZodArray",O.ZodObject="ZodObject",O.ZodUnion="ZodUnion",O.ZodDiscriminatedUnion="ZodDiscriminatedUnion",O.ZodIntersection="ZodIntersection",O.ZodTuple="ZodTuple",O.ZodRecord="ZodRecord",O.ZodMap="ZodMap",O.ZodSet="ZodSet",O.ZodFunction="ZodFunction",O.ZodLazy="ZodLazy",O.ZodLiteral="ZodLiteral",O.ZodEnum="ZodEnum",O.ZodEffects="ZodEffects",O.ZodNativeEnum="ZodNativeEnum",O.ZodOptional="ZodOptional",O.ZodNullable="ZodNullable",O.ZodDefault="ZodDefault",O.ZodCatch="ZodCatch",O.ZodPromise="ZodPromise",O.ZodBranded="ZodBranded",O.ZodPipeline="ZodPipeline",O.ZodReadonly="ZodReadonly",pt.create,pr.create,pA.create,pi.create,pn.create,pa.create,po.create,ps.create,pl.create,pc.create,pu.create,pd.create,pp.create,pm.create,ph.create,ph.strictCreate,pf.create,py.create,pv.create,p_.create,pb.create,pS.create,pw.create,pk.create,px.create,pR.create,pC.create,pT.create,pP.create,pE.create,pO.create,pI.create,pE.createWithPreprocess,pL.create;let pM=(t,r)=>{let i=0;for(;i<t.length&&i<r.length&&t[i]===r[i];i++);return[(t.length-i).toString(),...r.slice(i)].join("/")};function pZ(t){if("openAi"!==t.target)return{};let r=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===t.$refStrategy?pM(r,t.currentPath):r.join("/")}}function pU(t,r,i,n){n?.errorMessages&&i&&(t.errorMessage={...t.errorMessage,[r]:i})}function pF(t,r,i,n,a){t[r]=i,pU(t,r,n,a)}function pH(t,r){return me(t.type._def,r)}let pD=/^[cC][^\s-]{8,}$/,pV=/^[0-9a-z]+$/,pJ=/^[0-9A-HJKMNP-TV-Z]{26}$/,pB=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,pW=()=>(void 0===x&&(x=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),x),pG=/^(?:(?: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])$/,pK=/^(([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])$/,pY=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pX=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,pQ=/^[a-zA-Z0-9_-]{21}$/,p0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function p1(t,r){let i={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":pF(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,n.value):n.value,n.message,r);break;case"max":pF(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,n.value):n.value,n.message,r);break;case"email":switch(r.emailStrategy){case"format:email":p4(i,"email",n.message,r);break;case"format:idn-email":p4(i,"idn-email",n.message,r);break;case"pattern:zod":p5(i,pB,n.message,r)}break;case"url":p4(i,"uri",n.message,r);break;case"uuid":p4(i,"uuid",n.message,r);break;case"regex":p5(i,n.regex,n.message,r);break;case"cuid":p5(i,pD,n.message,r);break;case"cuid2":p5(i,pV,n.message,r);break;case"startsWith":p5(i,RegExp(`^${p2(n.value,r)}`),n.message,r);break;case"endsWith":p5(i,RegExp(`${p2(n.value,r)}$`),n.message,r);break;case"datetime":p4(i,"date-time",n.message,r);break;case"date":p4(i,"date",n.message,r);break;case"time":p4(i,"time",n.message,r);break;case"duration":p4(i,"duration",n.message,r);break;case"length":pF(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,n.value):n.value,n.message,r),pF(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,n.value):n.value,n.message,r);break;case"includes":p5(i,RegExp(p2(n.value,r)),n.message,r);break;case"ip":"v6"!==n.version&&p4(i,"ipv4",n.message,r),"v4"!==n.version&&p4(i,"ipv6",n.message,r);break;case"base64url":p5(i,pX,n.message,r);break;case"jwt":p5(i,p0,n.message,r);break;case"cidr":"v6"!==n.version&&p5(i,pG,n.message,r),"v4"!==n.version&&p5(i,pK,n.message,r);break;case"emoji":p5(i,pW(),n.message,r);break;case"ulid":p5(i,pJ,n.message,r);break;case"base64":switch(r.base64Strategy){case"format:binary":p4(i,"binary",n.message,r);break;case"contentEncoding:base64":pF(i,"contentEncoding","base64",n.message,r);break;case"pattern:zod":p5(i,pY,n.message,r)}break;case"nanoid":p5(i,pQ,n.message,r)}return i}function p2(t,r){return"escape"===r.patternStrategy?function(t){let r="";for(let i=0;i<t.length;i++)p9.has(t[i])||(r+="\\"),r+=t[i];return r}(t):t}let p9=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function p4(t,r,i,n){t.format||t.anyOf?.some(t=>t.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,0===Object.keys(t.errorMessage).length&&delete t.errorMessage)),t.anyOf.push({format:r,...i&&n.errorMessages&&{errorMessage:{format:i}}})):pF(t,"format",r,i,n)}function p5(t,r,i,n){t.pattern||t.allOf?.some(t=>t.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,0===Object.keys(t.errorMessage).length&&delete t.errorMessage)),t.allOf.push({pattern:p3(r,n),...i&&n.errorMessages&&{errorMessage:{pattern:i}}})):pF(t,"pattern",p3(r,n),i,n)}function p3(t,r){if(!r.applyRegexFlags||!t.flags)return t.source;let i={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=i.i?t.source.toLowerCase():t.source,a="",o=!1,s=!1,l=!1;for(let t=0;t<n.length;t++){if(o){a+=n[t],o=!1;continue}if(i.i){if(s){if(n[t].match(/[a-z]/)){l?(a+=n[t],a+=`${n[t-2]}-${n[t]}`.toUpperCase(),l=!1):"-"===n[t+1]&&n[t+2]?.match(/[a-z]/)?(a+=n[t],l=!0):a+=`${n[t]}${n[t].toUpperCase()}`;continue}}else if(n[t].match(/[a-z]/)){a+=`[${n[t]}${n[t].toUpperCase()}]`;continue}}if(i.m){if("^"===n[t]){a+=`(^|(?<=[\r
|
|
74
74
|
]))`;continue}else if("$"===n[t]){a+=`($|(?=[\r
|
|
75
75
|
]))`;continue}}if(i.s&&"."===n[t]){a+=s?`${n[t]}\r
|
|
76
76
|
`:`[${n[t]}\r
|
|
77
|
-
]`;continue}a+=n[t],"\\"===n[t]?o=!0:s&&"]"===n[t]?s=!1:s||"["!==n[t]||(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${r.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return a}function p7(t,r){if("openAi"===r.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===r.target&&t.keyType?._def.typeName===L.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((i,n)=>({...i,[n]:mt(t.valueType._def,{...r,currentPath:[...r.currentPath,"properties",n]})??pU(r)}),{}),additionalProperties:r.rejectedAdditionalProperties};let i={type:"object",additionalProperties:mt(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]})??r.allowedAdditionalProperties};if("openApi3"===r.target)return i;if(t.keyType?._def.typeName===L.ZodString&&t.keyType._def.checks?.length){let{type:n,...a}=p2(t.keyType._def,r);return{...i,propertyNames:a}}if(t.keyType?._def.typeName===L.ZodEnum)return{...i,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===L.ZodBranded&&t.keyType._def.type._def.typeName===L.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...a}=pJ(t.keyType._def,r);return{...i,propertyNames:a}}return i}let p8={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},me=(t,r)=>{let i=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((t,i)=>mt(t._def,{...r,currentPath:[...r.currentPath,"anyOf",`${i}`]})).filter(t=>!!t&&(!r.strictUnions||"object"==typeof t&&Object.keys(t).length>0));return i.length?{anyOf:i}:void 0};function mt(t,r,i=!1){let n=r.seen.get(t);if(r.override){let a=r.override?.(t,r,n,i);if(a!==dE)return a}if(n&&!i){let t=mr(n,r);if(void 0!==t)return t}let a={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,a);let o=((t,r,i)=>{switch(r){case L.ZodString:return p2(t,i);case L.ZodNumber:let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",pF(n,"type",r.message,i);break;case"min":"jsonSchema7"===i.target?r.inclusive?pH(n,"minimum",r.value,r.message,i):pH(n,"exclusiveMinimum",r.value,r.message,i):(r.inclusive||(n.exclusiveMinimum=!0),pH(n,"minimum",r.value,r.message,i));break;case"max":"jsonSchema7"===i.target?r.inclusive?pH(n,"maximum",r.value,r.message,i):pH(n,"exclusiveMaximum",r.value,r.message,i):(r.inclusive||(n.exclusiveMaximum=!0),pH(n,"maximum",r.value,r.message,i));break;case"multipleOf":pH(n,"multipleOf",r.value,r.message,i)}return n;case L.ZodObject:return function(t,r){let i="openAi"===r.target,n={type:"object",properties:{}},a=[],o=t.shape();for(let t in o){let s=o[t];if(void 0===s||void 0===s._def)continue;let l=function(t){try{return t.isOptional()}catch{return!0}}(s);l&&i&&("ZodOptional"===s._def.typeName&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),l=!1);let c=mt(s._def,{...r,currentPath:[...r.currentPath,"properties",t],propertyPath:[...r.currentPath,"properties",t]});void 0!==c&&(n.properties[t]=c,l||a.push(t))}a.length&&(n.required=a);let s=function(t,r){if("ZodNever"!==t.catchall._def.typeName)return mt(t.catchall._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return r.allowedAdditionalProperties;case"strict":return r.rejectedAdditionalProperties;case"strip":return"strict"===r.removeAdditionalStrategy?r.allowedAdditionalProperties:r.rejectedAdditionalProperties}}(t,r);return void 0!==s&&(n.additionalProperties=s),n}(t,i);case L.ZodBigInt:let a={type:"integer",format:"int64"};if(!t.checks)return a;for(let r of t.checks)switch(r.kind){case"min":"jsonSchema7"===i.target?r.inclusive?pH(a,"minimum",r.value,r.message,i):pH(a,"exclusiveMinimum",r.value,r.message,i):(r.inclusive||(a.exclusiveMinimum=!0),pH(a,"minimum",r.value,r.message,i));break;case"max":"jsonSchema7"===i.target?r.inclusive?pH(a,"maximum",r.value,r.message,i):pH(a,"exclusiveMaximum",r.value,r.message,i):(r.inclusive||(a.exclusiveMaximum=!0),pH(a,"maximum",r.value,r.message,i));break;case"multipleOf":pH(a,"multipleOf",r.value,r.message,i)}return a;case L.ZodBoolean:return{type:"boolean"};case L.ZodDate:return function t(r,i,n){let a=n??i.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((n,a)=>t(r,i,n))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var o=r,s=i;let l={type:"integer",format:"unix-time"};if("openApi3"===s.target)return l;for(let t of o.checks)switch(t.kind){case"min":pH(l,"minimum",t.value,t.message,s);break;case"max":pH(l,"maximum",t.value,t.message,s)}return l}}(t,i);case L.ZodUndefined:return{not:pU(i)};case L.ZodNull:return"openApi3"===i.target?{enum:["null"],nullable:!0}:{type:"null"};case L.ZodArray:let o;return o={type:"array"},t.type?._def&&t.type?._def?.typeName!==L.ZodAny&&(o.items=mt(t.type._def,{...i,currentPath:[...i.currentPath,"items"]})),t.minLength&&pH(o,"minItems",t.minLength.value,t.minLength.message,i),t.maxLength&&pH(o,"maxItems",t.maxLength.value,t.maxLength.message,i),t.exactLength&&(pH(o,"minItems",t.exactLength.value,t.exactLength.message,i),pH(o,"maxItems",t.exactLength.value,t.exactLength.message,i)),o;case L.ZodUnion:case L.ZodDiscriminatedUnion:if("openApi3"===i.target)return me(t,i);let s=t.options instanceof Map?Array.from(t.options.values()):t.options;if(s.every(t=>t._def.typeName in p8&&(!t._def.checks||!t._def.checks.length))){let t=s.reduce((t,r)=>{let i=p8[r._def.typeName];return i&&!t.includes(i)?[...t,i]:t},[]);return{type:t.length>1?t:t[0]}}if(s.every(t=>"ZodLiteral"===t._def.typeName&&!t.description)){let t=s.reduce((t,r)=>{let i=typeof r._def.value;switch(i){case"string":case"number":case"boolean":return[...t,i];case"bigint":return[...t,"integer"];case"object":if(null===r._def.value)return[...t,"null"];default:return t}},[]);if(t.length===s.length){let r=t.filter((t,r,i)=>i.indexOf(t)===r);return{type:r.length>1?r:r[0],enum:s.reduce((t,r)=>t.includes(r._def.value)?t:[...t,r._def.value],[])}}}else if(s.every(t=>"ZodEnum"===t._def.typeName))return{type:"string",enum:s.reduce((t,r)=>[...t,...r._def.values.filter(r=>!t.includes(r))],[])};return me(t,i);case L.ZodIntersection:let l,c,u;return l=[mt(t.left._def,{...i,currentPath:[...i.currentPath,"allOf","0"]}),mt(t.right._def,{...i,currentPath:[...i.currentPath,"allOf","1"]})].filter(t=>!!t),c="jsonSchema2019-09"===i.target?{unevaluatedProperties:!1}:void 0,u=[],l.forEach(t=>{if((!("type"in t)||"string"!==t.type)&&"allOf"in t)u.push(...t.allOf),void 0===t.unevaluatedProperties&&(c=void 0);else{let r=t;if("additionalProperties"in t&&!1===t.additionalProperties){let{additionalProperties:i,...n}=t;r=n}else c=void 0;u.push(r)}}),u.length?{allOf:u,...c}:void 0;case L.ZodTuple:return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((t,r)=>mt(t._def,{...i,currentPath:[...i.currentPath,"items",`${r}`]})).reduce((t,r)=>void 0===r?t:[...t,r],[]),additionalItems:mt(t.rest._def,{...i,currentPath:[...i.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((t,r)=>mt(t._def,{...i,currentPath:[...i.currentPath,"items",`${r}`]})).reduce((t,r)=>void 0===r?t:[...t,r],[])};case L.ZodRecord:return p7(t,i);case L.ZodLiteral:let d;return"bigint"!=(d=typeof t.value)&&"number"!==d&&"boolean"!==d&&"string"!==d?{type:Array.isArray(t.value)?"array":"object"}:"openApi3"===i.target?{type:"bigint"===d?"integer":d,enum:[t.value]}:{type:"bigint"===d?"integer":d,const:t.value};case L.ZodEnum:return{type:"string",enum:Array.from(t.values)};case L.ZodNativeEnum:let p,m,h;return p=t.values,{type:1===(h=Array.from(new Set((m=Object.keys(t.values).filter(t=>"number"!=typeof p[p[t]]).map(t=>p[t])).map(t=>typeof t)))).length?"string"===h[0]?"string":"number":["string","number"],enum:m};case L.ZodNullable:if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return"openApi3"===i.target?{type:p8[t.innerType._def.typeName],nullable:!0}:{type:[p8[t.innerType._def.typeName],"null"]};if("openApi3"===i.target){let r=mt(t.innerType._def,{...i,currentPath:[...i.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let f=mt(t.innerType._def,{...i,currentPath:[...i.currentPath,"anyOf","0"]});return f&&{anyOf:[f,{type:"null"}]};case L.ZodOptional:if(i.currentPath.toString()===i.propertyPath?.toString())return mt(t.innerType._def,i);let g=mt(t.innerType._def,{...i,currentPath:[...i.currentPath,"anyOf","1"]});return g?{anyOf:[{not:pU(i)},g]}:pU(i);case L.ZodMap:if("record"===i.mapStrategy)return p7(t,i);return{type:"array",maxItems:125,items:{type:"array",items:[mt(t.keyType._def,{...i,currentPath:[...i.currentPath,"items","items","0"]})||pU(i),mt(t.valueType._def,{...i,currentPath:[...i.currentPath,"items","items","1"]})||pU(i)],minItems:2,maxItems:2}};case L.ZodSet:let y;return y={type:"array",uniqueItems:!0,items:mt(t.valueType._def,{...i,currentPath:[...i.currentPath,"items"]})},t.minSize&&pH(y,"minItems",t.minSize.value,t.minSize.message,i),t.maxSize&&pH(y,"maxItems",t.maxSize.value,t.maxSize.message,i),y;case L.ZodLazy:return()=>t.getter()._def;case L.ZodPromise:return mt(t.type._def,i);case L.ZodNaN:case L.ZodNever:return"openAi"===i.target?void 0:{not:pU({...i,currentPath:[...i.currentPath,"not"]})};case L.ZodEffects:return"input"===i.effectStrategy?mt(t.schema._def,i):pU(i);case L.ZodAny:case L.ZodUnknown:return pU(i);case L.ZodDefault:return{...mt(t.innerType._def,i),default:t.defaultValue()};case L.ZodBranded:return pJ(t,i);case L.ZodReadonly:case L.ZodCatch:return mt(t.innerType._def,i);case L.ZodPipeline:if("input"===i.pipeStrategy)return mt(t.in._def,i);if("output"===i.pipeStrategy)return mt(t.out._def,i);let v=mt(t.in._def,{...i,currentPath:[...i.currentPath,"allOf","0"]}),_=mt(t.out._def,{...i,currentPath:[...i.currentPath,"allOf",v?"1":"0"]});return{allOf:[v,_].filter(t=>void 0!==t)};case L.ZodFunction:case L.ZodVoid:case L.ZodSymbol:default:return}})(t,t.typeName,r),s="function"==typeof o?mt(o(),r):o;if(s&&mi(t,r,s),r.postProcess){let i=r.postProcess(s,t,r);return a.jsonSchema=s,i}return a.jsonSchema=s,s}let mr=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:pZ(r.currentPath,t.path)};case"none":case"seen":if(t.path.length<r.currentPath.length&&t.path.every((t,i)=>r.currentPath[i]===t))return console.warn(`Recursive reference detected at ${r.currentPath.join("/")}! Defaulting to any`),pU(r);return"seen"===r.$refStrategy?pU(r):void 0}},mi=(t,r,i)=>(t.description&&(i.description=t.description,r.markdownDescription&&(i.markdownDescription=t.description)),i);Symbol("ZodOutput"),Symbol("ZodInput");(M=globalThis).__zod_globalRegistry??(M.__zod_globalRegistry=new class t{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let i=r[0];return this._map.set(t,i),i&&"object"==typeof i&&"id"in i&&this._idmap.set(i.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&"object"==typeof r&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let i={...this.get(r)??{}};delete i.id;let n={...i,...this._map.get(t)};return Object.keys(n).length?n:void 0}return this._map.get(t)}has(t){return this._map.has(t)}});let mn=globalThis.__zod_globalRegistry;function ma(t){let r=t?.target??"draft-2020-12";return"draft-4"===r&&(r="draft-04"),"draft-7"===r&&(r="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??mn,target:r,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function mo(t,r,i={path:[],schemaPath:[]}){var n;let a=t._zod.def,o=r.seen.get(t);if(o)return o.count++,i.schemaPath.includes(t)&&(o.cycle=i.path),o.schema;let s={schema:{},count:1,cycle:void 0,path:i.path};r.seen.set(t,s);let l=t._zod.toJSONSchema?.();if(l)s.schema=l;else{let n={...i,schemaPath:[...i.schemaPath,t],path:i.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(r,s.schema,n);else{let i=s.schema,o=r.processors[a.type];if(!o)throw Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);o(t,r,i,n)}let o=t._zod.parent;o&&(s.ref||(s.ref=o),mo(o,r,n),r.seen.get(o).isParent=!0)}let c=r.metadataRegistry.get(t);return c&&Object.assign(s.schema,c),"input"===r.io&&function t(r,i){let n=i??{seen:new Set};if(n.seen.has(r))return!1;n.seen.add(r);let a=r._zod.def;if("transform"===a.type)return!0;if("array"===a.type)return t(a.element,n);if("set"===a.type)return t(a.valueType,n);if("lazy"===a.type)return t(a.getter(),n);if("promise"===a.type||"optional"===a.type||"nonoptional"===a.type||"nullable"===a.type||"readonly"===a.type||"default"===a.type||"prefault"===a.type)return t(a.innerType,n);if("intersection"===a.type)return t(a.left,n)||t(a.right,n);if("record"===a.type||"map"===a.type)return t(a.keyType,n)||t(a.valueType,n);if("pipe"===a.type)return!!r._zod.traits.has("$ZodCodec")||t(a.in,n)||t(a.out,n);if("object"===a.type){for(let r in a.shape)if(t(a.shape[r],n))return!0;return!1}if("union"===a.type){for(let r of a.options)if(t(r,n))return!0;return!1}if("tuple"===a.type){for(let r of a.items)if(t(r,n))return!0;if(a.rest&&t(a.rest,n))return!0}return!1}(t)&&(delete s.schema.examples,delete s.schema.default),"input"===r.io&&"_prefault"in s.schema&&((n=s.schema).default??(n.default=s.schema._prefault)),delete s.schema._prefault,r.seen.get(t).schema}function ms(t,r){let i=t.seen.get(r);if(!i)throw Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let r of t.seen.entries()){let i=t.metadataRegistry.get(r[0])?.id;if(i){let t=n.get(i);if(t&&t!==r[0])throw Error(`Duplicate schema id "${i}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(i,r[0])}}let a=r=>{if(r[1].schema.$ref)return;let n=r[1],{ref:a,defId:o}=(r=>{let n="draft-2020-12"===t.target?"$defs":"definitions";if(t.external){let i=t.external.registry.get(r[0])?.id,a=t.external.uri??(t=>t);if(i)return{ref:a(i)};let o=r[1].defId??r[1].schema.id??`schema${t.counter++}`;return r[1].defId=o,{defId:o,ref:`${a("__shared")}#/${n}/${o}`}}if(r[1]===i)return{ref:"#"};let a=`#/${n}/`,o=r[1].schema.id??`__schema${t.counter++}`;return{defId:o,ref:a+o}})(r);n.def={...n.schema},o&&(n.defId=o);let s=n.schema;for(let t in s)delete s[t];s.$ref=a};if("throw"===t.cycles)for(let r of t.seen.entries()){let t=r[1];if(t.cycle)throw Error(`Cycle detected: #/${t.cycle?.join("/")}/<root>
|
|
78
|
-
|
|
79
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let n=i[1];if(r===i[0]){a(i);continue}if(t.external){let n=t.external.registry.get(i[0])?.id;if(r!==i[0]&&n){a(i);continue}}if(t.metadataRegistry.get(i[0])?.id||n.cycle||n.count>1&&"ref"===t.reused){a(i);continue}}}function ml(t,r){let i=t.seen.get(r);if(!i)throw Error("Unprocessed schema. This is a bug in Zod.");let n=r=>{let i=t.seen.get(r);if(null===i.ref)return;let a=i.def??i.schema,o={...a},s=i.ref;if(i.ref=null,s){n(s);let i=t.seen.get(s),l=i.schema;if(l.$ref&&("draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target)?(a.allOf=a.allOf??[],a.allOf.push(l)):Object.assign(a,l),Object.assign(a,o),r._zod.parent===s)for(let t in a)"$ref"!==t&&"allOf"!==t&&(t in o||delete a[t]);if(l.$ref&&i.def)for(let t in a)"$ref"!==t&&"allOf"!==t&&t in i.def&&JSON.stringify(a[t])===JSON.stringify(i.def[t])&&delete a[t]}let l=r._zod.parent;if(l&&l!==s){n(l);let r=t.seen.get(l);if(r?.schema.$ref&&(a.$ref=r.schema.$ref,r.def))for(let t in a)"$ref"!==t&&"allOf"!==t&&t in r.def&&JSON.stringify(a[t])===JSON.stringify(r.def[t])&&delete a[t]}t.override({zodSchema:r,jsonSchema:a,path:i.path??[]})};for(let r of[...t.seen.entries()].reverse())n(r[0]);let a={};if("draft-2020-12"===t.target?a.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===t.target?a.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===t.target?a.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let i=t.external.registry.get(r)?.id;if(!i)throw Error("Schema is missing an `id` property");a.$id=t.external.uri(i)}Object.assign(a,i.def??i.schema);let o=t.metadataRegistry.get(r)?.id;void 0!==o&&a.id===o&&delete a.id;let s=t.external?.defs??{};for(let r of t.seen.entries()){let t=r[1];t.def&&t.defId&&(t.def.id===t.defId&&delete t.def.id,s[t.defId]=t.def)}t.external||Object.keys(s).length>0&&("draft-2020-12"===t.target?a.$defs=s:a.definitions=s);try{let i=JSON.parse(JSON.stringify(a));return Object.defineProperty(i,"~standard",{value:{...r["~standard"],jsonSchema:{input:mc(r,"input",t.processors),output:mc(r,"output",t.processors)}},enumerable:!1,writable:!1}),i}catch(t){throw Error("Error converting schema to JSON.")}}let mc=(t,r,i={})=>n=>{let{libraryOptions:a,target:o}=n??{},s=ma({...a??{},target:o,io:r,processors:i});return mo(t,s),ms(s,t),ml(s,t)},mu={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},md={string:(t,r,i,n)=>{i.type="string";let{minimum:a,maximum:o,format:s,patterns:l,contentEncoding:c}=t._zod.bag;if("number"==typeof a&&(i.minLength=a),"number"==typeof o&&(i.maxLength=o),s&&(i.format=mu[s]??s,""===i.format&&delete i.format,"time"===s&&delete i.format),c&&(i.contentEncoding=c),l&&l.size>0){let t=[...l];1===t.length?i.pattern=t[0].source:t.length>1&&(i.allOf=[...t.map(t=>({..."draft-07"===r.target||"draft-04"===r.target||"openapi-3.0"===r.target?{type:"string"}:{},pattern:t.source}))])}},number:(t,r,i,n)=>{let{minimum:a,maximum:o,format:s,multipleOf:l,exclusiveMaximum:c,exclusiveMinimum:u}=t._zod.bag;"string"==typeof s&&s.includes("int")?i.type="integer":i.type="number";let d="number"==typeof u&&u>=(a??-1/0),p="number"==typeof c&&c<=(o??1/0),m="draft-04"===r.target||"openapi-3.0"===r.target;d?m?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:"number"==typeof a&&(i.minimum=a),p?m?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:"number"==typeof o&&(i.maximum=o),"number"==typeof l&&(i.multipleOf=l)},boolean:(t,r,i,n)=>{i.type="boolean"},bigint:(t,r,i,n)=>{if("throw"===r.unrepresentable)throw Error("BigInt cannot be represented in JSON Schema")},symbol:(t,r,i,n)=>{if("throw"===r.unrepresentable)throw Error("Symbols cannot be represented in JSON Schema")},null:(t,r,i,n)=>{"openapi-3.0"===r.target?(i.type="string",i.nullable=!0,i.enum=[null]):i.type="null"},undefined:(t,r,i,n)=>{if("throw"===r.unrepresentable)throw Error("Undefined cannot be represented in JSON Schema")},void:(t,r,i,n)=>{if("throw"===r.unrepresentable)throw Error("Void cannot be represented in JSON Schema")},never:(t,r,i,n)=>{i.not={}},any:(t,r,i,n)=>{},unknown:(t,r,i,n)=>{},date:(t,r,i,n)=>{if("throw"===r.unrepresentable)throw Error("Date cannot be represented in JSON Schema")},enum:(t,r,i,n)=>{var a;let o,s=(o=Object.values(a=t._zod.def.entries).filter(t=>"number"==typeof t),Object.entries(a).filter(([t,r])=>-1===o.indexOf(+t)).map(([t,r])=>r));s.every(t=>"number"==typeof t)&&(i.type="number"),s.every(t=>"string"==typeof t)&&(i.type="string"),i.enum=s},literal:(t,r,i,n)=>{let a=t._zod.def,o=[];for(let t of a.values)if(void 0===t){if("throw"===r.unrepresentable)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof t)if("throw"===r.unrepresentable)throw Error("BigInt literals cannot be represented in JSON Schema");else o.push(Number(t));else o.push(t);if(0===o.length);else if(1===o.length){let t=o[0];i.type=null===t?"null":typeof t,"draft-04"===r.target||"openapi-3.0"===r.target?i.enum=[t]:i.const=t}else o.every(t=>"number"==typeof t)&&(i.type="number"),o.every(t=>"string"==typeof t)&&(i.type="string"),o.every(t=>"boolean"==typeof t)&&(i.type="boolean"),o.every(t=>null===t)&&(i.type="null"),i.enum=o},nan:(t,r,i,n)=>{if("throw"===r.unrepresentable)throw Error("NaN cannot be represented in JSON Schema")},template_literal:(t,r,i,n)=>{let a=t._zod.pattern;if(!a)throw Error("Pattern not found in template literal");i.type="string",i.pattern=a.source},file:(t,r,i,n)=>{let a={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:s,mime:l}=t._zod.bag;void 0!==o&&(a.minLength=o),void 0!==s&&(a.maxLength=s),l?1===l.length?(a.contentMediaType=l[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=l.map(t=>({contentMediaType:t}))):Object.assign(i,a)},success:(t,r,i,n)=>{i.type="boolean"},custom:(t,r,i,n)=>{if("throw"===r.unrepresentable)throw Error("Custom types cannot be represented in JSON Schema")},function:(t,r,i,n)=>{if("throw"===r.unrepresentable)throw Error("Function types cannot be represented in JSON Schema")},transform:(t,r,i,n)=>{if("throw"===r.unrepresentable)throw Error("Transforms cannot be represented in JSON Schema")},map:(t,r,i,n)=>{if("throw"===r.unrepresentable)throw Error("Map cannot be represented in JSON Schema")},set:(t,r,i,n)=>{if("throw"===r.unrepresentable)throw Error("Set cannot be represented in JSON Schema")},array:(t,r,i,n)=>{let a=t._zod.def,{minimum:o,maximum:s}=t._zod.bag;"number"==typeof o&&(i.minItems=o),"number"==typeof s&&(i.maxItems=s),i.type="array",i.items=mo(a.element,r,{...n,path:[...n.path,"items"]})},object:(t,r,i,n)=>{let a=t._zod.def;i.type="object",i.properties={};let o=a.shape;for(let t in o)i.properties[t]=mo(o[t],r,{...n,path:[...n.path,"properties",t]});let s=new Set([...new Set(Object.keys(o))].filter(t=>{let i=a.shape[t]._zod;return"input"===r.io?void 0===i.optin:void 0===i.optout}));s.size>0&&(i.required=Array.from(s)),a.catchall?._zod.def.type==="never"?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=mo(a.catchall,r,{...n,path:[...n.path,"additionalProperties"]})):"output"===r.io&&(i.additionalProperties=!1)},union:(t,r,i,n)=>{let a=t._zod.def,o=!1===a.inclusive,s=a.options.map((t,i)=>mo(t,r,{...n,path:[...n.path,o?"oneOf":"anyOf",i]}));o?i.oneOf=s:i.anyOf=s},intersection:(t,r,i,n)=>{let a=t._zod.def,o=mo(a.left,r,{...n,path:[...n.path,"allOf",0]}),s=mo(a.right,r,{...n,path:[...n.path,"allOf",1]}),l=t=>"allOf"in t&&1===Object.keys(t).length;i.allOf=[...l(o)?o.allOf:[o],...l(s)?s.allOf:[s]]},tuple:(t,r,i,n)=>{let a=t._zod.def;i.type="array";let o="draft-2020-12"===r.target?"prefixItems":"items",s="draft-2020-12"===r.target||"openapi-3.0"===r.target?"items":"additionalItems",l=a.items.map((t,i)=>mo(t,r,{...n,path:[...n.path,o,i]})),c=a.rest?mo(a.rest,r,{...n,path:[...n.path,s,..."openapi-3.0"===r.target?[a.items.length]:[]]}):null;"draft-2020-12"===r.target?(i.prefixItems=l,c&&(i.items=c)):"openapi-3.0"===r.target?(i.items={anyOf:l},c&&i.items.anyOf.push(c),i.minItems=l.length,c||(i.maxItems=l.length)):(i.items=l,c&&(i.additionalItems=c));let{minimum:u,maximum:d}=t._zod.bag;"number"==typeof u&&(i.minItems=u),"number"==typeof d&&(i.maxItems=d)},record:(t,r,i,n)=>{let a=t._zod.def;i.type="object";let o=a.keyType,s=o._zod.bag,l=s?.patterns;if("loose"===a.mode&&l&&l.size>0){let t=mo(a.valueType,r,{...n,path:[...n.path,"patternProperties","*"]});for(let r of(i.patternProperties={},l))i.patternProperties[r.source]=t}else("draft-07"===r.target||"draft-2020-12"===r.target)&&(i.propertyNames=mo(a.keyType,r,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=mo(a.valueType,r,{...n,path:[...n.path,"additionalProperties"]});let c=o._zod.values;if(c){let t=[...c].filter(t=>"string"==typeof t||"number"==typeof t);t.length>0&&(i.required=t)}},nullable:(t,r,i,n)=>{let a=t._zod.def,o=mo(a.innerType,r,n),s=r.seen.get(t);"openapi-3.0"===r.target?(s.ref=a.innerType,i.nullable=!0):i.anyOf=[o,{type:"null"}]},nonoptional:(t,r,i,n)=>{let a=t._zod.def;mo(a.innerType,r,n),r.seen.get(t).ref=a.innerType},default:(t,r,i,n)=>{let a=t._zod.def;mo(a.innerType,r,n),r.seen.get(t).ref=a.innerType,i.default=JSON.parse(JSON.stringify(a.defaultValue))},prefault:(t,r,i,n)=>{let a=t._zod.def;mo(a.innerType,r,n),r.seen.get(t).ref=a.innerType,"input"===r.io&&(i._prefault=JSON.parse(JSON.stringify(a.defaultValue)))},catch:(t,r,i,n)=>{let a,o=t._zod.def;mo(o.innerType,r,n),r.seen.get(t).ref=o.innerType;try{a=o.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}i.default=a},pipe:(t,r,i,n)=>{let a=t._zod.def,o=a.in._zod.traits.has("$ZodTransform"),s="input"===r.io?o?a.out:a.in:a.out;mo(s,r,n),r.seen.get(t).ref=s},readonly:(t,r,i,n)=>{let a=t._zod.def;mo(a.innerType,r,n),r.seen.get(t).ref=a.innerType,i.readOnly=!0},promise:(t,r,i,n)=>{let a=t._zod.def;mo(a.innerType,r,n),r.seen.get(t).ref=a.innerType},optional:(t,r,i,n)=>{let a=t._zod.def;mo(a.innerType,r,n),r.seen.get(t).ref=a.innerType},lazy:(t,r,i,n)=>{let a=t._zod.innerType;mo(a,r,n),r.seen.get(t).ref=a}};function mp(t,r={}){let{strict:i=!1}=r,n=Object.entries(t),a=t=>({target:r})=>{let a={},o=[];for(let[i,s]of n)a[i]=function(t,r,i){let n=t["~standard"];if(n.jsonSchema)return n.jsonSchema[i]({target:r});if("zod"===t["~standard"].vendor&&!("_zod"in t)&&"_def"in t){let i=((t,r)=>{let i,n,a=(n=void 0!==(i="string"==typeof r?{...dI,name:r}:{...dI,...r}).name?[...i.basePath,i.definitionPath,i.name]:i.basePath,{...i,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(i.definitions).map(([t,r])=>[r._def,{def:r._def,path:[...i.basePath,i.definitionPath,t],jsonSchema:void 0}]))}),o="object"==typeof r&&r.definitions?Object.entries(r.definitions).reduce((t,[r,i])=>({...t,[r]:mt(i._def,{...a,currentPath:[...a.basePath,a.definitionPath,r]},!0)??pU(a)}),{}):void 0,s="string"==typeof r?r:r?.nameStrategy==="title"?void 0:r?.name,l=mt(t._def,void 0===s?a:{...a,currentPath:[...a.basePath,a.definitionPath,s]},!1)??pU(a),c="object"==typeof r&&void 0!==r.name&&"title"===r.nameStrategy?r.name:void 0;void 0!==c&&(l.title=c),a.flags.hasReferencedOpenAiAnyType&&(o||(o={}),o[a.openAiAnyTypeName]||(o[a.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===a.$refStrategy?"1":[...a.basePath,a.definitionPath,a.openAiAnyTypeName].join("/")}}));let u=void 0===s?o?{...l,[a.definitionPath]:o}:l:{$ref:[..."relative"===a.$refStrategy?[]:a.basePath,a.definitionPath,s].join("/"),[a.definitionPath]:{...o,[s]:l}};return"jsonSchema7"===a.target?u.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===a.target||"openAi"===a.target)&&(u.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===a.target&&("anyOf"in u||"oneOf"in u||"allOf"in u||"type"in u&&Array.isArray(u.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),u})(t,{$refStrategy:"none",target:"openapi-3.0"===r?"openApi3":"jsonSchema7"});return delete i.$schema,i}if("zod"===n.vendor&&"_zod"in t)try{let r=function(t,r){if("_idmap"in t){let r=ma({...void 0,processors:md}),i={};for(let i of t._idmap.entries()){let[t,n]=i;mo(n,r)}let n={};for(let a of(r.external={registry:t,uri:void 0,defs:i},t._idmap.entries())){let[t,i]=a;ms(r,i),n[t]=ml(r,i)}return Object.keys(i).length>0&&(n.__shared={["draft-2020-12"===r.target?"$defs":"definitions"]:i}),{schemas:n}}let i=ma({...void 0,processors:md});return mo(t,i),ms(i,t),ml(i,t)}(t);return delete r.$schema,r}catch(t){throw Error(`Failed to convert a zod schema to JSON Schema (zod v4 without "~standard.jsonSchema"). Upgrade to zod >= 4.2.0. Original error: ${t instanceof Error?t.message:String(t)}`)}throw Error(`Schema library "${n.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".`)}(s,r,t),!function(t,r){if("function"!=typeof t.safeParse)return!1;try{let i=t.safeParse(void 0);return i.success&&("input"===r||void 0===i.data)}catch{return!1}}(s,t)&&o.push(i);let s={type:"object",properties:a};return o.length>0&&(s.required=o),i&&(s.additionalProperties=!1),s},o=async r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{issues:[{message:"Expected an object."}]};let a={},o=[];for(let[t,i]of n){let n=await i["~standard"].validate(r[t]);if(n.issues)for(let r of n.issues)o.push({message:r.message,path:[t,...r.path??[]]});else(t in r||void 0!==n.value)&&(a[t]=n.value)}if(i)for(let i of Object.keys(r))i in t||o.push({message:`Unrecognized key: "${i}"`,path:[i]});return o.length>0?{issues:o}:{value:a}};return{shape:t,"~standard":{version:1,vendor:"xmcp",validate:o,jsonSchema:{input:a("input"),output:a("output")}}}}let mm=(t,r)=>{globalThis[t]=r},mh=t=>globalThis[t];function mf({name:t,fallback:r=!0}){let i=Symbol.for(`xmcp-context-${t}`),n=Symbol.for(`xmcp-context-${t}-fallback-store`);if(mh(i))return mh(i);let a=new R,o=globalThis[n]??{current:null};mm(n,o);let s={provider:(t,i)=>(r&&(o.current=t),a.run(t,i)),getContext:()=>{let i=a.getStore();if(i)return i;if(r&&o.current)return o.current;throw Error(`getContext() can only be used within the ${t} context.`)},setContext:i=>{let n=a.getStore()??(r?o.current:null);if(!n)throw Error(`setContext() can only be used within the ${t} context.`);Object.assign(n,i)}};return mm(i,s),s}let mg=mf({name:"http-request-context"});mg.setContext;let my=mg.getContext,mv=mg.provider,m_=mf({name:"client-info-context"});m_.setContext;let mb=m_.getContext;m_.provider;let mS=t=>"object"==typeof t&&null!==t&&!Array.isArray(t),mw=t=>{if(!mS(t)||"string"!=typeof t.name||"string"!=typeof t.version)return;let r={name:t.name,version:t.version};return"string"==typeof t.title&&(r.title=t.title),"string"==typeof t.websiteUrl&&(r.websiteUrl=t.websiteUrl),"string"==typeof t.description&&(r.description=t.description),r},mx=t=>{if(t&&"initialize"===t.method&&mS(t.params))return mw(t.params.clientInfo)},mk=(t,r)=>{let i=r.toLowerCase();for(let[r,n]of Object.entries(t)){if(r.toLowerCase()!==i)continue;let t=Array.isArray(n)?n[0]:n;if("string"!=typeof t)break;let a=t.trim();return a.length>0?a:void 0}},mR=new Set(["message","mode","requestedSchema"]),m$=new Set(["elicitationId","message","mode","url"]),mC=new Set(["properties","required","type"]),mT=new Set(["default","description","format","maxLength","minLength","title","type"]),mO=new Set(["default","description","enum","enumNames","title","type"]),mP=new Set(["default","description","title","type"]),mE=new Set(["default","description","maximum","minimum","title","type"]),mI=new Set(["date","date-time","email","uri"]);async function mq(t,r,i){let n=function(t){let r=t.mode??"form";if("url"===r)return function(t){let r;mz(t,"Elicitation request must be a plain object."),mj(t,m$,"URL elicitation"),mN(t.message,"URL elicitation requires a string message."),mA(t.elicitationId,"URL elicitation requires a non-empty elicitationId."),mA(t.url,"URL elicitation requires a non-empty URL.");try{r=new URL(t.url)}catch{throw Error("URL elicitation requires a valid http or https URL.")}if("http:"!==r.protocol&&"https:"!==r.protocol)throw Error("URL elicitation requires a valid http or https URL.")}(t),t;if("form"!==r)throw Error(`Unsupported elicitation mode "${String(t.mode)}". Expected "form" or "url".`);return function(t){mz(t,"Elicitation request must be a plain object."),mj(t,mR,"Form elicitation"),mN(t.message,"Form elicitation requires a string message.");let r=t.requestedSchema;if(mz(r,"Form elicitation requires a flat object schema."),mj(r,mC,"Form elicitation schema"),"object"!==r.type)throw Error('Form elicitation schema must use type "object".');for(let[t,i]of(mz(r.properties,"Form elicitation schema requires a properties object."),Object.entries(r.properties)))!function(t,r){if(mz(r,`Form elicitation field "${t}" must be a plain object.`),mL(r.title,`Form elicitation field "${t}" title must be a string.`),mL(r.description,`Form elicitation field "${t}" description must be a string.`),"string"===r.type&&"enum"in r){var i,n;if(mj(r,mO,`Form elicitation field "${t}"`),mZ(r.enum,`Form elicitation field "${t}" enum values must be strings.`),i=r.enumNames,n=`Form elicitation field "${t}" enumNames must be strings.`,void 0!==i&&mZ(i,n),void 0!==r.enumNames&&r.enumNames.length!==r.enum.length)throw Error(`Form elicitation field "${t}" enumNames length must match enum length.`);if(mL(r.default,`Form elicitation field "${t}" default must be a string.`),void 0!==r.default&&!r.enum.includes(r.default))throw Error(`Form elicitation field "${t}" default must be one of its enum values.`);return}if("string"===r.type&&!("enum"in r)){mj(r,mT,`Form elicitation field "${t}"`),mM(r.minLength,`Form elicitation field "${t}" minLength must be a number.`),mM(r.maxLength,`Form elicitation field "${t}" maxLength must be a number.`),mL(r.default,`Form elicitation field "${t}" default must be a string.`);let i=r.format;if(mL(i,`Form elicitation field "${t}" format must be a string.`),void 0!==i&&!mI.has(i))throw Error(`Form elicitation field "${t}" format must be one of: ${Array.from(mI).join(", ")}.`);return}if("boolean"===r.type){if(mj(r,mP,`Form elicitation field "${t}"`),void 0!==r.default&&"boolean"!=typeof r.default)throw Error(`Form elicitation field "${t}" default must be a boolean.`);return}if("number"===r.type||"integer"===r.type){mj(r,mE,`Form elicitation field "${t}"`),mM(r.minimum,`Form elicitation field "${t}" minimum must be a number.`),mM(r.maximum,`Form elicitation field "${t}" maximum must be a number.`),mM(r.default,`Form elicitation field "${t}" default must be a number.`);return}throw Error(`Form elicitation field "${t}" uses unsupported type "${String(r.type)}". Supported types are string, boolean, number, integer, and string enums.`)}(t,i);if(void 0!==r.required){if(!Array.isArray(r.required)||r.required.some(t=>"string"!=typeof t))throw Error("Form elicitation schema required fields must be a string array.");for(let t of r.required)if(!(t in r.properties))throw Error(`Form elicitation schema required field "${t}" is not defined in properties.`)}}(t),{...t,mode:"form"}}(r);try{let r=await t.mcpReq.elicitInput(n,i);return{...r,content:r.content??void 0}}catch(t){if(t instanceof lB&&t.code===lV.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 t}}function mj(t,r,i){let n=Object.keys(t).filter(t=>!r.has(t));if(0!==n.length)throw Error(`${i} includes unsupported key(s): ${n.join(", ")}.`)}function mz(t,r){if("object"!=typeof t||null===t||Array.isArray(t))throw Error(r)}function mN(t,r){if("string"!=typeof t)throw Error(r)}function mA(t,r){if("string"!=typeof t||0===t.trim().length)throw Error(r)}function mL(t,r){if(void 0!==t&&"string"!=typeof t)throw Error(r)}function mM(t,r){if(void 0!==t&&"number"!=typeof t)throw Error(r)}function mZ(t,r){if(!Array.isArray(t)||t.some(t=>"string"!=typeof t))throw Error(r)}let mU=new Set(["_meta","includeContext","maxTokens","messages","metadata","modelPreferences","stopSequences","systemPrompt","temperature"]),mF=new Set(["task","toolChoice","tools"]),mH=new Set(["text","image","audio"]);async function mJ(t,r,i){let n=function(t){mD(t,"Sampling request must be a plain object.");let r=Object.keys(t),i=r.filter(t=>mF.has(t));if(i.length>0)throw Error(`Sampling request key(s) not supported by xmcp yet: ${i.join(", ")}.`);let n=r.filter(t=>!mU.has(t));if(n.length>0)throw Error(`Sampling request includes unsupported key(s): ${n.join(", ")}.`);if(!Array.isArray(t.messages)||0===t.messages.length)throw Error("Sampling requires at least one message.");for(let[r,i]of t.messages.entries())!function(t,r){if(mD(r,`Sampling message at index ${t} must be a plain object.`),"user"!==r.role&&"assistant"!==r.role)throw Error(`Sampling message at index ${t} requires role "user" or "assistant".`);let i=r.content;mD(i,`Sampling message at index ${t} requires a content object.`);let n=i.type;if("string"!=typeof n||!mH.has(n))throw Error(`Sampling message at index ${t} uses unsupported content type "${String(n)}". Supported types are text, image, and audio.`);if("text"===n&&"string"!=typeof i.text)throw Error(`Sampling message at index ${t} requires string text content.`);if(("image"===n||"audio"===n)&&("string"!=typeof i.data||"string"!=typeof i.mimeType))throw Error(`Sampling message at index ${t} requires base64 data and a mimeType.`)}(r,i);if("number"!=typeof t.maxTokens)throw Error("Sampling requires a numeric maxTokens.");return t}(r);try{return await t.mcpReq.requestSampling(n,i)}catch(t){if(t instanceof lB&&t.code===lV.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 t}}function mD(t,r){if("object"!=typeof t||null===t||Array.isArray(t))throw Error(r)}let mV={text:t=>"string"!=typeof t.text?{valid:!1,error:'Text content must have a "text" property of type string'}:{valid:!0},image:t=>"string"!=typeof t.data?{valid:!1,error:'Image content must have a "data" property of type string (base64-encoded image)'}:"string"!=typeof t.mimeType?{valid:!1,error:'Image content must have a "mimeType" property of type string'}:{valid:!0},audio:t=>"string"!=typeof t.data?{valid:!1,error:'Audio content must have a "data" property of type string (base64-encoded audio)'}:"string"!=typeof t.mimeType?{valid:!1,error:'Audio content must have a "mimeType" property of type string'}:{valid:!0},resource_link:t=>"string"!=typeof t.name?{valid:!1,error:'Resource link content must have a "name" property of type string'}:"string"!=typeof t.uri?{valid:!1,error:'Resource link content must have a "uri" property of type string'}:void 0!==t.title&&"string"!=typeof t.title?{valid:!1,error:'Resource link "title" property must be a string if provided'}:void 0!==t.description&&"string"!=typeof t.description?{valid:!1,error:'Resource link "description" property must be a string if provided'}:void 0!==t.mimeType&&"string"!=typeof t.mimeType?{valid:!1,error:'Resource link "mimeType" property must be a string if provided'}:{valid:!0}};function mB(t){if(!t||"object"!=typeof t)return{valid:!1,error:"Content must be an object"};if("string"!=typeof t.type)return{valid:!1,error:'Content must have a "type" property of type string'};if(void 0!==t._meta&&(null===t._meta||"object"!=typeof t._meta))return{valid:!1,error:'Content "_meta" property must be an object if provided'};let r=mV[t.type];return r?r(t):{valid:!0}}function mW(t,r,i,n){if(null===t||"object"!=typeof t||Array.isArray(t))throw Error(`Tool "${i}" ${n}: expected a plain object.`);let a=new Set(Object.keys(r)),o=Object.keys(t).filter(t=>!a.has(t));if(o.length>0)throw Error(`Tool "${i}" ${n}: unrecognized key(s): ${o.join(", ")}`);for(let[a,o]of Object.entries(r))try{o.parse(t[a])}catch(t){throw Error(`Tool "${i}" ${n}: ${t?.message??`invalid field "${a}"`}`)}}function mG(t){return!!(t&&"object"==typeof t&&Object.keys(t).some(t=>t.startsWith("ui/")))}function mK(t){let r=t.mcpReq.envelope,i=mw(r?.[aK]);if(!i)try{let t,r=my();i=r.clientInfo??(t=r.headers,mw({name:mk(t,"x-mcp-client-name"),version:mk(t,"x-mcp-client-version"),title:mk(t,"x-mcp-client-title"),websiteUrl:mk(t,"x-mcp-client-website-url"),description:mk(t,"x-mcp-client-description")}))}catch{}if(!i)try{i=mb().clientInfo}catch{}return i}function mY(t){return t.endsWith(".tsx")}let mX=new class{add(t,r){this.resources.set(t,r)}getAll(){return this.resources}clear(){this.resources.clear()}has(t){return this.resources.has(t)}constructor(){var t,r;t="resources",r=new Map,t in this?Object.defineProperty(this,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):this[t]=r}};function mQ(t){let r={};return!function t(i,n=""){if(i&&"object"==typeof i)for(let[a,o]of Object.entries(i)){let i=n?`${n}/${a}`:a;!o||"object"!=typeof o||Array.isArray(o)||o instanceof Date||o instanceof RegExp?r[i]=o:t(o,i)}}(t),r}let m0=["ui/resourceUri","resourceUri","visibility"],m1=["prefersBorder","domain","csp","permissions","connectDomains","resourceDomains","frameDomains","baseUriDomains"],m2=mf({name:"request-context",fallback:!1});function m9(t){let r=[...t];return(t,i,n)=>(function(t,r,i){let n,a=new Map;if(t.http){let t=my(),r=Object.fromEntries(Object.entries(t.headers).map(([t,r])=>[t,Array.isArray(r)?Object.freeze([...r]):r]));n=Object.freeze({id:t.id,headers:Object.freeze(r)})}return m2.provider(Object.freeze({clientInfo:r?Object.freeze({...r}):void 0,http:n,signal:t.mcpReq.signal,set(t,r){a.set(t,r)},get:t=>a.get(t),async progress(r,i){let n=t.mcpReq._meta?.progressToken;void 0!==n&&await t.mcpReq.notify({method:"notifications/progress",params:{progressToken:n,progress:r,...void 0===i?{}:{total:i}}})},log:(r,i)=>t.mcpReq.log(r,i)}),i)})(i,mK(i),async()=>{if(0===r.length)return n();let i=Object.freeze({...function(){try{return m2.getContext()}catch{throw Error("getRequestContext() can only be used while handling an MCP request.")}}(),method:t.method,params:Object.freeze({...t.params})}),a=-1,o=async t=>{if(t<=a)throw Error("MCP middleware next() can only be called once");a=t;let s=r[t];return s?s(i,()=>o(t+1)):n()};return o(0)})}let m4=new Set(["tools/list","prompts/get","prompts/list","resources/read","resources/list","resources/templates/list","completion/complete"]);function m5(t){let{tags:r,enabled:i,...n}=t;return{...n,_meta:void 0===r?n._meta:{...n._meta,"xmcp/tags":r}}}function m3(t){return"object"==typeof t&&null!==t&&Object.entries(t).every(([t,r])=>"string"==typeof t&&"object"==typeof r&&null!==r&&"parse"in r&&"function"==typeof r.parse)}function m6(t){return(t.split("/").pop()||t).replace(/\.[^/.]+$/,"")}function m7(t,r,i){return t.names?.includes(r)===!0||t.tags?.some(t=>i.includes(t))===!0}function m8(t,r){return r?new Map([...t].filter(([t,{metadata:i}])=>{if(i?.enabled===!1)return!1;let n=i?.name??m6(t),a=i?.tags??[];return(!r.include||m7(r.include,n,a))&&(!r.exclude||!m7(r.exclude,n,a))})):t}function he(t){return Error(`[xmcp] Invalid prompt file: ${t}
|
|
80
|
-
-> Default export must be a
|
|
81
|
-
-> ${i}`)});let a=i.length;t.warn(`[xmcp] ${a}
|
|
82
|
-
-> Default export must be a
|
|
83
|
-
-> ${i}`)});let a=i.length;t.warn(`[xmcp] ${a}
|
|
84
|
-
-> Default export must be a tool handler function.`)}async function hc(t){let r=new Map,i=[];for(let n of(await Promise.all(Object.entries(t).map(async([t,r])=>{let i=await r(),n=function(t,r){if("object"!=typeof t||null===t)throw hl(r);let i=Object.keys(t),n=t.default,a=i.filter(t=>"__esModule"!==t);if(0===i.length||1===a.length&&"default"===a[0]&&"object"==typeof n&&null!==n&&0===Object.keys(n).length)return"empty";if(!("default"in t)||void 0===t.default)return"missing-default";if("function"!=typeof t.default)throw hl(r);return"valid"}(i,t);return"empty"===n?{skipped:!0,issue:{path:t,message:"File is empty."}}:"missing-default"===n?{skipped:!0,issue:{path:t,message:"File does not export a default tool handler."}}:{skipped:!1,path:t,toolModule:i}})))){if(n.skipped){i.push(n.issue);continue}r.set(n.path,n.toolModule)}return{toolModules:r,skippedTools:i}}let hu=function(t=console){let r="";return i=>{let n=i.map(({path:t,message:r})=>`${t}:${r}`).sort().join("|");if(n===r||(r=n,0===i.length))return;i.forEach(({path:r,message:i})=>{t.warn(`[xmcp] Failed to load tool file: ${r}
|
|
85
|
-
-> ${i}`)});let a=i.length;t.warn(`[xmcp] ${a} tool${1===a?"":"s"} skipped due to empty files or missing default exports`)}}(),hd=INJECTED_TOOLS,hp=INJECTED_PROMPTS,hm=INJECTED_RESOURCES,hh=SERVER_INFO;async function hf(t,r,i,n){let a=await INJECTED_MIDDLEWARE?.(),o=function(t){if(void 0===t)return[];let r=Array.isArray(t)?[...t]:[t];if(!r.every(t=>"function"==typeof t))throw Error("src/middleware.ts must export mcp as a function or an array of functions");return r}(a?.mcp),s="undefined"!=typeof OBSERVABILITY_CONFIG&&OBSERVABILITY_CONFIG.enabled?function(t=t=>console.error(t)){let r=new Map,i=[];function n(r){try{t(JSON.stringify({"@timestamp":new Date().toISOString(),...r}))}catch{}}return{middleware:async(t,a)=>{let o,s,l;if("tools/call"!==t.method&&"prompts/get"!==t.method&&"resources/read"!==t.method)return a();try{s=performance.now(),o={log:{level:"info"},...function(t){let r=t.http?.headers.traceparent;if("string"!=typeof r)return{};let i=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/.exec(r);return!i||"ff"===i[1]||/^0+$/.test(i[2])||/^0+$/.test(i[3])||"00"===i[1]&&void 0!==i[5]?{}:{trace:{id:i[2]},parent:{id:i[3]}}}(t),transaction:{id:crypto.randomUUID()},...t.http?{http:{request:{id:t.http.id}}}:{},xmcp:{method:t.method,component:"resources/read"===t.method?function(t){try{let n=new URL(t).href;return r.get(n)??i.find(({template:t})=>t.uriTemplate.match(n))?.name??"unknown"}catch{return"unknown"}}(t.params.uri):t.params.name}}}catch{return a()}n({...o,event:{kind:"event",category:["api"],type:["start"],action:"execution.start"}});let c="unknown";try{let r=await a();try{c=t.signal.aborted?"cancelled":cQ(r)?"input_required":"isError"in r&&!0===r.isError?"failure":"success","failure"===c&&(l={message:"Operation returned an error result"})}catch{}return r}catch(r){throw l={message:"cancelled"==(c=t.signal.aborted?"cancelled":"failure")?"Operation cancelled":"Operation threw an exception"},r}finally{try{n({...o,log:{level:"failure"===c?"error":"info"},event:{kind:"event",category:["api"],type:["end"],action:"execution.end",duration:Math.round((performance.now()-s)*1e6),outcome:"success"===c?"success":"failure"===c?"failure":"unknown"},xmcp:{...o.xmcp,status:c},...l?{error:l}:{}})}catch{}}},registerResource(t,n){try{"string"==typeof n?r.set(new URL(n).href,t):i.push({name:t,template:n})}catch{}}}}():void 0;s&&o.unshift(s.middleware),mX.clear();let l="undefined"==typeof COMPONENTS_CONFIG?void 0:COMPONENTS_CONFIG;return!function(t,r,i){let n=t.server,a=n.setRequestHandler,o=m9(r);n.setRequestHandler=(t,...r)=>{if(m4.has(t)&&1===r.length&&"function"==typeof r[0]){let t=r[0];r[0]=(r,i)=>o({method:r.method,params:r.params??{}},i,()=>t(r,i))}Reflect.apply(a,n,[t,...r])};try{i()}finally{n.setRequestHandler=a}}(t,o,()=>{var a,c;!function(t,r,i=[]){r.forEach((r,n)=>{var a,o;let s,l,c,u={name:m6(n),description:"No description provided"},{default:d,metadata:p,schema:m,outputSchema:h}=r;if("object"==typeof p&&null!==p&&Object.assign(u,p),!1===u.enabled)return;if("function"==typeof d&&"__x402"in d){let t=F.g.__XMCP_X402_REGISTRY;t&&t.set(u.name,d.__x402)}let f={};if(m3(m)?f=m:null!=m&&console.warn(`Invalid schema for tool "${u.name}" at ${n}. Expected Record<string, z.ZodType>`),null!=h)if(m3(h))s=h;else throw Error(`Invalid outputSchema for tool "${u.name}" at ${n}. Expected Record<string, z.ZodType>`);u.annotations={...u.annotations??{}},void 0===u.annotations.title&&(u.annotations.title=u.name),u._meta={...m5(u)._meta};let g=mY(n),y=!!(a=u._meta)&&"object"==typeof a&&"ui"in a&&"object"==typeof a.ui||g,v=u._meta;if(y){let t=`ui://app/${u.name}.html`;u._meta.ui||(u._meta.ui={}),u._meta.ui.resourceUri||(u._meta.ui.resourceUri=t);let r=function(t){let r={},i={};if(t.ui&&"object"==typeof t.ui){let n=t.ui,a={},o={};for(let[t,r]of Object.entries(n))m0.includes(t)?a[t]=r:m1.includes(t)?o[t]=r:a[t]=r;Object.keys(a).length>0&&(r.ui=a),Object.keys(o).length>0&&(i.ui=o)}for(let[i,n]of Object.entries(t))"ui"!==i&&(r[i]=n);return{toolMeta:r,resourceMeta:i}}(v);v=r.toolMeta;let i=r.resourceMeta;i.ui=i.ui||{},i.ui.csp=i.ui.csp||{},i.ui.csp.resourceDomains=i.ui.csp.resourceDomains||[],i.ui.csp.resourceDomains.includes("https://esm.sh")||i.ui.csp.resourceDomains.push("https://esm.sh"),mX.add(u.name,{name:u.name,uri:t,handler:d,mimeType:"text/html;profile=mcp-app",_meta:i,toolPath:g?n:void 0})}let _=mQ(v),b=y?_:void 0;l=mY(n)&&y?async(t,r)=>({content:[{type:"text",text:""}],_meta:b,structuredContent:{args:t}}):function(t,r,i,n="unknown-tool"){return async(a,o)=>{let s,l,c=t(a,(s=mK(o),l=function(t){if(!t)return;let r={};return t.headers.forEach((t,i)=>{r[i]=t}),r}(o.http?.req),{signal:o.mcpReq.signal,authInfo:o.http?.authInfo,sessionId:o.sessionId,_meta:o.mcpReq._meta,requestId:o.mcpReq.id,requestInfo:l?{headers:l}:void 0,clientInfo:s,sendNotification:t=>o.mcpReq.notify(t),sendRequest:(t,r,i)=>o.mcpReq.send(t,r,i),elicit:(t,r)=>mq(o,t,r),sample:(t,r)=>mJ(o,t,r),inputResponses:o.mcpReq.inputResponses,requestState:o.mcpReq.requestState}));if(c instanceof Promise&&(c=await c),cQ(c))return c;if("string"==typeof c||"number"==typeof c){if(i){let t=Object.entries(i);if(1===t.length){let[r,i]=t[0];try{return i.parse(c),{content:[{type:"text",text:"number"==typeof c?`${c}`:c}],structuredContent:{[r]:c}}}catch{}}}return mG(r)?{content:[{type:"text",text:""}],structuredContent:{args:a},_meta:r}:{content:[{type:"text",text:"number"==typeof c?`${c}`:c}]}}if(!i||!c||"object"!=typeof c||Array.isArray(c)||"structuredContent"in c||"content"in c&&Array.isArray(c.content)||"_meta"in c||"isError"in c||(mW(c,i,n,"returned data that does not match outputSchema"),c={structuredContent:c}),c&&"object"==typeof c&&"_meta"in c&&!("content"in c)&&!("structuredContent"in c)){let t=c._meta;if(mG(t))return{content:[{type:"text",text:""}],_meta:t}}if(!c||"object"!=typeof c){let t=null===c?"null":typeof c,r=void 0===c?"undefined":null===c?"null":"object"==typeof c?JSON.stringify(c,null,2):String(c);throw Error(`Tool handler must return a CallToolResult, string, or number. Got ${t}: ${r}
|
|
77
|
+
]`;continue}a+=n[t],"\\"===n[t]?o=!0:s&&"]"===n[t]?s=!1:s||"["!==n[t]||(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${r.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return a}function p6(t,r){if("openAi"===r.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===r.target&&t.keyType?._def.typeName===z.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((i,n)=>({...i,[n]:me(t.valueType._def,{...r,currentPath:[...r.currentPath,"properties",n]})??pZ(r)}),{}),additionalProperties:r.rejectedAdditionalProperties};let i={type:"object",additionalProperties:me(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]})??r.allowedAdditionalProperties};if("openApi3"===r.target)return i;if(t.keyType?._def.typeName===z.ZodString&&t.keyType._def.checks?.length){let{type:n,...a}=p1(t.keyType._def,r);return{...i,propertyNames:a}}if(t.keyType?._def.typeName===z.ZodEnum)return{...i,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===z.ZodBranded&&t.keyType._def.type._def.typeName===z.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...a}=pH(t.keyType._def,r);return{...i,propertyNames:a}}return i}let p7={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},p8=(t,r)=>{let i=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((t,i)=>me(t._def,{...r,currentPath:[...r.currentPath,"anyOf",`${i}`]})).filter(t=>!!t&&(!r.strictUnions||"object"==typeof t&&Object.keys(t).length>0));return i.length?{anyOf:i}:void 0};function me(t,r,i=!1){let n=r.seen.get(t);if(r.override){let a=r.override?.(t,r,n,i);if(a!==dE)return a}if(n&&!i){let t=mt(n,r);if(void 0!==t)return t}let a={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,a);let o=((t,r,i)=>{switch(r){case z.ZodString:return p1(t,i);case z.ZodNumber:let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",pU(n,"type",r.message,i);break;case"min":"jsonSchema7"===i.target?r.inclusive?pF(n,"minimum",r.value,r.message,i):pF(n,"exclusiveMinimum",r.value,r.message,i):(r.inclusive||(n.exclusiveMinimum=!0),pF(n,"minimum",r.value,r.message,i));break;case"max":"jsonSchema7"===i.target?r.inclusive?pF(n,"maximum",r.value,r.message,i):pF(n,"exclusiveMaximum",r.value,r.message,i):(r.inclusive||(n.exclusiveMaximum=!0),pF(n,"maximum",r.value,r.message,i));break;case"multipleOf":pF(n,"multipleOf",r.value,r.message,i)}return n;case z.ZodObject:return function(t,r){let i="openAi"===r.target,n={type:"object",properties:{}},a=[],o=t.shape();for(let t in o){let s=o[t];if(void 0===s||void 0===s._def)continue;let l=function(t){try{return t.isOptional()}catch{return!0}}(s);l&&i&&("ZodOptional"===s._def.typeName&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),l=!1);let c=me(s._def,{...r,currentPath:[...r.currentPath,"properties",t],propertyPath:[...r.currentPath,"properties",t]});void 0!==c&&(n.properties[t]=c,l||a.push(t))}a.length&&(n.required=a);let s=function(t,r){if("ZodNever"!==t.catchall._def.typeName)return me(t.catchall._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return r.allowedAdditionalProperties;case"strict":return r.rejectedAdditionalProperties;case"strip":return"strict"===r.removeAdditionalStrategy?r.allowedAdditionalProperties:r.rejectedAdditionalProperties}}(t,r);return void 0!==s&&(n.additionalProperties=s),n}(t,i);case z.ZodBigInt:let a={type:"integer",format:"int64"};if(!t.checks)return a;for(let r of t.checks)switch(r.kind){case"min":"jsonSchema7"===i.target?r.inclusive?pF(a,"minimum",r.value,r.message,i):pF(a,"exclusiveMinimum",r.value,r.message,i):(r.inclusive||(a.exclusiveMinimum=!0),pF(a,"minimum",r.value,r.message,i));break;case"max":"jsonSchema7"===i.target?r.inclusive?pF(a,"maximum",r.value,r.message,i):pF(a,"exclusiveMaximum",r.value,r.message,i):(r.inclusive||(a.exclusiveMaximum=!0),pF(a,"maximum",r.value,r.message,i));break;case"multipleOf":pF(a,"multipleOf",r.value,r.message,i)}return a;case z.ZodBoolean:return{type:"boolean"};case z.ZodDate:return function t(r,i,n){let a=n??i.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((n,a)=>t(r,i,n))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var o=r,s=i;let l={type:"integer",format:"unix-time"};if("openApi3"===s.target)return l;for(let t of o.checks)switch(t.kind){case"min":pF(l,"minimum",t.value,t.message,s);break;case"max":pF(l,"maximum",t.value,t.message,s)}return l}}(t,i);case z.ZodUndefined:return{not:pZ(i)};case z.ZodNull:return"openApi3"===i.target?{enum:["null"],nullable:!0}:{type:"null"};case z.ZodArray:let o;return o={type:"array"},t.type?._def&&t.type?._def?.typeName!==z.ZodAny&&(o.items=me(t.type._def,{...i,currentPath:[...i.currentPath,"items"]})),t.minLength&&pF(o,"minItems",t.minLength.value,t.minLength.message,i),t.maxLength&&pF(o,"maxItems",t.maxLength.value,t.maxLength.message,i),t.exactLength&&(pF(o,"minItems",t.exactLength.value,t.exactLength.message,i),pF(o,"maxItems",t.exactLength.value,t.exactLength.message,i)),o;case z.ZodUnion:case z.ZodDiscriminatedUnion:if("openApi3"===i.target)return p8(t,i);let s=t.options instanceof Map?Array.from(t.options.values()):t.options;if(s.every(t=>t._def.typeName in p7&&(!t._def.checks||!t._def.checks.length))){let t=s.reduce((t,r)=>{let i=p7[r._def.typeName];return i&&!t.includes(i)?[...t,i]:t},[]);return{type:t.length>1?t:t[0]}}if(s.every(t=>"ZodLiteral"===t._def.typeName&&!t.description)){let t=s.reduce((t,r)=>{let i=typeof r._def.value;switch(i){case"string":case"number":case"boolean":return[...t,i];case"bigint":return[...t,"integer"];case"object":if(null===r._def.value)return[...t,"null"];default:return t}},[]);if(t.length===s.length){let r=t.filter((t,r,i)=>i.indexOf(t)===r);return{type:r.length>1?r:r[0],enum:s.reduce((t,r)=>t.includes(r._def.value)?t:[...t,r._def.value],[])}}}else if(s.every(t=>"ZodEnum"===t._def.typeName))return{type:"string",enum:s.reduce((t,r)=>[...t,...r._def.values.filter(r=>!t.includes(r))],[])};return p8(t,i);case z.ZodIntersection:let l,c,u;return l=[me(t.left._def,{...i,currentPath:[...i.currentPath,"allOf","0"]}),me(t.right._def,{...i,currentPath:[...i.currentPath,"allOf","1"]})].filter(t=>!!t),c="jsonSchema2019-09"===i.target?{unevaluatedProperties:!1}:void 0,u=[],l.forEach(t=>{if((!("type"in t)||"string"!==t.type)&&"allOf"in t)u.push(...t.allOf),void 0===t.unevaluatedProperties&&(c=void 0);else{let r=t;if("additionalProperties"in t&&!1===t.additionalProperties){let{additionalProperties:i,...n}=t;r=n}else c=void 0;u.push(r)}}),u.length?{allOf:u,...c}:void 0;case z.ZodTuple:return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((t,r)=>me(t._def,{...i,currentPath:[...i.currentPath,"items",`${r}`]})).reduce((t,r)=>void 0===r?t:[...t,r],[]),additionalItems:me(t.rest._def,{...i,currentPath:[...i.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((t,r)=>me(t._def,{...i,currentPath:[...i.currentPath,"items",`${r}`]})).reduce((t,r)=>void 0===r?t:[...t,r],[])};case z.ZodRecord:return p6(t,i);case z.ZodLiteral:let d;return"bigint"!=(d=typeof t.value)&&"number"!==d&&"boolean"!==d&&"string"!==d?{type:Array.isArray(t.value)?"array":"object"}:"openApi3"===i.target?{type:"bigint"===d?"integer":d,enum:[t.value]}:{type:"bigint"===d?"integer":d,const:t.value};case z.ZodEnum:return{type:"string",enum:Array.from(t.values)};case z.ZodNativeEnum:let p,m,h;return p=t.values,{type:1===(h=Array.from(new Set((m=Object.keys(t.values).filter(t=>"number"!=typeof p[p[t]]).map(t=>p[t])).map(t=>typeof t)))).length?"string"===h[0]?"string":"number":["string","number"],enum:m};case z.ZodNullable:if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return"openApi3"===i.target?{type:p7[t.innerType._def.typeName],nullable:!0}:{type:[p7[t.innerType._def.typeName],"null"]};if("openApi3"===i.target){let r=me(t.innerType._def,{...i,currentPath:[...i.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let f=me(t.innerType._def,{...i,currentPath:[...i.currentPath,"anyOf","0"]});return f&&{anyOf:[f,{type:"null"}]};case z.ZodOptional:if(i.currentPath.toString()===i.propertyPath?.toString())return me(t.innerType._def,i);let g=me(t.innerType._def,{...i,currentPath:[...i.currentPath,"anyOf","1"]});return g?{anyOf:[{not:pZ(i)},g]}:pZ(i);case z.ZodMap:if("record"===i.mapStrategy)return p6(t,i);return{type:"array",maxItems:125,items:{type:"array",items:[me(t.keyType._def,{...i,currentPath:[...i.currentPath,"items","items","0"]})||pZ(i),me(t.valueType._def,{...i,currentPath:[...i.currentPath,"items","items","1"]})||pZ(i)],minItems:2,maxItems:2}};case z.ZodSet:let y;return y={type:"array",uniqueItems:!0,items:me(t.valueType._def,{...i,currentPath:[...i.currentPath,"items"]})},t.minSize&&pF(y,"minItems",t.minSize.value,t.minSize.message,i),t.maxSize&&pF(y,"maxItems",t.maxSize.value,t.maxSize.message,i),y;case z.ZodLazy:return()=>t.getter()._def;case z.ZodPromise:return me(t.type._def,i);case z.ZodNaN:case z.ZodNever:return"openAi"===i.target?void 0:{not:pZ({...i,currentPath:[...i.currentPath,"not"]})};case z.ZodEffects:return"input"===i.effectStrategy?me(t.schema._def,i):pZ(i);case z.ZodAny:case z.ZodUnknown:return pZ(i);case z.ZodDefault:return{...me(t.innerType._def,i),default:t.defaultValue()};case z.ZodBranded:return pH(t,i);case z.ZodReadonly:case z.ZodCatch:return me(t.innerType._def,i);case z.ZodPipeline:if("input"===i.pipeStrategy)return me(t.in._def,i);if("output"===i.pipeStrategy)return me(t.out._def,i);let v=me(t.in._def,{...i,currentPath:[...i.currentPath,"allOf","0"]}),_=me(t.out._def,{...i,currentPath:[...i.currentPath,"allOf",v?"1":"0"]});return{allOf:[v,_].filter(t=>void 0!==t)};case z.ZodFunction:case z.ZodVoid:case z.ZodSymbol:default:return}})(t,t.typeName,r),s="function"==typeof o?me(o(),r):o;if(s&&mr(t,r,s),r.postProcess){let i=r.postProcess(s,t,r);return a.jsonSchema=s,i}return a.jsonSchema=s,s}let mt=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:pM(r.currentPath,t.path)};case"none":case"seen":if(t.path.length<r.currentPath.length&&t.path.every((t,i)=>r.currentPath[i]===t))return console.warn(`Recursive reference detected at ${r.currentPath.join("/")}! Defaulting to any`),pZ(r);return"seen"===r.$refStrategy?pZ(r):void 0}},mr=(t,r,i)=>(t.description&&(i.description=t.description,r.markdownDescription&&(i.markdownDescription=t.description)),i);function mi(t,r={}){let{strict:i=!1}=r,n=Object.entries(t),a=t=>({target:r})=>{let a={},o=[];for(let[i,s]of n)a[i]=function(t,r,i){let n=t["~standard"];if(n.jsonSchema)return n.jsonSchema[i]({target:r});if("zod"===t["~standard"].vendor&&!("_zod"in t)&&"_def"in t){let i=((t,r)=>{let i,n,a=(n=void 0!==(i="string"==typeof r?{...dO,name:r}:{...dO,...r}).name?[...i.basePath,i.definitionPath,i.name]:i.basePath,{...i,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(i.definitions).map(([t,r])=>[r._def,{def:r._def,path:[...i.basePath,i.definitionPath,t],jsonSchema:void 0}]))}),o="object"==typeof r&&r.definitions?Object.entries(r.definitions).reduce((t,[r,i])=>({...t,[r]:me(i._def,{...a,currentPath:[...a.basePath,a.definitionPath,r]},!0)??pZ(a)}),{}):void 0,s="string"==typeof r?r:r?.nameStrategy==="title"?void 0:r?.name,l=me(t._def,void 0===s?a:{...a,currentPath:[...a.basePath,a.definitionPath,s]},!1)??pZ(a),c="object"==typeof r&&void 0!==r.name&&"title"===r.nameStrategy?r.name:void 0;void 0!==c&&(l.title=c),a.flags.hasReferencedOpenAiAnyType&&(o||(o={}),o[a.openAiAnyTypeName]||(o[a.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===a.$refStrategy?"1":[...a.basePath,a.definitionPath,a.openAiAnyTypeName].join("/")}}));let u=void 0===s?o?{...l,[a.definitionPath]:o}:l:{$ref:[..."relative"===a.$refStrategy?[]:a.basePath,a.definitionPath,s].join("/"),[a.definitionPath]:{...o,[s]:l}};return"jsonSchema7"===a.target?u.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===a.target||"openAi"===a.target)&&(u.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===a.target&&("anyOf"in u||"oneOf"in u||"allOf"in u||"type"in u&&Array.isArray(u.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),u})(t,{$refStrategy:"none",target:"openapi-3.0"===r?"openApi3":"jsonSchema7"});return delete i.$schema,i}if("zod"===n.vendor&&"_zod"in t)try{let r=ni(t);return delete r.$schema,r}catch(t){throw Error(`Failed to convert a zod schema to JSON Schema (zod v4 without "~standard.jsonSchema"). Upgrade to zod >= 4.2.0. Original error: ${t instanceof Error?t.message:String(t)}`)}throw Error(`Schema library "${n.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".`)}(s,r,t),!function(t,r){if("function"!=typeof t.safeParse)return!1;try{let i=t.safeParse(void 0);return i.success&&("input"===r||void 0===i.data)}catch{return!1}}(s,t)&&o.push(i);let s={type:"object",properties:a};return o.length>0&&(s.required=o),i&&(s.additionalProperties=!1),s},o=async r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{issues:[{message:"Expected an object."}]};let a={},o=[];for(let[t,i]of n){let n=await i["~standard"].validate(r[t]);if(n.issues)for(let r of n.issues)o.push({message:r.message,path:[t,...r.path??[]]});else(t in r||void 0!==n.value)&&(a[t]=n.value)}if(i)for(let i of Object.keys(r))i in t||o.push({message:`Unrecognized key: "${i}"`,path:[i]});return o.length>0?{issues:o}:{value:a}};return{shape:t,"~standard":{version:1,vendor:"xmcp",validate:o,jsonSchema:{input:a("input"),output:a("output")}}}}let mn=(t,r)=>{globalThis[t]=r},ma=t=>globalThis[t];function mo({name:t,fallback:r=!0}){let i=Symbol.for(`xmcp-context-${t}`),n=Symbol.for(`xmcp-context-${t}-fallback-store`);if(ma(i))return ma(i);let a=new R,o=globalThis[n]??{current:null};mn(n,o);let s={provider:(t,i)=>(r&&(o.current=t),a.run(t,i)),getContext:()=>{let i=a.getStore();if(i)return i;if(r&&o.current)return o.current;throw Error(`getContext() can only be used within the ${t} context.`)},setContext:i=>{let n=a.getStore()??(r?o.current:null);if(!n)throw Error(`setContext() can only be used within the ${t} context.`);Object.assign(n,i)}};return mn(i,s),s}let ms=mo({name:"http-request-context"});ms.setContext;let ml=ms.getContext,mc=ms.provider,mu=mo({name:"client-info-context"});mu.setContext;let md=mu.getContext;mu.provider;let mp=t=>"object"==typeof t&&null!==t&&!Array.isArray(t),mm=t=>{if(!mp(t)||"string"!=typeof t.name||"string"!=typeof t.version)return;let r={name:t.name,version:t.version};return"string"==typeof t.title&&(r.title=t.title),"string"==typeof t.websiteUrl&&(r.websiteUrl=t.websiteUrl),"string"==typeof t.description&&(r.description=t.description),r},mh=t=>{if(t&&"initialize"===t.method&&mp(t.params))return mm(t.params.clientInfo)},mf=(t,r)=>{let i=r.toLowerCase();for(let[r,n]of Object.entries(t)){if(r.toLowerCase()!==i)continue;let t=Array.isArray(n)?n[0]:n;if("string"!=typeof t)break;let a=t.trim();return a.length>0?a:void 0}},mg=new Set(["message","mode","requestedSchema"]),my=new Set(["elicitationId","message","mode","url"]),mv=new Set(["properties","required","type"]),m_=new Set(["default","description","format","maxLength","minLength","title","type"]),mb=new Set(["default","description","enum","enumNames","title","type"]),mS=new Set(["default","description","title","type"]),mw=new Set(["default","description","maximum","minimum","title","type"]),mk=new Set(["date","date-time","email","uri"]);async function mx(t,r,i){let n=function(t){let r=t.mode??"form";if("url"===r)return function(t){let r;m$(t,"Elicitation request must be a plain object."),mR(t,my,"URL elicitation"),mC(t.message,"URL elicitation requires a string message."),mT(t.elicitationId,"URL elicitation requires a non-empty elicitationId."),mT(t.url,"URL elicitation requires a non-empty URL.");try{r=new URL(t.url)}catch{throw Error("URL elicitation requires a valid http or https URL.")}if("http:"!==r.protocol&&"https:"!==r.protocol)throw Error("URL elicitation requires a valid http or https URL.")}(t),t;if("form"!==r)throw Error(`Unsupported elicitation mode "${String(t.mode)}". Expected "form" or "url".`);return function(t){m$(t,"Elicitation request must be a plain object."),mR(t,mg,"Form elicitation"),mC(t.message,"Form elicitation requires a string message.");let r=t.requestedSchema;if(m$(r,"Form elicitation requires a flat object schema."),mR(r,mv,"Form elicitation schema"),"object"!==r.type)throw Error('Form elicitation schema must use type "object".');for(let[t,i]of(m$(r.properties,"Form elicitation schema requires a properties object."),Object.entries(r.properties)))!function(t,r){if(m$(r,`Form elicitation field "${t}" must be a plain object.`),mP(r.title,`Form elicitation field "${t}" title must be a string.`),mP(r.description,`Form elicitation field "${t}" description must be a string.`),"string"===r.type&&"enum"in r){var i,n;if(mR(r,mb,`Form elicitation field "${t}"`),mO(r.enum,`Form elicitation field "${t}" enum values must be strings.`),i=r.enumNames,n=`Form elicitation field "${t}" enumNames must be strings.`,void 0!==i&&mO(i,n),void 0!==r.enumNames&&r.enumNames.length!==r.enum.length)throw Error(`Form elicitation field "${t}" enumNames length must match enum length.`);if(mP(r.default,`Form elicitation field "${t}" default must be a string.`),void 0!==r.default&&!r.enum.includes(r.default))throw Error(`Form elicitation field "${t}" default must be one of its enum values.`);return}if("string"===r.type&&!("enum"in r)){mR(r,m_,`Form elicitation field "${t}"`),mE(r.minLength,`Form elicitation field "${t}" minLength must be a number.`),mE(r.maxLength,`Form elicitation field "${t}" maxLength must be a number.`),mP(r.default,`Form elicitation field "${t}" default must be a string.`);let i=r.format;if(mP(i,`Form elicitation field "${t}" format must be a string.`),void 0!==i&&!mk.has(i))throw Error(`Form elicitation field "${t}" format must be one of: ${Array.from(mk).join(", ")}.`);return}if("boolean"===r.type){if(mR(r,mS,`Form elicitation field "${t}"`),void 0!==r.default&&"boolean"!=typeof r.default)throw Error(`Form elicitation field "${t}" default must be a boolean.`);return}if("number"===r.type||"integer"===r.type){mR(r,mw,`Form elicitation field "${t}"`),mE(r.minimum,`Form elicitation field "${t}" minimum must be a number.`),mE(r.maximum,`Form elicitation field "${t}" maximum must be a number.`),mE(r.default,`Form elicitation field "${t}" default must be a number.`);return}throw Error(`Form elicitation field "${t}" uses unsupported type "${String(r.type)}". Supported types are string, boolean, number, integer, and string enums.`)}(t,i);if(void 0!==r.required){if(!Array.isArray(r.required)||r.required.some(t=>"string"!=typeof t))throw Error("Form elicitation schema required fields must be a string array.");for(let t of r.required)if(!(t in r.properties))throw Error(`Form elicitation schema required field "${t}" is not defined in properties.`)}}(t),{...t,mode:"form"}}(r);try{let r=await t.mcpReq.elicitInput(n,i);return{...r,content:r.content??void 0}}catch(t){if(t instanceof lJ&&t.code===lV.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 t}}function mR(t,r,i){let n=Object.keys(t).filter(t=>!r.has(t));if(0!==n.length)throw Error(`${i} includes unsupported key(s): ${n.join(", ")}.`)}function m$(t,r){if("object"!=typeof t||null===t||Array.isArray(t))throw Error(r)}function mC(t,r){if("string"!=typeof t)throw Error(r)}function mT(t,r){if("string"!=typeof t||0===t.trim().length)throw Error(r)}function mP(t,r){if(void 0!==t&&"string"!=typeof t)throw Error(r)}function mE(t,r){if(void 0!==t&&"number"!=typeof t)throw Error(r)}function mO(t,r){if(!Array.isArray(t)||t.some(t=>"string"!=typeof t))throw Error(r)}let mI=new Set(["_meta","includeContext","maxTokens","messages","metadata","modelPreferences","stopSequences","systemPrompt","temperature"]),mq=new Set(["task","toolChoice","tools"]),mj=new Set(["text","image","audio"]);async function mA(t,r,i){let n=function(t){mN(t,"Sampling request must be a plain object.");let r=Object.keys(t),i=r.filter(t=>mq.has(t));if(i.length>0)throw Error(`Sampling request key(s) not supported by xmcp yet: ${i.join(", ")}.`);let n=r.filter(t=>!mI.has(t));if(n.length>0)throw Error(`Sampling request includes unsupported key(s): ${n.join(", ")}.`);if(!Array.isArray(t.messages)||0===t.messages.length)throw Error("Sampling requires at least one message.");for(let[r,i]of t.messages.entries())!function(t,r){if(mN(r,`Sampling message at index ${t} must be a plain object.`),"user"!==r.role&&"assistant"!==r.role)throw Error(`Sampling message at index ${t} requires role "user" or "assistant".`);let i=r.content;mN(i,`Sampling message at index ${t} requires a content object.`);let n=i.type;if("string"!=typeof n||!mj.has(n))throw Error(`Sampling message at index ${t} uses unsupported content type "${String(n)}". Supported types are text, image, and audio.`);if("text"===n&&"string"!=typeof i.text)throw Error(`Sampling message at index ${t} requires string text content.`);if(("image"===n||"audio"===n)&&("string"!=typeof i.data||"string"!=typeof i.mimeType))throw Error(`Sampling message at index ${t} requires base64 data and a mimeType.`)}(r,i);if("number"!=typeof t.maxTokens)throw Error("Sampling requires a numeric maxTokens.");return t}(r);try{return await t.mcpReq.requestSampling(n,i)}catch(t){if(t instanceof lJ&&t.code===lV.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 t}}function mN(t,r){if("object"!=typeof t||null===t||Array.isArray(t))throw Error(r)}let mL={text:t=>"string"!=typeof t.text?{valid:!1,error:'Text content must have a "text" property of type string'}:{valid:!0},image:t=>"string"!=typeof t.data?{valid:!1,error:'Image content must have a "data" property of type string (base64-encoded image)'}:"string"!=typeof t.mimeType?{valid:!1,error:'Image content must have a "mimeType" property of type string'}:{valid:!0},audio:t=>"string"!=typeof t.data?{valid:!1,error:'Audio content must have a "data" property of type string (base64-encoded audio)'}:"string"!=typeof t.mimeType?{valid:!1,error:'Audio content must have a "mimeType" property of type string'}:{valid:!0},resource_link:t=>"string"!=typeof t.name?{valid:!1,error:'Resource link content must have a "name" property of type string'}:"string"!=typeof t.uri?{valid:!1,error:'Resource link content must have a "uri" property of type string'}:void 0!==t.title&&"string"!=typeof t.title?{valid:!1,error:'Resource link "title" property must be a string if provided'}:void 0!==t.description&&"string"!=typeof t.description?{valid:!1,error:'Resource link "description" property must be a string if provided'}:void 0!==t.mimeType&&"string"!=typeof t.mimeType?{valid:!1,error:'Resource link "mimeType" property must be a string if provided'}:{valid:!0}};function mz(t){if(!t||"object"!=typeof t)return{valid:!1,error:"Content must be an object"};if("string"!=typeof t.type)return{valid:!1,error:'Content must have a "type" property of type string'};if(void 0!==t._meta&&(null===t._meta||"object"!=typeof t._meta))return{valid:!1,error:'Content "_meta" property must be an object if provided'};let r=mL[t.type];return r?r(t):{valid:!0}}function mM(t,r,i,n){if(null===t||"object"!=typeof t||Array.isArray(t))throw Error(`Tool "${i}" ${n}: expected a plain object.`);let a=new Set(Object.keys(r)),o=Object.keys(t).filter(t=>!a.has(t));if(o.length>0)throw Error(`Tool "${i}" ${n}: unrecognized key(s): ${o.join(", ")}`);for(let[a,o]of Object.entries(r))try{o.parse(t[a])}catch(t){throw Error(`Tool "${i}" ${n}: ${t?.message??`invalid field "${a}"`}`)}}function mZ(t){return!!(t&&"object"==typeof t&&Object.keys(t).some(t=>t.startsWith("ui/")))}function mU(t){let r=t.mcpReq.envelope,i=mm(r?.[aG]);if(!i)try{let t,r=ml();i=r.clientInfo??(t=r.headers,mm({name:mf(t,"x-mcp-client-name"),version:mf(t,"x-mcp-client-version"),title:mf(t,"x-mcp-client-title"),websiteUrl:mf(t,"x-mcp-client-website-url"),description:mf(t,"x-mcp-client-description")}))}catch{}if(!i)try{i=md().clientInfo}catch{}return i}function mF(t){return t.endsWith(".tsx")}let mH=new class{add(t,r){this.resources.set(t,r)}getAll(){return this.resources}clear(){this.resources.clear()}has(t){return this.resources.has(t)}constructor(){var t,r;t="resources",r=new Map,t in this?Object.defineProperty(this,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):this[t]=r}};function mD(t){let r={};return!function t(i,n=""){if(i&&"object"==typeof i)for(let[a,o]of Object.entries(i)){let i=n?`${n}/${a}`:a;!o||"object"!=typeof o||Array.isArray(o)||o instanceof Date||o instanceof RegExp?r[i]=o:t(o,i)}}(t),r}let mV=["ui/resourceUri","resourceUri","visibility"],mJ=["prefersBorder","domain","csp","permissions","connectDomains","resourceDomains","frameDomains","baseUriDomains"],mB=mo({name:"request-context",fallback:!1});function mW(t){let r=[...t];return(t,i,n)=>(function(t,r,i){let n,a=new Map;if(t.http){let t=ml(),r=Object.fromEntries(Object.entries(t.headers).map(([t,r])=>[t,Array.isArray(r)?Object.freeze([...r]):r]));n=Object.freeze({id:t.id,headers:Object.freeze(r)})}return mB.provider(Object.freeze({clientInfo:r?Object.freeze({...r}):void 0,http:n,signal:t.mcpReq.signal,set(t,r){a.set(t,r)},get:t=>a.get(t),async progress(r,i){let n=t.mcpReq._meta?.progressToken;void 0!==n&&await t.mcpReq.notify({method:"notifications/progress",params:{progressToken:n,progress:r,...void 0===i?{}:{total:i}}})},log:(r,i)=>t.mcpReq.log(r,i)}),i)})(i,mU(i),async()=>{if(0===r.length)return n();let i=Object.freeze({...function(){try{return mB.getContext()}catch{throw Error("getRequestContext() can only be used while handling an MCP request.")}}(),method:t.method,params:Object.freeze({...t.params})}),a=-1,o=async t=>{if(t<=a)throw Error("MCP middleware next() can only be called once");a=t;let s=r[t];return s?s(i,()=>o(t+1)):n()};return o(0)})}let mG=new Set(["tools/list","prompts/get","prompts/list","resources/read","resources/list","resources/templates/list","completion/complete"]);function mK(t){let{tags:r,enabled:i,...n}=t;return{...n,_meta:void 0===r?n._meta:{...n._meta,"xmcp/tags":r}}}function mY(t){return"object"==typeof t&&null!==t&&Object.entries(t).every(([t,r])=>"string"==typeof t&&"object"==typeof r&&null!==r&&"parse"in r&&"function"==typeof r.parse)}function mX(t){return(t.split("/").pop()||t).replace(/\.[^/.]+$/,"")}function mQ(t,r,i){return t.names?.includes(r)===!0||t.tags?.some(t=>i.includes(t))===!0}function m0(t,r){return r?new Map([...t].filter(([t,{metadata:i}])=>{if(i?.enabled===!1)return!1;let n=i?.name??mX(t),a=i?.tags??[];return(!r.include||mQ(r.include,n,a))&&(!r.exclude||!mQ(r.exclude,n,a))})):t}function m1(t){return Error(`[xmcp] Invalid prompt file: ${t}
|
|
78
|
+
-> Default export must be a prompt handler function.`)}async function m2(t){let r=new Map,i=[];for(let n of(await Promise.all(Object.entries(t).map(async([t,r])=>{let i=await r(),n=function(t,r){if("object"!=typeof t||null===t)throw m1(r);let i=Object.keys(t),n=t.default,a=i.filter(t=>"__esModule"!==t);if(0===i.length||1===a.length&&"default"===a[0]&&"object"==typeof n&&null!==n&&0===Object.keys(n).length)return"empty";if(!("default"in t)||void 0===t.default)return"missing-default";if("function"!=typeof t.default)throw m1(r);return"valid"}(i,t);return"empty"===n?{skipped:!0,issue:{path:t,message:"File is empty."}}:"missing-default"===n?{skipped:!0,issue:{path:t,message:"File does not export a default prompt handler."}}:{skipped:!1,path:t,promptModule:i}})))){if(n.skipped){i.push(n.issue);continue}r.set(n.path,n.promptModule)}return{promptModules:r,skippedPrompts:i}}let m9=function(t=console){let r="";return i=>{let n=i.map(({path:t,message:r})=>`${t}:${r}`).sort().join("|");if(n===r||(r=n,0===i.length))return;i.forEach(({path:r,message:i})=>{t.warn(`[xmcp] Failed to load prompt file: ${r}
|
|
79
|
+
-> ${i}`)});let a=i.length;t.warn(`[xmcp] ${a} prompt${1===a?"":"s"} skipped due to empty files or missing default exports`)}}();function m4(t){return Error(`[xmcp] Invalid resource file: ${t}
|
|
80
|
+
-> Default export must be a resource handler function.`)}async function m5(t){let r=new Map,i=[];for(let n of(await Promise.all(Object.entries(t).map(async([t,r])=>{let i=await r(),n=function(t,r){if("object"!=typeof t||null===t)throw m4(r);let i=Object.keys(t),n=t.default,a=i.filter(t=>"__esModule"!==t);if(0===i.length||1===a.length&&"default"===a[0]&&"object"==typeof n&&null!==n&&0===Object.keys(n).length)return"empty";if(!("default"in t)||void 0===t.default)return"missing-default";if("function"!=typeof t.default)throw m4(r);return"valid"}(i,t);return"empty"===n?{skipped:!0,issue:{path:t,message:"File is empty."}}:"missing-default"===n?{skipped:!0,issue:{path:t,message:"File does not export a default resource handler."}}:{skipped:!1,path:t,resourceModule:i}})))){if(n.skipped){i.push(n.issue);continue}r.set(n.path,n.resourceModule)}return{resourceModules:r,skippedResources:i}}let m3=function(t=console){let r="";return i=>{let n=i.map(({path:t,message:r})=>`${t}:${r}`).sort().join("|");if(n===r||(r=n,0===i.length))return;i.forEach(({path:r,message:i})=>{t.warn(`[xmcp] Failed to load resource file: ${r}
|
|
81
|
+
-> ${i}`)});let a=i.length;t.warn(`[xmcp] ${a} resource${1===a?"":"s"} skipped due to empty files or missing default exports`)}}();function m6(t){let r=t.replace(/\\/g,"/");if(!r)throw Error("Invalid tool path: path is empty");let i=r.replace(/\.[^/.]+$/,"").replace(/\//g,"_");return{normalizedPath:r,baseName:i}}function m7(t){let r=t.split("/").filter(t=>""!==t),i=r.findIndex(t=>t.match(/^\(.+\)$/));if(-1===i)return null;let n=r[r.length-1];if(n&&n.match(/^\[.+\]\.ts$/))return null;let a=r[i].slice(1,-1),o=r.slice(i+1),s=o[o.length-1];if(s&&s.includes(".")){let t=s.split(".")[0];"index"!==t?o[o.length-1]=t:o.pop()}let l=[],c=[],u=o.map(t=>{if(!t.match(/^\[.+\]$/))return c.push(t),t;{let r=t.slice(1,-1);return l.push(r),`{${r}}`}}),d=`${a}://${u.join("/")}`,p=l.length>0?"template":"direct";return{filePath:t,uriTemplate:d,scheme:a,parameters:l,pathSegments:c,type:p}}function m8(t){return Error(`[xmcp] Invalid tool file: ${t}
|
|
82
|
+
-> Default export must be a tool handler function.`)}async function he(t){let r=new Map,i=[];for(let n of(await Promise.all(Object.entries(t).map(async([t,r])=>{let i=await r(),n=function(t,r){if("object"!=typeof t||null===t)throw m8(r);let i=Object.keys(t),n=t.default,a=i.filter(t=>"__esModule"!==t);if(0===i.length||1===a.length&&"default"===a[0]&&"object"==typeof n&&null!==n&&0===Object.keys(n).length)return"empty";if(!("default"in t)||void 0===t.default)return"missing-default";if("function"!=typeof t.default)throw m8(r);return"valid"}(i,t);return"empty"===n?{skipped:!0,issue:{path:t,message:"File is empty."}}:"missing-default"===n?{skipped:!0,issue:{path:t,message:"File does not export a default tool handler."}}:{skipped:!1,path:t,toolModule:i}})))){if(n.skipped){i.push(n.issue);continue}r.set(n.path,n.toolModule)}return{toolModules:r,skippedTools:i}}let ht=function(t=console){let r="";return i=>{let n=i.map(({path:t,message:r})=>`${t}:${r}`).sort().join("|");if(n===r||(r=n,0===i.length))return;i.forEach(({path:r,message:i})=>{t.warn(`[xmcp] Failed to load tool file: ${r}
|
|
83
|
+
-> ${i}`)});let a=i.length;t.warn(`[xmcp] ${a} tool${1===a?"":"s"} skipped due to empty files or missing default exports`)}}(),hr=INJECTED_TOOLS,hi=INJECTED_PROMPTS,hn=INJECTED_RESOURCES,ha=SERVER_INFO;async function ho(t,r,i,n){let a=await INJECTED_MIDDLEWARE?.(),o=function(t){if(void 0===t)return[];let r=Array.isArray(t)?[...t]:[t];if(!r.every(t=>"function"==typeof t))throw Error("src/middleware.ts must export mcp as a function or an array of functions");return r}(a?.mcp),s="undefined"!=typeof OBSERVABILITY_CONFIG&&OBSERVABILITY_CONFIG.enabled?function(t=t=>console.error(t)){let r=new Map,i=[];function n(r){try{t(JSON.stringify({"@timestamp":new Date().toISOString(),...r}))}catch{}}return{middleware:async(t,a)=>{let o,s,l;if("tools/call"!==t.method&&"prompts/get"!==t.method&&"resources/read"!==t.method)return a();try{s=performance.now(),o={log:{level:"info"},...function(t){let r=t.http?.headers.traceparent;if("string"!=typeof r)return{};let i=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/.exec(r);return!i||"ff"===i[1]||/^0+$/.test(i[2])||/^0+$/.test(i[3])||"00"===i[1]&&void 0!==i[5]?{}:{trace:{id:i[2]},parent:{id:i[3]}}}(t),transaction:{id:crypto.randomUUID()},...t.http?{http:{request:{id:t.http.id}}}:{},xmcp:{method:t.method,component:"resources/read"===t.method?function(t){try{let n=new URL(t).href;return r.get(n)??i.find(({template:t})=>t.uriTemplate.match(n))?.name??"unknown"}catch{return"unknown"}}(t.params.uri):t.params.name}}}catch{return a()}n({...o,event:{kind:"event",category:["api"],type:["start"],action:"execution.start"}});let c="unknown";try{let r=await a();try{c=t.signal.aborted?"cancelled":cX(r)?"input_required":"isError"in r&&!0===r.isError?"failure":"success","failure"===c&&(l={message:"Operation returned an error result"})}catch{}return r}catch(r){throw l={message:"cancelled"==(c=t.signal.aborted?"cancelled":"failure")?"Operation cancelled":"Operation threw an exception"},r}finally{try{n({...o,log:{level:"failure"===c?"error":"info"},event:{kind:"event",category:["api"],type:["end"],action:"execution.end",duration:Math.round((performance.now()-s)*1e6),outcome:"success"===c?"success":"failure"===c?"failure":"unknown"},xmcp:{...o.xmcp,status:c},...l?{error:l}:{}})}catch{}}},registerResource(t,n){try{"string"==typeof n?r.set(new URL(n).href,t):i.push({name:t,template:n})}catch{}}}}():void 0;s&&o.unshift(s.middleware),mH.clear();let l="undefined"==typeof COMPONENTS_CONFIG?void 0:COMPONENTS_CONFIG;return!function(t,r,i){let n=t.server,a=n.setRequestHandler,o=mW(r);n.setRequestHandler=(t,...r)=>{if(mG.has(t)&&1===r.length&&"function"==typeof r[0]){let t=r[0];r[0]=(r,i)=>o({method:r.method,params:r.params??{}},i,()=>t(r,i))}Reflect.apply(a,n,[t,...r])};try{i()}finally{n.setRequestHandler=a}}(t,o,()=>{var a,c;!function(t,r,i=[]){r.forEach((r,n)=>{var a,o;let s,l,c,u={name:mX(n),description:"No description provided"},{default:d,metadata:p,schema:m,outputSchema:h}=r;if("object"==typeof p&&null!==p&&Object.assign(u,p),!1===u.enabled)return;if("function"==typeof d&&"__x402"in d){let t=U.g.__XMCP_X402_REGISTRY;t&&t.set(u.name,d.__x402)}let f={};if(mY(m)?f=m:null!=m&&console.warn(`Invalid schema for tool "${u.name}" at ${n}. Expected Record<string, z.ZodType>`),null!=h)if(mY(h))s=h;else throw Error(`Invalid outputSchema for tool "${u.name}" at ${n}. Expected Record<string, z.ZodType>`);u.annotations={...u.annotations??{}},void 0===u.annotations.title&&(u.annotations.title=u.name),u._meta={...mK(u)._meta};let g=mF(n),y=!!(a=u._meta)&&"object"==typeof a&&"ui"in a&&"object"==typeof a.ui||g,v=u._meta;if(y){let t=`ui://app/${u.name}.html`;u._meta.ui||(u._meta.ui={}),u._meta.ui.resourceUri||(u._meta.ui.resourceUri=t);let r=function(t){let r={},i={};if(t.ui&&"object"==typeof t.ui){let n=t.ui,a={},o={};for(let[t,r]of Object.entries(n))mV.includes(t)?a[t]=r:mJ.includes(t)?o[t]=r:a[t]=r;Object.keys(a).length>0&&(r.ui=a),Object.keys(o).length>0&&(i.ui=o)}for(let[i,n]of Object.entries(t))"ui"!==i&&(r[i]=n);return{toolMeta:r,resourceMeta:i}}(v);v=r.toolMeta;let i=r.resourceMeta;i.ui=i.ui||{},i.ui.csp=i.ui.csp||{},i.ui.csp.resourceDomains=i.ui.csp.resourceDomains||[],i.ui.csp.resourceDomains.includes("https://esm.sh")||i.ui.csp.resourceDomains.push("https://esm.sh"),mH.add(u.name,{name:u.name,uri:t,handler:d,mimeType:"text/html;profile=mcp-app",_meta:i,toolPath:g?n:void 0})}let _=mD(v),b=y?_:void 0;l=mF(n)&&y?async(t,r)=>({content:[{type:"text",text:""}],_meta:b,structuredContent:{args:t}}):function(t,r,i,n="unknown-tool"){return async(a,o)=>{let s,l,c=t(a,(s=mU(o),l=function(t){if(!t)return;let r={};return t.headers.forEach((t,i)=>{r[i]=t}),r}(o.http?.req),{signal:o.mcpReq.signal,authInfo:o.http?.authInfo,sessionId:o.sessionId,_meta:o.mcpReq._meta,requestId:o.mcpReq.id,requestInfo:l?{headers:l}:void 0,clientInfo:s,sendNotification:t=>o.mcpReq.notify(t),sendRequest:(t,r,i)=>o.mcpReq.send(t,r,i),elicit:(t,r)=>mx(o,t,r),sample:(t,r)=>mA(o,t,r),inputResponses:o.mcpReq.inputResponses,requestState:o.mcpReq.requestState}));if(c instanceof Promise&&(c=await c),cX(c))return c;if("string"==typeof c||"number"==typeof c){if(i){let t=Object.entries(i);if(1===t.length){let[r,i]=t[0];try{return i.parse(c),{content:[{type:"text",text:"number"==typeof c?`${c}`:c}],structuredContent:{[r]:c}}}catch{}}}return mZ(r)?{content:[{type:"text",text:""}],structuredContent:{args:a},_meta:r}:{content:[{type:"text",text:"number"==typeof c?`${c}`:c}]}}if(!i||!c||"object"!=typeof c||Array.isArray(c)||"structuredContent"in c||"content"in c&&Array.isArray(c.content)||"_meta"in c||"isError"in c||(mM(c,i,n,"returned data that does not match outputSchema"),c={structuredContent:c}),c&&"object"==typeof c&&"_meta"in c&&!("content"in c)&&!("structuredContent"in c)){let t=c._meta;if(mZ(t))return{content:[{type:"text",text:""}],_meta:t}}if(!c||"object"!=typeof c){let t=null===c?"null":typeof c,r=void 0===c?"undefined":null===c?"null":"object"==typeof c?JSON.stringify(c,null,2):String(c);throw Error(`Tool handler must return a CallToolResult, string, or number. Got ${t}: ${r}
|
|
86
84
|
|
|
87
85
|
Expected CallToolResult format:
|
|
88
86
|
{
|
|
@@ -132,7 +130,7 @@ Or both for backwards compatibility:
|
|
|
132
130
|
{
|
|
133
131
|
content: [{ type: "text", text: "fallback" }],
|
|
134
132
|
structuredContent: { your: "data" }
|
|
135
|
-
}`)}if(p&&!u&&!d){let{isError:t,...r}=c,i=Object.keys(r).length>0?`Tool execution failed: ${JSON.stringify(r)}`:"Tool execution failed";c.content=[{type:"text",text:i}],u=!0}if(i&&d&&!p&&
|
|
133
|
+
}`)}if(p&&!u&&!d){let{isError:t,...r}=c,i=Object.keys(r).length>0?`Tool execution failed: ${JSON.stringify(r)}`:"Tool execution failed";c.content=[{type:"text",text:i}],u=!0}if(i&&d&&!p&&mM(c.structuredContent,i,n,"returned structuredContent that does not match outputSchema"),!u&&d&&(c.content=[{type:"text",text:JSON.stringify(c.structuredContent)}],u=!0),u)for(let t=0;t<c.content.length;t++){let r=c.content[t],i=mz(r);if(!i.valid)throw Error(`Invalid content item at index ${t}: ${i.error}
|
|
136
134
|
|
|
137
135
|
Content item: ${JSON.stringify(r,null,2)}
|
|
138
136
|
|
|
@@ -149,7 +147,7 @@ Expected format:
|
|
|
149
147
|
key: "value",
|
|
150
148
|
nested: { data: "here" }
|
|
151
149
|
}
|
|
152
|
-
}`)}}return c}}(d,b,s,u.name);let S={title:u.annotations?.title,description:u.description,inputSchema:
|
|
150
|
+
}`)}}return c}}(d,b,s,u.name);let S={title:u.annotations?.title,description:u.description,inputSchema:mi(f),outputSchema:s?mi(s,{strict:!0}):void 0,annotations:u.annotations,icons:u.icons,_meta:_};t.registerTool(u.name,S,(o=u.name,c=mW(i),(t,r)=>c({method:"tools/call",params:{name:o,arguments:t}},r,()=>l(t,r))))})}(t,m0(r,l),o),m0(i,l).forEach((r,i)=>{let n=mX(i),a={name:n,title:n,description:"No description provided"},o={},{default:s,metadata:l,schema:c}=r;if("object"==typeof l&&null!==l&&Object.assign(a,l),!1===a.enabled)return;let u=function(t,r="assistant"){return async(i,n)=>{let a,o=t(i,n);if(o instanceof Promise&&(o=await o),Array.isArray(o)||null!==o&&"object"==typeof o&&"messages"in o){let t=Array.isArray(o)?{messages:o}:o,r=await ux.GetPromptResult["~standard"].validate(t);if(r.issues){let t=r.issues.map(t=>{let r=t.path?.map(t=>"object"==typeof t?t.key:t).join(".");return`${r||"result"}: ${t.message}`});throw Error(`Invalid prompt result: ${t.join("; ")}`)}return t}if("string"==typeof o||"number"==typeof o)a={type:"text",text:"number"==typeof o?`${o}`:o};else{let t=mz(o);if(t.valid)a=o;else{let r=null===o?"null":typeof o,i=void 0===o?"undefined":null===o?"null":"object"==typeof o?JSON.stringify(o,null,2):String(o);throw Error(`Prompt handler must return a PromptContent object, string, number, PromptMessage[], or GetPromptResult. Got ${r}: ${i}
|
|
153
151
|
|
|
154
152
|
Validation error: ${t.error}
|
|
155
153
|
|
|
@@ -162,7 +160,7 @@ Expected formats:
|
|
|
162
160
|
- Image content: { type: "image", data: "base64data", mimeType: "image/jpeg" }
|
|
163
161
|
- Audio content: { type: "audio", data: "base64data", mimeType: "audio/mpeg" }
|
|
164
162
|
- Resource link: { type: "resource_link", name: "resource name", uri: "resource://uri" }
|
|
165
|
-
- All content types support an optional "_meta" object property`)}}if("user"!==r&&"assistant"!==r)throw Error(`Invalid role: ${r}`);return{messages:[{role:r,content:a}]}}}(s,a.role||"assistant");
|
|
163
|
+
- All content types support an optional "_meta" object property`)}}if("user"!==r&&"assistant"!==r)throw Error(`Invalid role: ${r}`);return{messages:[{role:r,content:a}]}}}(s,a.role||"assistant");mY(c)?Object.assign(o,c):null!=c&&console.warn(`Invalid schema for prompt "${a.name}" at ${i}. Expected Record<string, z.ZodType>`),t.registerPrompt(a.name,{title:a.title,description:a.description,icons:a.icons,_meta:mK(a)._meta,argsSchema:mi(o)},u)}),a=m0(n,l),c=s?.registerResource,[...mH.getAll()].forEach(([r,i])=>{let n=i.mimeType||"text/html;profile=mcp-app",a=i?._meta?mD(i._meta):void 0,o={name:i.name,description:`Auto-generated resource for ${i.name} tool`,mimeType:i.mimeType,_meta:a},s=async(t,r)=>{if(i.mimeType&&i.toolPath)try{var a;let t,r,o=(a=i.toolPath,IS_CLOUDFLARE?function(t){let{normalizedPath:r,baseName:i}=m6(t),n=5381;for(let t=0;t<r.length;t++)n=Math.imul(n,33)+r.charCodeAt(t)>>>0;let a=n.toString(16).slice(0,6).padStart(6,"0");return`${i}_${a}`}(a):function(t){let{normalizedPath:r,baseName:i}=m6(t),n=U(Object(function(){var t=Error("Cannot find module 'crypto'");throw t.code="MODULE_NOT_FOUND",t}())).createHash("md5").update(r).digest("hex").slice(0,6);return`${i}_${n}`}(a)),s=function(t){if(INJECTED_CLIENT_BUNDLES)return INJECTED_CLIENT_BUNDLES[t]||null;if(!IS_CLOUDFLARE)try{let r=U(Object(function(){var t=Error("Cannot find module 'fs'");throw t.code="MODULE_NOT_FOUND",t}())),i=U(Object(function(){var t=Error("Cannot find module 'path'");throw t.code="MODULE_NOT_FOUND",t}()));for(let n of[i.join(process.cwd(),"dist","client"),i.join(process.cwd(),"client")]){let a=i.join(n,`${t}.bundle.js`),o=i.join(n,`${t}.bundle.css`);if(r.existsSync(a)){let t,i=r.readFileSync(a,"utf-8");return r.existsSync(o)&&(t=r.readFileSync(o,"utf-8")),{js:i,css:t}}}}catch{}return null}(o);if(!s)throw Error(`React client bundle not found for "${i.name}" (bundle: "${o}").
|
|
166
164
|
React tool bundles are generated automatically when you run "xmcp build" (or "xmcp dev").
|
|
167
165
|
Please re-run the build so the framework can regenerate the bundle.`);let l=s.js,c=s.css,u=(t=`
|
|
168
166
|
<script type="module">
|
|
@@ -217,7 +215,7 @@ Please re-run the build so the framework can regenerate the bundle.`);let l=s.js
|
|
|
217
215
|
<div id="root"></div>
|
|
218
216
|
${t}
|
|
219
217
|
</body>
|
|
220
|
-
</html>`);return{contents:[{uri:i.uri,text:u,mimeType:n,_meta:i._meta}]}}catch(t){throw console.error(`React failed for ${i.name}:`,t),t}let o=i.handler({},r);if(o instanceof Promise&&(o=await o),"string"==typeof o)return{contents:[{uri:i.uri,text:o,mimeType:n,_meta:i._meta}]};if(o&&"object"==typeof o&&"_meta"in o&&!("content"in o))return{contents:[{uri:i.uri,text:"",mimeType:n,_meta:i._meta}]};if(o&&"object"==typeof o&&"content"in o&&Array.isArray(o.content)){let t=o.content.find(t=>"text"===t.type);if(t&&"text"===t.type&&"string"==typeof t.text)return{contents:[{uri:i.uri,text:t.text,mimeType:n,_meta:i._meta}]}}return{contents:[{uri:i.uri,text:"",mimeType:n,_meta:i._meta}]}};c?.(i.name,i.uri),t.registerResource(i.name,i.uri,o,s)}),a.forEach((r,i)=>{let n={name:
|
|
218
|
+
</html>`);return{contents:[{uri:i.uri,text:u,mimeType:n,_meta:i._meta}]}}catch(t){throw console.error(`React failed for ${i.name}:`,t),t}let o=i.handler({},r);if(o instanceof Promise&&(o=await o),"string"==typeof o)return{contents:[{uri:i.uri,text:o,mimeType:n,_meta:i._meta}]};if(o&&"object"==typeof o&&"_meta"in o&&!("content"in o))return{contents:[{uri:i.uri,text:"",mimeType:n,_meta:i._meta}]};if(o&&"object"==typeof o&&"content"in o&&Array.isArray(o.content)){let t=o.content.find(t=>"text"===t.type);if(t&&"text"===t.type&&"string"==typeof t.text)return{contents:[{uri:i.uri,text:t.text,mimeType:n,_meta:i._meta}]}}return{contents:[{uri:i.uri,text:"",mimeType:n,_meta:i._meta}]}};c?.(i.name,i.uri),t.registerResource(i.name,i.uri,o,s)}),a.forEach((r,i)=>{let n={name:mX(i),description:"No description provided"},{default:a,metadata:o,schema:s,complete:l}=r;if("object"==typeof o&&null!==o&&Object.assign(n,o),!1===n.enabled)return;let u={};mY(s)?u=s:null!=s&&console.warn(`Invalid schema for resource "${n.name}" at ${i}. Expected Record<string, z.ZodType>`);let d=m7(i);if(!d)return void console.warn(`Skipping resource "${n.name}" at ${i}: Invalid file path format`);let p=d.uriTemplate;n.mimeType&&n.mimeType.includes("html")&&(p=p.endsWith(".html")?p:`${p}.html`);let m=function(t,r,i={}){let n=m7(r);if(!n)throw Error(`Invalid resource file path: ${r}. Must follow (scheme)/path/[param] convention.`);return async(r,a)=>{let o=t(function(t,r,i){let n={},a={};if(0===r.parameters.length)return a;let o=r.uriTemplate.split("://")[1]||"",s=t.split("://")[1]||"",l=o.split("/"),c=s.split("/");for(let t=0;t<l.length&&t<c.length;t++){let r=l[t],i=c[t],a=r.match(/^\{(.+)\}$/);a&&(n[a[1]]=i)}for(let t of r.parameters){let r=n[t],o=i[t];if(void 0===r)throw Error(`Missing required parameter: ${t}`);if(!o){a[t]=r;continue}try{a[t]=o.parse(r)}catch(i){throw Error(`Invalid parameter "${t}": ${r}. Validation error: ${i instanceof Error?i.message:String(i)}`)}}return a}(r.href,n,i),a);if(o instanceof Promise&&(o=await o),cX(o))return o;if("string"==typeof o)return{contents:[{uri:r.href,text:o}]};if(!o||"object"!=typeof o||!Array.isArray(o.contents)){let t=null===o?"null":typeof o,r=void 0===o?"undefined":null===o?"null":"object"==typeof o?JSON.stringify(o,null,2):String(o);throw Error(`Resource handler must return a ReadResourceResult, InputRequiredResult, or string. Got ${t}: ${r}
|
|
221
219
|
|
|
222
220
|
Expected ReadResourceResult format:
|
|
223
221
|
{
|
|
@@ -226,7 +224,7 @@ Expected ReadResourceResult format:
|
|
|
226
224
|
{ uri: "resource://uri", mimeType: "application/json", text: "json content" },
|
|
227
225
|
{ uri: "resource://uri", blob: base64data }
|
|
228
226
|
]
|
|
229
|
-
}`)}return o.contents.forEach(t=>{t.uri||(t.uri=r.href)}),o}}(a,i,u);if("direct"===d.type)c?.(n.name,p),t.registerResource(n.name,p,
|
|
227
|
+
}`)}return o.contents.forEach(t=>{t.uri||(t.uri=r.href)}),o}}(a,i,u);if("direct"===d.type)c?.(n.name,p),t.registerResource(n.name,p,mK(n),m);else{let r=Object.create(null);for(let t of d.parameters)l&&Object.hasOwn(l,t)&&(r[t]=l[t]);let i=new dp(p,{list:void 0,complete:r}),o=async(t,r,i)=>{let n={};for(let t of d.parameters){let i=r[t],a=u[t];if(void 0===i)throw Error(`Missing required parameter: ${t}. Available variables: ${Object.keys(r)}`);a?n[t]=a.parse(i):n[t]=i}let o=a(n,i);return o instanceof Promise&&(o=await o),"string"==typeof o?{contents:[{uri:t.href,text:o}]}:o};c?.(n.name,i),t.registerResource(n.name,i,mK(n),o)}})}),t}async function hs(){let{toolModules:t,skippedTools:r}=await he(hr);return ht(r),t}async function hl(){let{promptModules:t,skippedPrompts:r}=await m2(hi);return m9(r),t}async function hc(){let{resourceModules:t,skippedResources:r}=await m5(hn);return m3(r),t}async function hu(){let{instructions:t,...r}=ha,i=new dd(r,{instructions:t}),n=hs(),a=hl(),o=hc(),[s,l,c]=await Promise.all([n,a,o]);return ho(i,s,l,c)}let hd="This MCP server was bootstrapped with xmcp.",hp={cursor:`
|
|
230
228
|
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
|
|
231
229
|
<g clip-path="url(#cursor)">
|
|
232
230
|
<path d="M18.1937 4.73376L10.1872 0.111231C9.93007 -0.0372398 9.61283 -0.0372398 9.35573 0.111231L1.34956 4.73376C1.13344 4.85855 1 5.08934 1 5.33929V14.6606C1 14.9106 1.13344 15.1414 1.34956 15.2662L9.3561 19.8887C9.6132 20.0372 9.93044 20.0372 10.1875 19.8887L18.1941 15.2662C18.4102 15.1414 18.5436 14.9106 18.5436 14.6606V5.33929C18.5436 5.08934 18.4102 4.85855 18.1941 4.73376H18.1937ZM17.6908 5.71291L9.96164 19.1001C9.90939 19.1903 9.77145 19.1535 9.77145 19.049V10.2832C9.77145 10.108 9.67785 9.94603 9.526 9.85808L1.9348 5.47536C1.84459 5.42311 1.88143 5.28517 1.98592 5.28517H17.4442C17.6637 5.28517 17.8009 5.5231 17.6912 5.71329H17.6908V5.71291Z" fill="currentColor" />
|
|
@@ -281,7 +279,7 @@ Expected ReadResourceResult format:
|
|
|
281
279
|
</clipPath>
|
|
282
280
|
</defs>
|
|
283
281
|
</svg>
|
|
284
|
-
`},
|
|
282
|
+
`},hm=String.raw`
|
|
285
283
|
:root {
|
|
286
284
|
color-scheme: dark;
|
|
287
285
|
--brand-white: #f7f7f7;
|
|
@@ -580,13 +578,13 @@ Expected ReadResourceResult format:
|
|
|
580
578
|
clip: rect(0, 0, 0, 0);
|
|
581
579
|
border: 0;
|
|
582
580
|
}
|
|
583
|
-
`;function
|
|
581
|
+
`;function hh(t,r){let i={};if(void 0!==t.origin){if(!0===t.origin)r&&(i["Access-Control-Allow-Origin"]=r);else if(!1!==t.origin)if(Array.isArray(t.origin)){let n=r&&t.origin.includes(r)?r:t.origin[0]||"*";i["Access-Control-Allow-Origin"]=n}else i["Access-Control-Allow-Origin"]=String(t.origin)}return void 0!==t.methods&&(i["Access-Control-Allow-Methods"]=Array.isArray(t.methods)?t.methods.join(","):String(t.methods)),void 0!==t.allowedHeaders&&(i["Access-Control-Allow-Headers"]=Array.isArray(t.allowedHeaders)?t.allowedHeaders.join(","):String(t.allowedHeaders)),void 0!==t.exposedHeaders&&(i["Access-Control-Expose-Headers"]=Array.isArray(t.exposedHeaders)?t.exposedHeaders.join(","):String(t.exposedHeaders)),"boolean"==typeof t.credentials&&(i["Access-Control-Allow-Credentials"]=String(t.credentials)),"number"==typeof t.maxAge&&(i["Access-Control-Max-Age"]=String(t.maxAge)),i}let hf=HTTP_CORS_CONFIG;function hg(t,r){let i=new Headers(t.headers);for(let[t,n]of Object.entries(hh(hf,r)))i.set(t,n);return new Response(t.body,{status:t.status,statusText:t.statusText,headers:i})}let hy=HTTP_CONFIG,hv=TEMPLATE_CONFIG,h_=INJECTED_MIDDLEWARE,hb=null;async function hS(){return h_?(hb||(hb=(async()=>{try{var t;let r=await h_();return t=r?.default,Array.isArray(t)?t.filter(hw):hw(t)?[t]:t&&"object"==typeof t&&"middleware"in t&&"function"==typeof t.middleware?[t.middleware]:[]}catch(t){return console.error("[Cloudflare-MCP] Failed to load middleware:",t),[]}})()),hb):[]}function hw(t){return"function"==typeof t}async function hk(t){let r=await hS();if(0===r.length)return{};let i={auth:void 0,setAuth:t=>{i.auth=t}};for(let n of r){let r=await n(t,i);if(r instanceof Response)return{response:r,authInfo:i.auth}}return{authInfo:i.auth}}function hx(t,...r){hy.debug&&console.log(`[Cloudflare-MCP] ${t}`,...r)}uU();let hR=function(t,r={}){var i;let{legacy:n,onerror:a,responseMode:o}=r;if("function"==typeof n)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,p=!1,m=t=>{try{a?.(t)}catch{}},h=r.bus??new dr(m),f={toolsChanged:()=>h.publish({kind:"tools_list_changed"}),promptsChanged:()=>h.publish({kind:"prompts_list_changed"}),resourcesChanged:()=>h.publish({kind:"resources_list_changed"}),resourceUpdated:t=>h.publish({kind:"resource_updated",uri:t})},g=function(t){let{bus:r,onerror:i}=t,n=t.maxSubscriptions??1024,a=t.keepAliveMs??15e3,o=new Set;return{serve:function(t,s,l,c){var u,d,p;let m,h,f,g,y,v,_;if(o.size>=n)return i?.(Error(`subscriptions/listen refused: subscription limit reached (${n})`)),di(t.id,-32603,"Subscription limit reached");let b=(u=t,(y=cL(cN).validateRequest("subscriptions/listen",u)).ok?y.value.params?.notifications:void 0);if(void 0===b)return di(t.id,-32602,"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter");let S=(d=b,p=l,v={},_=t=>void 0===p||!0===t,!0===d.toolsListChanged&&_(p?.tools?.listChanged)&&(v.toolsListChanged=!0),!0===d.promptsListChanged&&_(p?.prompts?.listChanged)&&(v.promptsListChanged=!0),!0===d.resourcesListChanged&&_(p?.resources?.listChanged)&&(v.resourcesListChanged=!0),void 0!==d.resourceSubscriptions&&d.resourceSubscriptions.length>0&&_(p?.resources?.subscribe)&&(v.resourceSubscriptions=[...d.resourceSubscriptions]),v),w=t.id,k=new TextEncoder,x=!1,R=t=>{if(!x)try{m.enqueue(k.encode(t))}catch(t){i?.(t instanceof Error?t:Error(String(t)))}},$=(t,r)=>{R(`event: message
|
|
584
582
|
data: ${JSON.stringify({jsonrpc:"2.0",method:t,params:r})}
|
|
585
583
|
|
|
586
|
-
`)},C=t=>{if(!
|
|
587
|
-
data: ${JSON.stringify({jsonrpc:"2.0",id:w,result:{resultType:"complete",_meta:{[
|
|
584
|
+
`)},C=t=>{if(!x){t&&R(`event: message
|
|
585
|
+
data: ${JSON.stringify({jsonrpc:"2.0",id:w,result:{resultType:"complete",_meta:{[aX]:w,[aK]:c}}})}
|
|
588
586
|
|
|
589
|
-
`),k=!0;try{h?.()}catch(t){i?.(t instanceof Error?t:Error(String(t)))}void 0!==f&&clearInterval(f),g?.(),o.delete(C);try{m.close()}catch{}}},T=new ReadableStream({start(t){m=t;let i=da({method:"notifications/subscriptions/acknowledged",params:{notifications:S}},w);$(i.method,i.params),h=r.subscribe(t=>{if(k||!function(t,r){switch(r.kind){case"tools_list_changed":return!0===t.toolsListChanged;case"prompts_list_changed":return!0===t.promptsListChanged;case"resources_list_changed":return!0===t.resourcesListChanged;case"resource_updated":return void 0!==t.resourceSubscriptions&&t.resourceSubscriptions.includes(r.uri)}}(S,t))return;let r=da(function(t){switch(t.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed"};case"prompts_list_changed":return{method:"notifications/prompts/list_changed"};case"resources_list_changed":return{method:"notifications/resources/list_changed"};case"resource_updated":return{method:"notifications/resources/updated",params:{uri:t.uri}}}}(t),w);$(r.method,r.params)}),f=dr(a,()=>R(": keepalive\n\n")),o.add(C)},cancel(){C(!1)}});if(void 0!==s)if(s.aborted)C(!1);else{let t=()=>C(!1);s.addEventListener("abort",t,{once:!0}),g=()=>s.removeEventListener("abort",t)}return new Response(T,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let t of o)t(!0)},get openCount(){return o.size}}}({bus:h,maxSubscriptions:r.maxSubscriptions??1024,keepAliveMs:r.keepAliveMs??15e3,onerror:m});"json"===o&&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"===n?void 0:(i=r.keepAliveMs,async(r,n)=>{if("POST"!==r.method.toUpperCase())return d$(405,-32e3,"Method not allowed.");try{let a=await t({era:"legacy",...n?.authInfo!==void 0&&{authInfo:n.authInfo},requestInfo:r}),o=new dk({sessionIdGenerator:void 0,...void 0!==i&&{keepAliveMs:i}});await a.connect(o);let s=()=>{o.close().catch(()=>{}),a.close().catch(()=>{})};r.signal?.addEventListener("abort",s,{once:!0});let l=await o.handleRequest(r,{...n?.authInfo!==void 0&&{authInfo:n.authInfo},...n?.parsedBody!==void 0&&{parsedBody:n.parsedBody}});if(null===l.body||"text/event-stream"!==uN(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 t=>{try{let{done:r,value:i}=await c.read();if(r){d(),t.close();return}void 0!==i&&t.enqueue(i)}catch(r){d(),t.error(r)}},cancel:t=>(d(),c.cancel(t).catch(()=>{}))});return new Response(p,{status:l.status,statusText:l.statusText,headers:l.headers})}catch(t){try{m?.(dT(t))}catch{}return dO(dR(n?.parsedBody))}});async function v(i,n,a){var p,h;let f=i.classification.revision;if(void 0===f||!lX.includes(f)){let t=new cb({supported:[...lX],requested:f??"unknown"});return m(t),d$(400,t.code,t.message,t.data,dR(i.message))}let y=function(t,r){if("request"!==r.messageKind)return;let i=r.message.method;if(void 0===t.mcpMethodHeader)return un("method-header-missing","(missing)",`the body names method ${i} but the required Mcp-Method header is absent`,"standard-header-validation");let n=Object.hasOwn(ua,i)?ua[i]:void 0;if(void 0===n)return;let a=r.message.params?.[n],o="string"==typeof a?a:void 0;if(void 0===t.mcpNameHeader){if(void 0===o)return;return un("name-header-missing","(missing)",`the body carries params.${n}="${o}" but the required Mcp-Name header is absent`,"standard-header-validation")}let s=uo(t.mcpNameHeader),l=c8(s);return void 0===l?un("name-header-invalid-encoding",s,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==o&&l!==o?un("name-header-mismatch",s,`the body carries params.${n}="${o}" but the Mcp-Name header names "${l}"`,"standard-header-validation"):void 0}({httpMethod:n.method,mcpMethodHeader:n.headers.get("mcp-method")??void 0,mcpNameHeader:n.headers.get("mcp-name")??void 0},i);if(void 0!==y)return m(Error(`Rejected inbound request (${y.cell}): ${y.message}`)),dC(y,dR(i.message));let v="request"===i.messageKind?cJ(i.message.params):void 0,_=v?.[aX];if("request"===i.messageKind){let t=Object.hasOwn(lW,p=i.message.method)?lW[p]:void 0;if(void 0!==t){let r=lK(t,_);if(void 0!==r){let t=new cS({requiredCapabilities:r});return m(t),d$(ur[t.code]??400,t.code,t.message,t.data,i.message.id)}}}let b=await t({era:"modern",...void 0!==a&&{authInfo:a},requestInfo:n}),S=b instanceof dp?b.server:b;if("request"===i.messageKind&&"subscriptions/listen"===i.message.method){let t=S.getCapabilities(),r=d(S);return b.close().catch(m),g.serve(i.message,n.signal,t,r)}if("request"===i.messageKind&&"tools/call"===i.message.method&&b instanceof dp){let t=i.message.params,r="string"==typeof t?.name?t.name:void 0,a=void 0===r?void 0:b.toolInputSchemaJson(r);if(void 0!==a){let r=c9(a);if(r.valid&&r.declarations.length>0){let a=function(t,r,i){for(let n of t){let t=`Mcp-Param-${n.headerName}`,a=i.get(t),o=function(t,r){let i=t;for(let t of r){if(null===i||"object"!=typeof i)return;i=i[t]}return i}(r,n.path);if(null==o)continue;let s=function(t){if("string"==typeof t)return t;if("boolean"==typeof t)return t?"true":"false";if("number"==typeof t){if(!Number.isFinite(t)||Number.isInteger(t)&&!Number.isSafeInteger(t))return;return String(t)}}(o);if(void 0===s)continue;if(null===a)return ue("param-header-missing",t,`the body carries ${c3(n.path)}=${JSON.stringify(o)} but the ${t} header is absent`);let l=c8(a);if(void 0===l)return ue("param-header-invalid-encoding",t,`the ${t} header carries an invalid Base64 sentinel value`);if(!(("integer"===n.type||"number"===n.type)&&c7.test(l)&&"number"==typeof o?Number(l)===o:l===s))return ue("param-header-mismatch",t,`the ${t} header decodes to ${JSON.stringify(l)} but the body carries ${c3(n.path)}=${JSON.stringify(o)}`)}}(r.declarations,t?.arguments,n.headers);if(void 0!==a)return b.close().catch(m),m(Error(`Rejected inbound request (${a.cell}): ${a.message}`)),dC(a,i.message.id)}}}l(S,f),u(S,lX),void 0!==v&&(h={clientInfo:v[aK],clientCapabilities:_},c(S,h));let w=S.onclose;s.add(S),S.onclose=()=>{s.delete(S),w?.()};try{let t=await dx(b,i.message,{classification:i.classification,request:n,...void 0!==a&&{authInfo:a},...void 0!==o&&{responseMode:o},...void 0!==r.keepAliveMs&&{keepAliveMs:r.keepAliveMs}});return"notification"===i.messageKind&&queueMicrotask(()=>void S.close().catch(()=>{})),t}catch(t){if(t instanceof lB&&t.code===lV.ConnectionClosed)return new Response(null,{status:499});return await S.close().catch(()=>{}),s.delete(S),m(dT(t)),dO(dR(i.message))}}async function _(t,r,i,n){if(void 0!==y)return y(r,{...void 0!==i&&{authInfo:i},...void 0!==n&&{parsedBody:n}});let a=function(t,r){switch(t.reason){case"http-method":return ui("http-method","modern-only-method-not-allowed",405,new cy(-32e3,"Method not allowed."),!0);case"batch":return ui("jsonrpc-shape","modern-only-batch-not-supported",400,new cy(cg.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 cy(cg.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let i=t.requestedVersion;return ui("era-classification","modern-only-missing-envelope",400,void 0===i?new cy(cg.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...r]}):new cb({supported:[...r],requested:i}),!0)}}}(t,lX);return void 0===a?new Response(null,{status:202}):(m(Error(`Rejected 2025-era request on a modern-only endpoint (${a.cell}): ${a.message}`)),dC(a,dR(n)))}async function b(t,r){let i=r?.authInfo;if("POST"===t.method.toUpperCase()&&!uA(t.headers.get("content-type")))return m(Error("Unsupported Media Type: Content-Type must be application/json")),d$(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let n=await dP(t,r?.parsedBody);if("unreadable-body"===n.step)return d$(400,-32700,"Parse error: the request body could not be read");if("no-json-body"===n.step)return void 0!==y?y(n.forwardRequest,{...void 0!==i&&{authInfo:i}}):d$(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:a,body:o,parsedBody:s,forwardRequest:l}=n;try{switch(a.kind){case"reject":return m(Error(`Rejected inbound request (${a.cell}): ${a.message}`)),dC(a,dR(o));case"modern":return await v(a,t,i);case"legacy":return await _(a,l,i,s)}}catch(t){return m(dT(t)),dO(dR(o))}}return{fetch:async(t,r)=>{if(p)throw Error("This MCP handler has been closed");try{return await b(t,r)}catch(t){return m(dT(t)),dO(dR(r?.parsedBody))}},notify:f,bus:h,close:async()=>{p=!0,g.closeAll();let t=[...s].map(t=>t.close().catch(()=>{}));s.clear(),await Promise.all(t)}}}(h_,{legacy:"stateless",responseMode:"json",onerror:t=>hq("MCP handler error:",t)});async function hz(t,r,i,n){let a=crypto.randomUUID(),o=await t.clone().json().catch(()=>void 0),s=(t=>{for(let r of Array.isArray(t)?t:[t]){let t=mx(r);if(t)return t}})(o),l={};return t.headers.forEach((t,r)=>{l[r]=t}),mv({id:a,headers:l,clientInfo:s},async()=>{try{let i=await hj.fetch(t,{authInfo:n,parsedBody:o});return hR(i,r)}catch(t){return console.error("[Cloudflare-MCP] Error handling MCP request:",t),hR(new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null}),{status:500,headers:{"Content-Type":"application/json"}}),r)}})}let hN={async fetch(t,r,i){let n=new URL(t.url).pathname,a=t.headers.get("origin");if(hq(`${t.method} ${n}`),"OPTIONS"===t.method)return new Response(null,{status:204,headers:new Headers(hx(hk,a))});let o=h$.endpoint?.startsWith("/")?h$.endpoint:`/${h$.endpoint||"mcp"}`;if("/health"===n)return hR(new Response(JSON.stringify({status:"ok",transport:"cloudflare-workers",mode:"stateless",auth:"none"}),{status:200,headers:{"Content-Type":"application/json"}}),a);if("/"===n&&"GET"===t.method){var s,l;return hR(new Response((s=hC.name,l=hC.description,`
|
|
587
|
+
`),x=!0;try{h?.()}catch(t){i?.(t instanceof Error?t:Error(String(t)))}void 0!==f&&clearInterval(f),g?.(),o.delete(C);try{m.close()}catch{}}},T=new ReadableStream({start(t){m=t;let i=dn({method:"notifications/subscriptions/acknowledged",params:{notifications:S}},w);$(i.method,i.params),h=r.subscribe(t=>{if(x||!function(t,r){switch(r.kind){case"tools_list_changed":return!0===t.toolsListChanged;case"prompts_list_changed":return!0===t.promptsListChanged;case"resources_list_changed":return!0===t.resourcesListChanged;case"resource_updated":return void 0!==t.resourceSubscriptions&&t.resourceSubscriptions.includes(r.uri)}}(S,t))return;let r=dn(function(t){switch(t.kind){case"tools_list_changed":return{method:"notifications/tools/list_changed"};case"prompts_list_changed":return{method:"notifications/prompts/list_changed"};case"resources_list_changed":return{method:"notifications/resources/list_changed"};case"resource_updated":return{method:"notifications/resources/updated",params:{uri:t.uri}}}}(t),w);$(r.method,r.params)}),f=dt(a,()=>R(": keepalive\n\n")),o.add(C)},cancel(){C(!1)}});if(void 0!==s)if(s.aborted)C(!1);else{let t=()=>C(!1);s.addEventListener("abort",t,{once:!0}),g=()=>s.removeEventListener("abort",t)}return new Response(T,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let t of o)t(!0)},get openCount(){return o.size}}}({bus:h,maxSubscriptions:r.maxSubscriptions??1024,keepAliveMs:r.keepAliveMs??15e3,onerror:m});"json"===o&&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"===n?void 0:(i=r.keepAliveMs,async(r,n)=>{if("POST"!==r.method.toUpperCase())return dR(405,-32e3,"Method not allowed.");try{let a=await t({era:"legacy",...n?.authInfo!==void 0&&{authInfo:n.authInfo},requestInfo:r}),o=new dk({sessionIdGenerator:void 0,...void 0!==i&&{keepAliveMs:i}});await a.connect(o);let s=()=>{o.close().catch(()=>{}),a.close().catch(()=>{})};r.signal?.addEventListener("abort",s,{once:!0});let l=await o.handleRequest(r,{...n?.authInfo!==void 0&&{authInfo:n.authInfo},...n?.parsedBody!==void 0&&{parsedBody:n.parsedBody}});if(null===l.body||"text/event-stream"!==uA(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 t=>{try{let{done:r,value:i}=await c.read();if(r){d(),t.close();return}void 0!==i&&t.enqueue(i)}catch(r){d(),t.error(r)}},cancel:t=>(d(),c.cancel(t).catch(()=>{}))});return new Response(p,{status:l.status,statusText:l.statusText,headers:l.headers})}catch(t){try{m?.(dC(t))}catch{}return dT(dx(n?.parsedBody))}});async function v(i,n,a){var p,h;let f=i.classification.revision;if(void 0===f||!lY.includes(f)){let t=new c_({supported:[...lY],requested:f??"unknown"});return m(t),dR(400,t.code,t.message,t.data,dx(i.message))}let y=function(t,r){if("request"!==r.messageKind)return;let i=r.message.method;if(void 0===t.mcpMethodHeader)return ui("method-header-missing","(missing)",`the body names method ${i} but the required Mcp-Method header is absent`,"standard-header-validation");let n=Object.hasOwn(un,i)?un[i]:void 0;if(void 0===n)return;let a=r.message.params?.[n],o="string"==typeof a?a:void 0;if(void 0===t.mcpNameHeader){if(void 0===o)return;return ui("name-header-missing","(missing)",`the body carries params.${n}="${o}" but the required Mcp-Name header is absent`,"standard-header-validation")}let s=ua(t.mcpNameHeader),l=c7(s);return void 0===l?ui("name-header-invalid-encoding",s,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==o&&l!==o?ui("name-header-mismatch",s,`the body carries params.${n}="${o}" but the Mcp-Name header names "${l}"`,"standard-header-validation"):void 0}({httpMethod:n.method,mcpMethodHeader:n.headers.get("mcp-method")??void 0,mcpNameHeader:n.headers.get("mcp-name")??void 0},i);if(void 0!==y)return m(Error(`Rejected inbound request (${y.cell}): ${y.message}`)),d$(y,dx(i.message));let v="request"===i.messageKind?cH(i.message.params):void 0,_=v?.[aY];if("request"===i.messageKind){let t=Object.hasOwn(lB,p=i.message.method)?lB[p]:void 0;if(void 0!==t){let r=lG(t,_);if(void 0!==r){let t=new cb({requiredCapabilities:r});return m(t),dR(ut[t.code]??400,t.code,t.message,t.data,i.message.id)}}}let b=await t({era:"modern",...void 0!==a&&{authInfo:a},requestInfo:n}),S=b instanceof dd?b.server:b;if("request"===i.messageKind&&"subscriptions/listen"===i.message.method){let t=S.getCapabilities(),r=d(S);return b.close().catch(m),g.serve(i.message,n.signal,t,r)}if("request"===i.messageKind&&"tools/call"===i.message.method&&b instanceof dd){let t=i.message.params,r="string"==typeof t?.name?t.name:void 0,a=void 0===r?void 0:b.toolInputSchemaJson(r);if(void 0!==a){let r=c2(a);if(r.valid&&r.declarations.length>0){let a=function(t,r,i){for(let n of t){let t=`Mcp-Param-${n.headerName}`,a=i.get(t),o=function(t,r){let i=t;for(let t of r){if(null===i||"object"!=typeof i)return;i=i[t]}return i}(r,n.path);if(null==o)continue;let s=function(t){if("string"==typeof t)return t;if("boolean"==typeof t)return t?"true":"false";if("number"==typeof t){if(!Number.isFinite(t)||Number.isInteger(t)&&!Number.isSafeInteger(t))return;return String(t)}}(o);if(void 0===s)continue;if(null===a)return c8("param-header-missing",t,`the body carries ${c5(n.path)}=${JSON.stringify(o)} but the ${t} header is absent`);let l=c7(a);if(void 0===l)return c8("param-header-invalid-encoding",t,`the ${t} header carries an invalid Base64 sentinel value`);if(!(("integer"===n.type||"number"===n.type)&&c6.test(l)&&"number"==typeof o?Number(l)===o:l===s))return c8("param-header-mismatch",t,`the ${t} header decodes to ${JSON.stringify(l)} but the body carries ${c5(n.path)}=${JSON.stringify(o)}`)}}(r.declarations,t?.arguments,n.headers);if(void 0!==a)return b.close().catch(m),m(Error(`Rejected inbound request (${a.cell}): ${a.message}`)),d$(a,i.message.id)}}}l(S,f),u(S,lY),void 0!==v&&(h={clientInfo:v[aG],clientCapabilities:_},c(S,h));let w=S.onclose;s.add(S),S.onclose=()=>{s.delete(S),w?.()};try{let t=await dw(b,i.message,{classification:i.classification,request:n,...void 0!==a&&{authInfo:a},...void 0!==o&&{responseMode:o},...void 0!==r.keepAliveMs&&{keepAliveMs:r.keepAliveMs}});return"notification"===i.messageKind&&queueMicrotask(()=>void S.close().catch(()=>{})),t}catch(t){if(t instanceof lJ&&t.code===lV.ConnectionClosed)return new Response(null,{status:499});return await S.close().catch(()=>{}),s.delete(S),m(dC(t)),dT(dx(i.message))}}async function _(t,r,i,n){if(void 0!==y)return y(r,{...void 0!==i&&{authInfo:i},...void 0!==n&&{parsedBody:n}});let a=function(t,r){switch(t.reason){case"http-method":return ur("http-method","modern-only-method-not-allowed",405,new cg(-32e3,"Method not allowed."),!0);case"batch":return ur("jsonrpc-shape","modern-only-batch-not-supported",400,new cg(cf.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return ur("jsonrpc-shape","modern-only-response-post",400,new cg(cf.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let i=t.requestedVersion;return ur("era-classification","modern-only-missing-envelope",400,void 0===i?new cg(cf.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...r]}):new c_({supported:[...r],requested:i}),!0)}}}(t,lY);return void 0===a?new Response(null,{status:202}):(m(Error(`Rejected 2025-era request on a modern-only endpoint (${a.cell}): ${a.message}`)),d$(a,dx(n)))}async function b(t,r){let i=r?.authInfo;if("POST"===t.method.toUpperCase()&&!uN(t.headers.get("content-type")))return m(Error("Unsupported Media Type: Content-Type must be application/json")),dR(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let n=await dP(t,r?.parsedBody);if("unreadable-body"===n.step)return dR(400,-32700,"Parse error: the request body could not be read");if("no-json-body"===n.step)return void 0!==y?y(n.forwardRequest,{...void 0!==i&&{authInfo:i}}):dR(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:a,body:o,parsedBody:s,forwardRequest:l}=n;try{switch(a.kind){case"reject":return m(Error(`Rejected inbound request (${a.cell}): ${a.message}`)),d$(a,dx(o));case"modern":return await v(a,t,i);case"legacy":return await _(a,l,i,s)}}catch(t){return m(dC(t)),dT(dx(o))}}return{fetch:async(t,r)=>{if(p)throw Error("This MCP handler has been closed");try{return await b(t,r)}catch(t){return m(dC(t)),dT(dx(r?.parsedBody))}},notify:f,bus:h,close:async()=>{p=!0,g.closeAll();let t=[...s].map(t=>t.close().catch(()=>{}));s.clear(),await Promise.all(t)}}}(hu,{legacy:"stateless",responseMode:"json",onerror:t=>hx("MCP handler error:",t)});async function h$(t,r,i,n){let a=crypto.randomUUID(),o=await t.clone().json().catch(()=>void 0),s=(t=>{for(let r of Array.isArray(t)?t:[t]){let t=mh(r);if(t)return t}})(o),l={};return t.headers.forEach((t,r)=>{l[r]=t}),mc({id:a,headers:l,clientInfo:s},async()=>{try{let i=await hR.fetch(t,{authInfo:n,parsedBody:o});return hg(i,r)}catch(t){return console.error("[Cloudflare-MCP] Error handling MCP request:",t),hg(new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null}),{status:500,headers:{"Content-Type":"application/json"}}),r)}})}let hC={async fetch(t,r,i){let n=new URL(t.url).pathname,a=t.headers.get("origin");if(hx(`${t.method} ${n}`),"OPTIONS"===t.method)return new Response(null,{status:204,headers:new Headers(hh(hf,a))});let o=hy.endpoint?.startsWith("/")?hy.endpoint:`/${hy.endpoint||"mcp"}`;if("/health"===n)return hg(new Response(JSON.stringify({status:"ok",transport:"cloudflare-workers",mode:"stateless",auth:"none"}),{status:200,headers:{"Content-Type":"application/json"}}),a);if("/"===n&&"GET"===t.method){var s,l;return hg(new Response((s=hv.name,l=hv.description,`
|
|
590
588
|
<!DOCTYPE html>
|
|
591
589
|
<html lang="en">
|
|
592
590
|
<head>
|
|
@@ -607,7 +605,7 @@ data: ${JSON.stringify({jsonrpc:"2.0",id:w,result:{resultType:"complete",_meta:{
|
|
|
607
605
|
rel="stylesheet"
|
|
608
606
|
/>
|
|
609
607
|
<style>
|
|
610
|
-
${
|
|
608
|
+
${hm}
|
|
611
609
|
</style>
|
|
612
610
|
</head>
|
|
613
611
|
<body>
|
|
@@ -617,7 +615,7 @@ ${hw}
|
|
|
617
615
|
<div class="section-header">
|
|
618
616
|
<h2 id="server-name" class="display text-gradient">xmcp server</h2>
|
|
619
617
|
<p id="server-description" class="lead">
|
|
620
|
-
${l||
|
|
618
|
+
${l||hd}
|
|
621
619
|
</p>
|
|
622
620
|
</div>
|
|
623
621
|
</div>
|
|
@@ -724,7 +722,7 @@ ${`
|
|
|
724
722
|
(templateConfig.serverName && templateConfig.serverName.trim()) || "xmcp server";
|
|
725
723
|
const resolvedDescription =
|
|
726
724
|
(templateConfig.serverDescription && templateConfig.serverDescription.trim()) ||
|
|
727
|
-
"${
|
|
725
|
+
"${hd}";
|
|
728
726
|
const endpointPath =
|
|
729
727
|
(templateConfig.endpoint && templateConfig.endpoint.trim()) || "/";
|
|
730
728
|
const normalizedEndpoint = endpointPath.startsWith("/")
|
|
@@ -746,7 +744,7 @@ ${`
|
|
|
746
744
|
elements.description.textContent = resolvedDescription;
|
|
747
745
|
}
|
|
748
746
|
|
|
749
|
-
const icons = ${JSON.stringify(
|
|
747
|
+
const icons = ${JSON.stringify(hp)};
|
|
750
748
|
|
|
751
749
|
const connectionOptions = [
|
|
752
750
|
{
|
|
@@ -949,4 +947,4 @@ args = ["-y", "mcp-remote", "\${serverUrl}"]\`,
|
|
|
949
947
|
</script>
|
|
950
948
|
</body>
|
|
951
949
|
</html>
|
|
952
|
-
`),{status:200,headers:{"Content-Type":"text/html"}}),a)}if(n===o)try{let{response:r,authInfo:n}=await
|
|
950
|
+
`),{status:200,headers:{"Content-Type":"text/html"}}),a)}if(n===o)try{let{response:r,authInfo:n}=await hk(t);if(r)return hg(r,a);return h$(t,a,i,n)}catch(t){return console.error("[Cloudflare-MCP] Middleware error:",t),hg(new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null}),{status:500,headers:{"Content-Type":"application/json"}}),a)}return hg(new Response(JSON.stringify({error:"Not found"}),{status:404,headers:{"Content-Type":"application/json"}}),a)}};var hT=F.A;export{hT as default};
|