UNPKG

xmcp

Version:

The TypeScript MCP framework

950 lines • 451 kB
let t,r,i,n,o,a,s,l,c,u,d,p,m,h,f,g,y,v,_,b,S,w,R,k;import{AsyncLocalStorage as x}from"async_hooks";var C,$,T,P,E,O,I,q,j,A,L,N,z,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:()=>hU});var D=Object.create,V=Object.defineProperty,J=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=>eR(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 eo(t){let r=+!!t.startsWith("^"),i=t.endsWith("$")?t.length-1:t.length;return t.slice(r,i)}let ea=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 o=ec(r);for(let a of i){let i=Object.getOwnPropertyDescriptor(o,a);i.enumerable&&(i.get?eu(t,a,()=>{let t=r._zod.def.shape[a];return n?n(t,a):t}):ed(t,a,n?n(i.value,a):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 eR(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 eC(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 e$(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 o=r._zod.def.checks;if(o&&o.length>0)throw Error(`.${n}() cannot be used on object schemas containing refinements`);let a=i?new Set(eC(r,i)):void 0,s={};return ep(s,r,Reflect.ownKeys(ec(r)),t&&((r,i)=>a&&!a.has(i)?r:new t({type:"optional",innerType:r}))),eS(r,em(r._zod.def,{shape:s,checks:[]}))}function eP(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 eE(t,r){return r.map(r=>(r.path??(r.path=[]),r.path.unshift(t),r))}function eO(t){return"string"==typeof t?t:t?.message}function eI(t,r,i){var n;for(let o=r;o<t.length;o++)(n=t[o]).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 o=t.schema!==t.inst?t.schema?._zod.def?.error:void 0,a=t.message?t.message:eO(t.inst?._zod.def?.error?.(t))??eO(o?.(t))??eO(r?.error?.(t))??eO(i.customError?.(t))??eO(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=a,r?.reportInput&&(s.input=t.input),s}let ej=/[\uD800-\uDBFF]/;function eA(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 eL(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 ez(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 ez(this,i,n(this))},set(t){ez(this,i,t)}})}return r}let eZ=!1,eU={configurable:!0,get(){eZ=!0}};function eF(r,i,n){let o=Object.getPrototypeOf(r._zod);if(i in o&&t!==r._zod){t=void 0;return}t=r._zod,Object.defineProperty(o,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"}),eD={value:void 0,enumerable:!1},eV="captureStackTrace"in Error?Error:null;function eJ(t,r,i,n){function o(t){this.def=t,this.constr=u,this.traits=new Set}o.prototype={};let a=i&&new WeakSet;function s(n,s){if(n._zod){if(n._zod.traits.has(t))return}else{eD.value=new o(s);try{Object.defineProperty(n,"_zod",eD)}finally{eD.value=void 0}}if(n._zod.traits.add(t),r(n,s),a){let t=Object.getPrototypeOf(n),r=n._zod.constr.prototype,o=t;for(;o&&o!==r;)o=Object.getPrototypeOf(o);let s=o??t;if(!a.has(s)){a.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:ez(this,r,i.bind(this))},set(t){ez(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=eV;if(r){let i=r.stackTraceLimit;if("number"==typeof i){try{r.stackTraceLimit=0}catch{return eV=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 o=globalThis.__zod_globalConfig?.postProcessor;return o&&o(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"}}(q=globalThis).__zod_globalConfig??(q.__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 o=r;if(!o)return n;r=void 0;let a={value:n,issues:null};return o.set(i.value,a),e9.push(a),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,o;let a;if("backward"!==i.direction&&(n=i,o=t.value,void 0!==(a=n[eX]?.backEdges)&&e0(o)&&a.has(o)))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,o,a,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 o,a;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 o=t(r,i,n);o>l&&(l=o)}},u=t=>{t>l&&(l=t)},d=r._zod.def;switch(d.type){case"object":{let r=el(d);u(r?((r,o)=>{let a=0;for(let s of Reflect.ownKeys(r)){let l=Object.getOwnPropertyDescriptor(r,s);if(o&&!l.enumerable)continue;let c=l.get?1:l.value?._zod?t(l.value,i,n):0;c>a&&(a=c)}return a})(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 o=d._cachedInner??(n?r._zod.innerType:void 0);u(o?t(o,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),o=r,1!==(a=l)&&e2.set(o,2===a),a}(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),o===u)d=a;else{var h;let r;(r=(h=m).buckets.get(t))||(r=new WeakMap,h.buckets.set(t,r)),d=r,o=u,a=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,}$/,to=`^(?=[\\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])$/,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=eJ("$ZodCheck",(t,r)=>{var i;t._zod??(t._zod={}),t._zod.def=r,(i=t._zod).onattach??(i.onattach=[])}),tR=t=>{let r=t.value;return null!=r&&void 0!==r.length},tk={number:"number",bigint:"bigint",object:"date"},tx=eJ("$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})}}),tC=eJ("$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})}}),t$=eJ("$ZodCheckMultipleOf",(t,r)=>{tw.init(t,r),t._zod.check=i=>{let n,o,a;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==(o=Math.round(n=i.value/r.value),a=4*Number.EPSILON*Math.max(Math.abs(n),1),Math.abs(n-o)<a?0:n-o))||i.issues.push({origin:typeof i.value,code:"not_multiple_of",divisor:r.value,input:i.value,inst:t,continue:!r.abort})}}),tT=eJ("$ZodCheckNumberFormat",(t,r)=>{tw.init(t,r),r.format=r.format||"float64";let i=r.format?.includes("int"),n=i?"int":"number",[o,a]=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<o&&s.issues.push({origin:"number",input:l,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!r.abort}),l>a&&s.issues.push({origin:"number",input:l,code:"too_big",maximum:a,inclusive:!0,inst:t,continue:!r.abort})}}),tP=eJ("$ZodCheckMaxLength",(t,r)=>{var i;tw.init(t,r),(i=t._zod.def).when??(i.when=tR),t._zod.check=i=>{let n=i.value,o=n.length;if(("string"==typeof n&&o>r.maximum?eA(n):o)<=r.maximum)return;let a=eL(n);i.issues.push({origin:a,code:"too_big",maximum:r.maximum,inclusive:!0,input:n,inst:t,continue:!r.abort})}}),tE=eJ("$ZodCheckMinLength",(t,r)=>{var i;tw.init(t,r),(i=t._zod.def).when??(i.when=tR),t._zod.check=i=>{let n=i.value,o=n.length;if(("string"==typeof n&&o>=r.minimum&&o<2*r.minimum?eA(n):o)>=r.minimum)return;let a=eL(n);i.issues.push({origin:a,code:"too_small",minimum:r.minimum,inclusive:!0,input:n,inst:t,continue:!r.abort})}}),tO=eJ("$ZodCheckLengthEquals",(t,r)=>{var i;tw.init(t,r),(i=t._zod.def).when??(i.when=tR),t._zod.check=i=>{let n=i.value,o=n.length,a="string"==typeof n&&o>=r.length&&o<=2*r.length?eA(n):o;if(a===r.length)return;let s=eL(n),l=a>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=eJ("$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=eJ("$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=eJ("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=tb),tI.init(t,r)}),tA=eJ("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=tS),tI.init(t,r)}),tL=eJ("$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})}}),tN=eJ("$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})}}),tz=eJ("$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=eJ("$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(", ")}) {
${r.join("\n")}
};`)(...Object.values(this.closed))}}let tU={major:4,minor:6,patch:5},tF=eJ("$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,o=t._zod.traits.has("$ZodCheck")?[t,...n??[]]:n?.length?[...n]:[];for(let r of o)for(let i of r._zod.onattach)i(t);if(0===o.length)(i=t._zod).deferred??(i.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let r=(r,i,n)=>{let o;if(r.memo)return r;let a=eP(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(a)continue;let i=r.issues.length,l=s._zod.check(r);if(l instanceof Promise&&n?.async===!1)throw new eB;if(o||l instanceof Promise)o=(o??Promise.resolve()).then(async()=>{await l,r.issues.length!==i&&(eI(r.issues,i,t),a||(a=eP(r,i)))});else{if(r.issues.length===i)continue;eI(r.issues,i,t),a||(a=eP(r,i))}}return o?o.then(()=>r):r},i=(i,n,a)=>{if(eP(i))return i.aborted=!0,i;let s=r(n,o,a);if(s instanceof Promise){if(!1===a.async)throw new eB;return s.then(r=>t._zod.parse(r,a))}return t._zod.parse(s,a)};t._zod.run=(n,a)=>{if(a.skipChecks)return t._zod.parse(n,a);if("backward"===a.direction){let r=t._zod.parse({value:n.value,issues:[]},{...a,skipChecks:!0});return r instanceof Promise?r.then(t=>i(t,n,a)):i(r,n,a)}let s=t._zod.parse(n,a);if(s instanceof Promise){if(!1===a.async)throw new eB;return s.then(t=>r(t,o,a))}return r(s,o,a)}}},{get"~standard"(){return ez(this,"~standard",tV(this),!1)},set"~standard"(value){ez(this,"~standard",value)}}),tH=(t,r)=>t.issues.length?{issues:t.issues.map(t=>eq(t,r,eK()))}:{value:t.value};async function tD(t,r){let i={async:!0};return tH(await t._zod.run({value:r,issues:[]},i),i)}function tV(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 tD(t,r)},vendor:"zod",version:1}}let tJ=eJ("$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=eJ("$ZodStringFormat",(t,r)=>{tI.init(t,r),tJ.init(t,r)}),tW=eJ("$ZodGUID",(t,r)=>{r.pattern??(r.pattern=tr),tB.init(t,r)}),tG=eJ("$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=eJ("$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=eJ("$ZodURL",(t,r)=>{tB.init(t,r),t._zod.check=i=>{try{var n,o;let a=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}}(a,r):tY(a)||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(a);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&&((o=r.protocol).lastIndex=0,!o.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(a);return}catch(n){i.issues.push({code:"invalid_format",format:"url",input:i.value,inst:t,continue:!r.abort})}}}),t1=eJ("$ZodEmoji",(t,r)=>{r.pattern??(r.pattern=RegExp(to,"u")),tB.init(t,r)}),t2=eJ("$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=eJ("$ZodCUID",(t,r)=>{r.pattern??(r.pattern=e5),tB.init(t,r)}),t4=eJ("$ZodCUID2",(t,r)=>{r.pattern??(r.pattern=e3),tB.init(t,r)}),t5=eJ("$ZodULID",(t,r)=>{r.pattern??(r.pattern=e6),tB.init(t,r)}),t3=eJ("$ZodXID",(t,r)=>{r.pattern??(r.pattern=e7),tB.init(t,r)}),t6=eJ("$ZodKSUID",(t,r)=>{r.pattern??(r.pattern=e8),tB.init(t,r)}),t7=eJ("$ZodISODateTime",(t,r)=>{let i,n,o;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("|")})`,o=r.local?`${n}|${th({precision:r.precision})}`:n,r.pattern=RegExp(`^${tp}T(?:${o})$`)),tB.init(t,r)}),t8=eJ("$ZodISODate",(t,r)=>{r.pattern??(r.pattern=tm),tB.init(t,r)}),re=eJ("$ZodISOTime",(t,r)=>{r.pattern??(r.pattern=RegExp(`^${th(r)}$`)),tB.init(t,r)}),rt=eJ("$ZodISODuration",(t,r)=>{r.pattern??(r.pattern=tt),tB.init(t,r)}),rr=eJ("$ZodIPv4",(t,r)=>{r.pattern??(r.pattern=ta),tB.init(t,r)}),ri=/^[0-9a-fA-F:.]+$/;function rn(t){return!!ri.test(t)&&tY(`http://[${t}]`)}let ro=eJ("$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})}}),ra=eJ("$ZodCIDRv4",(t,r)=>{r.pattern??(r.pattern=tl),tB.init(t,r)}),rs=eJ("$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 o=Number(n);return`${o}`===n&&!(o<0)&&!(o>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=eJ("$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=eJ("$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=eJ("$ZodE164",(t,r)=>{r.pattern??(r.pattern=td),tB.init(t,r)}),rh=eJ("$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 o=JSON.parse(atob(n));if("typ"in o&&o?.typ!=="JWT"||!o.alg||r&&(!("alg"in o)||o.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=eJ("$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 o=i.value;if("number"==typeof o&&!Number.isNaN(o)&&Number.isFinite(o))return i;let a="number"==typeof o?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:String(o):void 0;return i.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...a?{received:a}:{}}),i}}),rg=eJ("$ZodNumberFormat",(t,r)=>{tT.init(t,r),rf.init(t,r)}),ry=eJ("$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 o=i.value;return"boolean"==typeof o||i.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),i}}),rv=eJ("$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_=eJ("$ZodAny",(t,r)=>{tF.init(t,r),t._zod.parse=t=>t}),rb=eJ("$ZodUnknown",(t,r)=>{tF.init(t,r),t._zod.parse=t=>t}),rS=eJ("$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(...eE(i,t.issues)),r.value[i]=t.value}let rR=eJ("$ZodArray",(t,r)=>{tF.init(t,r);let i=eG.memoizer;i?.attach(t),t._zod.parse=(n,o)=>{let a=n.value;if(!Array.isArray(a))return n.issues.push({expected:"array",code:"invalid_type",input:a,inst:t}),n;n.value=i?i.alloc(t,n,Array(a.length),o):Array(a.length);let s=[],l=o?.abortEarly;for(let t=0;t<a.length;t++){let i=a[t],c=r.element._zod.run({value:i,issues:[]},o);if(c instanceof Promise)s.push(c.then(r=>rw(r,n,t)));else if(rw(c,n,t),l&&0!==c.issues.length&&eP(c))break}return s.length?Promise.all(s).then(()=>n):n}});function rk(t,r,i,n,o,a){let s=i in n,l="optional"===a;if(s||!l||"optional"!==o){if(t.issues.length){if(void 0!==o&&l&&!s)return;r.issues.push(...eE(i,t.issues))}if(!s&&void 0===o){t.issues.length||r.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[i]});return}void 0===t.value?(s||"defaulted"===o&&!l)&&(r.value[i]=void 0):r.value[i]=t.value}}let rx=[];function rC(t){var r;let i=Object.keys(t.shape),n=Object.getOwnPropertySymbols(t.shape),o=n.length?n:rx,a=o.length?[...i,...o]:i;for(let r of a)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:a,symbolKeys:o,keySet:new Set(i),numKeys:i.length,optionalKeys:new Set(s)}}function r$(t,r,i,n,o,a,s){let l=[],c=o.keySet,u=o.catchall._zod,d=u.def.type,p=u.optin,m=u.optout,h=0;for(let o in r){if(s&&i.issues.length!==h){if(eP(i,h))break;h=i.issues.length}if(c.has(o))continue;if("__proto__"===o){"never"===d&&l.push(o);continue}if("never"===d){l.push(o);continue}let a=u.run({value:r[o],issues:[]},n);a instanceof Promise?t.push(a.then(t=>rk(t,i,o,r,p,m))):rk(a,i,o,r,p,m)}return(l.length&&i.issues.push({code:"unrecognized_keys",keys:l,input:r,inst:a,continue:!0}),t.length)?Promise.all(t).then(()=>i):i}let rT=eJ("$ZodObject",(t,r)=>{let i;tF.init(t,r);let n=Object.getOwnPropertyDescriptor(r,"shape"),o=n?.get?n.get.raw:r.shape??{};if(o){let t=()=>{let i={...o};return Object.defineProperty(r,"shape",{value:i}),t.raw=i,i};t.raw=o,Object.defineProperty(r,"shape",{get:t})}let a=en(()=>rC(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=a.value);let o=r.value;if(!ef(o))return r.issues.push({expected:"object",code:"invalid_type",input:o,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(eP(r,p))break;p=r.issues.length}if("__proto__"===t)continue;let i=u[t],a=i._zod.optin,s=i._zod.optout,l=i._zod.run({value:o[t],issues:[]},n);l instanceof Promise?c.push(l.then(i=>rk(i,r,t,o,a,s))):rk(l,r,t,o,a,s)}return s?r$(c,o,r,n,a.value,t,!0===d):c.length?Promise.all(c).then(()=>r):r}}),rP=eJ("$ZodObjectJIT",(t,r)=>{let i,n;rT.init(t,r);let o=t._zod.parse,a=en(()=>rC(r)),s=eG.memoizer,l=!eG.jitless,c=l&&eg.value,u=r.catchall;t._zod.parse=(d,p)=>{n??(n=a.value);let m=d.value;return ef(m)?l&&c&&p?.async===!1&&!0!==p.jitless?(i||(i=(r=>{let i=a.value,n=i.symbolKeys,o=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)=>`
          let ${t}_ab = false;
          for (let i = 0; i < ${t}.issues.length; i++) {
            const iss = ${t}.issues[i];
            iss.path = iss.path ? [${r}, ...iss.path] : [${r}];
            payload.issues.push(iss);
            if (iss.continue !== true) ${t}_ab = true;
          }
          if (${t}_ab && ctx && ctx.abortEarly) {
            payload.value = newResult;
            return payload;
          }`;o.write("const input = payload.value;");let u=Object.create(null),d=0;for(let t of i.allKeys)u[t]=`key_${d++}`;for(let t of(o.write(s?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};"),i.allKeys)){if("__proto__"===t)continue;let i=u[t],a="symbol"==typeof t?`syms[${n.indexOf(t)}]`:JSON.stringify(t),s=`${a} in input`,d=r[t],p=d?._zod?.optin,m=void 0!==p,h=d?._zod?.optout==="optional";if(o.write(`const ${i} = ${l(a)};`),m&&h){let t="optional"===p?`${i}_present`:`${i}.value !== undefined || ${i}_present`;o.write(`
        const ${i}_present = ${s};
        if (!${i}.issues.length || ${i}_present) {
          if (${i}.issues.length) {${c(i,a)}
          }

          if (${t}) {
            newResult[${a}] = ${i}.value;
          }
        }

      `)}else m?(o.write(`
        if (${i}.issues.length) {${c(i,a)}
        }
      `),"defaulted"===p?o.write(`newResult[${a}] = ${i}.value;`):o.write(`
        if (${i}.value !== undefined || ${s}) {
          newResult[${a}] = ${i}.value;
        }
      `)):o.write(`
        const ${i}_present = ${s};
        if (${i}.issues.length) {${c(i,a)}
        }
        if (!${i}_present && !${i}.issues.length) {
          payload.issues.push({
            code: "invalid_type",
            expected: "nonoptional",
            input: undefined,
            path: [${a}]
          });
          if (ctx && ctx.abortEarly) {
            payload.value = newResult;
            return payload;
          }
        }

        if (${i}_present) {
          newResult[${a}] = ${i}.value;
        }

      `)}return o.write("payload.value = newResult;"),o.write("return payload;"),o.compile()})(r.shape)),d=i(d,p),u)?r$([],m,d,p,n,t,p?.abortEarly===!0):d:o(d,p):(d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d)}});function rE(t,r,i,n){for(let i of t)if(0===i.issues.length)return r.value=i.value,r;let o=t.filter(t=>!eP(t));return 1===o.length?(r.value=o[0].value,o[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 rO=eJ("$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=>eo(t.source)).join("|")})$`)}});let i=1===r.options.length?r.options[0]._zod.run:null;t._zod.parse=(n,o)=>{if(i)return i(n,o);let a=!1,s=[];for(let t of r.options){let r=t._zod.run({value:n.value,issues:[]},o);if(r instanceof Promise)s.push(r),a=!0;else{if(0===r.issues.length)return r;s.push(r)}}return a?Promise.all(s).then(r=>rE(r,n,t,o)):rE(s,n,t,o)}}),rI=eJ("$ZodDiscriminatedUnion",(t,r)=>{r.inclusive=!1,rO.init(t,r);let i=t._zod.parse;eF(t,"propValues",t=>{let r={},i=0;for(let n of t.def.options){let o=n._zod.propValues;if(!o||0===Object.keys(o).length)throw Error(`Invalid discriminated union option at index "${t.def.options.indexOf(n)}"`);for(let[n,a]of(o[t.def.discriminator]?.has(void 0)&&i++,Object.entries(o)))for(let t of(Object.prototype.hasOwnProperty.call(r,n)||es(r,n,new Set),a))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=(o,a)=>{let s=o.value;if(!ef(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),o;let l=s?.[r.discriminator],c=n.value.get(l);return c&&(void 0!==l||"backward"!==a.direction)?c._zod.run(o,a):r.unionFallback||"backward"===a.direction?i(o,a):(o.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}),o)}}),rq=eJ("$ZodIntersection",(t,r)=>{tF.init(t,r),t._zod.parse=(t,i)=>{let n=t.value,o=r.left._zod.run({value:n,issues:[]},i),a=r.right._zod.run({value:n,issues:[]},i);return o instanceof Promise||a instanceof Promise?Promise.all([o,a]).then(([r,i])=>rj(t,r,i)):rj(t,o,a)}});function rj(t,r,i){let n,o=new Map,a=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]);a.has(r)||a.set(r,t),i=[r]}else n??(n=t),i=t.keys;for(let t of i)o.has(t)||o.set(t,{}),o.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=[...o].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)&&a.has(i)&&t.issues.push(a.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),o=Object.keys(r).filter(t=>-1!==n.indexOf(t)),a={...r,...i};for(let n of(Object.prototype.hasOwnProperty.call(a,"__proto__")&&delete a.__proto__,o)){if("__proto__"===n)continue;let o=t(r[n],i[n]);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};a[n]=o.data}return{valid:!0,data:a}}if(Array.isArray(r)&&Array.isArray(i)){if(r.length!==i.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let o=0;o<r.length;o++){let a=t(r[o],i[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}(r.value,i.value);if(!c.valid){if(eP(t))return t;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return t.value=c.data,t}let rA=eJ("$ZodRecord",(t,r)=>{tF.init(t,r);let i=eG.memoizer;i?.attach(t),t._zod.parse=(n,o)=>{let a=n.value;if(!ey(a))return n.issues.push({expected:"record",code:"invalid_type",input:a,inst:t}),n;let s=[],l=r.keyType._zod.values;if(l&&!r.partial){let c;n.value=i?i.alloc(t,n,{},o):{};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:[]},o);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,o,eK())),input:i,path:[i],inst:t});continue}let c=l.value;if("__proto__"===c)continue;let d=r.valueType._zod.run({value:a[i],issues:[]},o);d instanceof Promise?s.push(d.then(t=>{t.issues.length&&n.issues.push(...eE(i,t.issues)),n.value[c]=t.value})):(d.issues.length&&n.issues.push(...eE(i,d.issues)),n.value[c]=d.value)}for(let t in a)if(!u.has(t))if("loose"===r.mode){if("__proto__"===t)continue;n.value[t]=a[t]}else(c=c??[]).push(t);c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:a,inst:t,keys:c,continue:!0})}else{let c;for(let u of(n.value=i?i.alloc(t,n,{},o):{},Reflect.ownKeys(a))){if("__proto__"===u||!Object.prototype.propertyIsEnumerable.call(a,u))continue;let i=r.keyType._zod.run({value:u,issues:[]},o);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:[]},o);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]=a[u]:l?(c=c??[]).push(u):n.issues.push({code:"invalid_key",origin:"record",issues:i.issues.map(t=>eq(t,o,eK())),input:u,path:[u],inst:t});continue}let d=i.value;if("__proto__"===d)continue;let p=r.valueType._zod.run({value:a[u],issues:[]},o);p instanceof Promise?s.push(p.then(t=>{t.issues.length&&n.issues.push(...eE(u,t.issues)),n.value[d]=t.value})):(p.issues.length&&n.issues.push(...eE(u,p.issues)),n.value[d]=p.value)}c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:a,inst:t,keys:c,continue:!0})}return s.length?Promise.all(s).then(()=>n):n}}),rL=eJ("$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,o)=>{let a=r.value;return n.has(a)||r.issues.push({code:"invalid_value",values:i,input:a,inst:t}),r}}),rN=eJ("$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,o)=>{let a=n.value;return i.has(a)||n.issues.push({code:"invalid_value",values:r.values,input:a,inst:t}),n}}),rz=eJ("$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 o=r.transform(i.value,i);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(t=>(i.value=t,i));if(o instanceof Promise)throw new eB;return i.value=o,i}});function rM(t,r){return t.value=r.issues.length?void 0:r.value,t}let rZ=eJ("$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(`^(${eo(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=eJ("$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=eJ("$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(`^(${eo(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=eJ("$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=>rD(t,r)):rD(n,r)}});function rD(t,r){return void 0===t.value&&(t.value=r.defaultValue),t}let rV=eJ("$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))}),rJ=eJ("$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 o=r.innerType._zod.run(i,n);return o instanceof Promise?o.then(r=>rB(r,t)):rB(o,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=eJ("$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=eJ("$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=eJ("$ZodPreprocess",(t,r)=>{rK.init(t,r)}),rQ=eJ("$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=eJ("$ZodLazy",(t,r)=>{var i;let n;tF.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}),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=eJ("$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,o=r.fn(n);if(o instanceof Promise)return o.then(r=>r9(r,i,n,t));r9(o,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(eN(t))}}(j=globalThis).__zod_globalRegistry??(j.__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 tx({check:"less_than",...ew(r),value:t,inclusive:!1})}function it(t,r){return new tx({check:"less_than",...ew(r),value:t,inclusive:!0})}function ir(t,r){return new tC({check:"greater_than",...ew(r),value:t,inclusive:!1})}function ii(t,r){return new tC({check:"greater_than",...ew(r),value:t,inclusive:!0})}function io(t,r){return new t$({check:"multiple_of",...ew(r),value:t})}function ia(t,r){return new tP({check:"max_length",...ew(r),maximum:t})}function is(t,r){return new tE({check:"min_length",...ew(r),minimum:t})}function il(t,r){return new tO({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,o){let a="function"==typeof r.unrepresentable?r.unrepresentable({zodSchema:t,path:n.path,message:o}):r.unrepresentable;if("any"===a)return!1;if(void 0===a||"throw"===a)throw Error(o);return Object.assign(i,a),!0}function im(t,r,i={path:[],schemaPath:[]}){var n;let o=t._zod.def,a=r.seen.get(t);if(a)return a.count++,i.schemaPath.includes(t)&&(a.cycle=i.path),a.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,a=r.processors[o.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);a(t,r,i,n)}let a=t._zod.parent;a&&(s.ref||(s.ref=a),im(a,r,n),r.seen.get(a).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 o=r._zod.def;if("transform"===o.type)return!0;if("array"===o.type)return t(o.element,n);if("set"===o.type)return t(o.valueType,n);if("lazy"===o.type)return t(o.getter(),n);if("promise"===o.type||"optional"===o.type||"nonoptional"===o.type||"nullable"===o.type||"readonly"===o.type||"default"===o.type||"prefault"===o.type||"catch"===o.type)return t(o.innerType,n);if("intersection"===o.type)return t(o.left,n)||t(o.right,n);if("record"===o.type||"map"===o.type)return t(o.keyType,n)||t(o.valueType,n);if("pipe"===o.type)return!!r._zod.traits.has("$ZodCodec")||t(o.in,n)||t(o.out,n);if("object"===o.type){for(let r in o.shape)if(t(o.shape[r],n))return!0;return!1}if("union"===o.type){for(let r of o.options)if(t(r,n))return!0;return!1}if("tuple"===o.type){for(let r of o.items)if(t(r,n))return!0;if(o.rest&&t(o.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 o=r=>{if(r[1].schema.$ref)return;let n=r[1],{ref:o,defId:a}=(r=>{let n="draft-2020-12"===t.target?"$defs":"definitions";if(t.external){let i=t.external.registry.get(r[0])?.id,o=t.external.uri??(t=>t);if(i)return{ref:o(i)};let a=r[1].defId??r[1].schema.id??`schema${t.counter++}`;return r[1].defId=a,{defId:a,ref:`${o("__shared")}#/${n}/${ih(a)}`}}let o=`#/${n}/`;if(r[1]===i&&!r[1].schema.id)return{ref:"#"};let a=r[1].schema.id??`__schema${t.counter++}`;return{defId:a,ref:o+ih(a)}})(r);n.def={...n.schema},a&&(n.defId=a);let s=n.schema;for(let t in s)delete s[t];s.$ref=o};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>

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]){o(i);continue}if(t.external){let n=t.external.registry.get(i[0])?.id;if(r!==i[0]&&n){o(i);continue}}if(t.metadataRegistry.get(i[0])?.id||n.cycle){o(i);continue}n.count>1&&"ref"===t.reused&&o(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 o={type:"object",properties:i};if(n.size&&(o.required=[...n]),r.every(t=>!1===t.additionalProperties))o.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?o.additionalProperties=t[0]:t.length>1&&(o.additionalProperties={allOf:t})}return o}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 o=i.def??i.schema,a={...o},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)?(o.allOf=o.allOf??[],o.allOf.push(l)):iu(o,l),iu(o,a),r._zod.parent===s)for(let t in o)"$ref"!==t&&"allOf"!==t&&(t in a||delete o[t]);if(l.$ref&&i.def)for(let t in o)"$ref"!==t&&"allOf"!==t&&t in i.def&&JSON.stringify(o[t])===JSON.stringify(i.def[t])&&delete o[t]}let l=r._zod.parent;if(l&&l!==s){n(l);let r=t.seen.get(l);if(r?.schema.$ref&&(o.$ref=r.schema.$ref,r.def))for(let t in o)"$ref"!==t&&"allOf"!==t&&t in r.def&&JSON.stringify(o[t])===JSON.stringify(r.def[t])&&delete o[t]}t.override({zodSchema:r,jsonSchema:o,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 o=r.type;for(let t of Array.isArray(o)?o:[o]){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],o=iv.find(r=>Array.isArray(t[r]));if(1!==Object.keys(t).length)return;let a=r.filter(r=>r!==t),s=t[o].map(t=>ib([...a,t]));if(s.some(t=>!t))return;n={[o]:s}}else n=ib(r);n&&(delete t.allOf,iu(t,n))}(t)}}let o={};if("draft-2020-12"===t.target?o.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===t.target?o.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===t.target?o.$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");o.$id=t.external.uri(i)}iu(o,i.defId?i.schema:i.def??i.schema);let a=t.metadataRegistry.get(r)?.id;void 0!==a&&o.id===a&&delete o.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?o.$defs=s:o.definitions=s);try{let i=JSON.parse(JSON.stringify(o));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:o,target:a}=n??{},s=id({...o??{},target:a,io:r,processors:i});return im(t,s),ig(s,t),iS(s,t)},iR=(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)=>{iR(t,"minimum",r),ik(t,"maximum",r)},iC=(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)},iT=(t,r)=>{t.mime=t.mime?t.mime.filter(t=>r.includes(t)):[...r]},iP=(t,r)=>{t.format=r,r.includes("int")&&(t.isInt=!0)},iE=(t,r)=>iR(t,"minimum",r.minimum),iO=(t,r)=>ik(t,"maximum",r.maximum),iI=t=>(r,i)=>{iP(r,i.format);let[n,o]=t[i.format];iR(r,"minimum",n),ik(r,"maximum",o)},iq={greater_than:(t,r)=>iR(t,r.inclusive?"minimum":"exclusiveMinimum",r.value),less_than:(t,r)=>ik(t,r.inclusive?"maximum":"exclusiveMaximum",r.value),multiple_of:(t,r)=>iC(t,r.value),number_format:iI(ek),bigint_format:iI(ex),min_length:iE,max_length:iO,length_equals:(t,r)=>ix(t,r.length),min_size:iE,max_size:iO,size_equals:(t,r)=>ix(t,r.size),string_format:(t,r)=>{iP(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)=>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&&iR(r,"minimum",n.minimum),void 0!==n.exclusiveMinimum&&iR(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&&iC(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??[]))i$(r,t);return r}let iA={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},iL=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})?$/]]),iN=t=>iL.get(t)??t,iz=(t,r,i,n)=>{i.type="string";let{minimum:o,maximum:a,format:s,patterns:l,contentEncoding:c,laxFormat:u}=ij(t);if("number"==typeof o&&(i.minLength=o),"number"==typeof a&&(i.maxLength=a),s&&(i.format=iA[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}))])}},iM=(t,r,i,n)=>{let{minimum:o,maximum:a,multipleOf:s,exclusiveMaximum:l,exclusiveMinimum:c,isInt:u}=ij(t);i.type=u?"integer":"number";let d="number"==typeof c&&c>=(o??-1/0),p="number"==typeof l&&l<=(a??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 o&&(i.minimum=o),p?m?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:"number"==typeof a&&(i.maximum=a),s){let o=new Set;for(let a of s)Number.isFinite(a)&&0!==a?o.add(Math.abs(a)):ip(t,r,i,n,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...l]=o;void 0!==a&&(i.multipleOf=a),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)=>{},iD=(t,r,i,n)=>{},iV=(t,r,i,n)=>{let o=ee(t._zod.def.entries);if(0===o.length){i.not={};return}o.every(t=>"number"==typeof t)&&(i.type="number"),o.every(t=>"string"==typeof t)&&(i.type="string"),i.enum=o},iJ=(t,r,i,n)=>{let o=t._zod.def;if(0===o.values.length){i.not={};return}let a=[];for(let s of o.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;a.push(Number(s))}else a.push(s);if(0===a.length);else if(1===a.length){let t=a[0];i.type=null===t?"null":typeof t,"draft-04"===r.target||"openapi-3.0"===r.target?i.enum=[t]:i.const=t}else a.every(t=>"number"==typeof t)&&(i.type="number"),a.every(t=>"string"==typeof t)&&(i.type="string"),a.every(t=>"boolean"==typeof t)&&(i.type="boolean"),a.every(t=>null===t)&&(i.type="null"),i.enum=a},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 o=t._zod.def,{minimum:a,maximum:s}=ij(t);"number"==typeof a&&(i.minItems=a),"number"==typeof s&&(i.maxItems=s),i.type="array",i.items=im(o.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 o=t._zod.def,a=o.shape;if(Object.getOwnPropertySymbols(a).length&&ip(t,r,i,n,"Symbol keys cannot be represented in JSON Schema"))return;for(let t in i.type="object",i.properties={},a)es(i.properties,t,im(a[t],r,{...n,path:[...n.path,"properties",t]}));let s=[];for(let t of Object.keys(a)){let i=o.shape[t];("input"===r.io?void 0===iK(i):void 0===i._zod.optout)&&s.push(t)}s.length>0&&(i.required=s),o.catchall?._zod.def.type==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=im(o.catchall,r,{...n,path:[...n.path,"additionalProperties"]})):"output"===r.io&&(i.additionalProperties=!1)},iX=(t,r,i,n)=>{let o=t._zod.def,a=!1===o.inclusive,s=o.options.map((t,i)=>im(t,r,{...n,path:[...n.path,a?"oneOf":"anyOf",i]}));a?i.oneOf=s:i.anyOf=s},iQ=(t,r,i,n)=>{let o=t._zod.def,a=im(o.left,r,{...n,path:[...n.path,"allOf",0]}),s=im(o.right,r,{...n,path:[...n.path,"allOf",1]}),l=t=>"allOf"in t&&1===Object.keys(t).length,c=[...l(a)?a.allOf:[a],...l(s)?s.allOf:[s]];i.allOf=c,r.intersections.push(c)},i0=new WeakMap,i1=(t,r,i,n)=>{let o=t._zod.def;i.type="object";let a=o.keyType,s=ij(a).patterns;if("loose"===o.mode&&s&&s.size>0){let t=im(o.valueType,r,{...n,path:[...n.path,"patternProperties","*"]});for(let r of(i.patternProperties={},s))es(i.patternProperties,iN(r).source,t)}else{if("draft-07"===r.target||"draft-2020-12"===r.target){i.propertyNames=im(o.keyType,r,{...n,path:[...n.path,"propertyNames"]});let a=i0.get(r);a||(a=[],i0.set(r,a),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 o=t.seen.get(n),a=(o?.def??o?.schema)?.propertyNames;if(!a||!0===a||i.has(a))continue;let s=function t(r,i,n){if(i.$ref){if(n.has(i))return i;n.add(i);let o=r.get(i)?.def;if(!o)return i;let a=t(r,o,n);return a===o?i:a}for(let o of["anyOf","oneOf"]){let a=i[o];if(!Array.isArray(a))continue;let s=a.map(i=>t(r,i,n));s.some((t,r)=>t!==a[r])&&(i={...i,[o]:s})}let o=Array.isArray(i.type)?i.type:[i.type],a=!o.includes("string")&&o.some(t=>"number"===t||"integer"===t),s=i.enum??(void 0!==i.const?[i.const]:void 0);if(!a&&!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)),a&&(f.type="string",s||(f.pattern=(o.includes("number")?ty:tg).source)),f}(r,a,new Set);s!==a&&i.set(a,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))),a.push(t)}i.additionalProperties=im(o.valueType,r,{...n,path:[...n.path,"additionalProperties"]})}let l=a._zod.values,c="input"===r.io&&void 0!==iK(o.valueType);if(l&&!o.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 o=t._zod.def,a=im(o.innerType,r,n),s=r.seen.get(t);"openapi-3.0"===r.target?(s.ref=o.innerType,i.nullable=!0):i.anyOf=[a,{type:"null"}]},i9=(t,r,i,n)=>{let o=t._zod.def;im(o.innerType,r,n),r.seen.get(t).ref=o.innerType},i4=Symbol();function i5(t,r,i,n,o){let a=!1,s=JSON.stringify(t,(t,r)=>"bigint"!=typeof r?r:(a=!0,null));return a?(ip(r,i,n,o,"BigInt defaults cannot be represented in JSON Schema"),i4):JSON.parse(s)}let i3=(t,r,i,n)=>{let o=t._zod.def;im(o.innerType,r,n),r.seen.get(t).ref=o.innerType;let a=i5(o.defaultValue,t,r,i,n);a!==i4&&(i.default=a)},i6=(t,r,i,n)=>{let o=t._zod.def;if(im(o.innerType,r,n),r.seen.get(t).ref=o.innerType,"input"!==r.io)return;let a=i5(o.defaultValue,t,r,i,n);a!==i4&&(i._prefault=a)},i7=(t,r,i,n)=>{let o,a=t._zod.def;im(a.innerType,r,n),r.seen.get(t).ref=a.innerType;try{o=a.catchValue(void 0)}catch{ip(t,r,i,n,"Dynamic catch values are not supported in JSON Schema");return}i.default=o},i8=(t,r,i,n)=>{let o=t._zod.def,a=o.in._zod.traits.has("$ZodTransform"),s="input"===r.io?a?o.out:o.in:o.out;im(s,r,n),r.seen.get(t).ref=s},ne=(t,r,i,n)=>{let o=t._zod.def;im(o.innerType,r,n),r.seen.get(t).ref=o.innerType,i.readOnly=!0},nt=(t,r,i,n)=>{let o=t._zod.def;im(o.innerType,r,n),r.seen.get(t).ref=o.innerType},nr=(t,r,i,n)=>{let o=t._zod.innerType;im(o,r,n),r.seen.get(t).ref=o},ni={string:iz,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:iD,date:(t,r,i,n)=>{ip(t,r,i,n,"Date cannot be represented in JSON Schema")},enum:iV,literal:iJ,nan:(t,r,i,n)=>{ip(t,r,i,n,"NaN cannot be represented in JSON Schema")},template_literal:(t,r,i,n)=>{let o=t._zod.pattern;if(!o)throw Error("Pattern not found in template literal");i.type="string",i.pattern=o.source},file:(t,r,i,n)=>{i.type="string",i.format="binary",i.contentEncoding="binary";let{minimum:o,maximum:a,mime:s}=ij(t);void 0!==o&&(i.minLength=o),void 0!==a&&(i.maxLength=a),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 o=t._zod.def;i.type="array";let a="draft-2020-12"===r.target?"prefixItems":"items",s="draft-2020-12"===r.target||"openapi-3.0"===r.target?"items":"additionalItems",l=o.items.map((t,i)=>im(t,r,{...n,path:[...n.path,a,i]})),c=o.rest?im(o.rest,r,{...n,path:[...n.path,s,..."openapi-3.0"===r.target?[o.items.length]:[]]}):null,u=o.items.length;for(;u>0;){let t=o.items[u-1];if(!("input"===r.io?void 0!==iK(t):"optional"===t._zod.optout))break;u--}let d=o.items.length,p=!o.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 o=t._zod.def;im(o.innerType,r,n),r.seen.get(t).ref=o.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 o={};for(let a of(i.external={registry:t,uri:r?.uri,defs:n},t._idmap.entries())){let[t,r]=a;ig(i,r),es(o,t,iS(i,r))}return Object.keys(n).length>0&&(o.__shared={["draft-2020-12"===i.target?"$defs":"definitions"]:n}),{schemas:o}}let i=id({...r,processors:ni});return im(t,i),ig(i,t),iS(i,t)}let no={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},na={value:void 0,enumerable:!1},ns=new WeakSet([Object.prototype,Error.prototype]),nl=(t,r)=>{t.name="$ZodError",na.value=r,Object.defineProperty(t,"issues",na),na.value=void 0,Object.defineProperty(t,"message",no);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=eJ("$ZodError",nl);function nu(t,r){return{callee:r?.callee??t,Err:r?.Err}}eJ("$ZodError",nl,void 0,{Parent:Error});let nd=t=>{let r=(i,n,o,a)=>{let s=o?{...o,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(a?.Err??t)(l.issues.map(t=>eq(t,s,eK())));throw eh(i,a?.callee??r),i}return l.value};return r},np=t=>{let r=async(i,n,o,a)=>{let s=o?{...o,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(a?.Err??t)(l.issues.map(t=>eq(t,s,eK())));throw eh(i,a?.callee??r),i}return l.value};return r},nm=t=>(r,i,n)=>{let o=n?{...n,async:!1}:{async:!1},a=r._zod.run({value:i,issues:[]},o);if(a instanceof Promise)throw new eB;return a.issues.length?nh(t,a.issues,o):{success:!0,data:a.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 o=n?{...n,async:!0}:{async:!0},a=r._zod.run({value:i,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?nh(t,a.issues,o):{success:!0,data:a.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},o=t._zod.run({value:r,issues:[]},n);return o instanceof Promise&&(o=await o),0===o.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=eJ("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,o=[])=>{for(let a of t.issues)if("invalid_union"===a.code&&a.errors.length)a.errors.map(t=>n({issues:t},[...o,...a.path]));else if("invalid_key"===a.code)n({issues:a.issues},[...o,...a.path]);else if("invalid_element"===a.code)n({issues:a.issues},[...o,...a.path]);else{let t=[...o,...a.path];if(0===t.length)i._errors.push(r(a));else{let n=i,o=0;for(;o<t.length;){let i=t[o],s=o===t.length-1;if("_errors"===i){s&&n._errors.push(r(a)),o++;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(a)),n=l,o++}}}};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 o,a;(o=s.path[0],a=()=>[],!Object.prototype.hasOwnProperty.call(i,o)&&("__proto__"===o?Object.defineProperty(i,o,{value:a(),writable:!0,enumerable:!0,configurable:!0}):i[o]=a()),i[o]).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),nR=np(nS),nk=nm(nS),nx=nf(nS),nC=(m=nd(nS),h=(t,r,i,n)=>m(t,r,i?{...i,direction:"backward"}:{direction:"backward"},nu(h,n))),n$=(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 o=i?{...i,direction:"backward"}:{direction:"backward"};return await y(t,r,o,nu(v,n))}),nP=(_=np(nS),b=async(t,r,i,n)=>await _(t,r,i,nu(b,n))),nE=(t,r,i)=>{let n=i?{...i,direction:"backward"}:{direction:"backward"};return nm(nS)(t,r,n)},nO=(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 nA=eJ("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 ${eR(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 oV({type:"custom",check:"custom",fn:t,...ew(r)})}(t,r))},superRefine(t,r){return this.check(function(t,r){var i;let n,o;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)),(o=new tw({check:"custom",...ew(r)}))._zod.check=i,n=o}(t,r))},overwrite(t){return this.check(ic(t))},optional(){return oO(this)},exactOptional(){var t;return t=this,new oI({type:"optional",innerType:t})},nullable(){return oj(this)},nullish(){return oO(oj(this))},nonoptional(t){var r;return r=this,new oN({type:"nonoptional",innerType:r,...ew(t)})},array(){return op(this)},or(t){return oy([this,t])},and(t){return oS(this,t)},transform(t){return oZ(this,oP(t))},default(t){var r,i;return r=this,i=t,new oA({type:"default",innerType:r,get defaultValue(){return"function"==typeof i?i():ev(i)}})},prefault(t){var r,i;return r=this,i=t,new oL({type:"prefault",innerType:r,get defaultValue(){return"function"==typeof i?i():ev(i)}})},catch(t){return function(t,r){let i;return new oz({type:"catch",innerType:t,catchValue:"function"==typeof r?r:((i=()=>r)["~constantCatch"]=!0,i)})}(this,t)},pipe(t){return oZ(this,t)},readonly(){var t;return t=this,new oF({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 ez(this,"~standard",{...tV(this),jsonSchema:{input:iw(this,"input"),output:iw(this,"output")}},!1)},set"~standard"(value){ez(this,"~standard",value)},parse:function t(r,i){return nw(this,r,i,{callee:t})},parseAsync:async function t(r,i){return await nR(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){ez(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,o=i?{...i,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},a=t._zod.bag.fallbackRun;if(a?(o[ny]=!0,n=a({value:r,issues:[]},o)):n=t._zod.run({value:r,issues:[]},o),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 nC(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 nT(this,r,i,{callee:t})},decodeAsync:async function t(r,i){return await nP(this,r,i,{callee:t})},safeEncode(t,r){return nE(this,t,r)},safeDecode(t,r){return nO(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}}),nL=eJ("_ZodString",(t,r)=>{tJ.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iz(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 tL({check:"string_format",format:"includes",...ew(r),includes:t})}(...t))},startsWith(...t){return this.check(function(t,r){return new tN({check:"string_format",format:"starts_with",...ew(r),prefix:t})}(...t))},endsWith(...t){return this.check(function(t,r){return new tz({check:"string_format",format:"ends_with",...ew(r),suffix:t})}(...t))},min(...t){return this.check(is(...t))},max(...t){return this.check(ia(...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 tA({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,"")))}})),nN=eJ("ZodString",(t,r)=>{tJ.init(t,r),nL.init(t,r)},{email(t){return this.check(r3(nD,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 nV({type:"string",format:"guid",check:"string_format",abort:!1,...ew(t)}))},uuid(t){return this.check(new nJ({type:"string",format:"uuid",check:"string_format",abort:!1,...ew(t)}))},uuidv4(t){return this.check(new nJ({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ew(t)}))},uuidv6(t){return this.check(new nJ({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ew(t)}))},uuidv7(t){return this.check(new nJ({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 nz(t){return new nN(r5({type:"string",...ew(t)}))}let nM=eJ("ZodStringFormat",(t,r)=>{tB.init(t,r),nL.init(t,r)}),nZ=eJ("ZodISODateTime",(t,r)=>{t7.init(t,r),nM.init(t,r)}),nU=eJ("ZodISODate",(t,r)=>{t8.init(t,r),nM.init(t,r)}),nF=eJ("ZodISOTime",(t,r)=>{re.init(t,r),nM.init(t,r)}),nH=eJ("ZodISODuration",(t,r)=>{rt.init(t,r),nM.init(t,r)}),nD=eJ("ZodEmail",(t,r)=>{tK.init(t,r),nM.init(t,r)}),nV=eJ("ZodGUID",(t,r)=>{tW.init(t,r),nM.init(t,r)}),nJ=eJ("ZodUUID",(t,r)=>{tG.init(t,r),nM.init(t,r)}),nB=eJ("ZodURL",(t,r)=>{t0.init(t,r),nM.init(t,r)}),nW=eJ("ZodEmoji",(t,r)=>{t1.init(t,r),nM.init(t,r)}),nG=eJ("ZodNanoID",(t,r)=>{t2.init(t,r),nM.init(t,r)}),nK=eJ("ZodCUID",(t,r)=>{t9.init(t,r),nM.init(t,r)}),nY=eJ("ZodCUID2",(t,r)=>{t4.init(t,r),nM.init(t,r)}),nX=eJ("ZodULID",(t,r)=>{t5.init(t,r),nM.init(t,r)}),nQ=eJ("ZodXID",(t,r)=>{t3.init(t,r),nM.init(t,r)}),n0=eJ("ZodKSUID",(t,r)=>{t6.init(t,r),nM.init(t,r)}),n1=eJ("ZodIPv4",(t,r)=>{rr.init(t,r),nM.init(t,r)}),n2=eJ("ZodIPv6",(t,r)=>{ro.init(t,r),nM.init(t,r)}),n9=eJ("ZodCIDRv4",(t,r)=>{ra.init(t,r),nM.init(t,r)}),n4=eJ("ZodCIDRv6",(t,r)=>{rs.init(t,r),nM.init(t,r)}),n5=eJ("ZodBase64",(t,r)=>{ru.init(t,r),nM.init(t,r)}),n3=eJ("ZodBase64URL",(t,r)=>{rp.init(t,r),nM.init(t,r)}),n6=eJ("ZodE164",(t,r)=>{rm.init(t,r),nM.init(t,r)}),n7=eJ("ZodJWT",(t,r)=>{rh.init(t,r),nM.init(t,r)}),n8=eJ("ZodNumber",(t,r)=>{rf.init(t,r),nA.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(or(t))},safe(t){return this.check(or(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(io(t,r))},step(t,r){return this.check(io(t,r))},finite(){return this}}));function oe(t){return new n8(r5({type:"number",checks:[],...ew(t)}))}let ot=eJ("ZodNumberFormat",(t,r)=>{rg.init(t,r),n8.init(t,r)});function or(t){return new ot({type:"number",check:"number_format",abort:!1,format:"safeint",...ew(t)})}let oi=eJ("ZodBoolean",(t,r)=>{ry.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iZ(t,r,i,n)});function on(t){return new oi({type:"boolean",...ew(t)})}let oo=eJ("ZodNull",(t,r)=>{rv.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iU(t,r,i,n)});function oa(t){return new oo({type:"null",...ew(t)})}let os=eJ("ZodAny",(t,r)=>{r_.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iH(t,r,i,n)}),ol=eJ("ZodUnknown",(t,r)=>{rb.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iD(t,r,i,n)});function oc(){return new ol({type:"unknown"})}let ou=eJ("ZodNever",(t,r)=>{rS.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iF(t,r,i,n)}),od=eJ("ZodArray",(t,r)=>{nj(),rR.init(t,r),nA.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(ia(t,r))},length(t,r){return this.check(il(t,r))},unwrap(){return this.element}});function op(t,r){return new od({type:"array",element:t,...ew(r)})}let om=eJ("ZodObject",(t,r)=>{var i;let n,o;nj(),rP.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iY(t,r,i,n),i="shape",(o=i in(n=Object.getPrototypeOf(t))?void 0:n)&&Object.defineProperty(o,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 ox(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:oc()}))},loose(){return this.clone(em(this._zod.def,{catchall:oc()}))},strict(){return this.clone(em(this._zod.def,{catchall:new ou({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:e$(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: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 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 o={};return ep(o,t,eC(t,r)),eS(t,em(i,{shape:o,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 o=new Set(eC(t,r)),a={};return ep(a,t,Reflect.ownKeys(ec(t)).filter(t=>!o.has(t))),eS(t,em(i,{shape:a,checks:[]}))}(this,t)},partial(...t){return eT(oE,this,t[0])},exactPartial(...t){return eT(oI,this,t[0],"exactPartial")},required(...t){var r;let i,n;return i=(r=t[0])?new Set(eC(this,r)):void 0,ep(n={},this,Reflect.ownKeys(ec(this)),(t,r)=>i&&!i.has(r)?t:new oN({type:"nonoptional",innerType:t})),eS(this,em(this._zod.def,{shape:n}))}});function oh(t,r){return new om({type:"object",shape:t??{},...ew(r)})}function of(t,r){return new om({type:"object",shape:t,catchall:oc(),...ew(r)})}let og=eJ("ZodUnion",(t,r)=>{rO.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iX(t,r,i,n),t.options=r.options});function oy(t,r){return new og({type:"union",options:t,...ew(r)})}let ov=eJ("ZodDiscriminatedUnion",(t,r)=>{og.init(t,r),rI.init(t,r)});function o_(t,r,i){return new ov({type:"union",options:r,discriminator:t,...ew(i)})}let ob=eJ("ZodIntersection",(t,r)=>{rq.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iQ(t,r,i,n)});function oS(t,r){return new ob({type:"intersection",left:t,right:r})}let ow=eJ("ZodRecord",(t,r)=>{nj(),rA.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i1(t,r,i,n),t.keyType=r.keyType,t.valueType=r.valueType});function oR(t,r,i){return new ow(r&&r._zod?{type:"record",keyType:t,valueType:r,...ew(i)}:{type:"record",keyType:nz(),valueType:t,...ew(r)})}let ok=eJ("ZodEnum",(t,r)=>{rL.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iV(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 o={};for(let n of t)if(i.has(n))o[n]=r.entries[n];else throw Error(`Key ${n} not found in enum`);return new ok({...r,checks:[],...ew(n),entries:o})},t.exclude=(t,n)=>{let o={...r.entries};for(let r of t)if(i.has(r))delete o[r];else throw Error(`Key ${r} not found in enum`);return new ok({...r,checks:[],...ew(n),entries:o})}});function ox(t,r){return new ok({type:"enum",entries:Array.isArray(t)?Object.fromEntries(t.map(t=>[t,t])):t,...ew(r)})}let oC=eJ("ZodLiteral",(t,r)=>{rN.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iJ(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 o$(t,r){return new oC({type:"literal",values:Array.isArray(t)?t:[t],...ew(r)})}let oT=eJ("ZodTransform",(t,r)=>{nj(),rz.init(t,r),nA.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(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 o=r.transform(i.value,i);return o instanceof Promise?o.then(t=>(i.value=t,i)):(i.value=o,i)}});function oP(t){return new oT({type:"transform",transform:t})}let oE=eJ("ZodOptional",(t,r)=>{rZ.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>nt(t,r,i,n),t.unwrap=()=>t._zod.def.innerType});function oO(t){return new oE({type:"optional",innerType:t})}let oI=eJ("ZodExactOptional",(t,r)=>{rU.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>nt(t,r,i,n),t.unwrap=()=>t._zod.def.innerType}),oq=eJ("ZodNullable",(t,r)=>{rF.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i2(t,r,i,n),t.unwrap=()=>t._zod.def.innerType});function oj(t){return new oq({type:"nullable",innerType:t})}let oA=eJ("ZodDefault",(t,r)=>{rH.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i3(t,r,i,n),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap}),oL=eJ("ZodPrefault",(t,r)=>{rV.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i6(t,r,i,n),t.unwrap=()=>t._zod.def.innerType}),oN=eJ("ZodNonOptional",(t,r)=>{rJ.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i9(t,r,i,n),t.unwrap=()=>t._zod.def.innerType}),oz=eJ("ZodCatch",(t,r)=>{rG.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i7(t,r,i,n),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap}),oM=eJ("ZodPipe",(t,r)=>{rK.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>i8(t,r,i,n),t.in=r.in,t.out=r.out});function oZ(t,r){return new oM({type:"pipe",in:t,out:r})}let oU=eJ("ZodPreprocess",(t,r)=>{oM.init(t,r),rX.init(t,r)}),oF=eJ("ZodReadonly",(t,r)=>{rQ.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>ne(t,r,i,n),t.unwrap=()=>t._zod.def.innerType}),oH=eJ("ZodLazy",(t,r)=>{r1.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>nr(t,r,i,n),t.unwrap=()=>t._zod.def.getter()});function oD(t){return new oH({type:"lazy",getter:t})}let oV=eJ("ZodCustom",(t,r)=>{r2.init(t,r),nA.init(t,r),t._zod.processJSONSchema=(r,i,n)=>iB(t,r,i,n)});function oJ(t,r){return new oU({type:"pipe",in:oP(t),out:r})}A||(A={});let oB="2025-11-25",oW=[oB,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],oG="io.modelcontextprotocol/protocolVersion",oK="io.modelcontextprotocol/clientInfo",oY="io.modelcontextprotocol/serverInfo",oX="io.modelcontextprotocol/clientCapabilities",oQ="io.modelcontextprotocol/subscriptionId",o0="io.modelcontextprotocol/logLevel",o1=oD(()=>oy([nz(),oe(),on(),oa(),oR(nz(),o1),op(o1)])),o2=oR(nz(),o1),o9=op(o1),o4=oy([nz(),oe().int()]),o5=nz(),o3=oh({ttl:oe().optional()}),o6=oh({taskId:nz()}),o7=of({progressToken:o4.optional(),"io.modelcontextprotocol/related-task":o6.optional()}),o8=oh({_meta:o7.optional()}),ae=o8.extend({task:o3.optional()}),at=oh({method:nz(),params:o8.loose().optional()}),ar=oh({_meta:o7.optional()}),ai=oh({method:nz(),params:ar.loose().optional()}),an=of({get[oY](){return a_.optional().catch(void 0)}}),ao=of({_meta:an.optional()}),aa=oy([nz(),oe().int()]),as=oh({jsonrpc:o$("2.0"),id:aa,...at.shape}).strict(),al=oh({jsonrpc:o$("2.0"),...ai.shape}).strict(),ac=oh({jsonrpc:o$("2.0"),id:aa,result:ao}).strict(),au=oh({jsonrpc:o$("2.0"),id:aa.optional(),error:oh({code:oe().int(),message:nz(),data:oc().optional()})}).strict(),ad=oy([as,al,ac,au]),ap=oy([ac,au]),am=ao.strict(),ah=ar.extend({requestId:aa.optional(),reason:nz().optional()}),af=ai.extend({method:o$("notifications/cancelled"),params:ah}),ag=oh({src:nz(),mimeType:nz().optional(),sizes:op(nz()).optional(),theme:ox(["light","dark"]).optional()}),ay=oh({icons:op(ag).optional()}),av=oh({name:nz(),title:nz().optional()}),a_=av.extend({...av.shape,...ay.shape,version:nz(),websiteUrl:nz().optional(),description:nz().optional()}),ab=oS(oh({applyDefaults:on().optional()}),o2),aS=oJ(t=>t&&"object"==typeof t&&!Array.isArray(t)&&0===Object.keys(t).length?{form:{}}:t,oS(oh({form:ab.optional(),url:o2.optional()}),o2.optional())),aw=of({list:o2.optional(),cancel:o2.optional(),requests:of({sampling:of({createMessage:o2.optional()}).optional(),elicitation:of({create:o2.optional()}).optional()}).optional()}),aR=of({list:o2.optional(),cancel:o2.optional(),requests:of({tools:of({call:o2.optional()}).optional()}).optional()}),ak=oh({experimental:oR(nz(),o2).optional(),sampling:oh({context:o2.optional(),tools:o2.optional()}).optional(),elicitation:aS.optional(),roots:oh({listChanged:on().optional()}).optional(),tasks:aw.optional(),extensions:oR(nz(),o2).optional()}),ax=o8.extend({protocolVersion:nz(),capabilities:ak,clientInfo:a_}),aC=at.extend({method:o$("initialize"),params:ax}),a$=oh({experimental:oR(nz(),o2).optional(),logging:o2.optional(),completions:o2.optional(),prompts:oh({listChanged:on().optional()}).optional(),resources:oh({subscribe:on().optional(),listChanged:on().optional()}).optional(),tools:oh({listChanged:on().optional()}).optional(),tasks:aR.optional(),extensions:oR(nz(),o2).optional()}),aT=ao.extend({protocolVersion:nz(),capabilities:a$,serverInfo:a_,instructions:nz().optional()}),aP=ai.extend({method:o$("notifications/initialized"),params:ar.optional()}),aE=at.extend({method:o$("server/discover"),params:o8.optional()}),aO=ao.extend({supportedVersions:op(nz()),capabilities:a$,instructions:nz().optional()}),aI=at.extend({method:o$("ping"),params:o8.optional()}),aq=oh({progress:oe(),total:oO(oe()),message:oO(nz())}),aj=oh({...ar.shape,...aq.shape,progressToken:o4}),aA=ai.extend({method:o$("notifications/progress"),params:aj}),aL=o8.extend({cursor:o5.optional()}),aN=at.extend({params:aL.optional()}),az=ao.extend({nextCursor:o5.optional()}),aM=oh({uri:nz(),mimeType:oO(nz()),_meta:oR(nz(),oc()).optional()}),aZ=aM.extend({text:nz()}),aU=nz().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),aF=aM.extend({blob:aU}),aH=ox(["user","assistant"]),aD=oh({audience:op(aH).optional(),priority:oe().min(0).max(1).optional(),lastModified:r7(nZ,{offset:!0}).optional()}),aV=oh({...av.shape,...ay.shape,uri:nz(),description:oO(nz()),mimeType:oO(nz()),size:oO(oe()),annotations:aD.optional(),_meta:oO(of({}))}),aJ=oh({...av.shape,...ay.shape,uriTemplate:nz(),description:oO(nz()),mimeType:oO(nz()),annotations:aD.optional(),_meta:oO(of({}))}),aB=aN.extend({method:o$("resources/list")}),aW=az.extend({resources:op(aV)}),aG=aN.extend({method:o$("resources/templates/list")}),aK=az.extend({resourceTemplates:op(aJ)}),aY=o8.extend({uri:nz()}),aX=at.extend({method:o$("resources/read"),params:aY}),aQ=ao.extend({contents:op(oy([aZ,aF]))}),a0=ai.extend({method:o$("notifications/resources/list_changed"),params:ar.optional()}),a1=at.extend({method:o$("resources/subscribe"),params:aY}),a2=at.extend({method:o$("resources/unsubscribe"),params:aY}),a9=oh({toolsListChanged:on().optional(),promptsListChanged:on().optional(),resourcesListChanged:on().optional(),resourceSubscriptions:op(nz()).optional()}),a4=o8.extend({notifications:a9}),a5=at.extend({method:o$("subscriptions/listen"),params:a4}),a3=ar.extend({notifications:a9}),a6=ai.extend({method:o$("notifications/subscriptions/acknowledged"),params:a3}),a7=an.extend({[oQ]:aa}),a8=ao.extend({_meta:a7}),se=ar.extend({uri:nz()}),st=ai.extend({method:o$("notifications/resources/updated"),params:se}),sr=oh({name:nz(),description:oO(nz()),required:oO(on())}),si=oh({...av.shape,...ay.shape,description:oO(nz()),arguments:oO(op(sr)),_meta:oO(of({}))}),sn=aN.extend({method:o$("prompts/list")}),so=az.extend({prompts:op(si)}),sa=o8.extend({name:nz(),arguments:oR(nz(),nz()).optional()}),ss=at.extend({method:o$("prompts/get"),params:sa}),sl=oh({type:o$("text"),text:nz(),annotations:aD.optional(),_meta:oR(nz(),oc()).optional()}),sc=oh({type:o$("image"),data:aU,mimeType:nz(),annotations:aD.optional(),_meta:oR(nz(),oc()).optional()}),su=oh({type:o$("audio"),data:aU,mimeType:nz(),annotations:aD.optional(),_meta:oR(nz(),oc()).optional()}),sd=oh({type:o$("tool_use"),name:nz(),id:nz(),input:oR(nz(),oc()),_meta:oR(nz(),oc()).optional()}),sp=oh({type:o$("resource"),resource:oy([aZ,aF]),annotations:aD.optional(),_meta:oR(nz(),oc()).optional()}),sm=aV.extend({type:o$("resource_link")}),sh=oy([sl,sc,su,sm,sp]),sf=oh({role:aH,content:sh}),sg=ao.extend({description:nz().optional(),messages:op(sf)}),sy=ai.extend({method:o$("notifications/prompts/list_changed"),params:ar.optional()}),sv=oh({title:nz().optional(),readOnlyHint:on().optional(),destructiveHint:on().optional(),idempotentHint:on().optional(),openWorldHint:on().optional()}),s_=oh({taskSupport:ox(["required","optional","forbidden"]).optional()}),sb=oh({...av.shape,...ay.shape,description:nz().optional(),inputSchema:oh({type:o$("object"),properties:oR(nz(),o1).optional(),required:op(nz()).optional()}).catchall(oc()),outputSchema:of({$schema:nz().optional()}).optional(),annotations:sv.optional(),execution:s_.optional(),_meta:oR(nz(),oc()).optional()}),sS=aN.extend({method:o$("tools/list")}),sw=az.extend({tools:op(sb)}),sR=ao.extend({content:op(sh).default([]),structuredContent:oc().optional(),isError:on().optional()}),sk=sR.or(ao.extend({toolResult:oc()})),sx=ae.extend({name:nz(),arguments:oR(nz(),oc()).optional()}),sC=at.extend({method:o$("tools/call"),params:sx}),s$=ai.extend({method:o$("notifications/tools/list_changed"),params:ar.optional()}),sT=oh({autoRefresh:on().default(!0),debounceMs:oe().int().nonnegative().default(300)}),sP=ox(["debug","info","notice","warning","error","critical","alert","emergency"]),sE=o8.extend({level:sP}),sO=at.extend({method:o$("logging/setLevel"),params:sE}),sI=ar.extend({level:sP,logger:nz().optional(),data:oc()}),sq=ai.extend({method:o$("notifications/message"),params:sI}),sj=oh({name:nz().optional()}),sA=oh({hints:op(sj).optional(),costPriority:oe().min(0).max(1).optional(),speedPriority:oe().min(0).max(1).optional(),intelligencePriority:oe().min(0).max(1).optional()}),sL=oh({mode:ox(["auto","required","none"]).optional()}),sN=oh({type:o$("tool_result"),toolUseId:nz().describe("The unique identifier for the corresponding tool call."),content:op(sh),structuredContent:oc().optional(),isError:on().optional(),_meta:oR(nz(),oc()).optional()}),sz=o_("type",[sl,sc,su]),sM=o_("type",[sl,sc,su,sd,sN]),sZ=oh({role:aH,content:oy([sM,op(sM)]),_meta:oR(nz(),oc()).optional()}),sU=ae.extend({messages:op(sZ),modelPreferences:sA.optional(),systemPrompt:nz().optional(),includeContext:ox(["none","thisServer","allServers"]).optional(),temperature:oe().optional(),maxTokens:oe().int(),stopSequences:op(nz()).optional(),metadata:o2.optional(),tools:op(sb).optional(),toolChoice:sL.optional()}),sF=at.extend({method:o$("sampling/createMessage"),params:sU}),sH=ao.extend({model:nz(),stopReason:oO(ox(["endTurn","stopSequence","maxTokens"]).or(nz())),role:aH,content:sz}),sD=ao.extend({model:nz(),stopReason:oO(ox(["endTurn","stopSequence","maxTokens","toolUse"]).or(nz())),role:aH,content:oy([sM,op(sM)])}),sV=oh({type:o$("boolean"),title:nz().optional(),description:nz().optional(),default:on().optional()}),sJ=oh({type:o$("string"),title:nz().optional(),description:nz().optional(),minLength:oe().optional(),maxLength:oe().optional(),format:ox(["email","uri","date","date-time"]).optional(),default:nz().optional()}),sB=oh({type:ox(["number","integer"]),title:nz().optional(),description:nz().optional(),minimum:oe().optional(),maximum:oe().optional(),default:oe().optional()}),sW=oh({type:o$("string"),title:nz().optional(),description:nz().optional(),enum:op(nz()),default:nz().optional()}),sG=oh({type:o$("string"),title:nz().optional(),description:nz().optional(),oneOf:op(oh({const:nz(),title:nz()})),default:nz().optional()}),sK=oh({type:o$("string"),title:nz().optional(),description:nz().optional(),enum:op(nz()),enumNames:op(nz()).optional(),default:nz().optional()}),sY=oy([sW,sG]),sX=oh({type:o$("array"),title:nz().optional(),description:nz().optional(),minItems:oe().optional(),maxItems:oe().optional(),items:oh({type:o$("string"),enum:op(nz())}),default:op(nz()).optional()}),sQ=oh({type:o$("array"),title:nz().optional(),description:nz().optional(),minItems:oe().optional(),maxItems:oe().optional(),items:oh({anyOf:op(oh({const:nz(),title:nz()}))}),default:op(nz()).optional()}),s0=oy([sX,sQ]),s1=oy([sK,sY,s0]),s2=oy([s1,sV,sJ,sB]),s9=ae.extend({mode:o$("form").optional(),message:nz(),requestedSchema:oh({type:o$("object"),properties:oR(nz(),s2),required:op(nz()).optional()}).catchall(oc())}),s4=ae.extend({mode:o$("url"),message:nz(),elicitationId:nz(),url:nz().url()}),s5=oy([s9,s4]),s3=at.extend({method:o$("elicitation/create"),params:s5}),s6=ar.extend({elicitationId:nz()}),s7=ai.extend({method:o$("notifications/elicitation/complete"),params:s6}),s8=ao.extend({action:ox(["accept","decline","cancel"]),content:oJ(t=>null===t?void 0:t,oR(nz(),oy([nz(),oe(),on(),op(nz())])).optional())}),le=oh({type:o$("ref/resource"),uri:nz()}),lt=oh({type:o$("ref/prompt"),name:nz()}),lr=o8.extend({ref:oy([lt,le]),argument:oh({name:nz(),value:nz()}),context:oh({arguments:oR(nz(),nz()).optional()}).optional()}),li=at.extend({method:o$("completion/complete"),params:lr}),ln=ao.extend({completion:of({values:op(nz()).max(100),total:oO(oe().int()),hasMore:oO(on())})}),lo=oh({uri:nz().startsWith("file://"),name:nz().optional(),_meta:oR(nz(),oc()).optional()}),la=at.extend({method:o$("roots/list"),params:o8.optional()}),ls=ao.extend({roots:op(lo)}),ll=ai.extend({method:o$("notifications/roots/list_changed"),params:ar.optional()}),lc=of({ttl:oe().optional(),pollInterval:oe().optional()}),lu=ox(["working","input_required","completed","failed","cancelled"]),ld=oh({taskId:nz(),status:lu,ttl:oy([oe(),oa()]),createdAt:nz(),lastUpdatedAt:nz(),pollInterval:oO(oe()),statusMessage:oO(nz())}),lp=ao.extend({task:ld}),lm=ar.merge(ld),lh=ai.extend({method:o$("notifications/tasks/status"),params:lm}),lf=at.extend({method:o$("tasks/get"),params:o8.extend({taskId:nz()})}),lg=ao.merge(ld),ly=at.extend({method:o$("tasks/result"),params:o8.extend({taskId:nz()})}),lv=ao.loose(),l_=aN.extend({method:o$("tasks/list")}),lb=az.extend({tasks:op(ld)}),lS=at.extend({method:o$("tasks/cancel"),params:o8.extend({taskId:nz()})}),lw=ao.merge(ld),lR=oy([aI,aC,aE,li,sO,ss,sn,aB,aG,aX,a1,a2,a5,sC,sS]),lk=oy([af,aA,aP,ll]),lx=oy([am,sH,sD,s8,ls]),lC=oy([aI,sF,s3,la]),l$=oy([af,aA,sq,st,a0,s$,sy,a6,s7]),lT=oy([am,aT,aO,ln,sg,so,aW,aK,aQ,sR,sw,a8]),lP=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"}),lE=of({resource:nz().url(),authorization_servers:op(lP).optional(),jwks_uri:nz().url().optional(),scopes_supported:op(nz()).optional(),bearer_methods_supported:op(nz()).optional(),resource_signing_alg_values_supported:op(nz()).optional(),resource_name:nz().optional(),resource_documentation:nz().optional(),resource_policy_uri:nz().url().optional(),resource_tos_uri:nz().url().optional(),tls_client_certificate_bound_access_tokens:on().optional(),authorization_details_types_supported:op(nz()).optional(),dpop_signing_alg_values_supported:op(nz()).optional(),dpop_bound_access_tokens_required:on().optional()}),lO=of({issuer:nz(),authorization_endpoint:lP,token_endpoint:lP,registration_endpoint:lP.optional(),scopes_supported:op(nz()).optional(),response_types_supported:op(nz()),response_modes_supported:op(nz()).optional(),grant_types_supported:op(nz()).optional(),token_endpoint_auth_methods_supported:op(nz()).optional(),token_endpoint_auth_signing_alg_values_supported:op(nz()).optional(),service_documentation:lP.optional(),revocation_endpoint:lP.optional(),revocation_endpoint_auth_methods_supported:op(nz()).optional(),revocation_endpoint_auth_signing_alg_values_supported:op(nz()).optional(),introspection_endpoint:nz().optional(),introspection_endpoint_auth_methods_supported:op(nz()).optional(),introspection_endpoint_auth_signing_alg_values_supported:op(nz()).optional(),code_challenge_methods_supported:op(nz()).optional(),client_id_metadata_document_supported:on().optional(),authorization_response_iss_parameter_supported:on().optional().catch(void 0),dpop_signing_alg_values_supported:op(nz()).optional()}),lI=of({issuer:nz(),authorization_endpoint:lP,token_endpoint:lP,userinfo_endpoint:lP.optional(),jwks_uri:lP,registration_endpoint:lP.optional(),scopes_supported:op(nz()).optional(),response_types_supported:op(nz()),response_modes_supported:op(nz()).optional(),grant_types_supported:op(nz()).optional(),acr_values_supported:op(nz()).optional(),subject_types_supported:op(nz()),id_token_signing_alg_values_supported:op(nz()),id_token_encryption_alg_values_supported:op(nz()).optional(),id_token_encryption_enc_values_supported:op(nz()).optional(),userinfo_signing_alg_values_supported:op(nz()).optional(),userinfo_encryption_alg_values_supported:op(nz()).optional(),userinfo_encryption_enc_values_supported:op(nz()).optional(),request_object_signing_alg_values_supported:op(nz()).optional(),request_object_encryption_alg_values_supported:op(nz()).optional(),request_object_encryption_enc_values_supported:op(nz()).optional(),token_endpoint_auth_methods_supported:op(nz()).optional(),token_endpoint_auth_signing_alg_values_supported:op(nz()).optional(),display_values_supported:op(nz()).optional(),claim_types_supported:op(nz()).optional(),claims_supported:op(nz()).optional(),service_documentation:nz().optional(),claims_locales_supported:op(nz()).optional(),ui_locales_supported:op(nz()).optional(),claims_parameter_supported:on().optional(),request_parameter_supported:on().optional(),request_uri_parameter_supported:on().optional(),require_request_uri_registration:on().optional(),op_policy_uri:lP.optional(),op_tos_uri:lP.optional(),client_id_metadata_document_supported:on().optional(),authorization_response_iss_parameter_supported:on().optional().catch(void 0)}),lq=oh({...lI.shape,...lO.pick({code_challenge_methods_supported:!0}).shape}),lj=oh({access_token:nz(),id_token:nz().optional(),token_type:nz(),expires_in:new n8(r5({type:"number",coerce:!0,checks:[],...ew(void 0)})).optional(),scope:nz().optional(),refresh_token:nz().optional(),issuer:nz().optional().catch(void 0)}).strip(),lA=oh({issued_token_type:o$("urn:ietf:params:oauth:token-type:id-jag"),access_token:nz(),token_type:nz().optional(),expires_in:oe().optional(),scope:nz().optional()}).strip(),lL=oh({error:nz(),error_description:nz().optional(),error_uri:nz().optional()}),lN=lP.optional().or(o$("").transform(()=>void 0)),lz=oh({redirect_uris:op(lP),token_endpoint_auth_method:nz().optional(),grant_types:op(nz()).optional(),response_types:op(nz()).optional(),application_type:nz().optional(),client_name:nz().optional(),client_uri:lP.optional(),logo_uri:lN,scope:nz().optional(),contacts:op(nz()).optional(),tos_uri:lN,policy_uri:nz().optional(),jwks_uri:lP.optional(),jwks:new os({type:"any"}).optional(),software_id:nz().optional(),software_version:nz().optional(),software_statement:nz().optional()}).strip(),lM=oh({client_id:nz(),client_secret:nz().optional(),client_id_issued_at:oe().optional(),client_secret_expires_at:oe().optional(),issuer:nz().optional().catch(void 0)}).strip(),lZ=lz.merge(lM),lU=oh({error:nz(),error_description:nz().optional()}).strip(),lF=oh({token:nz(),token_type_hint:nz().optional()}).strip(),lH=Symbol.for("mcp.sdk.errorBrands");function lD(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 lV(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)}let lJ=((C={}).InvalidRequest="invalid_request",C.InvalidClient="invalid_client",C.InvalidGrant="invalid_grant",C.UnauthorizedClient="unauthorized_client",C.UnsupportedGrantType="unsupported_grant_type",C.InvalidScope="invalid_scope",C.AccessDenied="access_denied",C.ServerError="server_error",C.TemporarilyUnavailable="temporarily_unavailable",C.UnsupportedResponseType="unsupported_response_type",C.UnsupportedTokenType="unsupported_token_type",C.InvalidToken="invalid_token",C.MethodNotAllowed="method_not_allowed",C.TooManyRequests="too_many_requests",C.InvalidClientMetadata="invalid_client_metadata",C.InvalidRedirectUri="invalid_redirect_uri",C.InsufficientScope="insufficient_scope",C.InvalidTarget="invalid_target",C.InvalidDpopProof="invalid_dpop_proof",C.UseDpopNonce="use_dpop_nonce",C);var lB=class t extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return lV(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 lV(this,t)}constructor(t,r,i){super(r),this.code=t,this.errorUri=i,this.name="OAuthError",lD(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 lW=(($={}).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 lG=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](t){return lV(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 lV(this,t)}constructor(t,r,i,n){super(r,n),this.code=t,this.data=i,this.name="SdkError",lD(this,new.target)}};(class extends lG{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(t,r,i,n){super(t,r,i,n),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}});let lK={};function lY(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function lX(t,r){let i={};for(let[n,o]of Object.entries(t)){if(void 0===o)continue;let t=void 0===r?void 0:r[n];if(void 0===t){i[n]=o;continue}if(lY(o)&&lY(t)){let r={};for(let[i,a]of Object.entries(o))void 0!==a&&void 0===t[i]&&("elicitation"!==n||"form"!==i||void 0!==t.form||void 0!==t.url)&&(r[i]=a);Object.keys(r).length>0&&(i[n]=r)}}return Object.keys(i).length>0?i:void 0}let lQ="2026-07-28",l0=[lQ];function l1(t){return t.filter(t=>t>=lQ)}function l2(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 l9=["task","inputRequests","requestState"];function l4(t){return null===t||"object"!=typeof t||Array.isArray(t)||void 0!==t.content||l9.some(r=>r in t)?t:{...t,content:[]}}function l5(){let t,r,n,o,a,s,l,c,u,d,p,m,h,f,g,y,v,_,b,S,w,R,k,x,C,$,T,P,E,O,I,q,j,A,L,N,z,M,Z,U,F,H,D,V,J,B,W,G,K,Y,X,Q,ee,et,er,ei,en,eo,ea,es,el,ec,eu,ed,ep,em,eh,ef,eg,ey,ev,e_,eb,eS,ew,eR,ek,ex,eC,e$,eT,eP,eE,eO,eI,eq,ej,eA,eL,eN,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,to,ta,ts,tl,tc,tu,td,tp,tm,th,tf,tg,ty,tv,t_,tb,tS,tw,tR;return i??=(t=oD(()=>oy([nz(),oe(),on(),oa(),oR(nz(),t),op(t)])),r=oR(nz(),t),n=oy([nz(),oe().int()]),o=nz(),a=oh({ttl:oe().optional()}),s=oh({taskId:nz()}),u=(c=oh({_meta:(l=of({progressToken:n.optional(),"io.modelcontextprotocol/related-task":s.optional()})).optional()})).extend({task:a.optional()}),d=oh({method:nz(),params:c.loose().optional()}),p=oh({_meta:l.optional()}),m=oh({method:nz(),params:p.loose().optional()}),h=of({_meta:l.optional()}),f=oy([nz(),oe().int()]),g=h.strict(),y=p.extend({requestId:f.optional(),reason:nz().optional()}),v=m.extend({method:o$("notifications/cancelled"),params:y}),_=oh({src:nz(),mimeType:nz().optional(),sizes:op(nz()).optional(),theme:ox(["light","dark"]).optional()}),b=oh({icons:op(_).optional()}),w=(S=oh({name:nz(),title:nz().optional()})).extend({...S.shape,...b.shape,version:nz(),websiteUrl:nz().optional(),description:nz().optional()}),R=oS(oh({applyDefaults:on().optional()}),r),k=oJ(t=>t&&"object"==typeof t&&!Array.isArray(t)&&0===Object.keys(t).length?{form:{}}:t,oS(oh({form:R.optional(),url:r.optional()}),r.optional())),x=of({list:r.optional(),cancel:r.optional(),requests:of({sampling:of({createMessage:r.optional()}).optional(),elicitation:of({create:r.optional()}).optional()}).optional()}),C=of({list:r.optional(),cancel:r.optional(),requests:of({tools:of({call:r.optional()}).optional()}).optional()}),$=oh({experimental:oR(nz(),r).optional(),sampling:oh({context:r.optional(),tools:r.optional()}).optional(),elicitation:k.optional(),roots:oh({listChanged:on().optional()}).optional(),tasks:x.optional(),extensions:oR(nz(),r).optional()}),T=c.extend({protocolVersion:nz(),capabilities:$,clientInfo:w}),P=d.extend({method:o$("initialize"),params:T}),E=oh({experimental:oR(nz(),r).optional(),logging:r.optional(),completions:r.optional(),prompts:oh({listChanged:on().optional()}).optional(),resources:oh({subscribe:on().optional(),listChanged:on().optional()}).optional(),tools:oh({listChanged:on().optional()}).optional(),tasks:C.optional(),extensions:oR(nz(),r).optional()}),O=h.extend({protocolVersion:nz(),capabilities:E,serverInfo:w,instructions:nz().optional()}),I=m.extend({method:o$("notifications/initialized"),params:p.optional()}),q=d.extend({method:o$("ping"),params:c.optional()}),j=oh({progress:oe(),total:oO(oe()),message:oO(nz())}),A=oh({...p.shape,...j.shape,progressToken:n}),L=m.extend({method:o$("notifications/progress"),params:A}),N=c.extend({cursor:o.optional()}),z=d.extend({params:N.optional()}),M=h.extend({nextCursor:o.optional()}),U=(Z=oh({uri:nz(),mimeType:oO(nz()),_meta:oR(nz(),oc()).optional()})).extend({text:nz()}),F=nz().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),H=Z.extend({blob:F}),V=oh({audience:op(D=ox(["user","assistant"])).optional(),priority:oe().min(0).max(1).optional(),lastModified:r7(nZ,{offset:!0}).optional()}),J=oh({...S.shape,...b.shape,uri:nz(),description:oO(nz()),mimeType:oO(nz()),size:oO(oe()),annotations:V.optional(),_meta:oO(of({}))}),B=oh({...S.shape,...b.shape,uriTemplate:nz(),description:oO(nz()),mimeType:oO(nz()),annotations:V.optional(),_meta:oO(of({}))}),W=z.extend({method:o$("resources/list")}),G=M.extend({resources:op(J)}),K=z.extend({method:o$("resources/templates/list")}),Y=M.extend({resourceTemplates:op(B)}),X=c.extend({uri:nz()}),Q=d.extend({method:o$("resources/read"),params:X}),ee=h.extend({contents:op(oy([U,H]))}),et=m.extend({method:o$("notifications/resources/list_changed"),params:p.optional()}),er=d.extend({method:o$("resources/subscribe"),params:X}),ei=d.extend({method:o$("resources/unsubscribe"),params:X}),en=p.extend({uri:nz()}),eo=m.extend({method:o$("notifications/resources/updated"),params:en}),ea=oh({name:nz(),description:oO(nz()),required:oO(on())}),es=oh({...S.shape,...b.shape,description:oO(nz()),arguments:oO(op(ea)),_meta:oO(of({}))}),el=z.extend({method:o$("prompts/list")}),ec=M.extend({prompts:op(es)}),eu=c.extend({name:nz(),arguments:oR(nz(),nz()).optional()}),ed=d.extend({method:o$("prompts/get"),params:eu}),ep=oh({type:o$("text"),text:nz(),annotations:V.optional(),_meta:oR(nz(),oc()).optional()}),em=oh({type:o$("image"),data:F,mimeType:nz(),annotations:V.optional(),_meta:oR(nz(),oc()).optional()}),eh=oh({type:o$("audio"),data:F,mimeType:nz(),annotations:V.optional(),_meta:oR(nz(),oc()).optional()}),ef=oh({type:o$("tool_use"),name:nz(),id:nz(),input:oR(nz(),oc()),_meta:oR(nz(),oc()).optional()}),eg=oh({type:o$("resource"),resource:oy([U,H]),annotations:V.optional(),_meta:oR(nz(),oc()).optional()}),e_=oh({role:D,content:ev=oy([ep,em,eh,ey=J.extend({type:o$("resource_link")}),eg])}),eb=h.extend({description:nz().optional(),messages:op(e_)}),eS=m.extend({method:o$("notifications/prompts/list_changed"),params:p.optional()}),ew=oh({title:nz().optional(),readOnlyHint:on().optional(),destructiveHint:on().optional(),idempotentHint:on().optional(),openWorldHint:on().optional()}),eR=oh({taskSupport:ox(["required","optional","forbidden"]).optional()}),ek=oh({...S.shape,...b.shape,description:nz().optional(),inputSchema:oh({type:o$("object"),properties:oR(nz(),t).optional(),required:op(nz()).optional()}).catchall(oc()),outputSchema:oh({type:o$("object"),properties:oR(nz(),t).optional(),required:op(nz()).optional()}).catchall(oc()).optional(),annotations:ew.optional(),execution:eR.optional(),_meta:oR(nz(),oc()).optional()}),ex=z.extend({method:o$("tools/list")}),eC=M.extend({tools:op(ek)}),e$=h.extend({content:op(ev),structuredContent:oR(nz(),oc()).optional(),isError:on().optional()}),eT=u.extend({name:nz(),arguments:oR(nz(),oc()).optional()}),eP=d.extend({method:o$("tools/call"),params:eT}),eE=m.extend({method:o$("notifications/tools/list_changed"),params:p.optional()}),eO=ox(["debug","info","notice","warning","error","critical","alert","emergency"]),eI=c.extend({level:eO}),eq=d.extend({method:o$("logging/setLevel"),params:eI}),ej=p.extend({level:eO,logger:nz().optional(),data:oc()}),eA=m.extend({method:o$("notifications/message"),params:ej}),eL=oh({name:nz().optional()}),eN=oh({hints:op(eL).optional(),costPriority:oe().min(0).max(1).optional(),speedPriority:oe().min(0).max(1).optional(),intelligencePriority:oe().min(0).max(1).optional()}),ez=oh({mode:ox(["auto","required","none"]).optional()}),eM=oh({type:o$("tool_result"),toolUseId:nz().describe("The unique identifier for the corresponding tool call."),content:op(ev),structuredContent:oh({}).loose().optional(),isError:on().optional(),_meta:oR(nz(),oc()).optional()}),eZ=o_("type",[ep,em,eh]),eF=oh({role:D,content:oy([eU=o_("type",[ep,em,eh,ef,eM]),op(eU)]),_meta:oR(nz(),oc()).optional()}),eH=u.extend({messages:op(eF),modelPreferences:eN.optional(),systemPrompt:nz().optional(),includeContext:ox(["none","thisServer","allServers"]).optional(),temperature:oe().optional(),maxTokens:oe().int(),stopSequences:op(nz()).optional(),metadata:r.optional(),tools:op(ek).optional(),toolChoice:ez.optional()}),eD=d.extend({method:o$("sampling/createMessage"),params:eH}),eV=h.extend({model:nz(),stopReason:oO(ox(["endTurn","stopSequence","maxTokens"]).or(nz())),role:D,content:eZ}),eJ=h.extend({model:nz(),stopReason:oO(ox(["endTurn","stopSequence","maxTokens","toolUse"]).or(nz())),role:D,content:oy([eU,op(eU)])}),eB=oh({type:o$("boolean"),title:nz().optional(),description:nz().optional(),default:on().optional()}),eW=oh({type:o$("string"),title:nz().optional(),description:nz().optional(),minLength:oe().optional(),maxLength:oe().optional(),format:ox(["email","uri","date","date-time"]).optional(),default:nz().optional()}),eG=oh({type:ox(["number","integer"]),title:nz().optional(),description:nz().optional(),minimum:oe().optional(),maximum:oe().optional(),default:oe().optional()}),eK=oh({type:o$("string"),title:nz().optional(),description:nz().optional(),enum:op(nz()),default:nz().optional()}),eY=oh({type:o$("string"),title:nz().optional(),description:nz().optional(),oneOf:op(oh({const:nz(),title:nz()})),default:nz().optional()}),eX=oh({type:o$("string"),title:nz().optional(),description:nz().optional(),enum:op(nz()),enumNames:op(nz()).optional(),default:nz().optional()}),eQ=oy([eK,eY]),e0=oh({type:o$("array"),title:nz().optional(),description:nz().optional(),minItems:oe().optional(),maxItems:oe().optional(),items:oh({type:o$("string"),enum:op(nz())}),default:op(nz()).optional()}),e2=oy([e0,e1=oh({type:o$("array"),title:nz().optional(),description:nz().optional(),minItems:oe().optional(),maxItems:oe().optional(),items:oh({anyOf:op(oh({const:nz(),title:nz()}))}),default:op(nz()).optional()})]),e9=oy([eX,eQ,e2]),e4=oy([e9,eB,eW,eG]),e5=u.extend({mode:o$("form").optional(),message:nz(),requestedSchema:oh({type:o$("object"),properties:oR(nz(),e4),required:op(nz()).optional()}).catchall(oc())}),e6=oy([e5,e3=u.extend({mode:o$("url"),message:nz(),elicitationId:nz(),url:nz().url()})]),e7=d.extend({method:o$("elicitation/create"),params:e6}),e8=p.extend({elicitationId:nz()}),te=m.extend({method:o$("notifications/elicitation/complete"),params:e8}),tt=h.extend({action:ox(["accept","decline","cancel"]),content:oJ(t=>null===t?void 0:t,oR(nz(),oy([nz(),oe(),on(),op(nz())])).optional())}),tr=oh({type:o$("ref/resource"),uri:nz()}),ti=oh({type:o$("ref/prompt"),name:nz()}),tn=c.extend({ref:oy([ti,tr]),argument:oh({name:nz(),value:nz()}),context:oh({arguments:oR(nz(),nz()).optional()}).optional()}),to=d.extend({method:o$("completion/complete"),params:tn}),ta=h.extend({completion:of({values:op(nz()).max(100),total:oO(oe().int()),hasMore:oO(on())})}),ts=oh({uri:nz().startsWith("file://"),name:nz().optional(),_meta:oR(nz(),oc()).optional()}),tl=d.extend({method:o$("roots/list"),params:c.optional()}),tc=h.extend({roots:op(ts)}),tu=m.extend({method:o$("notifications/roots/list_changed"),params:p.optional()}),td=of({ttl:oe().optional(),pollInterval:oe().optional()}),tp=ox(["working","input_required","completed","failed","cancelled"]),tm=oh({taskId:nz(),status:tp,ttl:oy([oe(),oa()]),createdAt:nz(),lastUpdatedAt:nz(),pollInterval:oO(oe()),statusMessage:oO(nz())}),th=h.extend({task:tm}),tf=p.merge(tm),tg=m.extend({method:o$("notifications/tasks/status"),params:tf}),ty=d.extend({method:o$("tasks/get"),params:c.extend({taskId:nz()})}),tv=h.merge(tm),t_=d.extend({method:o$("tasks/result"),params:c.extend({taskId:nz()})}),tb=h.loose(),tS=z.extend({method:o$("tasks/list")}),tw=M.extend({tasks:op(tm)}),tR=d.extend({method:o$("tasks/cancel"),params:c.extend({taskId:nz()})}),{JSONValueSchema:t,JSONObjectSchema:r,ProgressTokenSchema:n,CursorSchema:o,TaskMetadataSchema:a,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:x,ServerTasksCapabilitySchema:C,ClientCapabilitiesSchema:$,InitializeRequestParamsSchema:T,InitializeRequestSchema:P,ServerCapabilitiesSchema:E,InitializeResultSchema:O,InitializedNotificationSchema:I,PingRequestSchema:q,ProgressSchema:j,ProgressNotificationParamsSchema:A,ProgressNotificationSchema:L,PaginatedRequestParamsSchema:N,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:eo,PromptArgumentSchema:ea,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:eR,ToolSchema:ek,ListToolsRequestSchema:ex,ListToolsResultSchema:eC,CallToolResultSchema:e$,CallToolRequestParamsSchema:eT,CallToolRequestSchema:eP,ToolListChangedNotificationSchema:eE,LoggingLevelSchema:eO,SetLevelRequestParamsSchema:eI,SetLevelRequestSchema:eq,LoggingMessageNotificationParamsSchema:ej,LoggingMessageNotificationSchema:eA,ModelHintSchema:eL,ModelPreferencesSchema:eN,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:to,CompleteResultSchema:ta,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:tR,CancelTaskResultSchema:h.merge(tm),ClientRequestSchema:oy([q,P,to,eq,ed,el,W,K,Q,er,ei,eP,ex,ty,t_,tS,tR]),ClientNotificationSchema:oy([v,L,I,tu,tg]),ClientResultSchema:oy([g,eV,eJ,tt,tc,tv,tw,th]),ServerRequestSchema:oy([q,eD,e7,tl,ty,t_,tS,tR]),ServerNotificationSchema:oy([v,L,eA,eo,et,eE,eS,tg,te]),ServerResultSchema:oy([g,O,ta,eb,ec,G,Y,ee,e$,eC,tv,tw,th]),CallToolResultWireSchema:oc().superRefine((t,r)=>{if(!("object"!=typeof t||null===t||Array.isArray(t))&&void 0===t.content){for(let i of l9)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(l4).pipe(e$)})}function l3(t){return"object"!==t.type}let l6=new Set(["const","enum","default","examples"]),l7=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function l8(t){return void 0!==t&&!("string"==typeof t&&t.startsWith("#"))}let 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,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},ct={"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},cr={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 ci(){if(n)return n;let t=l5();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 cn(t){return Object.prototype.hasOwnProperty.call(ce,t)}function co(t){return Object.prototype.hasOwnProperty.call(ct,t)}function ca(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function cs(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(ce),Object.keys(ct);let cl={ok:!1,reason:"not-in-era"};function cc(t){return ca(t)&&ca(t.outputSchema)&&l3(t.outputSchema)}let cu={era:"2025-11-25",hasRequestMethod:cn,hasNotificationMethod:co,validateRequest:(t,r)=>cs(cn(t)?ci().requestSchemas[t]:void 0,r),validateResult:(t,r)=>cs(Object.prototype.hasOwnProperty.call(cr,t)?ci().resultSchemas[t]:void 0,r),validateNotification:(t,r)=>cs(co(t)?ci().notificationSchemas[t]:void 0,r),hasInputRequestMethod:()=>!1,validateInputRequest:()=>cl,validateInputResponse:()=>cl,samplingResultVariant:(t,r)=>{let i=l5();return cs(t?i.CreateMessageResultWithToolsSchema:i.CreateMessageResultSchema,r)},outboundEnvelope:t=>void 0,validateEnvelopeMeta:t=>[],projectCallToolResult(t,r){let i=l2(t),n=i.structuredContent;if(void 0===n)return i;let o="object"!=typeof n||null===n||Array.isArray(n),a=void 0!==r&&l3(r);return o||a?{...i,structuredContent:{result:n}}:i},decodeResult(t,r){if(ca(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=>cc(t))?{...r,tools:i.map(t=>cc(t)?{...t,outputSchema:function(t){var r;let i="string"==typeof t.$schema?t.$schema:void 0;if(l8(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,o=(t,r)=>{if(Array.isArray(t))return t.map(t=>o(t,!1));if(null===t||"object"!=typeof t||!r&&l8(t.$id))return t;let i={},a=!1;for(let[s,l]of Object.entries(t))r?i[s]=o(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?a=!0:l6.has(s)?i[s]=l:l7.has(s)?i[s]=o(l,!0):i[s]=o(l,!1);return a&&("$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:o(t,!1)},required:["result"]}}(t.outputSchema)}:t)}:r},encodeErrorCode:t=>-32002===t?-32602:t,checkInboundEnvelope:t=>void 0};function cd(){return o??=function(){let t=oD(()=>oy([nz(),oe(),on(),oa(),oR(nz(),t),op(t)])),r=oR(nz(),t),i=oy([nz(),oe().int()]),n=nz(),o=oy([nz(),oe().int()]),a=ox(["user","assistant"]),s=ox(["debug","info","notice","warning","error","critical","alert","emergency"]),l=nz().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),c=oh({ttl:oe().optional()}),u=oh({taskId:nz()}),d=of({progressToken:i.optional(),"io.modelcontextprotocol/related-task":u.optional()}),p=oh({_meta:d.optional()}),m=p.extend({task:c.optional()}),h=oh({_meta:d.optional()}),f=oh({method:nz(),params:h.loose().optional()}),g=oh({src:nz(),mimeType:nz().optional(),sizes:op(nz()).optional(),theme:ox(["light","dark"]).optional()}),y=oh({icons:op(g).optional()}),v=oh({name:nz(),title:nz().optional()}),_=v.extend({...v.shape,...y.shape,version:nz(),websiteUrl:nz().optional(),description:nz().optional()}),b=oS(oh({applyDefaults:on().optional()}),r),S=oJ(t=>t&&"object"==typeof t&&!Array.isArray(t)&&0===Object.keys(t).length?{form:{}}:t,oS(oh({form:b.optional(),url:r.optional()}),r.optional())),w=of({list:r.optional(),cancel:r.optional(),requests:of({sampling:of({createMessage:r.optional()}).optional(),elicitation:of({create:r.optional()}).optional()}).optional()}),R=of({list:r.optional(),cancel:r.optional(),requests:of({tools:of({call:r.optional()}).optional()}).optional()}),k=oh({experimental:oR(nz(),r).optional(),sampling:oh({context:r.optional(),tools:r.optional()}).optional(),elicitation:S.optional(),roots:oh({listChanged:on().optional()}).optional(),tasks:w.optional(),extensions:oR(nz(),r).optional()}),x=oh({experimental:oR(nz(),r).optional(),logging:r.optional(),completions:r.optional(),prompts:oh({listChanged:on().optional()}).optional(),resources:oh({subscribe:on().optional(),listChanged:on().optional()}).optional(),tools:oh({listChanged:on().optional()}).optional(),tasks:R.optional(),extensions:oR(nz(),r).optional()}),C=oh({progress:oe(),total:oO(oe()),message:oO(nz())}),$=oh({...h.shape,...C.shape,progressToken:i}),T=f.extend({method:o$("notifications/progress"),params:$}),P=h.extend({level:s,logger:nz().optional(),data:oc()}),E=f.extend({method:o$("notifications/message"),params:P}),O=oh({uri:nz(),mimeType:oO(nz()),_meta:oR(nz(),oc()).optional()}),I=O.extend({text:nz()}),q=O.extend({blob:l}),j=oh({audience:op(a).optional(),priority:oe().min(0).max(1).optional(),lastModified:r7(nZ,{offset:!0}).optional()}),A=oh({...v.shape,...y.shape,uri:nz(),description:oO(nz()),mimeType:oO(nz()),size:oO(oe()),annotations:j.optional(),_meta:oO(of({}))}),L=oh({...v.shape,...y.shape,uriTemplate:nz(),description:oO(nz()),mimeType:oO(nz()),annotations:j.optional(),_meta:oO(of({}))}),N=f.extend({method:o$("notifications/resources/list_changed"),params:h.optional()}),z=h.extend({uri:nz()}),M=f.extend({method:o$("notifications/resources/updated"),params:z}),Z=oh({name:nz(),description:oO(nz()),required:oO(on())}),U=oh({...v.shape,...y.shape,description:oO(nz()),arguments:oO(op(Z)),_meta:oO(of({}))}),F=f.extend({method:o$("notifications/prompts/list_changed"),params:h.optional()}),H=oh({type:o$("text"),text:nz(),annotations:j.optional(),_meta:oR(nz(),oc()).optional()}),D=oh({type:o$("image"),data:l,mimeType:nz(),annotations:j.optional(),_meta:oR(nz(),oc()).optional()}),V=oh({type:o$("audio"),data:l,mimeType:nz(),annotations:j.optional(),_meta:oR(nz(),oc()).optional()}),J=oh({type:o$("tool_use"),name:nz(),id:nz(),input:oR(nz(),oc()),_meta:oR(nz(),oc()).optional()}),B=oh({type:o$("resource"),resource:oy([I,q]),annotations:j.optional(),_meta:oR(nz(),oc()).optional()}),W=A.extend({type:o$("resource_link")}),G=oy([H,D,V,W,B]),K=oh({role:a,content:G}),Y=oh({title:nz().optional(),readOnlyHint:on().optional(),destructiveHint:on().optional(),idempotentHint:on().optional(),openWorldHint:on().optional()}),X=f.extend({method:o$("notifications/tools/list_changed"),params:h.optional()}),Q=oh({name:nz().optional()}),ee=oh({hints:op(Q).optional(),costPriority:oe().min(0).max(1).optional(),speedPriority:oe().min(0).max(1).optional(),intelligencePriority:oe().min(0).max(1).optional()}),et=oh({mode:ox(["auto","required","none"]).optional()}),er=oh({type:o$("boolean"),title:nz().optional(),description:nz().optional(),default:on().optional()}),ei=oh({type:o$("string"),title:nz().optional(),description:nz().optional(),minLength:oe().optional(),maxLength:oe().optional(),format:ox(["email","uri","date","date-time"]).optional(),default:nz().optional()}),en=oh({type:ox(["number","integer"]),title:nz().optional(),description:nz().optional(),minimum:oe().optional(),maximum:oe().optional(),default:oe().optional()}),eo=oh({type:o$("string"),title:nz().optional(),description:nz().optional(),enum:op(nz()),default:nz().optional()}),ea=oh({type:o$("string"),title:nz().optional(),description:nz().optional(),oneOf:op(oh({const:nz(),title:nz()})),default:nz().optional()}),es=oh({type:o$("string"),title:nz().optional(),description:nz().optional(),enum:op(nz()),enumNames:op(nz()).optional(),default:nz().optional()}),el=oy([eo,ea]),ec=oh({type:o$("array"),title:nz().optional(),description:nz().optional(),minItems:oe().optional(),maxItems:oe().optional(),items:oh({type:o$("string"),enum:op(nz())}),default:op(nz()).optional()}),eu=oh({type:o$("array"),title:nz().optional(),description:nz().optional(),minItems:oe().optional(),maxItems:oe().optional(),items:oh({anyOf:op(oh({const:nz(),title:nz()}))}),default:op(nz()).optional()}),ed=oy([ec,eu]),ep=oy([es,el,ed]),em=oy([ep,er,ei,en]),eh=m.extend({mode:o$("form").optional(),message:nz(),requestedSchema:oh({type:o$("object"),properties:oR(nz(),em),required:op(nz()).optional()}).catchall(oc())}),ef=oh({type:o$("ref/resource"),uri:nz()}),eg=oh({type:o$("ref/prompt"),name:nz()}),ey=oh({uri:nz().startsWith("file://"),name:nz().optional(),_meta:oR(nz(),oc()).optional()}),ev=k.shape,e_=oh({experimental:ev.experimental,sampling:ev.sampling,elicitation:ev.elicitation,roots:ev.roots,extensions:ev.extensions}),eb=x.shape,eS=oh({experimental:eb.experimental,logging:eb.logging,completions:eb.completions,prompts:eb.prompts,resources:eb.resources,tools:eb.tools,extensions:eb.extensions}),ew=of({progressToken:i.optional(),[oG]:nz(),[oK]:_.optional(),[oX]:e_,[o0]:s.optional()}),eR=oh({...v.shape,...y.shape,description:nz().optional(),inputSchema:of({$schema:nz().optional(),type:o$("object")}),outputSchema:of({$schema:nz().optional()}).optional(),annotations:Y.optional(),_meta:oR(nz(),oc()).optional()}),ek=oh({type:o$("tool_result"),toolUseId:nz(),content:op(G),structuredContent:oc().optional(),isError:on().optional(),_meta:oR(nz(),oc()).optional()}),ex=oy([H,D,V,J,ek]),eC=oh({role:a,content:oy([ex,op(ex)]),_meta:oR(nz(),oc()).optional()}),e$=nz(),eT=of({[oY]:_.optional().catch(void 0)}),eP=eT.optional();function eE(t){return of({_meta:eP,resultType:e$.default("complete"),...t})}let eO=eE({}),eI=eE({nextCursor:n.optional()}),eq=eE({content:op(G),structuredContent:oc().optional(),isError:on().optional()}),ej=eE({ttlMs:oe().int().min(0),cacheScope:ox(["public","private"]),tools:op(eR),nextCursor:n.optional()}),eA=eE({ttlMs:oe().int().min(0),cacheScope:ox(["public","private"]),prompts:op(U),nextCursor:n.optional()}),eL=eE({description:nz().optional(),messages:op(K)}),eN=eE({ttlMs:oe().int().min(0),cacheScope:ox(["public","private"]),resources:op(A),nextCursor:n.optional()}),ez=eE({ttlMs:oe().int().min(0),cacheScope:ox(["public","private"]),resourceTemplates:op(L),nextCursor:n.optional()}),eM=eE({ttlMs:oe().int().min(0),cacheScope:ox(["public","private"]),contents:op(oy([I,q]))}),eZ=eE({completion:oh({values:op(nz()).max(100),total:oe().int().optional(),hasMore:on().optional()}).loose()}),eU=eE({ttlMs:oe().int().min(0),cacheScope:ox(["public","private"])}),eF=eE({ttlMs:oe().int().min(0).catch(0),cacheScope:ox(["public","private"]).catch("private"),supportedVersions:op(nz()),capabilities:eS,instructions:nz().optional()}),eH=oh({messages:op(eC),modelPreferences:ee.optional(),systemPrompt:nz().optional(),includeContext:ox(["none","thisServer","allServers"]).optional(),temperature:oe().optional(),maxTokens:oe().int(),stopSequences:op(nz()).optional(),metadata:r.optional(),tools:op(eR).optional(),toolChoice:et.optional()}),eD=oh({method:o$("sampling/createMessage"),params:eH}),eV=oh({method:o$("roots/list"),params:oh({_meta:oR(nz(),oc()).optional()}).optional()}),eJ=oh({...eC.shape,model:nz(),stopReason:nz().optional()}),eB=oh({roots:op(ey)}),eW=oh({action:ox(["accept","decline","cancel"]),content:oR(nz(),oy([nz(),oe(),on(),op(nz())])).optional()}),eG=oh({mode:o$("url"),message:nz(),url:nz().url()}),eK=oy([eh,eG]),eY=oh({method:o$("elicitation/create"),params:eK}),eX=oy([eD,eV,eY]),eQ=oy([eJ,eB,eW]),e0=oR(nz(),eX),e1=oR(nz(),eQ),e2=eE({inputRequests:e0.optional(),requestState:nz().optional()}),e9={inputResponses:e1.optional(),requestState:nz().optional()},e4=oh({_meta:ew,...e9}),e5=of({progressToken:i.optional()});function e3(t,r){return oh({method:o$(t),params:oh({_meta:ew,...r})})}function e6(t,r){return oh({method:o$(t),params:oh({_meta:e5.optional(),...r}).optional()})}let e7={name:nz(),arguments:oR(nz(),oc()).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:nz(),arguments:oR(nz(),nz()).optional(),...e9}),tn=e3("resources/list",e8),to=e3("resources/templates/list",e8),ta=e3("resources/read",{uri:nz(),...e9}),ts={ref:oy([eg,ef]),argument:oh({name:nz(),value:nz()}),context:oh({arguments:oR(nz(),nz()).optional()}).optional()},tl=e3("completion/complete",ts),tc=e3("server/discover",{}),tu=oh({toolsListChanged:on().optional(),promptsListChanged:on().optional(),resourcesListChanged:on().optional(),resourceSubscriptions:op(nz()).optional()}),td={notifications:tu},tp=e3("subscriptions/listen",td),tm=eT.extend({"io.modelcontextprotocol/subscriptionId":o}),th=of({_meta:tm,resultType:e$.default("complete")}),tf={"tools/call":e6("tools/call",e7),"tools/list":e6("tools/list",e8),"prompts/get":e6("prompts/get",{name:nz(),arguments:oR(nz(),nz()).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:nz()}),"completion/complete":e6("completion/complete",ts),"server/discover":e6("server/discover",{}),"subscriptions/listen":e6("subscriptions/listen",td)};function tg(t){return of({_meta:eP,...t})}let ty={"tools/call":tg({content:op(G),structuredContent:oc().optional(),isError:on().optional()}),"tools/list":tg({ttlMs:oe().int().min(0),cacheScope:ox(["public","private"]),tools:op(eR),nextCursor:n.optional()}),"prompts/get":tg({description:nz().optional(),messages:op(K)}),"prompts/list":tg({ttlMs:oe().int().min(0),cacheScope:ox(["public","private"]),prompts:op(U),nextCursor:n.optional()}),"resources/list":tg({ttlMs:oe().int().min(0),cacheScope:ox(["public","private"]),resources:op(A),nextCursor:n.optional()}),"resources/templates/list":tg({ttlMs:oe().int().min(0),cacheScope:ox(["public","private"]),resourceTemplates:op(L),nextCursor:n.optional()}),"resources/read":tg({ttlMs:oe().int().min(0),cacheScope:ox(["public","private"]),contents:op(oy([I,q]))}),"completion/complete":tg({completion:oh({values:op(nz()).max(100),total:oe().int().optional(),hasMore:on().optional()}).loose()}),"server/discover":tg({ttlMs:oe().int().min(0).catch(0),cacheScope:ox(["public","private"]).catch("private"),supportedVersions:op(nz()),capabilities:eS,instructions:nz().optional()}),"subscriptions/listen":tg({})},tv=of({"io.modelcontextprotocol/subscriptionId":o.optional()}),t_=oh({method:o$("notifications/subscriptions/acknowledged"),params:oh({_meta:tv.optional(),notifications:tu})}),tb=oh({_meta:tv.optional(),requestId:o,reason:nz().optional()}),tS=oh({method:o$("notifications/cancelled"),params:tb}),tw=t=>oh({jsonrpc:o$("2.0"),id:oy([nz(),oe().int()]),result:t}).strict();return{JSONValueSchema:t,JSONObjectSchema:r,ProgressTokenSchema:i,CursorSchema:n,RequestIdSchema:o,RoleSchema:a,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:R,ClientCapabilitiesSchema:k,ServerCapabilitiesSchema:x,ProgressSchema:C,ProgressNotificationParamsSchema:$,ProgressNotificationSchema:T,LoggingMessageNotificationParamsSchema:P,LoggingMessageNotificationSchema:E,ResourceContentsSchema:O,TextResourceContentsSchema:I,BlobResourceContentsSchema:q,AnnotationsSchema:j,ResourceSchema:A,ResourceTemplateSchema:L,ResourceListChangedNotificationSchema:N,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:eo,TitledSingleSelectEnumSchemaSchema:ea,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:eR,ToolResultContentSchema:ek,SamplingMessageContentBlockSchema:ex,SamplingMessageSchema:eC,ResultTypeSchema:e$,ResultMetaSchema:eT,ResultSchema:eO,PaginatedResultSchema:eI,CallToolResultSchema:eq,ListToolsResultSchema:ej,ListPromptsResultSchema:eA,GetPromptResultSchema:eL,ListResourcesResultSchema:eN,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:to,ReadResourceRequestSchema:ta,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":N,"notifications/tools/list_changed":X,"notifications/prompts/list_changed":F,"notifications/subscriptions/acknowledged":t_},JSONRPCResultResponseSchema:tw(eO),CallToolResultResponseSchema:tw(oy([eq,e2])),ListToolsResultResponseSchema:tw(ej),ListPromptsResultResponseSchema:tw(eA),GetPromptResultResponseSchema:tw(oy([eL,e2])),ListResourcesResultResponseSchema:tw(eN),ListResourceTemplatesResultResponseSchema:tw(ez),ReadResourceResultResponseSchema:tw(oy([eM,e2])),CompleteResultResponseSchema:tw(eZ),DiscoverResultResponseSchema:tw(eF),SubscriptionsListenResultResponseSchema:tw(th)}}()}let cp=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"],cm=Symbol("modelcontextprotocol.resultCacheHintFallback");function ch(t,r){if(void 0===r)return t;let i=t[cm];if(void 0===i)return{...t,[cm]:r};let n={},o=i.ttlMs??r.ttlMs;void 0!==o&&(n.ttlMs=o);let a=i.cacheScope??r.cacheScope;return void 0!==a&&(n.cacheScope=a),{...t,[cm]:n}}function cf(t){return"number"==typeof t&&Number.isSafeInteger(t)&&t>=0}function cg(t){return"public"===t||"private"===t}function cy(t,r){if(void 0!==t.ttlMs&&!cf(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&&!cg(t.cacheScope))throw RangeError(`Invalid cache hint for ${r}: cacheScope must be 'public' or 'private' (got ${String(t.cacheScope)})`)}let cv=((T={})[T.ParseError=-32700]="ParseError",T[T.InvalidRequest=-32600]="InvalidRequest",T[T.MethodNotFound=-32601]="MethodNotFound",T[T.InvalidParams=-32602]="InvalidParams",T[T.InternalError=-32603]="InternalError",T[T.ResourceNotFound=-32002]="ResourceNotFound",T[T.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",T[T.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",T[T.UrlElicitationRequired=-32042]="UrlElicitationRequired",T);var c_=class t extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return lV(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 lV(this,t)}constructor(t,r,i){super(r),this.code=t,this.data=i,this.name="ProtocolError",lD(this,new.target)}static fromError(r,i,n){return r===cv.UrlElicitationRequired&&n&&n.elicitations?new cS(n.elicitations,i):r===cv.UnsupportedProtocolVersion&&n&&Array.isArray(n.supported)&&"string"==typeof n.requested?new cw({supported:n.supported,requested:n.requested},i):(r===cv.InvalidParams||r===cv.ResourceNotFound)&&"string"==typeof n?.uri&&(r===cv.ResourceNotFound||1===Object.keys(n).length)?new cb(n.uri,i):r===cv.MissingRequiredClientCapability&&n&&null!==n.requiredCapabilities&&"object"==typeof n.requiredCapabilities&&!Array.isArray(n.requiredCapabilities)?new cR({requiredCapabilities:n.requiredCapabilities},i):new t(r,i,n)}},cb=class extends c_{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(t,r=`Resource not found: ${t}`){super(cv.InvalidParams,r,{uri:t})}get uri(){return this.data.uri}},cS=class extends c_{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(cv.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}},cw=class extends c_{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(t,r=`Unsupported protocol version: ${t.requested}`){super(cv.UnsupportedProtocolVersion,r,t)}get supported(){return this.data.supported}get requested(){return this.data.requested}},cR=class extends c_{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(t,r=`Missing required client capabilities: ${Object.keys(t.requiredCapabilities).join(", ")}`){super(cv.MissingRequiredClientCapability,r,t)}get requiredCapabilities(){return this.data.requiredCapabilities}};let ck=["tools/call","prompts/get","resources/read"],cx=["elicitation/create","sampling/createMessage","roots/list"];function cC(){if(a)return a;let t=cd();return a={request:{"elicitation/create":oh({method:o$("elicitation/create"),params:t.ElicitRequestParamsSchema}),"sampling/createMessage":oh({method:o$("sampling/createMessage"),params:t.CreateMessageRequestParamsSchema}),"roots/list":oh({method:o$("roots/list"),params:of({}).optional()})},response:{"elicitation/create":t.ElicitResultSchema,"sampling/createMessage":t.CreateMessageResultSchema,"roots/list":t.ListRootsResultSchema}}}function c$(t){return cx.includes(t)}function cT(t){return c$(t)?cC().request[t]:void 0}let cP={"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},cE={"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(cP,t)}function cI(t){return Object.prototype.hasOwnProperty.call(cE,t)}function cq(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function cj(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(cP),Object.keys(cE);let cA={ok:!1,reason:"not-in-era"},cL=[oG,oX],cN={era:"2026-07-28",hasRequestMethod:cO,hasNotificationMethod:cI,hasInputRequestMethod:t=>void 0!==cT(t),validateRequest:(t,r)=>cj(cO(t)?cd().dispatchRequestSchemas[t]:void 0,r),validateResult:(t,r)=>cj(Object.prototype.hasOwnProperty.call(cP,t)?cd().dispatchResultSchemas[t]:void 0,r),validateNotification:(t,r)=>cj(cI(t)?cd().notificationSchemas2026[t]:void 0,r),validateInputRequest:(t,r)=>cj(cT(t),r),validateInputResponse:(t,r)=>cj(c$(t)?cC().response[t]:void 0,r),samplingResultVariant:()=>cA,outboundEnvelope:t=>({[oG]:t.protocolVersion,[oK]:t.clientInfo,[oX]:t.clientCapabilities,...void 0!==t.logLevel&&{[o0]:t.logLevel}}),validateEnvelopeMeta(t){let r=[];for(let i of cL)i in t||r.push({key:i,problem:"missing"});let i=cd().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=>l2(t),inputRequestSchema:cT,decodeResult(t,r){if(!cq(r))return{kind:"invalid",error:new lG(lW.InvalidResult,`Invalid result for ${t}: not an object`,{method:t})};let i=r.resultType;if(void 0===i)return{kind:"invalid",error:new lG(lW.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 lG(lW.InvalidResult,`Invalid result for ${t}: non-string resultType`,{method:t,resultType:i})};if("input_required"===i){let i=r.inputRequests,n=cq(i)?i:{},o=r.requestState,a=void 0===r._meta?void 0:cd().ResultMetaSchema.safeParse(r._meta),s=a?.success?a.data:void 0;return 0===Object.keys(n).length&&"string"!=typeof o?{kind:"invalid",error:new lG(lW.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 o&&{requestState:o},...void 0!==s&&{_meta:s}}}if("complete"!==i)return{kind:"invalid",error:new lG(lW.UnsupportedResultType,`Unsupported result type '${i}' for ${t}`,{resultType:i,method:t})};let n=cz(),o=Object.hasOwn(n,t)?n[t]:void 0;if(void 0!==o){let i=o.safeParse(r);if(!i.success)return{kind:"invalid",error:new lG(lW.InvalidResult,`Invalid result for ${t}: ${i.error}`,{method:t})}}let a={...r};return delete a.resultType,{kind:"complete",result:a}},encodeResult:(t,r,i)=>(function(t,r){if(void 0===r)return t;let i=t._meta;return void 0===i?{...t,_meta:{[oY]:r}}:null===i||"object"!=typeof i||Array.isArray(i)||void 0!==i[oY]?t:{...t,_meta:{...i,[oY]:r}}})(function(t,r){var i,n;let o=r[cm];if("complete"!==r.resultType||!cp.includes(t)){let t;return void 0===o?r:(t={...r},delete t[cm],t)}let a=cf(r.ttlMs)?r.ttlMs:void 0!==(i=o)&&cf(i.ttlMs)?i.ttlMs:0,s=cg(r.cacheScope)?r.cacheScope:void 0!==(n=o)&&cg(n.cacheScope)?n.cacheScope:"private",l={...r,ttlMs:a,cacheScope:s};return delete l[cm],l}(t,function(t,r){let i=r.resultType;if(void 0===i)return{...r,resultType:"complete"};if("complete"===i||ck.includes(t))return r;throw new c_(cv.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,o=()=>(n||(i={...i},n=!0),i),a=r.tools;"tools/list"===t&&Array.isArray(a)&&a.some(t=>cq(t)&&"execution"in t)&&(o().tools=a.map(t=>{if(!cq(t)||!("execution"in t))return t;let r={...t};return delete r.execution,r}));let s=r.capabilities;if(cq(s)&&"tasks"in s){let t={...s};delete t.tasks,o().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=cd().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 cz(){if(s)return s;let t=cd();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 cM="2026-07-28";function cZ(t){return void 0!==t&&t>=lQ?cN:cu}function cU(t){return void 0!==t.revision?cZ(t.revision).era:"modern"===t.era?cN.era:cu.era}function cF(t){return cV.some(r=>r.hasRequestMethod(t))}function cH(t){return cV.some(r=>r.hasNotificationMethod(t))}function cD(t){return"tasks/get"===t||"tasks/cancel"===t}let cV=[cu,cN];function cJ(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function cB(t){if(!cJ(t))return;let r=t._meta;return cJ(r)?r:void 0}function cW(t){let r=cB(t);return void 0!==r&&oG in r}function cG(t){let r=cB(t)?.[oG];return"string"==typeof r?r:void 0}function cK(t){return cZ(cM).validateEnvelopeMeta(t)}var cY=((t,r)=>{let i={};for(var n in t)V(i,n,{get:t[n],enumerable:!0});return r&&V(i,Symbol.toStringTag,{value:"Module"}),i})({AnnotationsSchema:()=>aD,AudioContentSchema:()=>su,BaseMetadataSchema:()=>av,BaseRequestParamsSchema:()=>o8,BlobResourceContentsSchema:()=>aF,BooleanSchemaSchema:()=>sV,CallToolRequestParamsSchema:()=>sx,CallToolRequestSchema:()=>sC,CallToolResultSchema:()=>sR,CancelTaskRequestSchema:()=>lS,CancelTaskResultSchema:()=>lw,CancelledNotificationParamsSchema:()=>ah,CancelledNotificationSchema:()=>af,ClientCapabilitiesSchema:()=>ak,ClientNotificationSchema:()=>lk,ClientRequestSchema:()=>lR,ClientResultSchema:()=>lx,ClientTasksCapabilitySchema:()=>aw,CompatibilityCallToolResultSchema:()=>sk,CompleteRequestParamsSchema:()=>lr,CompleteRequestSchema:()=>li,CompleteResultSchema:()=>ln,ContentBlockSchema:()=>sh,CreateMessageRequestParamsSchema:()=>sU,CreateMessageRequestSchema:()=>sF,CreateMessageResultSchema:()=>sH,CreateMessageResultWithToolsSchema:()=>sD,CreateTaskResultSchema:()=>lp,CursorSchema:()=>o5,DiscoverRequestSchema:()=>aE,DiscoverResultSchema:()=>aO,ElicitRequestFormParamsSchema:()=>s9,ElicitRequestParamsSchema:()=>s5,ElicitRequestSchema:()=>s3,ElicitRequestURLParamsSchema:()=>s4,ElicitResultSchema:()=>s8,ElicitationCompleteNotificationParamsSchema:()=>s6,ElicitationCompleteNotificationSchema:()=>s7,EmbeddedResourceSchema:()=>sp,EmptyResultSchema:()=>am,EnumSchemaSchema:()=>s1,GetPromptRequestParamsSchema:()=>sa,GetPromptRequestSchema:()=>ss,GetPromptResultSchema:()=>sg,GetTaskPayloadRequestSchema:()=>ly,GetTaskPayloadResultSchema:()=>lv,GetTaskRequestSchema:()=>lf,GetTaskResultSchema:()=>lg,IconSchema:()=>ag,IconsSchema:()=>ay,ImageContentSchema:()=>sc,ImplementationSchema:()=>a_,InitializeRequestParamsSchema:()=>ax,InitializeRequestSchema:()=>aC,InitializeResultSchema:()=>aT,InitializedNotificationSchema:()=>aP,JSONArraySchema:()=>o9,JSONObjectSchema:()=>o2,JSONRPCErrorResponseSchema:()=>au,JSONRPCMessageSchema:()=>ad,JSONRPCNotificationSchema:()=>al,JSONRPCRequestSchema:()=>as,JSONRPCResponseSchema:()=>ap,JSONRPCResultResponseSchema:()=>ac,JSONValueSchema:()=>o1,LegacyTitledEnumSchemaSchema:()=>sK,ListChangedOptionsBaseSchema:()=>sT,ListPromptsRequestSchema:()=>sn,ListPromptsResultSchema:()=>so,ListResourceTemplatesRequestSchema:()=>aG,ListResourceTemplatesResultSchema:()=>aK,ListResourcesRequestSchema:()=>aB,ListResourcesResultSchema:()=>aW,ListRootsRequestSchema:()=>la,ListRootsResultSchema:()=>ls,ListTasksRequestSchema:()=>l_,ListTasksResultSchema:()=>lb,ListToolsRequestSchema:()=>sS,ListToolsResultSchema:()=>sw,LoggingLevelSchema:()=>sP,LoggingMessageNotificationParamsSchema:()=>sI,LoggingMessageNotificationSchema:()=>sq,ModelHintSchema:()=>sj,ModelPreferencesSchema:()=>sA,MultiSelectEnumSchemaSchema:()=>s0,NotificationSchema:()=>ai,NotificationsParamsSchema:()=>ar,NumberSchemaSchema:()=>sB,PaginatedRequestParamsSchema:()=>aL,PaginatedRequestSchema:()=>aN,PaginatedResultSchema:()=>az,PingRequestSchema:()=>aI,PrimitiveSchemaDefinitionSchema:()=>s2,ProgressNotificationParamsSchema:()=>aj,ProgressNotificationSchema:()=>aA,ProgressSchema:()=>aq,ProgressTokenSchema:()=>o4,PromptArgumentSchema:()=>sr,PromptListChangedNotificationSchema:()=>sy,PromptMessageSchema:()=>sf,PromptReferenceSchema:()=>lt,PromptSchema:()=>si,ReadResourceRequestParamsSchema:()=>aY,ReadResourceRequestSchema:()=>aX,ReadResourceResultSchema:()=>aQ,RelatedTaskMetadataSchema:()=>o6,RequestIdSchema:()=>aa,RequestMetaSchema:()=>o7,RequestSchema:()=>at,ResourceContentsSchema:()=>aM,ResourceLinkSchema:()=>sm,ResourceListChangedNotificationSchema:()=>a0,ResourceRequestParamsSchema:()=>aY,ResourceSchema:()=>aV,ResourceTemplateReferenceSchema:()=>le,ResourceTemplateSchema:()=>aJ,ResourceUpdatedNotificationParamsSchema:()=>se,ResourceUpdatedNotificationSchema:()=>st,ResultMetaObjectSchema:()=>an,ResultSchema:()=>ao,RoleSchema:()=>aH,RootSchema:()=>lo,RootsListChangedNotificationSchema:()=>ll,SamplingContentSchema:()=>sz,SamplingMessageContentBlockSchema:()=>sM,SamplingMessageSchema:()=>sZ,ServerCapabilitiesSchema:()=>a$,ServerNotificationSchema:()=>l$,ServerRequestSchema:()=>lC,ServerResultSchema:()=>lT,ServerTasksCapabilitySchema:()=>aR,SetLevelRequestParamsSchema:()=>sE,SetLevelRequestSchema:()=>sO,SingleSelectEnumSchemaSchema:()=>sY,StringSchemaSchema:()=>sJ,SubscribeRequestParamsSchema:()=>aY,SubscribeRequestSchema:()=>a1,SubscriptionFilterSchema:()=>a9,SubscriptionsAcknowledgedNotificationParamsSchema:()=>a3,SubscriptionsAcknowledgedNotificationSchema:()=>a6,SubscriptionsListenRequestParamsSchema:()=>a4,SubscriptionsListenRequestSchema:()=>a5,SubscriptionsListenResultMetaSchema:()=>a7,SubscriptionsListenResultSchema:()=>a8,TaskAugmentedRequestParamsSchema:()=>ae,TaskCreationParamsSchema:()=>lc,TaskMetadataSchema:()=>o3,TaskSchema:()=>ld,TaskStatusNotificationParamsSchema:()=>lm,TaskStatusNotificationSchema:()=>lh,TaskStatusSchema:()=>lu,TextContentSchema:()=>sl,TextResourceContentsSchema:()=>aZ,TitledMultiSelectEnumSchemaSchema:()=>sQ,TitledSingleSelectEnumSchemaSchema:()=>sG,ToolAnnotationsSchema:()=>sv,ToolChoiceSchema:()=>sL,ToolExecutionSchema:()=>s_,ToolListChangedNotificationSchema:()=>s$,ToolResultContentSchema:()=>sN,ToolSchema:()=>sb,ToolUseContentSchema:()=>sd,UnsubscribeRequestParamsSchema:()=>aY,UnsubscribeRequestSchema:()=>a2,UntitledMultiSelectEnumSchemaSchema:()=>sX,UntitledSingleSelectEnumSchemaSchema:()=>sW});let cX=t=>as.safeParse(t).success,cQ=t=>al.safeParse(t).success,c0=t=>ac.safeParse(t).success,c1=t=>au.safeParse(t).success,c2=t=>"object"==typeof t&&null!==t&&!Array.isArray(t)&&"input_required"===t.resultType,c9="x-mcp-header",c4=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,c5=new Set(["string","integer","boolean","number"]);function c3(t){let r=[],i=new Map,n=(t,o,a)=>{if(null===t||"object"!=typeof t)return;if(c9 in t){if(!a||0===o.length)return`${c8(o)}: 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[c9];if("string"!=typeof n||0===n.length)return`${c8(o)}: x-mcp-header MUST be a non-empty string`;if(!c4.test(n))return`${c8(o)}: 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||!c5.has(s))return`${c8(o)}: 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:o,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,[...o,t],a);if(void 0!==i)return i}for(let r of c6){let i=t[r];if(void 0!==i)for(let t of Array.isArray(i)?i:null!==i&&"object"==typeof i&&c7.has(r)?Object.values(i):[i]){let i=n(t,[...o,`<${r}>`],!1);if(void 0!==i)return i}}},o=n(t,[],!0);return void 0===o?{valid:!0,declarations:r}:{valid:!1,reason:o}}let c6=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],c7=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function c8(t){return 0===t.length?"<root>":t.join(".")}let ue=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ut=/^-?\d+(\.\d+)?$/;function ur(t){if(!(t.startsWith("=?base64?")&&t.endsWith("?=")))return t;let r=t.slice(9,t.length-2);if(ue.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 ui(t,r,i){return{kind:"reject",rung:"param-header-validation",cell:t,httpStatus:400,code:un,message:`Bad Request: the request headers and body disagree: ${i}`,data:{mismatch:{header:r,body:i}},settled:!0}}let un=-32020;cv.InvalidRequest,cv.UnsupportedProtocolVersion,cv.InvalidParams,cv.MethodNotFound,cv.InvalidParams,cv.MissingRequiredClientCapability;let uo={[cv.ParseError]:400,[cv.InvalidRequest]:400,[cv.MethodNotFound]:404,[cv.UnsupportedProtocolVersion]:400,[cv.MissingRequiredClientCapability]:400,[un]:400};function ua(t,r,i,n,o){return{kind:"reject",rung:t,cell:r,httpStatus:i,code:n.code,message:n.message,...void 0!==n.data&&{data:n.data},settled:o}}function us(t,r,i,n="era-classification"){return ua(n,t,400,new c_(un,`Bad Request: the request headers and body disagree: ${i}`,{mismatch:{header:r,body:i}}),!0)}let ul={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function uc(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 uu(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function ud(t){return void 0===t?{era:"modern"}:{era:t>=lQ?"modern":"legacy",revision:t}}function up(t){return new Set(t.flatMap(t=>Object.keys(t.shape)))}function um(t){if(null==t)return!1;let r=typeof t;return("object"===r||"function"===r)&&"~standard"in t&&"function"==typeof t["~standard"]?.validate}let uh=!1,uf="draft-2020-12";function ug(t,r="input"){let i,n=t["~standard"];if(n.jsonSchema)i=n.jsonSchema[r]({target:uf});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().");uh||(uh=!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:uf,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 uy(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 uv=/\\\.\\d\{(\d+)\}/;function u_(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}let ub=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function uS(t){return ub.has(t)||t.startsWith("x-")}let uw=new Set(["$schema",...Object.keys(s9.shape.requestedSchema.shape)]),uR={string:up([sJ,sW,sG,sK]),number:up([sB]),integer:up([sB]),boolean:up([sV]),array:up([sX,sQ])},uk=new Set(sJ.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(!um(t.requestedSchema))return{...t,mode:"form",requestedSchema:t.requestedSchema};let i=t.requestedSchema["~standard"].vendor,n=function(t,r){let i={},n=[];for(let[o,a]of Object.entries(t))"properties"===o&&u_(a)?i[o]=Object.fromEntries(Object.entries(a).map(([t,i])=>[t,function(t,r,i,n){if(!u_(t))return t;let o="string"==typeof t.type&&Object.hasOwn(uR,t.type)?uR[t.type]:void 0;if(void 0===o)return t;let a={};for(let[l,c]of Object.entries(t))if(o.has(l)||uS(l))a[l]=c;else if("pattern"===l&&"string"===t.type&&"string"==typeof t.format)if(uk.has(t.format)){var s;"string"==typeof c&&(s=t.format,"zod"!==i||(function(t,r){let i;switch(t){case"email":i=[r3(nD,void 0)];break;case"uri":i=[r6(nB,void 0)];break;case"date":i=[r8(nU,void 0)];break;case"date-time":let n,o;n=uv.exec(r),o=[void 0,-1,0],n&&o.push(Number(n[1])),i=[!1,!0].flatMap(t=>[!1,!0].flatMap(r=>o.map(i=>r7(nZ,{local:t,offset:r,precision:i}))))}return new Set(i.map(t=>{let r;return r=nn(t,{target:uf,io:"input"}),"string"==typeof r.pattern?r.pattern:void 0}).filter(t=>void 0!==t))})(s,c).has(c))||n.push(`${r}.${l}`)}else a[l]=c;else n.push(`${r}.${l}`);return a}(i,`properties.${t}`,r,n)])):uw.has(o)?i[o]=a:uS(o)||n.push(o);if(n.length>0)throw new c_(cv.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return i}(function(t){try{return ug(t,"input")}catch(r){let t=r instanceof Error?r.message:String(r);throw new c_(cv.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${t}`)}}(t.requestedSchema),i),o=(r=s9.shape.requestedSchema,nk(r,n));if(!o.success)throw new c_(cv.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${function(t,r){if(!u_(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,o.error.message)}`);let a=function t(r,i,n=""){return Array.isArray(r)&&Array.isArray(i)?r.flatMap((r,o)=>t(r,i[o],`${n}[${o}]`)):u_(r)&&u_(i)?Object.entries(r).flatMap(([r,o])=>{let a=n?`${n}.${r}`:r;return Object.prototype.hasOwnProperty.call(i,r)?t(o,i[r],a):uS(r)?[]:[a]}):[]}(n,o.data);if(a.length>0)throw new c_(cv.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${a.join(", ")}`);let s=(o.data.required??[]).filter(t=>!Object.prototype.hasOwnProperty.call(o.data.properties,t));if(s.length>0)throw new c_(cv.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...t,mode:"form",requestedSchema:o.data}}(t)}}catch(t){throw t instanceof c_?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 ux={},uC={};function u$(t,r){let i=t.slice(0,-6);ux[i]=r,uC[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"])u$(t,cY[t]);for(let[t,r]of Object.entries({IdJagTokenExchangeResponseSchema:lA,OAuthClientInformationFullSchema:lZ,OAuthClientInformationSchema:lM,OAuthClientMetadataSchema:lz,OAuthClientRegistrationErrorSchema:lU,OAuthErrorResponseSchema:lL,OAuthMetadataSchema:lO,OAuthProtectedResourceMetadataSchema:lE,OAuthTokenRevocationRequestSchema:lF,OAuthTokensSchema:lj,OpenIdProviderDiscoveryMetadataSchema:lq,OpenIdProviderMetadataSchema:lI}))u$(t,r);let uT=Object.freeze(ux);Object.freeze(uC);let uP=[oG,oK,oX,o0],uE=["inputResponses","requestState"];function uO(t,r){let i=t.params;if(!uL(i))return{message:t,lifted:{}};let n=i._meta,o=uL(n)?uP.filter(t=>t in n):[],a="request"===r?uE.filter(t=>t in i):[];if(0===o.length&&0===a.length)return{message:t,lifted:{}};let s={},l={...i};if(o.length>0&&uL(n)){let t={},r={...n};for(let i of o)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 a)"inputResponses"===t&&(s.inputResponses=l[t]),"requestState"===t&&(s.requestState=l[t]),delete l[t];return{message:{...t,params:l},lifted:s}}function uI(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 uq=(P=void 0,()=>P);function uj(t,r){return{...t,mcpReq:{...t.mcpReq,requestState:()=>r}}}var uA=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_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??oW,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 lG(lW.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){void 0!==t.params.requestId&&this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,i,n,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:i,resetTimeoutOnProgress:o,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 lG(lW.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),c0(t)||c1(t)?this._onresponse(t):cX(t)?this._onrequest(t,r):cQ(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 lG(lW.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}=uO(t,"notification"),n=this._negotiatedWireCodec();if(r?.classification===void 0&&"drop"===this._shouldDropInbound(t))return;if(r?.classification!==void 0){let t=cU(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(cH(i.method)&&!n.hasNotificationMethod(i.method))return;let o=this._notificationHandlers.get(i.method),a=this.fallbackNotificationHandler;(void 0!==o||void 0!==a)&&Promise.resolve().then(()=>void 0===o?a(i):o(i,n)).catch(t=>this._onerror(Error(`Uncaught error in notification handler: ${t}`)))}_onrequest(t,r){var i;let{message:n,lifted:o}=uO(t,"request"),a=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 o={jsonrpc:"2.0",id:n.id,error:{code:t,message:r,...void 0!==i&&{data:i}}};s?.send(o).catch(t=>this._onerror(Error(`Failed to send an error response: ${t}`)))};if(r?.classification!==void 0){let t=cU(r.classification);if(t!==a.era){this._onerror(Error(`Era mismatch on inbound request '${n.method}': classified as ${t} but this instance serves ${a.era}`));let i=r.classification.revision??t;l(cv.UnsupportedProtocolVersion,`Unsupported protocol version: ${i}`,{supported:this._supportedProtocolVersions,requested:i});return}}if(cF(n.method)&&!a.hasRequestMethod(n.method)&&!(cD(n.method)&&this._customSchemaRequestMethods.has(n.method)))return void l(cv.MethodNotFound,"Method not found");let c=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(void 0===c)return void l(cv.MethodNotFound,"Method not found");let u=a.checkInboundEnvelope(o);if(void 0!==u)return void l(cv.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===o.inputResponses?void 0:function(t){let r={},i=[];if(!uN(t))return{accepted:r,droppedKeys:i};for(let[n,o]of Object.entries(t)){if(!uN(o)||"method"in o||"result"in o){i.push(n);continue}r[n]=o}return{accepted:r,droppedKeys:i}}(o.inputResponses),f={sessionId:s?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...void 0!==o.envelope&&{envelope:o.envelope},...void 0!==h&&{inputResponses:h.accepted},...void 0!==h&&h.droppedKeys.length>0&&{droppedInputResponseKeys:h.droppedKeys},requestState:void 0===o.requestState?uq:(i=o.requestState,()=>i),signal:m.signal,send:(t,r,i)=>{let n=this._resolveOutboundCodec(t.method);if(this._assertOutboundRequestInEra(n,t.method),um(r))return p(t,r,i);let o=uI(n,t.method);if(void 0===o)throw TypeError(`'${t.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return p(t,o,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=a.encodeResult(n.method,t,this._outboundServerInfo())}catch(t){this._onerror(Error(`Failed to encode result for ${n.method}: ${t}`)),l(cv.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:cv.InternalError,i={jsonrpc:"2.0",id:n.id,error:{code:a.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),o=this._progressHandlers.get(n);if(!o)return void this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));let a=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(t){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),a(t);return}o(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(c0(t)?t:c_.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(um(r))return cD(t.method)||this._assertOutboundRequestInEra(n,t.method),this._requestWithSchemaViaCodec(n,t,r,i);this._assertOutboundRequestInEra(n,t.method);let o=uI(n,t.method);if(void 0===o)throw TypeError(`'${t.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(n,t,o,r)}_negotiatedWireCodec(){return cZ(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 cZ(void 0);case"server/discover":return cZ(cM);default:return}}(t);if(r)return r}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(t,r){if(cF(r)&&!t.hasRequestMethod(r))throw new lG(lW.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 o,a,{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 lG?t:new lG(lW.RequestTimeout,String(t))}let f=t.era===cM&&!0===this._transport.hasPerRequestStream?new AbortController:void 0,g=this._requestMessageId++;a=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?"initialize"!==r.method&&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 lG?t:new lG(lW.RequestTimeout,String(t))))};this._responseHandlers.set(g,o=>{let a;if(!n?.signal?.aborted){if(_=!0,o instanceof Error)return m(o);try{a=t.decodeResult(r.method,o.result)}catch(t){return m(t instanceof Error?t:Error(String(t)))}if("invalid"===a.kind)return m(a.error);if("input_required"===a.kind){var s;return n?.allowInputRequired===!0?p({resultType:"input_required",inputRequests:(s=a).inputRequests,...void 0!==s.requestState&&{requestState:s.requestState},...void 0!==s._meta&&{_meta:s._meta}}):p(this._resolveNonCompleteResult(a,{codec:t,request:r,resultSchema:i,options:n,flowStartedAt:d,retry:(n,o)=>this._requestWithSchemaViaCodec(t,void 0===n?{method:r.method}:{method:r.method,params:n},i,o)}))}uy(i,a.result).then(t=>{t.success?p(t.data):m(new lG(lW.InvalidResult,`Invalid result for ${r.method}: ${t.error}`))},m)}}),o=()=>b(n?.signal?.reason),n?.signal?.addEventListener("abort",o,{once:!0});let S=n?.timeout??6e4;this._setupTimeout(g,S,n?.maxTotalTimeout,()=>b(new lG(lW.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(()=>{o&&n?.signal?.removeEventListener("abort",o),void 0!==a&&(this._responseHandlers.delete(a),this._cleanupTimeout(a))})}async notification(t,r){return await this._notificationViaCodec(this._resolveOutboundCodec(t.method),t,r)}async _notificationViaCodec(t,r,i){if(!this._transport)throw new lG(lW.NotConnected,"Not connected");if(cH(r.method)&&!t.hasNotificationMethod(r.method))throw new lG(lW.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===void 0){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(!cF(t))throw TypeError(`'${t}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);n=(i,n)=>{let o=this._negotiatedWireCodec(),a=o.validateRequest(t,i);if(a.ok||"not-in-era"!==a.reason||(a=o.validateInputRequest(t,i)),!a.ok){if("not-in-era"===a.reason)throw new c_(cv.InternalError,`No wire schema for ${t} in the resolved era`);throw Error(a.message)}return Promise.resolve(r(a.value,n))}}else if(i)n=async(n,o)=>{let a=await uy(r.params,{...n.params});if(!a.success)throw new c_(cv.InvalidParams,`Invalid params for ${t}: ${a.error}`);return i(a.data,o)};else throw TypeError("setRequestHandler: handler is required");"function"==typeof r?this._customSchemaRequestMethods.delete(t):this._customSchemaRequestMethods.add(t),this._requestHandlers.set(t,this._wrapHandler(t,n))}_wrapHandler(t,r){return r}_outboundServerInfo(){}removeRequestHandler(t){this._requestHandlers.delete(t),this._customSchemaRequestMethods.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(!cH(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 o=n.validateNotification(t,i);if(!o.ok){if("not-in-era"===o.reason)throw new c_(cv.InternalError,`No wire schema for ${t} in the resolved era`);throw Error(o.message)}return Promise.resolve(r(o.value))});return}if(!i)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(t,async n=>{let o=await uy(r.params,{...n.params});if(!o.success)throw new c_(cv.InvalidParams,`Invalid params for notification ${t}: ${o.error}`);await i(o.data,n)})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}};function uL(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function uN(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 o,a=B(r),s=0,l=a.length;s<l;s++)o=a[s],G.call(t,o)||o===i||V(t,o,{get:(t=>r[t]).bind(null,o),enumerable:!(n=J(r,o))||n.enumerable});return t})(V(null!=(R=(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 o(t){this.parameters=Object.create(null),this.type=t}t.parse=function(t){if(!t)throw TypeError("argument string is required");var a,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 o(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,a=s[1].toLowerCase(),34===(l=s[2]).charCodeAt(0)&&-1!==(l=l.slice(1,-1)).indexOf("\\")&&(l=l.replace(i,"$1")),p.parameters[a]=l}if(u!==c.length)throw TypeError("invalid parameter format")}return p}},()=>(w||S((w={exports:{}}).exports,w),w.exports))())?D(W(R)):{},"default",{value:R,enumerable:!0}),R);function uM(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 uZ(t){return"application/json"===t||"application/json"===uM(t)}let uU=/^[A-Za-z0-9._-]{1,128}$/;function uF(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"),!uU.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 uH=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="",o=0,a=0;for(;o<r.length;)if("{"===r[o]){n&&(i.push(n),n="");let s=r.indexOf("}",o);if(-1===s)throw Error("Unclosed template expression");if(++a>1e4)throw Error("Template contains too many expressions (max 10000)");let l=r.slice(o+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}),o=s+1}else n+=r[o],o++;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 o=this.expandPart(n,t);o&&(r+=("?"===n.operator||"&"===n.operator)&&i?o.replace("?","&"):o,("?"===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],o=0===t?"\\"+r.operator:"&";n.push({pattern:o+this.escapeRegExp(i)+"=([^&]+)",name:i})}return n}let o=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:o}),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:o}of this.partToRegExp(t))i+=r,n.push({name:o,exploded:t.exploded});i+="$",t.validateLength(i,1e6,"Generated regex pattern");let o=new RegExp(i),a=r.match(o);if(!a)return null;let s={};for(let[t,r]of n.entries()){let{name:i,exploded:n}=r,o=a[t+1];s[i.replace("*","")]=n&&o.includes(",")?o.split(","):o}return s}};function uD(t){if(void 0!==t){if(function(t){if("object"!=typeof t||null===t||um(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 oh(t);if("object"==typeof t&&null!==t&&!um(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(!um(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 uV(){l5(),cd(),ci(),cC(),cz()}function uJ(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(!uJ(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(!uJ(t[n],r[n]))return!1;return!0}return t===r}function uB(t){return encodeURI(t.replace(/~/g,"~0").replace(/\//g,"~1"))}let uW={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},uG={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},uK={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},uY="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 uX(t,r=Object.create(null),i=uY,n=""){if(t&&"object"==typeof t&&!Array.isArray(t)){let o=t.$id||t.id;if(o){let a=new URL(o,i.href);a.hash.length>1?r[a.href]=t:(a.hash="",""===n?i=a:uX(t,r,i))}}else if(!0!==t&&!1!==t)return r;let o=i.href+(n?"#"+n:"");if(void 0!==r[o])throw Error(`Duplicate schema URI "${o}".`);if(r[o]=t,!0===t||!1===t)return r;if(void 0===t.__absolute_uri__&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:o}),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 o in t.$anchor&&(r[new URL("#"+t.$anchor,i.href).href]=t),t){if(uK[o])continue;let a=`${n}/${uB(o)}`,s=t[o];if(Array.isArray(s)){if(uW[o]){let t=s.length;for(let n=0;n<t;n++)uX(s[n],r,i,`${a}/${n}`)}}else if(uG[o])for(let t in s)uX(s[t],r,i,`${a}/${uB(t)}`);else uX(s,r,i,a)}return r}let uQ=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,u0=[0,31,28,31,30,31,30,31,31,30,31,30,31],u1=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;function u2(t){return t.test.bind(t)}let u9={date:u4,time:u5.bind(void 0,!1),"date-time":function(t){let r=t.split(u3);return 2==r.length&&u4(r[0])&&u5(!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 u6.test(t)&&u7.test(t)},"uri-reference":u2(/^(?:[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":u2(/^(?:(?:[^\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:u2(/^(?:(?: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:u2(/^(?=.{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:u2(/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/),ipv6:u2(/^((([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(u8.test(t))return!1;try{return RegExp(t,"u"),!0}catch(t){return!1}},uuid:u2(/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i),"json-pointer":u2(/^(?:\/(?:[^~/]|~0|~1)*)*$/),"json-pointer-uri-fragment":u2(/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i),"relative-json-pointer":u2(/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/)};function u4(t){var r;let i=t.match(uQ);if(!i)return!1;let n=+i[1],o=+i[2],a=+i[3];return o>=1&&o<=12&&a>=1&&a<=(2==o&&(r=n)%4==0&&(r%100!=0||r%400==0)?29:u0[o])}function u5(t,r){let i=r.match(u1);if(!i)return!1;let n=+i[1],o=+i[2],a=+i[3],s=!!i[5];return(n<=23&&o<=59&&a<=59||23==n&&59==o&&60==a)&&(!t||s)}let u3=/t|\s/i,u6=/\/|:/,u7=/^(?:[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,u8=/[^\\]\\Z/;var de=class{schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",i=!0){this.schema=t,this.draft=r,this.shortCircuit=i,this.lookup=uX(t)}validate(t){return function t(r,i,n="2019-09",o=uX(i),a=!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:R,if:k,then:x,else:C,format:$,properties:T,patternProperties:P,additionalProperties:E,unevaluatedProperties:O,minProperties:I,maxProperties:q,propertyNames:j,dependentRequired:A,dependentSchemas:L,dependencies:N,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?o[ei]:s,p=`${c}/$recursiveRef`,m=t(r,null===s?i:s,n,o,a,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=o[er||m];if(void 0===i){let t=`Unresolved $ref "${m}".`;throw er&&er!==m&&(t+=`  Absolute URI "${er}".`),Error(t+=`
Known schemas:
- ${Object.keys(o).join("\n- ")}`)}let d=`${c}/$ref`,p=t(r,i,n,o,a,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?uJ(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=>uJ(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,o,a,s,l,i).valid&&en.push({instanceLocation:l,keyword:"not",keywordLocation:i,error:'Instance matched "not" schema.'})}let eo=[];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,o,a,!0===f?s:null,l,`${i}/${c}`,m);en.push(...h.errors),p=p||h.valid,h.valid&&eo.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,o,a,!0===f?s:null,l,`${i}/${c}`,m);en.push(...h.errors),p=p&&h.valid,h.valid&&eo.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!==R){let i=`${c}/oneOf`,d=en.length,p=R.filter((c,d)=>{let p=Object.create(u),m=t(r,c,n,o,a,!0===f?s:null,l,`${i}/${d}`,p);return en.push(...m.errors),m.valid&&eo.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,...eo),void 0!==k){let i=`${c}/if`;if(t(r,k,n,o,a,s,l,i,u).valid){if(void 0!==x){let d=t(r,x,n,o,a,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!==C){let d=t(r,C,n,o,a,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}/${uB(c)}`,u=t(c,j,n,o,a,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!==L)for(let i in L){let d=`${c}/dependentSchemas`;if(i in r){let c=t(r,L[i],n,o,a,s,l,`${d}/${uB(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!==N){let i=`${c}/dependencies`;for(let c in N)if(c in r){let u=N[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,o,a,s,l,`${i}/${uB(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}/${uB(c)}`,h=t(r[c],T[c],n,o,a,s,m,`${i}/${uB(c)}`);if(h.valid)u[c]=d[c]=!0;else if(p=a,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}/${uB(f)}`,y=t(r[f],h,n,o,a,s,g,`${i}/${uB(c)}`);y.valid?u[f]=d[f]=!0:(p=a,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}/${uB(c)}`,p=t(r[c],O,n,o,a,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}/${uB(c)}`,h=t(r[c],E,n,o,a,s,m,i);h.valid?u[c]=!0:(p=a,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,o,a,s,`${l}/${d}`,`${m}/${d}`);if(u[d]=!0,!i.valid&&(p=a,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,o,a,s,`${l}/${d}`,`${m}/${d}`);if(u[d]=!0,!i.valid&&(p=a,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,o,a,s,`${l}/${d}`,m);if(u[d]=!0,!i.valid&&(p=a,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,o,a,s,`${l}/${d}`,m);u[d]=!0,i.valid||(p=a,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,o,a,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,o,a,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],o="object"==typeof n&&null!==n;for(let a=0;a<i;a++){if(t===a)continue;let i=r[a];(n===i||o&&"object"==typeof i&&null!==i&&uJ(n,i))&&(en.push({instanceLocation:l,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${t} and ${a}.`}),t=Number.MAX_SAFE_INTEGER,a=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,o=0;for(;o<n;)i++,(r=t.charCodeAt(o++))>=55296&&r<=56319&&o<n&&(64512&(r=t.charCodeAt(o)))==56320&&o++;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!==$&&u9[$]&&!u9[$](r)&&en.push({instanceLocation:l,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${$}".`})}return{valid:0===en.length,errors:en}}(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),uX(t,this.lookup)}},dt=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 de(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("; ")}}}};uV();let dr=Symbol.for("mcp.completable");function di(t){return!!t&&"object"==typeof t&&dr in t}let dn=0x80000000-1;function da(t,r){if(!Number.isFinite(t)||t<1)return;let i=setInterval(r,Math.min(t,dn));return i.unref?.(),i}var ds=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 dl(t,r,i){return Response.json({jsonrpc:"2.0",error:{code:r,message:i},id:t},{status:200})}function dc(t,r){return{method:t.method,params:{...t.params,_meta:{...t.params?._meta,[oQ]:r}}}}function du(t){return t.replaceAll(/[\\"]/g,String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g," ")}function dd(t,r,i,n){let o=`Bearer error="${du(t)}", error_description="${du(r)}"`;return i.length>0&&(o+=`, scope="${du(i.join(" "))}"`),n&&(o+=`, resource_metadata="${du(n)}"`),o}async function dp(t,r,i){for(let o of t){let t=await i({request:o,...void 0!==r&&{authInfo:r}});if(void 0!==t){if(null===t||"object"!=typeof t||!Array.isArray(t.scopes)||0===t.scopes.length)throw TypeError("scope challenge must contain at least one scope");for(let[r,i]of t.scopes.entries()){var n=`scope challenge scopes[${r}]`;if("string"!=typeof i||!/^[\u0021\u0023-\u005B\u005D-\u007E]+$/.test(i))throw TypeError(`${n} must satisfy the OAuth scope-token grammar`)}if(void 0!==t.errorDescription&&"string"!=typeof t.errorDescription)throw TypeError("scope challenge errorDescription must be a string");if(void 0!==t.errorDescription&&!/^[\u0020-\u0021\u0023-\u005B\u005D-\u007E]+$/.test(t.errorDescription))throw TypeError("scope challenge errorDescription must satisfy the RFC 6750 error-description grammar");return t}}}function dm(t){if(t?.resourceMetadataUrl!==void 0)return t.resourceMetadataUrl;if(t?.resource?.protocol==="https:"||t?.resource?.protocol==="http:"){var r,i;let n,o;return n=new URL(r=t.resource),o=(i=r.pathname).length>1&&i.endsWith("/")?i.slice(0,-1):i,n.pathname=`/.well-known/oauth-protected-resource${"/"===o?"":o}`,n.hash="",n.href}}function dh(t,r){return function(t,r){let{requiredScopes:i=[],resourceMetadataUrl:n}=r??{};if(!(t instanceof lB)){let t=new lB(lJ.ServerError,"Internal Server Error");return Response.json(t.toResponseObject(),{status:500})}switch(t.code){case lJ.InvalidToken:{let r=dd(t.code,t.message,i,n);return Response.json(t.toResponseObject(),{status:401,headers:{"WWW-Authenticate":r}})}case lJ.InsufficientScope:{let r=dd(t.code,t.message,i,n);return Response.json(t.toResponseObject(),{status:403,headers:{"WWW-Authenticate":r}})}case lJ.ServerError:return Response.json(t.toResponseObject(),{status:500});default:return Response.json(t.toResponseObject(),{status:400})}}(new lB(lJ.InsufficientScope,t.errorDescription??"Insufficient scope"),{requiredScopes:[...t.scopes],resourceMetadataUrl:r})}function df(t,r,i){if(null===i||"object"!=typeof i||"string"!=typeof i.method)throw new c_(cv.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 c_(cv.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 dg(t,r){if("tools/call"===t)return{content:[{type:"text",text:r}],isError:!0};throw new c_(cv.InternalError,r)}var dy=class{constructor(t){this._host=t}async fulfill(t,r,i,n,o){let{maxRounds:a,roundTimeoutMs:s}=this._host,l=n.mcpReq.signal,c=o,u=0;for(;;){let o;if((u+=1)>a)return dg(t,`Multi-round-trip request '${t}' still required input after ${a} 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 c_(cv.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,o]of Object.entries(d)){let{embedded:a,required:s}=df(t,n,o);if("roots/list"!==a.method&&void 0===a.params)throw new c_(cv.InternalError,`Handler for ${t} returned an input request '${n}' of kind '${a.method}' without params`);if(void 0!==lX(s,r))return dg(t,`Cannot request input '${n}' (${a.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,a])}let a=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:a.signal},r=await Promise.all(i.map(async([r,i])=>{try{return[r,await this._dispatchLeg(i,t)]}catch(t){throw a.abort(t),t}}));o=Object.fromEntries(r)}catch(r){if(l.aborted)throw r;return dg(t,`Fulfilling input required by '${t}' failed: ${r instanceof Error?r.message:String(r)}`)}finally{a.dispose()}}else await function(t,r){return new Promise((t,i)=>{if(r?.aborted)return void i(r.reason instanceof lG?r.reason:new lG(lW.RequestTimeout,String(r.reason)));let n=setTimeout(()=>{r?.removeEventListener("abort",o),t()},250),o=()=>{clearTimeout(n),i(r?.reason instanceof lG?r.reason:new lG(lW.RequestTimeout,String(r?.reason)))};r?.addEventListener("abort",o,{once:!0})})}(0,l);let h={...n,mcpReq:{...n.mcpReq,inputResponses:o,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=uj(h,r))}let f=await r(i,h);if(!c2(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 dv=new Set(["tools/call","prompts/get","resources/read"]);var d_=class extends uA{_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 dy({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 dt,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&&cy(i,`cacheHints['${t}']`);this._cacheHints=r.cacheHints}this.setRequestHandler("initialize",t=>this._oninitialize(t)),this.setNotificationHandler("notifications/initialized",()=>this.oninitialized?.()),l1(this._supportedProtocolVersions).length>0&&this.setRequestHandler("server/discover",()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}async connect(t){if(void 0!==this.transport)throw new lG(lW.AlreadyConnected,"Use a separate Server instance per connection: this instance is already connected to a transport. To connect it to a new transport, call close() first.");await super.connect(t)}_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,o=nk(sP,n);return o.success&&this._loggingLevels.set(i,o.data),{}})}buildContext(t,r){let i=t.http||r?.request||r?.closeSSEStream||r?.closeStandaloneSSEStream;return{...t,mcpReq:{...t.mcpReq,log:(r,i,n)=>{let o;if(!this._capabilities.logging)return Promise.resolve();if(this._servedModernEra()){if(void 0===(o=t.mcpReq.envelope?.[o0]))return Promise.resolve()}else o=this._loggingLevels.get(t.sessionId)??this._loggingLevels.get(void 0);return void 0!==o&&this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(o)?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(sP.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 lG(lW.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 o=i[t];i[t]=uL(o)&&uL(n)?{...o,...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=dv.has(t);return void 0!==i||n?async(o,a)=>{let s=n?await this._invokeInputRequiredCapableHandler(t,r,o,a):await r(o,a);if(c2(s)){if(!n)throw new c_(cv.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:ch(s,i)}:async(i,n)=>{let o=await r(i,n);if(c2(o))throw new c_(cv.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 o}}return async(t,i)=>{let n=cZ(this._negotiatedProtocolVersion),o=n.validateRequest("tools/call",t);if(!o.ok)throw new c_("not-in-era"===o.reason?cv.InternalError:cv.InvalidParams,"not-in-era"===o.reason?"No wire schema for tools/call in the resolved era":`Invalid tools/call request: ${o.message}`);let a=await this._invokeInputRequiredCapableHandler("tools/call",r,t,i);if(c2(a))return a;let s=l4(a),l=n.validateResult("tools/call",s);if(!l.ok)throw new c_("not-in-era"===l.reason?cv.InternalError:cv.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>=lQ}async _invokeInputRequiredCapableHandler(t,r,i,n){let o,a=this._servedModernEra(),s=n.mcpReq.requestState();if(void 0!==s&&"string"!=typeof s)throw new c_(cv.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=uj(n,r))}try{o=await r(i,l)}catch(t){if(t instanceof c_&&t.code===cv.UrlElicitationRequired){if(!a)throw t;throw new c_(cv.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(!c2(o))return o;if(!a){if(!this._inputRequiredServing.legacyShim)throw new c_(cv.InternalError,`Handler for ${t} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??oB}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(t,r,i,l,o)}let c=o.inputRequests,u=null!=c&&Object.keys(c).length>0,d="string"==typeof o.requestState;if(!u&&!d)throw new c_(cv.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:o,required:a}=df(t,i,n),s=lX(a,r);if(void 0!==s)throw new cR({requiredCapabilities:s},`Cannot request input '${i}' (${o.method}): the request's client capabilities do not declare the required capability`)}}return o}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 c_(cv.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"})}}_inputRequestCapabilityView(t){return this._servedModernEra()?t.mcpReq.envelope?.[oX]:this._clientCapabilities}_assertPushApiInServedEra(t){if(this._servedModernEra())throw new lG(lW.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 lG(lW.CapabilityNotSupported,`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new lG(lW.CapabilityNotSupported,`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new lG(lW.CapabilityNotSupported,`Client does not support listing roots (required for ${t})`)}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new lG(lW.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 lG(lW.CapabilityNotSupported,`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new lG(lW.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 lG(lW.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 lG(lW.CapabilityNotSupported,`Client does not support URL elicitation (required for ${t})`)}}assertRequestHandlerCapability(t){switch(t){case"completion/complete":if(!this._capabilities.completions)throw new lG(lW.CapabilityNotSupported,`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new lG(lW.CapabilityNotSupported,`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new lG(lW.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 lG(lW.CapabilityNotSupported,`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new lG(lW.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>=lQ)),n=i.includes(r)?r:i[0]??oB;return this._negotiatedProtocolVersion=n,this.transport?.setProtocolVersion?.(n),{protocolVersion:n,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:l1(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 lG(lW.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),o=t.messages.length>1?t.messages.at(-2):void 0,a=o?Array.isArray(o.content)?o.content:[o.content]:[],s=a.some(t=>"tool_use"===t.type);if(n){if(i.some(t=>"tool_result"!==t.type))throw new c_(cv.InvalidParams,"The last message must contain only tool_result content if any is present");if(!s)throw new c_(cv.InvalidParams,"tool_result blocks are not matching any tool_use from the previous message")}if(s){let t=new Set(a.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 c_(cv.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),o=this._wireCodec().samplingResultVariant(i,n);if(!o.ok)throw new lG(lW.InvalidResult,`Invalid sampling/createMessage result: ${"invalid"===o.reason?o.message:o.reason}`);return o.value}async elicitInput(t,r){switch(this._assertPushApiInServedEra("elicitation/create"),t.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw new lG(lW.CapabilityNotSupported,"Client does not support url elicitation.");break;case"form":if(!this._clientCapabilities?.elicitation?.form)throw new lG(lW.CapabilityNotSupported,"Client does not support form elicitation.")}return this._sendElicitationLeg(t,r)}async _sendElicitationLeg(t,r,i){let n=t.mode??"form",o=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(o&&"accept"===n.action&&n.content&&i.requestedSchema)try{let t=this._jsonSchemaValidator.getValidator(i.requestedSchema)(n.content);if(!t.valid)throw new c_(cv.InvalidParams,`Elicitation response content does not match requested schema: ${t.errorMessage}`)}catch(t){if(t instanceof c_)throw t;throw new c_(cv.InternalError,`Error validating elicitation response: ${t instanceof Error?t.message:String(t)}`)}return n}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new lG(lW.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"})}},db=class{server;_maxToolInputElements;_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 dR;try{let i=ug(r.inputSchema,"input");return this._toolInputSchemaJson[t]=i,i}catch{return}}}constructor(t,r){this.server=new d_(t,r),this._maxToolInputElements=function(t){if(void 0!==t&&t!==1/0){if("number"!=typeof t||Number.isNaN(t)||t<1)throw RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(t)}`);return t}}(r?.maxToolInputElements),r?.capabilities?.tools&&this.setToolRequestHandlers(),r?.capabilities?.resources&&this.setResourceRequestHandlers(),r?.capabilities?.prompts&&this.setPromptRequestHandlers()}async connect(t){return"object"==typeof t&&null!==t&&"setScopeChallengeResolver"in t&&"function"==typeof t.setScopeChallengeResolver&&t.setScopeChallengeResolver(t=>this.resolveScopeChallenge(t)),await this.server.connect(t)}async close(){await this.server.close()}resolveScopeChallenge=t=>{switch(t.request.method){case"tools/call":{let r=t.request.params?.name;if("string"!=typeof r)return;let i=this._registeredTools[r];if(void 0===i||!i.enabled)return;return i.scopeChallenge?.(t)}case"resources/read":{let r,i=t.request.params?.uri;if("string"!=typeof i)return;try{r=new URL(i)}catch{return}let n=this._registeredResources[r.toString()];if(void 0!==n)return n.enabled?n.scopeChallenge?.(t):void 0;for(let i of Object.values(this._registeredResourceTemplates))if(i.resourceTemplate.uriTemplate.match(r.toString()))return i.enabled?i.scopeChallenge?.(t):void 0;return}case"prompts/get":{let r=t.request.params?.name;if("string"!=typeof r)return;let i=this._registeredPrompts[r];if(void 0===i||!i.enabled)return;return i.scopeChallenge?.(t)}default:return}};_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])=>{var i;let n,o,a={name:t,title:r.title,description:r.description,inputSchema:r.inputSchema?(i=t,(o=c3(n=ug(r.inputSchema,"input"))).valid||console.warn(`[mcp-sdk] tool '${i}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${o.reason}`),n):dR,annotations:r.annotations,icons:r.icons,execution:r.execution,_meta:r._meta};return r.outputSchema&&(a.outputSchema=ug(r.outputSchema,"output")),a})})),this.server.setRequestHandler("tools/call",async(t,r)=>{let i=this._registeredTools[t.params.name];if(!i)throw new c_(cv.InvalidParams,`Tool ${t.params.name} not found`);if(!i.enabled)throw new c_(cv.InvalidParams,`Tool ${t.params.name} disabled`);try{let n=await this.validateToolInput(i,t.params.arguments,t.params.name),o=await this.executeToolHandler(i,n,r);if(await this.validateToolOutput(i,o,t.params.name),c2(o))return o;return this.server.projectCallToolResult(o,i.outputSchemaJson)}catch(t){if(t instanceof c_&&t.code===cv.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(void 0!==this._maxToolInputElements&&function(t,r){let i=0,n=[t];for(;n.length>0;){let t=n.pop();if(null!==t&&"object"==typeof t)if(Array.isArray(t))for(let o of t){if(++i>r)return i;null!==o&&"object"==typeof o&&n.push(o)}else for(let o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;if(++i>r)return i;let a=t[o];null!==a&&"object"==typeof a&&n.push(a)}}return i}(r,this._maxToolInputElements)>this._maxToolInputElements)throw new c_(cv.InvalidParams,`Invalid arguments for tool ${i}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!t.inputSchema)return;let n=await uy(t.inputSchema,r??{});if(!n.success)throw new c_(cv.InvalidParams,`Input validation error: Invalid arguments for tool ${i}: ${n.error}`);return n.data}async validateToolOutput(t,r,i){if(!t.outputSchema||c2(r)||r.isError)return;if(void 0===r.structuredContent)throw new c_(cv.InvalidParams,`Output validation error: Tool ${i} has an output schema but no structured content was provided`);let n=await uy(t.outputSchema,r.structuredContent);if(!n.success)throw new c_(cv.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 c_(cv.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let i=this._registeredPrompts[r.name];if(!i)throw new c_(cv.InvalidParams,`Prompt ${r.name} not found`);if(!i.enabled)throw new c_(cv.InvalidParams,`Prompt ${r.name} disabled`);if(!i.argsSchema)return d$;let n=dP(dT(i.argsSchema)?.[t.params.argument.name]);if(!di(n))return d$;let o=n[dr]?.complete;return o?dC(await o(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 c_(cv.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let n=i.resourceTemplate.completeCallback(t.params.argument.name);return n?dC(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 c_(cv.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 c_(cv.InvalidParams,`Resource ${i} disabled`);return ch(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){if(!t.enabled)throw new c_(cv.InvalidParams,`Resource template ${t.resourceTemplate.uriTemplate} disabled`);return ch(await t.readCallback(i,n,r),t.cacheHint)}}throw new cb(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,o;return{name:t,title:r.title,description:r.description,arguments:r.argsSchema?(n=(i=ug(r.argsSchema,"input")).properties||{},o=i.required||[],Object.entries(n).map(([t,r])=>({name:t,description:r?.description,required:o.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 c_(cv.InvalidParams,`Prompt ${t.params.name} not found`);if(!i.enabled)throw new c_(cv.InvalidParams,`Prompt ${t.params.name} disabled`);return i.handler(t.params.arguments,r)}),this._promptHandlersInitialized=!0)}registerResource(t,r,i,n){let{cacheHint:o,scopeChallenge:a,...s}=i;if(void 0!==o&&cy(o,`resource ${t}`),"string"==typeof r){if(this._registeredResources[r])throw Error(`Resource ${r} is already registered`);let l=this._createRegisteredResource(t,i.title,r,s,a,n);return void 0!==o&&(l.cacheHint=o),this.setResourceRequestHandlers(),this.sendResourceListChanged(),l}{if(this._registeredResourceTemplates[t])throw Error(`Resource template ${t} is already registered`);let l=this._createRegisteredResourceTemplate(t,i.title,r,s,a,n);return void 0!==o&&(l.cacheHint=o),this.setResourceRequestHandlers(),this.sendResourceListChanged(),l}}_createRegisteredResource(t,r,i,n,o,a){let s={name:t,title:r,metadata:n,readCallback:a,scopeChallenge:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:t=>{void 0!==t.uri&&t.uri!==i&&(delete this._registeredResources[i],t.uri&&(this._registeredResources[t.uri]=s)),void 0!==t.name&&(s.name=t.name),void 0!==t.title&&(s.title=t.title),void 0!==t.metadata&&(s.metadata=t.metadata),void 0!==t.callback&&(s.readCallback=t.callback),void 0!==t.scopeChallenge&&(s.scopeChallenge=null===t.scopeChallenge?void 0:t.scopeChallenge),void 0!==t.enabled&&(s.enabled=t.enabled),this.sendResourceListChanged()}};return this._registeredResources[i]=s,s}_createRegisteredResourceTemplate(t,r,i,n,o,a){let s={resourceTemplate:i,title:r,metadata:n,readCallback:a,scopeChallenge:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:r=>{void 0!==r.name&&r.name!==t&&(delete this._registeredResourceTemplates[t],r.name&&(this._registeredResourceTemplates[r.name]=s)),void 0!==r.title&&(s.title=r.title),void 0!==r.template&&(s.resourceTemplate=r.template),void 0!==r.metadata&&(s.metadata=r.metadata),void 0!==r.callback&&(s.readCallback=r.callback),void 0!==r.scopeChallenge&&(s.scopeChallenge=null===r.scopeChallenge?void 0:r.scopeChallenge),void 0!==r.enabled&&(s.enabled=r.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=s;let l=i.uriTemplate.variableNames;return Array.isArray(l)&&l.some(t=>!!i.completeCallback(t))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,i,n,o,a,s,l){let c=n,u=o,d={title:r,description:i,argsSchema:n,icons:a,scopeChallenge:s,_meta:l,handler:dx(t,n,o),enabled:!0,disable:()=>d.update({enabled:!1}),enable:()=>d.update({enabled:!0}),remove:()=>d.update({name:null}),update:r=>{void 0!==r.name&&r.name!==t&&(delete this._registeredPrompts[t],r.name&&(this._registeredPrompts[r.name]=d)),void 0!==r.title&&(d.title=r.title),void 0!==r.description&&(d.description=r.description),void 0!==r.icons&&(d.icons=r.icons),void 0!==r.scopeChallenge&&(d.scopeChallenge=null===r.scopeChallenge?void 0:r.scopeChallenge),void 0!==r._meta&&(d._meta=r._meta);let i=!1;void 0!==r.argsSchema&&(d.argsSchema=r.argsSchema,c=r.argsSchema,i=!0),void 0!==r.callback&&(u=r.callback,i=!0),i&&(d.handler=dx(t,c,u)),void 0!==r.enabled&&(d.enabled=r.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[t]=d,n){let t=dT(n);t&&Object.values(t).some(t=>di(dP(t)))&&this.setCompletionRequestHandler()}return d}_createRegisteredTool(t,r,i,n,o,a,s,l,c,u,d){let p;uF(t);let m=d,h={title:r,description:i,inputSchema:n,outputSchema:o,get outputSchemaJson(){return p??=dk(h.outputSchema)},set outputSchemaJson(value){p=value},annotations:a,icons:s,execution:l,scopeChallenge:c,_meta:u,handler:d,executor:dw(n,d),enabled:!0,disable:()=>h.update({enabled:!1}),enable:()=>h.update({enabled:!0}),remove:()=>h.update({name:null}),update:r=>{void 0!==r.name&&r.name!==t&&("string"==typeof r.name&&uF(r.name),delete this._registeredTools[t],delete this._toolInputSchemaJson[t],r.name&&(delete this._toolInputSchemaJson[r.name],this._registeredTools[r.name]=h,t=r.name)),void 0!==r.title&&(h.title=r.title),void 0!==r.description&&(h.description=r.description);let i=!1;void 0!==r.paramsSchema&&(h.inputSchema=r.paramsSchema,delete this._toolInputSchemaJson[t],i=!0),void 0!==r.callback&&(h.handler=r.callback,m=r.callback,i=!0),i&&(h.executor=dw(h.inputSchema,m)),void 0!==r.outputSchema&&(h.outputSchema=r.outputSchema,h.outputSchemaJson=dk(r.outputSchema)),void 0!==r.annotations&&(h.annotations=r.annotations),void 0!==r.icons&&(h.icons=r.icons),void 0!==r.scopeChallenge&&(h.scopeChallenge=null===r.scopeChallenge?void 0:r.scopeChallenge),void 0!==r._meta&&(h._meta=r._meta),void 0!==r.enabled&&(h.enabled=r.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=h,this.setToolRequestHandlers(),this.sendToolListChanged(),h}registerTool(t,r,i){if(this._registeredTools[t])throw Error(`Tool ${t} is already registered`);let{title:n,description:o,inputSchema:a,outputSchema:s,annotations:l,icons:c,scopeChallenge:u,_meta:d}=r;return this._createRegisteredTool(t,n,o,uD(a),uD(s),l,c,void 0,u,d,i)}registerPrompt(t,r,i){if(this._registeredPrompts[t])throw Error(`Prompt ${t} is already registered`);let{title:n,description:o,argsSchema:a,icons:s,scopeChallenge:l,_meta:c}=r,u=this._createRegisteredPrompt(t,n,o,uD(a),i,s,l,c);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),u}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()}},dS=class{_uriTemplate;constructor(t,r){this._callbacks=r,this._uriTemplate="string"==typeof t?new uH(t):t}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(t){return this._callbacks.complete?.[t]}};function dw(t,r){return t?async(t,i)=>r(t,i):async(t,i)=>r(i)}let dR={type:"object",properties:{}};function dk(t){if(void 0!==t)try{return ug(t,"output")}catch{return}}function dx(t,r,i){return r?async(n,o)=>{let a=await uy(r,n??{});if(!a.success)throw new c_(cv.InvalidParams,`Invalid arguments for prompt ${t}: ${a.error}`);return i(a.data,o)}:async(t,r)=>i(r)}function dC(t){return{completion:{values:t.map(String).slice(0,100),total:t.length,hasMore:t.length>100}}}let d$={completion:{values:[],hasMore:!1}};function dT(t){if(t.shape&&"object"==typeof t.shape)return t.shape}function dP(t){return t?.type!=="optional"?t:t.def?.innerType??t}var dE=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 lG(lW.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(cX(t)){let r,o;this._requestId=t.id;let a=new Promise((t,i)=>{r=t,o=i});if(this._deferredResponse={promise:a,resolve:r,reject:o,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(),a}return this.onmessage(t,n),new Response(null,{status:202})}async send(t,r){if(this._closed)return;let i=c0(t)||c1(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=c1(t)?t.error.code:void 0,i=void 0!==r&&(this._dispatchWindowOpen||r===cv.MissingRequiredClientCapability)?uo[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}

`)}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 lG(lW.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=da(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
data: ${JSON.stringify(t)}

`)}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 dO(t,r,i){let n=new dE({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}})}function dI(t){return`Payload Too Large: Request body must not exceed ${t} bytes`}function dq(t){if(void 0===t)return 4194304;if("number"!=typeof t||!Number.isFinite(t)||t<=0)throw RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(t)}`);return t}async function dj(t,r=4194304){if(Number(t.headers.get("content-length"))>r)return{tooLarge:!0};if(null===t.body)return{tooLarge:!1,text:""};let i=t.body.getReader(),n=new TextDecoder,o=0,a="";try{for(;;){let{done:t,value:s}=await i.read();if(t)break;if((o+=s.byteLength)>r)return{tooLarge:!0};a+=n.decode(s,{stream:!0})}}finally{i.releaseLock()}return{tooLarge:!1,text:a+n.decode()}}var dA=class{sessionIdGenerator;_started=!1;_hasHandledRequest=!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;_maxRequestBodySize;_scopeChallengeResolver;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??oW,this._keepAliveMs=t.keepAliveMs??15e3,this._maxRequestBodySize=dq(t.maxRequestBodySize)}startKeepAlive(t,r){if(this._closed)return;let i=da(this._keepAliveMs,()=>{try{t.enqueue(r.encode(": keepalive\n\n"))}catch{void 0!==i&&clearInterval(i)}});return i}setScopeChallengeResolver(t){this._scopeChallengeResolver=t}async start(){if(this._started)throw Error("Transport already started");this._started=!0}setSupportedProtocolVersions(t){this._supportedProtocolVersions=t}createJsonErrorResponse(t,r,i,n){let o={code:r,message:i};return n?.data!==void 0&&(o.data=n.data),Response.json({jsonrpc:"2.0",error:o,id:null},{status:t,headers:{"Content-Type":"application/json",...n?.headers}})}async _checkScopeChallenge(t,r){if(!this._scopeChallengeResolver)return;let i=await dp(t.filter(t=>cX(t)),r,this._scopeChallengeResolver);return void 0===i?void 0:dh(i,dm(r))}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");if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;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 o=await this._eventStore.storeEvent(i,{}),a=`id: ${o}
data: 

`;void 0!==this._retryInterval&&(a=`id: ${o}
retry: ${this._retryInterval}
data: 

`),t.enqueue(r.encode(a))}async handleGetRequest(t){let r,i;if(!t.headers.get("accept")?.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept text/event-stream");let n=this.validateSession(t);if(n)return n;let o=this.validateProtocolVersion(t);if(o)return o;if(this._eventStore){let r=t.headers.get("last-event-id");if(r)return this.replayEvents(r)}if(void 0!==this._streamMapping.get(this._standaloneSseStreamId))return this.onerror?.(Error("Conflict: Only one SSE stream is allowed per session")),this.createJsonErrorResponse(409,-32e3,"Conflict: Only one SSE stream is allowed per session");let a=new TextEncoder,s=new ReadableStream({start:t=>{r=t},cancel:()=>{void 0!==i&&clearInterval(i),this._streamMapping.get(this._standaloneSseStreamId)?.controller===r&&this._streamMapping.delete(this._standaloneSseStreamId)}}),l={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};return void 0!==this.sessionId&&(l["mcp-session-id"]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:r,encoder:a,cleanup:()=>{void 0!==i&&clearInterval(i),this._streamMapping.delete(this._standaloneSseStreamId);try{r.close()}catch{}}}),i=this.startKeepAlive(r,a),new Response(s,{headers:l})}async replayEvents(t){if(!this._eventStore)return this.onerror?.(Error("Event store not configured")),this.createJsonErrorResponse(400,-32e3,"Event store not configured");try{let r,i,n,o;if(this._eventStore.getStreamIdForEventId){if(!(r=await this._eventStore.getStreamIdForEventId(t)))return this.onerror?.(Error("Invalid event ID format")),this.createJsonErrorResponse(400,-32e3,"Invalid event ID format");if(void 0!==this._streamMapping.get(r))return this.onerror?.(Error("Conflict: Stream already has an active connection")),this.createJsonErrorResponse(409,-32e3,"Conflict: Stream already has an active connection")}let a={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};void 0!==this.sessionId&&(a["mcp-session-id"]=this.sessionId);let s=new TextEncoder,l=!1,c=new ReadableStream({start:t=>{i=t},cancel:()=>{l=!0,void 0!==n&&clearInterval(n),void 0!==o&&this._streamMapping.get(o)?.controller===i&&this._streamMapping.delete(o)}}),u=new Set;if(o=await this._eventStore.replayEventsAfter(t,{send:async(t,r)=>{if(u.add(t),!this.writeSSEEvent(i,s,r,t))try{i.close()}catch{}}}),this._closed||l){try{i.close()}catch{}return this.createJsonErrorResponse(404,-32001,"Session not found")}if(this._streamMapping.get(o)?.cleanup(),this._streamMapping.set(o,{controller:i,encoder:s,replayedEventIds:u,cleanup:()=>{void 0!==n&&clearInterval(n),this._streamMapping.delete(o);try{i.close()}catch{}}}),o!==this._standaloneSseStreamId&&![...this._requestToStreamMapping.values()].includes(o)){this._streamMapping.delete(o);try{i.close()}catch{}}return this._streamMapping.get(o)?.controller===i&&(n=this.startKeepAlive(i,s)),new Response(c,{headers:a})}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(500,-32e3,"Error replaying events")}}writeSSEEvent(t,r,i,n){try{let o=`event: message
`;return n&&(o+=`id: ${n}
`),o+=`data: ${JSON.stringify(i)}

`,t.enqueue(r.encode(o)),!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,o,a,s,l=t.headers.get("accept");if(!l?.includes("application/json")||!l.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(!uZ(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{let r=await dj(t,this._maxRequestBodySize);if(r.tooLarge){let t=dI(this._maxRequestBodySize);return this.onerror?.(Error(t)),this.createJsonErrorResponse(413,-32e3,t)}i=JSON.parse(r.text)}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}else i=r.parsedBody;if(Array.isArray(i)&&i.length>100)return this.onerror?.(Error("Invalid Request: Batch must not exceed 100 messages")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Batch must not exceed 100 messages");try{n=Array.isArray(i)?i.map(t=>ad.parse(t)):[ad.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 c=n.some(t=>aC.safeParse(t).success);if(c){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(!c){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");try{o=await this._checkScopeChallenge(n,r?.authInfo)}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(500,-32603,"Internal server error")}if(o)return o;if(!n.some(t=>cX(t))){for(let i of n)this.onmessage?.(i,{authInfo:r?.authInfo,request:t});return new Response(null,{status:202})}let u=crypto.randomUUID(),d=n.find(t=>aC.safeParse(t).success),p=d?d.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(u,{resolveJson:i,cleanup:()=>{this._streamMapping.delete(u)}}),n))cX(t)&&this._requestToStreamMapping.set(t.id,u);for(let i of n)this.onmessage?.(i,{authInfo:r?.authInfo,request:t})});let m=new TextEncoder,h=new ReadableStream({start:t=>{a=t},cancel:()=>{void 0!==s&&clearInterval(s),this._streamMapping.get(u)?.controller===a&&this._streamMapping.delete(u)}}),f={"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&&(f["mcp-session-id"]=this.sessionId),n))cX(t)&&(this._streamMapping.set(u,{controller:a,encoder:m,cleanup:()=>{void 0!==s&&clearInterval(s),this._streamMapping.delete(u);try{a.close()}catch{}}}),this._requestToStreamMapping.set(t.id,u));for(let i of(await this.writePrimingEvent(a,m,u,p),n)){let n,o;cX(i)&&this._eventStore&&this.supportsEmptySSEData(p)&&(n=()=>{this.closeSSEStream(i.id)},o=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(i,{authInfo:r?.authInfo,request:t,closeSSEStream:n,closeStandaloneSSEStream:o})}return this._streamMapping.get(u)?.controller===a&&(s=this.startKeepAlive(a,m)),new Response(h,{status:200,headers:f})}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((c0(t)||c1(t))&&(i=t.id),void 0===i){let r;if(c0(t)||c1(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 o=this._streamMapping.get(n);if(!this._enableJsonResponse){let r;this._eventStore&&(r=await this._eventStore.storeEvent(n,t),o=this._streamMapping.get(n)),o?.controller&&o?.encoder&&(void 0===r||!o.replayedEventIds?.has(r))&&this.writeSSEEvent(o.controller,o.encoder,t,r)}if(c0(t)||c1(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(!o){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&&o.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?o.resolveJson(Response.json(i[0],{status:200,headers:t})):o.resolveJson(Response.json(i,{status:200,headers:t})),o.cleanup()}else o.cleanup();for(let t of r)this._requestResponseMap.delete(t),this._requestToStreamMapping.delete(t)}}}};function dL(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 dN(t,r,i,n,o=null){return Response.json({jsonrpc:"2.0",error:{code:r,message:i,...void 0!==n&&{data:n}},id:o},{status:t})}function dz(t,r=null){return dN(t.httpStatus,t.code,t.message,t.data,r)}function dM(t){return t instanceof Error?t:Error(String(t))}function dZ(t=null){return dN(500,-32603,"Internal server error",void 0,t)}function dU(t){if(void 0!==t.transport)throw Error("The factory returned an instance that is still serving another request. Return a new instance for each request.")}function dF(t){return{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}}async function dH(t,r,i=!0,n=4194304){let o,a=t.method.toUpperCase(),s=r,l=t,c=!1;if("POST"===a){if(void 0===s){let r;i&&(l=t.clone());try{let i=await dj(t,n);if(i.tooLarge)return{step:"body-too-large"};r=i.text}catch{return{step:"unreadable-body"}}try{o=0===r.length?void 0:JSON.parse(r)}catch{c=!0}c||void 0===o||(s=o)}else o=s;if(c||void 0===o)return{step:"no-json-body",forwardRequest:l}}return{step:"classified",outcome:function(t){if("POST"!==(t={...t,...void 0!==t.protocolVersionHeader&&{protocolVersionHeader:uc(t.protocolVersionHeader)},...void 0!==t.mcpMethodHeader&&{mcpMethodHeader:uc(t.mcpMethodHeader)},...void 0!==t.mcpNameHeader&&{mcpNameHeader:uc(t.mcpNameHeader)}}).httpMethod.toUpperCase())return{kind:"legacy",reason:"http-method"};let r=t.body;if(Array.isArray(r)){if(0===r.length)return ua("jsonrpc-shape","empty-batch",400,new c_(cv.InvalidRequest,"Bad Request: empty JSON-RPC batch"),!0);for(let t of r){if(cW(uu(t)?t.params:void 0))return ua("jsonrpc-shape","batch-with-modern-element",400,new c_(cv.InvalidRequest,"Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"),!0);if(!(cX(t)||cQ(t)||c0(t)||c1(t)))return ua("jsonrpc-shape","batch-with-invalid-element",400,new c_(cv.InvalidRequest,"Bad Request: JSON-RPC batch contains an invalid message"),!0)}return{kind:"legacy",reason:"batch"}}return c0(r)||c1(r)?{kind:"legacy",reason:"response"}:uu(r)&&cX(r)?function(t,r){let i=r.params,n=r.method,o=t.protocolVersionHeader,a=void 0!==o&&o>=lQ;if("initialize"===n&&!function(t){if(!cW(t))return!1;let r=cG(t);if(void 0===r||!(r>=lQ))return!1;let i=cB(t);return void 0!==i&&0===cK(i).length}(i)){if(a)return us("initialize-with-modern-header",o,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let t=uu(i)&&"string"==typeof i.protocolVersion?i.protocolVersion:void 0;return{kind:"legacy",reason:"initialize",...void 0!==t&&{requestedVersion:t}}}if(cW(i)){let a=cB(i),s=(void 0===a?[]:cK(a))[0];if(void 0!==s)return ua("envelope","envelope-invalid",400,new c_(cv.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${s.key}: ${s.problem}`,{envelope:s}),!0);let l=cG(i);return void 0!==o&&void 0!==l&&o!==l?us("header-body-version-mismatch",o,`the body envelope names protocol version ${l} but the MCP-Protocol-Version header names ${o}`):void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?us("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:ud(l)}}if(a){let t=cB(i),r=cK(t??{}).filter(t=>"missing"===t.problem).map(t=>t.key),n=void 0===t?["_meta"]:r.length>0?r:[oG];return ua("envelope","modern-header-without-claim",400,new c_(cv.InvalidParams,`Invalid params: the MCP-Protocol-Version header names protocol revision ${o}, 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!==o&&{requestedVersion:o}}}(t,r):uu(r)&&cQ(r)?function(t,r){let i=r.params,n=r.method,o=t.protocolVersionHeader,a=void 0!==o&&o>=lQ;if(cW(i)){let a=cG(i);if(void 0===a){let t=cB(i),r=(void 0===t?[]:cK(t)).find(t=>t.key===oG)??{key:oG,problem:"expected a protocol version string"};return ua("envelope","notification-envelope-invalid",400,new c_(cv.InvalidParams,`Invalid _meta envelope for protocol revision 2026-07-28: ${r.key}: ${r.problem}`,{envelope:r}),!0)}if(void 0!==o&&o!==a)return us("notification-header-body-version-mismatch",o,`the notification envelope names protocol version ${a} but the MCP-Protocol-Version header names ${o}`);let s=ud(a);return"modern"===s.era&&void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?us("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 a?void 0!==t.mcpMethodHeader&&t.mcpMethodHeader!==n?us("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:o}}:{kind:"legacy",reason:"notification",...void 0!==o&&{requestedVersion:o}}}(t,r):ua("jsonrpc-shape","invalid-json-rpc-body",400,new c_(cv.InvalidRequest,"Bad Request: the request body is not a valid JSON-RPC message"),!0)}({httpMethod:a,...dF(t),...void 0!==o&&{body:o}}),body:o,parsedBody:s,forwardRequest:l}}let dD=(t,r)=>{globalThis[t]=r},dV=t=>globalThis[t];function dJ({name:t,fallback:r=!0}){let i=Symbol.for(`xmcp-context-${t}`),n=Symbol.for(`xmcp-context-${t}-fallback-store`);if(dV(i))return dV(i);let o=new x,a=globalThis[n]??{current:null};dD(n,a);let s={provider:(t,i)=>(r&&(a.current=t),o.run(t,i)),getContext:()=>{let i=o.getStore();if(i)return i;if(r&&a.current)return a.current;throw Error(`getContext() can only be used within the ${t} context.`)},setContext:i=>{let n=o.getStore()??(r?a.current:null);if(!n)throw Error(`setContext() can only be used within the ${t} context.`);Object.assign(n,i)}};return dD(i,s),s}let dB=dJ({name:"http-request-context"});dB.setContext;let dW=dB.getContext,dG=dB.provider,dK=t=>"object"==typeof t&&null!==t&&!Array.isArray(t),dY=t=>{if(!dK(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},dX=t=>{if(t&&"initialize"===t.method&&dK(t.params))return dY(t.params.clientInfo)},dQ=(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 o=t.trim();return o.length>0?o:void 0}};function d0(t){let{tags:r,enabled:i,...n}=t;return{...n,_meta:void 0===r?n._meta:{...n._meta,"xmcp/tags":r}}}let d1=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}},d2=dJ({name:"request-context",fallback:!1}),d9=dJ({name:"client-info-context"});d9.setContext;let d4=d9.getContext;d9.provider;let d5=new Set(["message","mode","requestedSchema"]),d3=new Set(["elicitationId","message","mode","url"]),d6=new Set(["properties","required","type"]),d7=new Set(["default","description","format","maxLength","minLength","title","type"]),d8=new Set(["default","description","enum","enumNames","title","type"]),pe=new Set(["default","description","title","type"]),pt=new Set(["default","description","maximum","minimum","title","type"]),pr=new Set(["date","date-time","email","uri"]);async function pi(t,r,i){let n=function(t){let r=t.mode??"form";if("url"===r)return function(t){let r;po(t,"Elicitation request must be a plain object."),pn(t,d3,"URL elicitation"),pa(t.message,"URL elicitation requires a string message."),ps(t.elicitationId,"URL elicitation requires a non-empty elicitationId."),ps(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){po(t,"Elicitation request must be a plain object."),pn(t,d5,"Form elicitation"),pa(t.message,"Form elicitation requires a string message.");let r=t.requestedSchema;if(po(r,"Form elicitation requires a flat object schema."),pn(r,d6,"Form elicitation schema"),"object"!==r.type)throw Error('Form elicitation schema must use type "object".');for(let[t,i]of(po(r.properties,"Form elicitation schema requires a properties object."),Object.entries(r.properties)))!function(t,r){if(po(r,`Form elicitation field "${t}" must be a plain object.`),pl(r.title,`Form elicitation field "${t}" title must be a string.`),pl(r.description,`Form elicitation field "${t}" description must be a string.`),"string"===r.type&&"enum"in r){var i,n;if(pn(r,d8,`Form elicitation field "${t}"`),pu(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&&pu(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(pl(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)){pn(r,d7,`Form elicitation field "${t}"`),pc(r.minLength,`Form elicitation field "${t}" minLength must be a number.`),pc(r.maxLength,`Form elicitation field "${t}" maxLength must be a number.`),pl(r.default,`Form elicitation field "${t}" default must be a string.`);let i=r.format;if(pl(i,`Form elicitation field "${t}" format must be a string.`),void 0!==i&&!pr.has(i))throw Error(`Form elicitation field "${t}" format must be one of: ${Array.from(pr).join(", ")}.`);return}if("boolean"===r.type){if(pn(r,pe,`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){pn(r,pt,`Form elicitation field "${t}"`),pc(r.minimum,`Form elicitation field "${t}" minimum must be a number.`),pc(r.maximum,`Form elicitation field "${t}" maximum must be a number.`),pc(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 lG&&t.code===lW.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 pn(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 po(t,r){if("object"!=typeof t||null===t||Array.isArray(t))throw Error(r)}function pa(t,r){if("string"!=typeof t)throw Error(r)}function ps(t,r){if("string"!=typeof t||0===t.trim().length)throw Error(r)}function pl(t,r){if(void 0!==t&&"string"!=typeof t)throw Error(r)}function pc(t,r){if(void 0!==t&&"number"!=typeof t)throw Error(r)}function pu(t,r){if(!Array.isArray(t)||t.some(t=>"string"!=typeof t))throw Error(r)}let pd=new Set(["_meta","includeContext","maxTokens","messages","metadata","modelPreferences","stopSequences","systemPrompt","temperature"]),pp=new Set(["task","toolChoice","tools"]),pm=new Set(["text","image","audio"]);async function ph(t,r,i){let n=function(t){pf(t,"Sampling request must be a plain object.");let r=Object.keys(t),i=r.filter(t=>pp.has(t));if(i.length>0)throw Error(`Sampling request key(s) not supported by xmcp yet: ${i.join(", ")}.`);let n=r.filter(t=>!pd.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(pf(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;pf(i,`Sampling message at index ${t} requires a content object.`);let n=i.type;if("string"!=typeof n||!pm.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 lG&&t.code===lW.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 pf(t,r){if("object"!=typeof t||null===t||Array.isArray(t))throw Error(r)}let pg={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 py(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=pg[t.type];return r?r(t):{valid:!0}}function pv(t,r,i,n){if(null===t||"object"!=typeof t||Array.isArray(t))throw Error(`Tool "${i}" ${n}: expected a plain object.`);let o=new Set(Object.keys(r)),a=Object.keys(t).filter(t=>!o.has(t));if(a.length>0)throw Error(`Tool "${i}" ${n}: unrecognized key(s): ${a.join(", ")}`);for(let[o,a]of Object.entries(r))try{a.parse(t[o])}catch(t){throw Error(`Tool "${i}" ${n}: ${t?.message??`invalid field "${o}"`}`)}}function p_(t){return!!(t&&"object"==typeof t&&Object.keys(t).some(t=>t.startsWith("ui/")))}function pb(t){let r=t.mcpReq.envelope,i=dY(r?.[oK]);if(!i)try{let t,r=dW();i=r.clientInfo??(t=r.headers,dY({name:dQ(t,"x-mcp-client-name"),version:dQ(t,"x-mcp-client-version"),title:dQ(t,"x-mcp-client-title"),websiteUrl:dQ(t,"x-mcp-client-website-url"),description:dQ(t,"x-mcp-client-description")}))}catch{}if(!i)try{i=d4().clientInfo}catch{}return i}function pS(t){let r=[...t];return(t,i,n)=>(function(t,r,i){let n,o=new Map;if(t.http){let t=dW(),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 d2.provider(Object.freeze({clientInfo:r?Object.freeze({...r}):void 0,http:n,authInfo:t.http?.authInfo,signal:t.mcpReq.signal,set(t,r){o.set(t,r)},get:t=>o.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,pb(i),async()=>{if(0===r.length)return n();let i=Object.freeze({...function(){try{return d2.getContext()}catch{throw Error("getRequestContext() can only be used while handling an MCP request.")}}(),...t,params:Object.freeze({...t.params})}),o=-1,a=async t=>{if(t<=o)throw Error("MCP middleware next() can only be called once");o=t;let s=r[t];return s?s(i,()=>a(t+1)):n()};return a(0)})}let pw=new Set(["tools/list","prompts/get","prompts/list","resources/read","resources/list","resources/templates/list","completion/complete"]);function pR(t){return t.endsWith(".tsx")}let pk=Symbol("Let zodToJsonSchema decide on which parser to use"),px={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"};(E=L||(L={})).assertEqual=t=>{},E.assertIs=function(t){},E.assertNever=function(t){throw Error()},E.arrayToEnum=t=>{let r={};for(let i of t)r[i]=i;return r},E.getValidEnumValues=t=>{let r=E.objectKeys(t).filter(r=>"number"!=typeof t[t[r]]),i={};for(let n of r)i[n]=t[n];return E.objectValues(i)},E.objectValues=t=>E.objectKeys(t).map(function(r){return t[r]}),E.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},E.find=(t,r)=>{for(let i of t)if(r(i))return i},E.isInteger="function"==typeof Number.isInteger?t=>Number.isInteger(t):t=>"number"==typeof t&&Number.isFinite(t)&&Math.floor(t)===t,E.joinValues=function(t,r=" | "){return t.map(t=>"string"==typeof t?`'${t}'`:t).join(r)},E.jsonStringifyReplacer=(t,r)=>"bigint"==typeof r?r.toString():r,(N||(N={})).mergeShapes=(t,r)=>({...t,...r});let pC=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),p$=t=>{switch(typeof t){case"undefined":return pC.undefined;case"string":return pC.string;case"number":return Number.isNaN(t)?pC.nan:pC.number;case"boolean":return pC.boolean;case"function":return pC.function;case"bigint":return pC.bigint;case"symbol":return pC.symbol;case"object":if(Array.isArray(t))return pC.array;if(null===t)return pC.null;if(t.then&&"function"==typeof t.then&&t.catch&&"function"==typeof t.catch)return pC.promise;if("undefined"!=typeof Map&&t instanceof Map)return pC.map;if("undefined"!=typeof Set&&t instanceof Set)return pC.set;if("undefined"!=typeof Date&&t instanceof Date)return pC.date;return pC.object;default:return pC.unknown}},pT=L.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 pP 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 o of t.issues)if("invalid_union"===o.code)o.unionErrors.map(n);else if("invalid_return_type"===o.code)n(o.returnTypeError);else if("invalid_arguments"===o.code)n(o.argumentsError);else if(0===o.path.length)i._errors.push(r(o));else{let t=i,n=0;for(;n<o.path.length;){let i=o.path[n],a=n===o.path.length-1;if("_errors"===i){a&&t._errors.push(r(o)),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],a&&t._errors.push(r(o)),n++}}};return n(this),i}static assert(t){if(!(t instanceof pP))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.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()}}pP.create=t=>new pP(t);let pE=(t,r)=>{let i;switch(t.code){case pT.invalid_type:i=t.received===pC.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case pT.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(t.expected,L.jsonStringifyReplacer)}`;break;case pT.unrecognized_keys:i=`Unrecognized key(s) in object: ${L.joinValues(t.keys,", ")}`;break;case pT.invalid_union:i="Invalid input";break;case pT.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${L.joinValues(t.options)}`;break;case pT.invalid_enum_value:i=`Invalid enum value. Expected ${L.joinValues(t.options)}, received '${t.received}'`;break;case pT.invalid_arguments:i="Invalid function arguments";break;case pT.invalid_return_type:i="Invalid function return type";break;case pT.invalid_date:i="Invalid date";break;case pT.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}"`:L.assertNever(t.validation):i="regex"!==t.validation?`Invalid ${t.validation}`:"Invalid";break;case pT.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 pT.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 pT.custom:i="Invalid input";break;case pT.invalid_intersection_types:i="Intersection results could not be merged";break;case pT.not_multiple_of:i=`Number must be a multiple of ${t.multipleOf}`;break;case pT.not_finite:i="Number must be finite";break;default:i=r.defaultError,L.assertNever(t)}return{message:i}};(O=z||(z={})).errToObj=t=>"string"==typeof t?{message:t}:t||{},O.toString=t=>"string"==typeof t?t:t?.message;let pO=t=>{let{data:r,path:i,errorMaps:n,issueData:o}=t,a=[...i,...o.path||[]],s={...o,path:a};if(void 0!==o.message)return{...o,path:a,message:o.message};let l="";for(let t of n.filter(t=>!!t).slice().reverse())l=t(s,{data:r,defaultError:l}).message;return{...o,path:a,message:l}};function pI(t,r){let i=pO({issueData:r,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pE,void 0].filter(t=>!!t)});t.common.issues.push(i)}class pq{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 pj;"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 pq.mergeObjectSync(t,i)}static mergeObjectSync(t,r){let i={};for(let n of r){let{key:r,value:o}=n;if("aborted"===r.status||"aborted"===o.status)return pj;"dirty"===r.status&&t.dirty(),"dirty"===o.status&&t.dirty(),"__proto__"!==r.value&&(void 0!==o.value||n.alwaysSet)&&(i[r.value]=o.value)}return{status:t.value,value:i}}}let pj=Object.freeze({status:"aborted"}),pA=t=>({status:"dirty",value:t}),pL=t=>({status:"valid",value:t}),pN=t=>"undefined"!=typeof Promise&&t instanceof Promise;class pz{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 pM=(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 pP(t.common.issues);return this._error=r,this._error}}};function pZ(t){if(!t)return{};let{errorMap:r,invalid_type_error:i,required_error:n,description:o}=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:o}:{errorMap:(r,o)=>{let{message:a}=t;return"invalid_enum_value"===r.code?{message:a??o.defaultError}:void 0===o.data?{message:a??n??o.defaultError}:"invalid_type"!==r.code?{message:o.defaultError}:{message:a??i??o.defaultError}},description:o}}class pU{get description(){return this._def.description}_getType(t){return p$(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:p$(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new pq,ctx:{common:t.parent.common,data:t.data,parsedType:p$(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(pN(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:p$(t)},n=this._parseSync({data:t,path:i.path,parent:i});return pM(i,n)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:p$(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:p$(t)},n=this._parse({data:t,path:i.path,parent:i});return pM(i,await (pN(n)?n:Promise.resolve(n)))}refine(t,r){return this._refinement((i,n)=>{let o=t(i),a=()=>n.addIssue({code:pT.custom,..."string"==typeof r||void 0===r?{message:r}:"function"==typeof r?r(i):r});return"undefined"!=typeof Promise&&o instanceof Promise?o.then(t=>!!t||(a(),!1)):!!o||(a(),!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 mk({schema:this,typeName:M.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 mx.create(this,this._def)}nullable(){return mC.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ms.create(this)}promise(){return mR.create(this,this._def)}or(t){return mc.create([this,t],this._def)}and(t){return mp.create(this,t,this._def)}transform(t){return new mk({...pZ(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){return new m$({...pZ(this._def),innerType:this,defaultValue:"function"==typeof t?t:()=>t,typeName:M.ZodDefault})}brand(){return new mE({typeName:M.ZodBranded,type:this,...pZ(this._def)})}catch(t){return new mT({...pZ(this._def),innerType:this,catchValue:"function"==typeof t?t:()=>t,typeName:M.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return mO.create(this,t)}readonly(){return mI.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let pF=/^c[^\s-]{8,}$/i,pH=/^[0-9a-z]+$/,pD=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pV=/^[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,pJ=/^[a-z0-9_-]{21}$/i,pB=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pW=/^[-+]?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)?)??$/,pG=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,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])$/,pY=/^(?:(?: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])$/,pX=/^(([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]))$/,pQ=/^(([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])$/,p0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,p1=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,p2="((\\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])))",p9=RegExp(`^${p2}$`);function p4(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 p5 extends pU{_parse(t){var r,i,n,o;let a;if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==pC.string){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.string,received:r.parsedType}),pj}let s=new pq;for(let l of this._def.checks)if("min"===l.kind)t.data.length<l.value&&(pI(a=this._getOrReturnCtx(t,a),{code:pT.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&&(pI(a=this._getOrReturnCtx(t,a),{code:pT.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)&&(a=this._getOrReturnCtx(t,a),r?pI(a,{code:pT.too_big,maximum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}):i&&pI(a,{code:pT.too_small,minimum:l.value,type:"string",inclusive:!0,exact:!0,message:l.message}),s.dirty())}else if("email"===l.kind)pG.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"email",code:pT.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)||(pI(a=this._getOrReturnCtx(t,a),{validation:"emoji",code:pT.invalid_string,message:l.message}),s.dirty());else if("uuid"===l.kind)pV.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"uuid",code:pT.invalid_string,message:l.message}),s.dirty());else if("nanoid"===l.kind)pJ.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"nanoid",code:pT.invalid_string,message:l.message}),s.dirty());else if("cuid"===l.kind)pF.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"cuid",code:pT.invalid_string,message:l.message}),s.dirty());else if("cuid2"===l.kind)pH.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"cuid2",code:pT.invalid_string,message:l.message}),s.dirty());else if("ulid"===l.kind)pD.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"ulid",code:pT.invalid_string,message:l.message}),s.dirty());else if("url"===l.kind)try{new URL(t.data)}catch{pI(a=this._getOrReturnCtx(t,a),{validation:"url",code:pT.invalid_string,message:l.message}),s.dirty()}else"regex"===l.kind?(l.regex.lastIndex=0,l.regex.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"regex",code:pT.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)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.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)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:{startsWith:l.value},message:l.message}),s.dirty()):"endsWith"===l.kind?t.data.endsWith(l.value)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:{endsWith:l.value},message:l.message}),s.dirty()):"datetime"===l.kind?(function(t){let r=`${p2}T${p4(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)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:"datetime",message:l.message}),s.dirty()):"date"===l.kind?p9.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:"date",message:l.message}),s.dirty()):"time"===l.kind?RegExp(`^${p4(l)}$`).test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{code:pT.invalid_string,validation:"time",message:l.message}),s.dirty()):"duration"===l.kind?pW.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"duration",code:pT.invalid_string,message:l.message}),s.dirty()):"ip"===l.kind?(r=t.data,!(("v4"===(i=l.version)||!i)&&pK.test(r)||("v6"===i||!i)&&pX.test(r))&&1&&(pI(a=this._getOrReturnCtx(t,a),{validation:"ip",code:pT.invalid_string,message:l.message}),s.dirty())):"jwt"===l.kind?!function(t,r){if(!pB.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,"="),o=JSON.parse(atob(n));if("object"!=typeof o||null===o||"typ"in o&&o?.typ!=="JWT"||!o.alg||r&&o.alg!==r)return!1;return!0}catch{return!1}}(t.data,l.alg)&&(pI(a=this._getOrReturnCtx(t,a),{validation:"jwt",code:pT.invalid_string,message:l.message}),s.dirty()):"cidr"===l.kind?(n=t.data,!(("v4"===(o=l.version)||!o)&&pY.test(n)||("v6"===o||!o)&&pQ.test(n))&&1&&(pI(a=this._getOrReturnCtx(t,a),{validation:"cidr",code:pT.invalid_string,message:l.message}),s.dirty())):"base64"===l.kind?p0.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"base64",code:pT.invalid_string,message:l.message}),s.dirty()):"base64url"===l.kind?p1.test(t.data)||(pI(a=this._getOrReturnCtx(t,a),{validation:"base64url",code:pT.invalid_string,message:l.message}),s.dirty()):L.assertNever(l);return{status:s.value,value:t.data}}_regex(t,r,i){return this.refinement(r=>t.test(r),{validation:r,code:pT.invalid_string,...z.errToObj(i)})}_addCheck(t){return new p5({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...z.errToObj(t)})}url(t){return this._addCheck({kind:"url",...z.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...z.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...z.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...z.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...z.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...z.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...z.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...z.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...z.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...z.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...z.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...z.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,...z.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,...z.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...z.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...z.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...z.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...z.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...z.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...z.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...z.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...z.errToObj(r)})}nonempty(t){return this.min(1,z.errToObj(t))}trim(){return new p5({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new p5({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new p5({...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}}p5.create=t=>new p5({checks:[],typeName:M.ZodString,coerce:t?.coerce??!1,...pZ(t)});class p3 extends pU{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)!==pC.number){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.number,received:r.parsedType}),pj}let i=new pq;for(let n of this._def.checks)"int"===n.kind?L.isInteger(t.data)||(pI(r=this._getOrReturnCtx(t,r),{code:pT.invalid_type,expected:"integer",received:"float",message:n.message}),i.dirty()):"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.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)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.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,o=i>n?i:n;return Number.parseInt(t.toFixed(o).replace(".",""))%Number.parseInt(r.toFixed(o).replace(".",""))/10**o}(t.data,n.value)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):"finite"===n.kind?Number.isFinite(t.data)||(pI(r=this._getOrReturnCtx(t,r),{code:pT.not_finite,message:n.message}),i.dirty()):L.assertNever(n);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,z.toString(r))}gt(t,r){return this.setLimit("min",t,!1,z.toString(r))}lte(t,r){return this.setLimit("max",t,!0,z.toString(r))}lt(t,r){return this.setLimit("max",t,!1,z.toString(r))}setLimit(t,r,i,n){return new p3({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:z.toString(n)}]})}_addCheck(t){return new p3({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:z.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:z.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:z.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.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&&L.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)}}p3.create=t=>new p3({checks:[],typeName:M.ZodNumber,coerce:t?.coerce||!1,...pZ(t)});class p6 extends pU{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)!==pC.bigint)return this._getInvalidInput(t);let i=new pq;for(let n of this._def.checks)"min"===n.kind?(n.inclusive?t.data<n.value:t.data<=n.value)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.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)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),i.dirty()):"multipleOf"===n.kind?t.data%n.value!==BigInt(0)&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.not_multiple_of,multipleOf:n.value,message:n.message}),i.dirty()):L.assertNever(n);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.bigint,received:r.parsedType}),pj}gte(t,r){return this.setLimit("min",t,!0,z.toString(r))}gt(t,r){return this.setLimit("min",t,!1,z.toString(r))}lte(t,r){return this.setLimit("max",t,!0,z.toString(r))}lt(t,r){return this.setLimit("max",t,!1,z.toString(r))}setLimit(t,r,i,n){return new p6({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:i,message:z.toString(n)}]})}_addCheck(t){return new p6({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:z.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}}p6.create=t=>new p6({checks:[],typeName:M.ZodBigInt,coerce:t?.coerce??!1,...pZ(t)});class p7 extends pU{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==pC.boolean){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.boolean,received:r.parsedType}),pj}return pL(t.data)}}p7.create=t=>new p7({typeName:M.ZodBoolean,coerce:t?.coerce||!1,...pZ(t)});class p8 extends pU{_parse(t){let r;if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==pC.date){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.date,received:r.parsedType}),pj}if(Number.isNaN(t.data.getTime()))return pI(this._getOrReturnCtx(t),{code:pT.invalid_date}),pj;let i=new pq;for(let n of this._def.checks)"min"===n.kind?t.data.getTime()<n.value&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),i.dirty()):"max"===n.kind?t.data.getTime()>n.value&&(pI(r=this._getOrReturnCtx(t,r),{code:pT.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):L.assertNever(n);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new p8({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:z.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:z.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}}p8.create=t=>new p8({checks:[],coerce:t?.coerce||!1,typeName:M.ZodDate,...pZ(t)});class me extends pU{_parse(t){if(this._getType(t)!==pC.symbol){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.symbol,received:r.parsedType}),pj}return pL(t.data)}}me.create=t=>new me({typeName:M.ZodSymbol,...pZ(t)});class mt extends pU{_parse(t){if(this._getType(t)!==pC.undefined){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.undefined,received:r.parsedType}),pj}return pL(t.data)}}mt.create=t=>new mt({typeName:M.ZodUndefined,...pZ(t)});class mr extends pU{_parse(t){if(this._getType(t)!==pC.null){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.null,received:r.parsedType}),pj}return pL(t.data)}}mr.create=t=>new mr({typeName:M.ZodNull,...pZ(t)});class mi extends pU{constructor(){super(...arguments),this._any=!0}_parse(t){return pL(t.data)}}mi.create=t=>new mi({typeName:M.ZodAny,...pZ(t)});class mn extends pU{constructor(){super(...arguments),this._unknown=!0}_parse(t){return pL(t.data)}}mn.create=t=>new mn({typeName:M.ZodUnknown,...pZ(t)});class mo extends pU{_parse(t){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.never,received:r.parsedType}),pj}}mo.create=t=>new mo({typeName:M.ZodNever,...pZ(t)});class ma extends pU{_parse(t){if(this._getType(t)!==pC.undefined){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.void,received:r.parsedType}),pj}return pL(t.data)}}ma.create=t=>new ma({typeName:M.ZodVoid,...pZ(t)});class ms extends pU{_parse(t){let{ctx:r,status:i}=this._processInputParams(t),n=this._def;if(r.parsedType!==pC.array)return pI(r,{code:pT.invalid_type,expected:pC.array,received:r.parsedType}),pj;if(null!==n.exactLength){let t=r.data.length>n.exactLength.value,o=r.data.length<n.exactLength.value;(t||o)&&(pI(r,{code:t?pT.too_big:pT.too_small,minimum:o?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&&(pI(r,{code:pT.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&&(pI(r,{code:pT.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 pz(r,t,r.path,i)))).then(t=>pq.mergeArray(i,t));let o=[...r.data].map((t,i)=>n.type._parseSync(new pz(r,t,r.path,i)));return pq.mergeArray(i,o)}get element(){return this._def.type}min(t,r){return new ms({...this._def,minLength:{value:t,message:z.toString(r)}})}max(t,r){return new ms({...this._def,maxLength:{value:t,message:z.toString(r)}})}length(t,r){return new ms({...this._def,exactLength:{value:t,message:z.toString(r)}})}nonempty(t){return this.min(1,t)}}ms.create=(t,r)=>new ms({type:t,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...pZ(r)});class ml extends pU{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=L.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==pC.object){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.object,received:r.parsedType}),pj}let{status:r,ctx:i}=this._processInputParams(t),{shape:n,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof mo&&"strip"===this._def.unknownKeys))for(let t in i.data)o.includes(t)||a.push(t);let s=[];for(let t of o){let r=n[t],o=i.data[t];s.push({key:{status:"valid",value:t},value:r._parse(new pz(i,o,i.path,t)),alwaysSet:t in i.data})}if(this._def.catchall instanceof mo){let t=this._def.unknownKeys;if("passthrough"===t)for(let t of a)s.push({key:{status:"valid",value:t},value:{status:"valid",value:i.data[t]}});else if("strict"===t)a.length>0&&(pI(i,{code:pT.unrecognized_keys,keys:a}),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 a){let n=i.data[r];s.push({key:{status:"valid",value:r},value:t._parse(new pz(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=>pq.mergeObjectSync(r,t)):pq.mergeObjectSync(r,s)}get shape(){return this._def.shape()}strict(t){return z.errToObj,new ml({...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:z.errToObj(t).message??n}:{message:n}}}:{}})}strip(){return new ml({...this._def,unknownKeys:"strip"})}passthrough(){return new ml({...this._def,unknownKeys:"passthrough"})}extend(t){return new ml({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new ml({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:M.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new ml({...this._def,catchall:t})}pick(t){let r={};for(let i of L.objectKeys(t))t[i]&&this.shape[i]&&(r[i]=this.shape[i]);return new ml({...this._def,shape:()=>r})}omit(t){let r={};for(let i of L.objectKeys(this.shape))t[i]||(r[i]=this.shape[i]);return new ml({...this._def,shape:()=>r})}deepPartial(){return function t(r){if(r instanceof ml){let i={};for(let n in r.shape){let o=r.shape[n];i[n]=mx.create(t(o))}return new ml({...r._def,shape:()=>i})}if(r instanceof ms)return new ms({...r._def,type:t(r.element)});if(r instanceof mx)return mx.create(t(r.unwrap()));if(r instanceof mC)return mC.create(t(r.unwrap()));if(r instanceof mm)return mm.create(r.items.map(r=>t(r)));else return r}(this)}partial(t){let r={};for(let i of L.objectKeys(this.shape)){let n=this.shape[i];t&&!t[i]?r[i]=n:r[i]=n.optional()}return new ml({...this._def,shape:()=>r})}required(t){let r={};for(let i of L.objectKeys(this.shape))if(t&&!t[i])r[i]=this.shape[i];else{let t=this.shape[i];for(;t instanceof mx;)t=t._def.innerType;r[i]=t}return new ml({...this._def,shape:()=>r})}keyof(){return mb(L.objectKeys(this.shape))}}ml.create=(t,r)=>new ml({shape:()=>t,unknownKeys:"strip",catchall:mo.create(),typeName:M.ZodObject,...pZ(r)}),ml.strictCreate=(t,r)=>new ml({shape:()=>t,unknownKeys:"strict",catchall:mo.create(),typeName:M.ZodObject,...pZ(r)}),ml.lazycreate=(t,r)=>new ml({shape:t,unknownKeys:"strip",catchall:mo.create(),typeName:M.ZodObject,...pZ(r)});class mc extends pU{_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 pP(t.ctx.common.issues));return pI(r,{code:pT.invalid_union,unionErrors:i}),pj});{let t,n=[];for(let o of i){let i={...r,common:{...r.common,issues:[]},parent:null},a=o._parseSync({data:r.data,path:r.path,parent:i});if("valid"===a.status)return a;"dirty"!==a.status||t||(t={result:a,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 o=n.map(t=>new pP(t));return pI(r,{code:pT.invalid_union,unionErrors:o}),pj}}get options(){return this._def.options}}mc.create=(t,r)=>new mc({options:t,typeName:M.ZodUnion,...pZ(r)});let mu=t=>{if(t instanceof mv)return mu(t.schema);if(t instanceof mk)return mu(t.innerType());if(t instanceof m_)return[t.value];if(t instanceof mS)return t.options;if(t instanceof mw)return L.objectValues(t.enum);else if(t instanceof m$)return mu(t._def.innerType);else if(t instanceof mt)return[void 0];else if(t instanceof mr)return[null];else if(t instanceof mx)return[void 0,...mu(t.unwrap())];else if(t instanceof mC)return[null,...mu(t.unwrap())];else if(t instanceof mE)return mu(t.unwrap());else if(t instanceof mI)return mu(t.unwrap());else if(t instanceof mT)return mu(t._def.innerType);else return[]};class md extends pU{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==pC.object)return pI(r,{code:pT.invalid_type,expected:pC.object,received:r.parsedType}),pj;let i=this.discriminator,n=r.data[i],o=this.optionsMap.get(n);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(pI(r,{code:pT.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),pj)}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=mu(i.shape[t]);if(!r.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let o of r){if(n.has(o))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);n.set(o,i)}}return new md({typeName:M.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:n,...pZ(i)})}}class mp extends pU{_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=(t,n)=>{if("aborted"===t.status||"aborted"===n.status)return pj;let o=function t(r,i){let n=p$(r),o=p$(i);if(r===i)return{valid:!0,data:r};if(n===pC.object&&o===pC.object){let n=L.objectKeys(i),o=L.objectKeys(r).filter(t=>-1!==n.indexOf(t)),a={...r,...i};for(let n of(Object.prototype.hasOwnProperty.call(a,"__proto__")&&delete a.__proto__,o)){if("__proto__"===n)continue;let o=t(r[n],i[n]);if(!o.valid)return{valid:!1};a[n]=o.data}return{valid:!0,data:a}}if(n===pC.array&&o===pC.array){if(r.length!==i.length)return{valid:!1};let n=[];for(let o=0;o<r.length;o++){let a=t(r[o],i[o]);if(!a.valid)return{valid:!1};n.push(a.data)}return{valid:!0,data:n}}if(n===pC.date&&o===pC.date&&+r==+i)return{valid:!0,data:r};return{valid:!1}}(t.value,n.value);return o.valid?(("dirty"===t.status||"dirty"===n.status)&&r.dirty(),{status:r.value,value:o.data}):(pI(i,{code:pT.invalid_intersection_types}),pj)};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}))}}mp.create=(t,r,i)=>new mp({left:t,right:r,typeName:M.ZodIntersection,...pZ(i)});class mm extends pU{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==pC.array)return pI(i,{code:pT.invalid_type,expected:pC.array,received:i.parsedType}),pj;if(i.data.length<this._def.items.length)return pI(i,{code:pT.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),pj;!this._def.rest&&i.data.length>this._def.items.length&&(pI(i,{code:pT.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 pz(i,t,i.path,r)):null}).filter(t=>!!t);return i.common.async?Promise.all(n).then(t=>pq.mergeArray(r,t)):pq.mergeArray(r,n)}get items(){return this._def.items}rest(t){return new mm({...this._def,rest:t})}}mm.create=(t,r)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new mm({items:t,typeName:M.ZodTuple,rest:null,...pZ(r)})};class mh extends pU{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!==pC.object)return pI(i,{code:pT.invalid_type,expected:pC.object,received:i.parsedType}),pj;let n=[],o=this._def.keyType,a=this._def.valueType;for(let t in i.data)n.push({key:o._parse(new pz(i,t,i.path,t)),value:a._parse(new pz(i,i.data[t],i.path,t)),alwaysSet:t in i.data});return i.common.async?pq.mergeObjectAsync(r,n):pq.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(t,r,i){return new mh(r instanceof pU?{keyType:t,valueType:r,typeName:M.ZodRecord,...pZ(i)}:{keyType:p5.create(),valueType:t,typeName:M.ZodRecord,...pZ(r)})}}class mf extends pU{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!==pC.map)return pI(i,{code:pT.invalid_type,expected:pC.map,received:i.parsedType}),pj;let n=this._def.keyType,o=this._def.valueType,a=[...i.data.entries()].map(([t,r],a)=>({key:n._parse(new pz(i,t,i.path,[a,"key"])),value:o._parse(new pz(i,r,i.path,[a,"value"]))}));if(i.common.async){let t=new Map;return Promise.resolve().then(async()=>{for(let i of a){let n=await i.key,o=await i.value;if("aborted"===n.status||"aborted"===o.status)return pj;("dirty"===n.status||"dirty"===o.status)&&r.dirty(),t.set(n.value,o.value)}return{status:r.value,value:t}})}{let t=new Map;for(let i of a){let n=i.key,o=i.value;if("aborted"===n.status||"aborted"===o.status)return pj;("dirty"===n.status||"dirty"===o.status)&&r.dirty(),t.set(n.value,o.value)}return{status:r.value,value:t}}}}mf.create=(t,r,i)=>new mf({valueType:r,keyType:t,typeName:M.ZodMap,...pZ(i)});class mg extends pU{_parse(t){let{status:r,ctx:i}=this._processInputParams(t);if(i.parsedType!==pC.set)return pI(i,{code:pT.invalid_type,expected:pC.set,received:i.parsedType}),pj;let n=this._def;null!==n.minSize&&i.data.size<n.minSize.value&&(pI(i,{code:pT.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&&(pI(i,{code:pT.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let o=this._def.valueType;function a(t){let i=new Set;for(let n of t){if("aborted"===n.status)return pj;"dirty"===n.status&&r.dirty(),i.add(n.value)}return{status:r.value,value:i}}let s=[...i.data.values()].map((t,r)=>o._parse(new pz(i,t,i.path,r)));return i.common.async?Promise.all(s).then(t=>a(t)):a(s)}min(t,r){return new mg({...this._def,minSize:{value:t,message:z.toString(r)}})}max(t,r){return new mg({...this._def,maxSize:{value:t,message:z.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}mg.create=(t,r)=>new mg({valueType:t,minSize:null,maxSize:null,typeName:M.ZodSet,...pZ(r)});class my extends pU{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==pC.function)return pI(r,{code:pT.invalid_type,expected:pC.function,received:r.parsedType}),pj;function i(t,i){return pO({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,pE,pE].filter(t=>!!t),issueData:{code:pT.invalid_arguments,argumentsError:i}})}function n(t,i){return pO({data:t,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,pE,pE].filter(t=>!!t),issueData:{code:pT.invalid_return_type,returnTypeError:i}})}let o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof mR){let t=this;return pL(async function(...r){let s=new pP([]),l=await t._def.args.parseAsync(r,o).catch(t=>{throw s.addIssue(i(r,t)),s}),c=await Reflect.apply(a,this,l);return await t._def.returns._def.type.parseAsync(c,o).catch(t=>{throw s.addIssue(n(c,t)),s})})}{let t=this;return pL(function(...r){let s=t._def.args.safeParse(r,o);if(!s.success)throw new pP([i(r,s.error)]);let l=Reflect.apply(a,this,s.data),c=t._def.returns.safeParse(l,o);if(!c.success)throw new pP([n(l,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new my({...this._def,args:mm.create(t).rest(mn.create())})}returns(t){return new my({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,i){return new my({args:t||mm.create([]).rest(mn.create()),returns:r||mn.create(),typeName:M.ZodFunction,...pZ(i)})}}class mv extends pU{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})}}mv.create=(t,r)=>new mv({getter:t,typeName:M.ZodLazy,...pZ(r)});class m_ extends pU{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return pI(r,{received:r.data,code:pT.invalid_literal,expected:this._def.value}),pj}return{status:"valid",value:t.data}}get value(){return this._def.value}}function mb(t,r){return new mS({values:t,typeName:M.ZodEnum,...pZ(r)})}m_.create=(t,r)=>new m_({value:t,typeName:M.ZodLiteral,...pZ(r)});class mS extends pU{_parse(t){if("string"!=typeof t.data){let r=this._getOrReturnCtx(t),i=this._def.values;return pI(r,{expected:L.joinValues(i),received:r.parsedType,code:pT.invalid_type}),pj}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 pI(r,{received:r.data,code:pT.invalid_enum_value,options:i}),pj}return pL(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 mS.create(t,{...this._def,...r})}exclude(t,r=this._def){return mS.create(this.options.filter(r=>!t.includes(r)),{...this._def,...r})}}mS.create=mb;class mw extends pU{_parse(t){let r=L.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==pC.string&&i.parsedType!==pC.number){let t=L.objectValues(r);return pI(i,{expected:L.joinValues(t),received:i.parsedType,code:pT.invalid_type}),pj}if(this._cache||(this._cache=new Set(L.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let t=L.objectValues(r);return pI(i,{received:i.data,code:pT.invalid_enum_value,options:t}),pj}return pL(t.data)}get enum(){return this._def.values}}mw.create=(t,r)=>new mw({values:t,typeName:M.ZodNativeEnum,...pZ(r)});class mR extends pU{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);return r.parsedType!==pC.promise&&!1===r.common.async?(pI(r,{code:pT.invalid_type,expected:pC.promise,received:r.parsedType}),pj):pL((r.parsedType===pC.promise?r.data:Promise.resolve(r.data)).then(t=>this._def.type.parseAsync(t,{path:r.path,errorMap:r.common.contextualErrorMap})))}}mR.create=(t,r)=>new mR({type:t,typeName:M.ZodPromise,...pZ(r)});class mk extends pU{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:i}=this._processInputParams(t),n=this._def.effect||null,o={addIssue:t=>{pI(i,t),t.fatal?r.abort():r.dirty()},get path(){return i.path}};if(o.addIssue=o.addIssue.bind(o),"preprocess"===n.type){let t=n.transform(i.data,o);if(i.common.async)return Promise.resolve(t).then(async t=>{if("aborted"===r.value)return pj;let n=await this._def.schema._parseAsync({data:t,path:i.path,parent:i});return"aborted"===n.status?pj:"dirty"===n.status||"dirty"===r.value?pA(n.value):n});{if("aborted"===r.value)return pj;let n=this._def.schema._parseSync({data:t,path:i.path,parent:i});return"aborted"===n.status?pj:"dirty"===n.status||"dirty"===r.value?pA(n.value):n}}if("refinement"===n.type){let t=t=>{let r=n.refinement(t,o);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?pj:("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?pj:("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?pj:Promise.resolve(n.transform(t.value,o)).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 pj;let a=n.transform(t.value,o);if(a instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}L.assertNever(n)}}mk.create=(t,r,i)=>new mk({schema:t,typeName:M.ZodEffects,effect:r,...pZ(i)}),mk.createWithPreprocess=(t,r,i)=>new mk({schema:r,effect:{type:"preprocess",transform:t},typeName:M.ZodEffects,...pZ(i)});class mx extends pU{_parse(t){return this._getType(t)===pC.undefined?pL(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mx.create=(t,r)=>new mx({innerType:t,typeName:M.ZodOptional,...pZ(r)});class mC extends pU{_parse(t){return this._getType(t)===pC.null?pL(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mC.create=(t,r)=>new mC({innerType:t,typeName:M.ZodNullable,...pZ(r)});class m$ extends pU{_parse(t){let{ctx:r}=this._processInputParams(t),i=r.data;return r.parsedType===pC.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}m$.create=(t,r)=>new m$({innerType:t,typeName:M.ZodDefault,defaultValue:"function"==typeof r.default?r.default:()=>r.default,...pZ(r)});class mT extends pU{_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 pN(n)?n.then(t=>({status:"valid",value:"valid"===t.status?t.value:this._def.catchValue({get error(){return new pP(i.common.issues)},input:i.data})})):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new pP(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}mT.create=(t,r)=>new mT({innerType:t,typeName:M.ZodCatch,catchValue:"function"==typeof r.catch?r.catch:()=>r.catch,...pZ(r)});class mP extends pU{_parse(t){if(this._getType(t)!==pC.nan){let r=this._getOrReturnCtx(t);return pI(r,{code:pT.invalid_type,expected:pC.nan,received:r.parsedType}),pj}return{status:"valid",value:t.data}}}mP.create=t=>new mP({typeName:M.ZodNaN,...pZ(t)}),Symbol("zod_brand");class mE extends pU{_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 mO extends pU{_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?pj:"dirty"===t.status?(r.dirty(),pA(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?pj:"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 mO({in:t,out:r,typeName:M.ZodPipeline})}}class mI extends pU{_parse(t){let r=this._def.innerType._parse(t),i=t=>("valid"===t.status&&(t.value=Object.freeze(t.value)),t);return pN(r)?r.then(t=>i(t)):i(r)}unwrap(){return this._def.innerType}}mI.create=(t,r)=>new mI({innerType:t,typeName:M.ZodReadonly,...pZ(r)}),ml.lazycreate,(I=M||(M={})).ZodString="ZodString",I.ZodNumber="ZodNumber",I.ZodNaN="ZodNaN",I.ZodBigInt="ZodBigInt",I.ZodBoolean="ZodBoolean",I.ZodDate="ZodDate",I.ZodSymbol="ZodSymbol",I.ZodUndefined="ZodUndefined",I.ZodNull="ZodNull",I.ZodAny="ZodAny",I.ZodUnknown="ZodUnknown",I.ZodNever="ZodNever",I.ZodVoid="ZodVoid",I.ZodArray="ZodArray",I.ZodObject="ZodObject",I.ZodUnion="ZodUnion",I.ZodDiscriminatedUnion="ZodDiscriminatedUnion",I.ZodIntersection="ZodIntersection",I.ZodTuple="ZodTuple",I.ZodRecord="ZodRecord",I.ZodMap="ZodMap",I.ZodSet="ZodSet",I.ZodFunction="ZodFunction",I.ZodLazy="ZodLazy",I.ZodLiteral="ZodLiteral",I.ZodEnum="ZodEnum",I.ZodEffects="ZodEffects",I.ZodNativeEnum="ZodNativeEnum",I.ZodOptional="ZodOptional",I.ZodNullable="ZodNullable",I.ZodDefault="ZodDefault",I.ZodCatch="ZodCatch",I.ZodPromise="ZodPromise",I.ZodBranded="ZodBranded",I.ZodPipeline="ZodPipeline",I.ZodReadonly="ZodReadonly",p5.create,p3.create,mP.create,p6.create,p7.create,p8.create,me.create,mt.create,mr.create,mi.create,mn.create,mo.create,ma.create,ms.create,ml.create,ml.strictCreate,mc.create,md.create,mp.create,mm.create,mh.create,mf.create,mg.create,my.create,mv.create,m_.create,mS.create,mw.create,mR.create,mk.create,mx.create,mC.create,mk.createWithPreprocess,mO.create;let mq=(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 mj(t){if("openAi"!==t.target)return{};let r=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===t.$refStrategy?mq(r,t.currentPath):r.join("/")}}function mA(t,r,i,n){n?.errorMessages&&i&&(t.errorMessage={...t.errorMessage,[r]:i})}function mL(t,r,i,n,o){t[r]=i,mA(t,r,n,o)}function mN(t,r){return m4(t.type._def,r)}let mz=/^[cC][^\s-]{8,}$/,mM=/^[0-9a-z]+$/,mZ=/^[0-9A-HJKMNP-TV-Z]{26}$/,mU=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,mF=()=>(void 0===k&&(k=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),k),mH=/^(?:(?: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])$/,mD=/^(([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])$/,mV=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mJ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,mB=/^[a-zA-Z0-9_-]{21}$/,mW=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function mG(t,r){let i={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":mL(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,n.value):n.value,n.message,r);break;case"max":mL(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":mX(i,"email",n.message,r);break;case"format:idn-email":mX(i,"idn-email",n.message,r);break;case"pattern:zod":mQ(i,mU,n.message,r)}break;case"url":mX(i,"uri",n.message,r);break;case"uuid":mX(i,"uuid",n.message,r);break;case"regex":mQ(i,n.regex,n.message,r);break;case"cuid":mQ(i,mz,n.message,r);break;case"cuid2":mQ(i,mM,n.message,r);break;case"startsWith":mQ(i,RegExp(`^${mK(n.value,r)}`),n.message,r);break;case"endsWith":mQ(i,RegExp(`${mK(n.value,r)}$`),n.message,r);break;case"datetime":mX(i,"date-time",n.message,r);break;case"date":mX(i,"date",n.message,r);break;case"time":mX(i,"time",n.message,r);break;case"duration":mX(i,"duration",n.message,r);break;case"length":mL(i,"minLength","number"==typeof i.minLength?Math.max(i.minLength,n.value):n.value,n.message,r),mL(i,"maxLength","number"==typeof i.maxLength?Math.min(i.maxLength,n.value):n.value,n.message,r);break;case"includes":mQ(i,RegExp(mK(n.value,r)),n.message,r);break;case"ip":"v6"!==n.version&&mX(i,"ipv4",n.message,r),"v4"!==n.version&&mX(i,"ipv6",n.message,r);break;case"base64url":mQ(i,mJ,n.message,r);break;case"jwt":mQ(i,mW,n.message,r);break;case"cidr":"v6"!==n.version&&mQ(i,mH,n.message,r),"v4"!==n.version&&mQ(i,mD,n.message,r);break;case"emoji":mQ(i,mF(),n.message,r);break;case"ulid":mQ(i,mZ,n.message,r);break;case"base64":switch(r.base64Strategy){case"format:binary":mX(i,"binary",n.message,r);break;case"contentEncoding:base64":mL(i,"contentEncoding","base64",n.message,r);break;case"pattern:zod":mQ(i,mV,n.message,r)}break;case"nanoid":mQ(i,mB,n.message,r)}return i}function mK(t,r){return"escape"===r.patternStrategy?function(t){let r="";for(let i=0;i<t.length;i++)mY.has(t[i])||(r+="\\"),r+=t[i];return r}(t):t}let mY=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function mX(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}}})):mL(t,"format",r,i,n)}function mQ(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:m0(r,n),...i&&n.errorMessages&&{errorMessage:{pattern:i}}})):mL(t,"pattern",m0(r,n),i,n)}function m0(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,o="",a=!1,s=!1,l=!1;for(let t=0;t<n.length;t++){if(a){o+=n[t],a=!1;continue}if(i.i){if(s){if(n[t].match(/[a-z]/)){l?(o+=n[t],o+=`${n[t-2]}-${n[t]}`.toUpperCase(),l=!1):"-"===n[t+1]&&n[t+2]?.match(/[a-z]/)?(o+=n[t],l=!0):o+=`${n[t]}${n[t].toUpperCase()}`;continue}}else if(n[t].match(/[a-z]/)){o+=`[${n[t]}${n[t].toUpperCase()}]`;continue}}if(i.m){if("^"===n[t]){o+=`(^|(?<=[\r
]))`;continue}else if("$"===n[t]){o+=`($|(?=[\r
]))`;continue}}if(i.s&&"."===n[t]){o+=s?`${n[t]}\r
`:`[${n[t]}\r
]`;continue}o+=n[t],"\\"===n[t]?a=!0:s&&"]"===n[t]?s=!1:s||"["!==n[t]||(s=!0)}try{new RegExp(o)}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 o}function m1(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===M.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((i,n)=>({...i,[n]:m4(t.valueType._def,{...r,currentPath:[...r.currentPath,"properties",n]})??mj(r)}),{}),additionalProperties:r.rejectedAdditionalProperties};let i={type:"object",additionalProperties:m4(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]})??r.allowedAdditionalProperties};if("openApi3"===r.target)return i;if(t.keyType?._def.typeName===M.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=mG(t.keyType._def,r);return{...i,propertyNames:o}}if(t.keyType?._def.typeName===M.ZodEnum)return{...i,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===M.ZodBranded&&t.keyType._def.type._def.typeName===M.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=mN(t.keyType._def,r);return{...i,propertyNames:o}}return i}let m2={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},m9=(t,r)=>{let i=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((t,i)=>m4(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 m4(t,r,i=!1){let n=r.seen.get(t);if(r.override){let o=r.override?.(t,r,n,i);if(o!==pk)return o}if(n&&!i){let t=m5(n,r);if(void 0!==t)return t}let o={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,o);let a=((t,r,i)=>{switch(r){case M.ZodString:return mG(t,i);case M.ZodNumber:let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",mA(n,"type",r.message,i);break;case"min":"jsonSchema7"===i.target?r.inclusive?mL(n,"minimum",r.value,r.message,i):mL(n,"exclusiveMinimum",r.value,r.message,i):(r.inclusive||(n.exclusiveMinimum=!0),mL(n,"minimum",r.value,r.message,i));break;case"max":"jsonSchema7"===i.target?r.inclusive?mL(n,"maximum",r.value,r.message,i):mL(n,"exclusiveMaximum",r.value,r.message,i):(r.inclusive||(n.exclusiveMaximum=!0),mL(n,"maximum",r.value,r.message,i));break;case"multipleOf":mL(n,"multipleOf",r.value,r.message,i)}return n;case M.ZodObject:return function(t,r){let i="openAi"===r.target,n={type:"object",properties:{}},o=[],a=t.shape();for(let t in a){let s=a[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=m4(s._def,{...r,currentPath:[...r.currentPath,"properties",t],propertyPath:[...r.currentPath,"properties",t]});void 0!==c&&(n.properties[t]=c,l||o.push(t))}o.length&&(n.required=o);let s=function(t,r){if("ZodNever"!==t.catchall._def.typeName)return m4(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 M.ZodBigInt:let o={type:"integer",format:"int64"};if(!t.checks)return o;for(let r of t.checks)switch(r.kind){case"min":"jsonSchema7"===i.target?r.inclusive?mL(o,"minimum",r.value,r.message,i):mL(o,"exclusiveMinimum",r.value,r.message,i):(r.inclusive||(o.exclusiveMinimum=!0),mL(o,"minimum",r.value,r.message,i));break;case"max":"jsonSchema7"===i.target?r.inclusive?mL(o,"maximum",r.value,r.message,i):mL(o,"exclusiveMaximum",r.value,r.message,i):(r.inclusive||(o.exclusiveMaximum=!0),mL(o,"maximum",r.value,r.message,i));break;case"multipleOf":mL(o,"multipleOf",r.value,r.message,i)}return o;case M.ZodBoolean:return{type:"boolean"};case M.ZodDate:return function t(r,i,n){let o=n??i.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((n,o)=>t(r,i,n))};switch(o){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var a=r,s=i;let l={type:"integer",format:"unix-time"};if("openApi3"===s.target)return l;for(let t of a.checks)switch(t.kind){case"min":mL(l,"minimum",t.value,t.message,s);break;case"max":mL(l,"maximum",t.value,t.message,s)}return l}}(t,i);case M.ZodUndefined:return{not:mj(i)};case M.ZodNull:return"openApi3"===i.target?{enum:["null"],nullable:!0}:{type:"null"};case M.ZodArray:let a;return a={type:"array"},t.type?._def&&t.type?._def?.typeName!==M.ZodAny&&(a.items=m4(t.type._def,{...i,currentPath:[...i.currentPath,"items"]})),t.minLength&&mL(a,"minItems",t.minLength.value,t.minLength.message,i),t.maxLength&&mL(a,"maxItems",t.maxLength.value,t.maxLength.message,i),t.exactLength&&(mL(a,"minItems",t.exactLength.value,t.exactLength.message,i),mL(a,"maxItems",t.exactLength.value,t.exactLength.message,i)),a;case M.ZodUnion:case M.ZodDiscriminatedUnion:if("openApi3"===i.target)return m9(t,i);let s=t.options instanceof Map?Array.from(t.options.values()):t.options;if(s.every(t=>t._def.typeName in m2&&(!t._def.checks||!t._def.checks.length))){let t=s.reduce((t,r)=>{let i=m2[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 m9(t,i);case M.ZodIntersection:let l,c,u;return l=[m4(t.left._def,{...i,currentPath:[...i.currentPath,"allOf","0"]}),m4(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 M.ZodTuple:return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((t,r)=>m4(t._def,{...i,currentPath:[...i.currentPath,"items",`${r}`]})).reduce((t,r)=>void 0===r?t:[...t,r],[]),additionalItems:m4(t.rest._def,{...i,currentPath:[...i.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((t,r)=>m4(t._def,{...i,currentPath:[...i.currentPath,"items",`${r}`]})).reduce((t,r)=>void 0===r?t:[...t,r],[])};case M.ZodRecord:return m1(t,i);case M.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 M.ZodEnum:return{type:"string",enum:Array.from(t.values)};case M.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 M.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:m2[t.innerType._def.typeName],nullable:!0}:{type:[m2[t.innerType._def.typeName],"null"]};if("openApi3"===i.target){let r=m4(t.innerType._def,{...i,currentPath:[...i.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let f=m4(t.innerType._def,{...i,currentPath:[...i.currentPath,"anyOf","0"]});return f&&{anyOf:[f,{type:"null"}]};case M.ZodOptional:if(i.currentPath.toString()===i.propertyPath?.toString())return m4(t.innerType._def,i);let g=m4(t.innerType._def,{...i,currentPath:[...i.currentPath,"anyOf","1"]});return g?{anyOf:[{not:mj(i)},g]}:mj(i);case M.ZodMap:if("record"===i.mapStrategy)return m1(t,i);return{type:"array",maxItems:125,items:{type:"array",items:[m4(t.keyType._def,{...i,currentPath:[...i.currentPath,"items","items","0"]})||mj(i),m4(t.valueType._def,{...i,currentPath:[...i.currentPath,"items","items","1"]})||mj(i)],minItems:2,maxItems:2}};case M.ZodSet:let y;return y={type:"array",uniqueItems:!0,items:m4(t.valueType._def,{...i,currentPath:[...i.currentPath,"items"]})},t.minSize&&mL(y,"minItems",t.minSize.value,t.minSize.message,i),t.maxSize&&mL(y,"maxItems",t.maxSize.value,t.maxSize.message,i),y;case M.ZodLazy:return()=>t.getter()._def;case M.ZodPromise:return m4(t.type._def,i);case M.ZodNaN:case M.ZodNever:return"openAi"===i.target?void 0:{not:mj({...i,currentPath:[...i.currentPath,"not"]})};case M.ZodEffects:return"input"===i.effectStrategy?m4(t.schema._def,i):mj(i);case M.ZodAny:case M.ZodUnknown:return mj(i);case M.ZodDefault:return{...m4(t.innerType._def,i),default:t.defaultValue()};case M.ZodBranded:return mN(t,i);case M.ZodReadonly:case M.ZodCatch:return m4(t.innerType._def,i);case M.ZodPipeline:if("input"===i.pipeStrategy)return m4(t.in._def,i);if("output"===i.pipeStrategy)return m4(t.out._def,i);let v=m4(t.in._def,{...i,currentPath:[...i.currentPath,"allOf","0"]}),_=m4(t.out._def,{...i,currentPath:[...i.currentPath,"allOf",v?"1":"0"]});return{allOf:[v,_].filter(t=>void 0!==t)};case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:default:return}})(t,t.typeName,r),s="function"==typeof a?m4(a(),r):a;if(s&&m3(t,r,s),r.postProcess){let i=r.postProcess(s,t,r);return o.jsonSchema=s,i}return o.jsonSchema=s,s}let m5=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:mq(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`),mj(r);return"seen"===r.$refStrategy?mj(r):void 0}},m3=(t,r,i)=>(t.description&&(i.description=t.description,r.markdownDescription&&(i.markdownDescription=t.description)),i);function m6(t,r={}){let{strict:i=!1}=r,n=Object.entries(t),o=t=>({target:r})=>{let o={},a=[];for(let[i,s]of n)o[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,o=(n=void 0!==(i="string"==typeof r?{...px,name:r}:{...px,...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}]))}),a="object"==typeof r&&r.definitions?Object.entries(r.definitions).reduce((t,[r,i])=>({...t,[r]:m4(i._def,{...o,currentPath:[...o.basePath,o.definitionPath,r]},!0)??mj(o)}),{}):void 0,s="string"==typeof r?r:r?.nameStrategy==="title"?void 0:r?.name,l=m4(t._def,void 0===s?o:{...o,currentPath:[...o.basePath,o.definitionPath,s]},!1)??mj(o),c="object"==typeof r&&void 0!==r.name&&"title"===r.nameStrategy?r.name:void 0;void 0!==c&&(l.title=c),o.flags.hasReferencedOpenAiAnyType&&(a||(a={}),a[o.openAiAnyTypeName]||(a[o.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===o.$refStrategy?"1":[...o.basePath,o.definitionPath,o.openAiAnyTypeName].join("/")}}));let u=void 0===s?a?{...l,[o.definitionPath]:a}:l:{$ref:[..."relative"===o.$refStrategy?[]:o.basePath,o.definitionPath,s].join("/"),[o.definitionPath]:{...a,[s]:l}};return"jsonSchema7"===o.target?u.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===o.target||"openAi"===o.target)&&(u.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===o.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=nn(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)&&a.push(i);let s={type:"object",properties:o};return a.length>0&&(s.required=a),i&&(s.additionalProperties=!1),s},a=async r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{issues:[{message:"Expected an object."}]};let o={},a=[];for(let[t,i]of n){let n=await i["~standard"].validate(r[t]);if(n.issues)for(let r of n.issues)a.push({message:r.message,path:[t,...r.path??[]]});else(t in r||void 0!==n.value)&&(o[t]=n.value)}if(i)for(let i of Object.keys(r))i in t||a.push({message:`Unrecognized key: "${i}"`,path:[i]});return a.length>0?{issues:a}:{value:o}};return{shape:t,"~standard":{version:1,vendor:"xmcp",validate:a,jsonSchema:{input:o("input"),output:o("output")}}}}function m7(t){let r={};return!function t(i,n=""){if(i&&"object"==typeof i)for(let[o,a]of Object.entries(i)){let i=n?`${n}/${o}`:o;!a||"object"!=typeof a||Array.isArray(a)||a instanceof Date||a instanceof RegExp?r[i]=a:t(a,i)}}(t),r}let m8=["ui/resourceUri","resourceUri","visibility"],he=["prefersBorder","domain","csp","permissions","connectDomains","resourceDomains","frameDomains","baseUriDomains"];function ht(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 hr(t){return(t.split("/").pop()||t).replace(/\.[^/.]+$/,"")}function hi(t,r,i){return t.names?.includes(r)===!0||t.tags?.some(t=>i.includes(t))===!0}function hn(t,r){return r?new Map([...t].filter(([t,{metadata:i}])=>{if(i?.enabled===!1)return!1;let n=i?.name??hr(t),o=i?.tags??[];return(!r.include||hi(r.include,n,o))&&(!r.exclude||!hi(r.exclude,n,o))})):t}function ho(t){return Error(`[xmcp] Invalid prompt file: ${t}
   -> Default export must be a prompt handler function.`)}async function ha(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 ho(r);let i=Object.keys(t),n=t.default,o=i.filter(t=>"__esModule"!==t);if(0===i.length||1===o.length&&"default"===o[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 ho(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 hs=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}
   -> ${i}`)});let o=i.length;t.warn(`[xmcp] ${o} prompt${1===o?"":"s"} skipped due to empty files or missing default exports`)}}();function hl(t){return Error(`[xmcp] Invalid resource file: ${t}
   -> Default export must be a resource 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,o=i.filter(t=>"__esModule"!==t);if(0===i.length||1===o.length&&"default"===o[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 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 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 resource file: ${r}
   -> ${i}`)});let o=i.length;t.warn(`[xmcp] ${o} resource${1===o?"":"s"} skipped due to empty files or missing default exports`)}}();function hd(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 hp(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 o=r[i].slice(1,-1),a=r.slice(i+1),s=a[a.length-1];if(s&&s.includes(".")){let t=s.split(".")[0];"index"!==t?a[a.length-1]=t:a.pop()}let l=[],c=[],u=a.map(t=>{if(!t.match(/^\[.+\]$/))return c.push(t),t;{let r=t.slice(1,-1);return l.push(r),`{${r}}`}}),d=`${o}://${u.join("/")}`,p=l.length>0?"template":"direct";return{filePath:t,uriTemplate:d,scheme:o,parameters:l,pathSegments:c,type:p}}function hm(t){return Error(`[xmcp] Invalid tool file: ${t}
   -> Default export must be a tool handler function.`)}async function hh(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 hm(r);let i=Object.keys(t),n=t.default,o=i.filter(t=>"__esModule"!==t);if(0===i.length||1===o.length&&"default"===o[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 hm(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 hf=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}
   -> ${i}`)});let o=i.length;t.warn(`[xmcp] ${o} tool${1===o?"":"s"} skipped due to empty files or missing default exports`)}}(),hg=INJECTED_TOOLS,hy=INJECTED_PROMPTS,hv=INJECTED_RESOURCES,h_=SERVER_INFO;async function hb(t,r,i,n){let o=await INJECTED_MIDDLEWARE?.(),a=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}(o?.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,o)=>{let a,s,l;if("tools/call"!==t.method&&"prompts/get"!==t.method&&"resources/read"!==t.method)return o();try{s=performance.now(),a={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 o()}n({...a,event:{kind:"event",category:["api"],type:["start"],action:"execution.start"}});let c="unknown";try{let r=await o();try{c=t.signal.aborted?"cancelled":c2(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({...a,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:{...a.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&&a.unshift(s.middleware),d1.clear();let l="undefined"==typeof COMPONENTS_CONFIG?void 0:COMPONENTS_CONFIG;return!function(t,r,i){let n=t.server,o=n.setRequestHandler,a=pS(r);n.setRequestHandler=(t,...r)=>{if(pw.has(t)&&1===r.length&&"function"==typeof r[0]){let t=r[0];r[0]=(r,i)=>a({method:r.method,params:r.params??{}},i,()=>t(r,i))}Reflect.apply(o,n,[t,...r])};try{i()}finally{n.setRequestHandler=o}}(t,a,()=>{var o,c;!function(t,r,i=[]){r.forEach((r,n)=>{var o,a;let s,l,c,u,d={name:hr(n),description:"No description provided"},{default:p,metadata:m,schema:h,outputSchema:f}=r;if("object"==typeof m&&null!==m&&Object.assign(d,m),!1===d.enabled)return;if("function"==typeof p&&"__x402"in p){let t=F.g.__XMCP_X402_REGISTRY;t&&t.set(d.name,p.__x402)}let g={};if(ht(h)?g=h:null!=h&&console.warn(`Invalid schema for tool "${d.name}" at ${n}. Expected Record<string, z.ZodType>`),null!=f)if(ht(f))s=f;else throw Error(`Invalid outputSchema for tool "${d.name}" at ${n}. Expected Record<string, z.ZodType>`);d.annotations={...d.annotations??{}},void 0===d.annotations.title&&(d.annotations.title=d.name),d._meta={...d0(d)._meta};let y=pR(n),v=!!(o=d._meta)&&"object"==typeof o&&"ui"in o&&"object"==typeof o.ui||y,_=d._meta;if(v){let t=`ui://app/${d.name}.html`;d._meta.ui||(d._meta.ui={}),d._meta.ui.resourceUri||(d._meta.ui.resourceUri=t);let r=function(t){let r={},i={};if(t.ui&&"object"==typeof t.ui){let n=t.ui,o={},a={};for(let[t,r]of Object.entries(n))m8.includes(t)?o[t]=r:he.includes(t)?a[t]=r:o[t]=r;Object.keys(o).length>0&&(r.ui=o),Object.keys(a).length>0&&(i.ui=a)}for(let[i,n]of Object.entries(t))"ui"!==i&&(r[i]=n);return{toolMeta:r,resourceMeta:i}}(_);_=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"),d1.add(d.name,{name:d.name,uri:t,handler:p,mimeType:"text/html;profile=mcp-app",_meta:i,toolPath:y?n:void 0})}let b=m7(_),S=v?b:void 0;l=pR(n)&&v?async(t,r)=>({content:[{type:"text",text:""}],_meta:S,structuredContent:{args:t}}):function(t,r,i,n="unknown-tool"){return async(o,a)=>{let s,l,c=t(o,(s=pb(a),l=function(t){if(!t)return;let r={};return t.headers.forEach((t,i)=>{r[i]=t}),r}(a.http?.req),{signal:a.mcpReq.signal,authInfo:a.http?.authInfo,sessionId:a.sessionId,_meta:a.mcpReq._meta,requestId:a.mcpReq.id,requestInfo:l?{headers:l}:void 0,clientInfo:s,sendNotification:t=>a.mcpReq.notify(t),sendRequest:(t,r,i)=>a.mcpReq.send(t,r,i),elicit:(t,r)=>pi(a,t,r),sample:(t,r)=>ph(a,t,r),inputResponses:a.mcpReq.inputResponses,requestState:a.mcpReq.requestState}));if(c instanceof Promise&&(c=await c),c2(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 p_(r)?{content:[{type:"text",text:""}],structuredContent:{args:o},_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||(pv(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(p_(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}

Expected CallToolResult format:
{
  content: [
    { type: "text", text: "your text here" },
    { type: "image", data: "base64data", mimeType: "image/jpeg" },
    { type: "audio", data: "base64data", mimeType: "audio/mpeg" },
    { type: "resource_link", name: "resource name", uri: "resource://uri" }
    // All content types support an optional "_meta" object property
  ]
}

Or with structured content:
{
  structuredContent: { your: "data" }
}

Or both for backwards compatibility:
{
  content: [{ type: "text", text: "fallback" }],
  structuredContent: { your: "data" }
}

Or for widget metadata only:
{
  _meta: {
    "ui/...": ...
  }
}`)}let u="content"in c&&Array.isArray(c.content),d="structuredContent"in c,p="isError"in c&&!0===c.isError;if(!u&&!d&&!p){let t=JSON.stringify(c,null,2);throw Error(`Tool handler must return at least 'content' or 'structuredContent'. Got: ${t}

Expected CallToolResult format:
{
  content: [
    { type: "text", text: "your text here" },
    { type: "image", data: "base64data", mimeType: "image/jpeg" },
    { type: "audio", data: "base64data", mimeType: "audio/mpeg" },
    { type: "resource_link", name: "resource name", uri: "resource://uri" }
  ]
}

Or with structured content:
{
  structuredContent: { your: "data" }
}

Or both for backwards compatibility:
{
  content: [{ type: "text", text: "fallback" }],
  structuredContent: { your: "data" }
}`)}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&&pv(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=py(r);if(!i.valid)throw Error(`Invalid content item at index ${t}: ${i.error}

Content item: ${JSON.stringify(r,null,2)}

Expected content formats:
- Text: { type: "text", text: "your text here" }
- Image: { type: "image", data: "base64data", mimeType: "image/jpeg" }
- Audio: { type: "audio", data: "base64data", mimeType: "audio/mpeg" }
- Resource: { type: "resource_link", name: "name", uri: "uri" }
All content types support an optional "_meta" object property`)}if(d){let t=c.structuredContent;if(null===t||"object"!=typeof t||Array.isArray(t)){let r=Array.isArray(t)?"array":typeof t;throw Error(`'structuredContent' must be a plain object (not an array or primitive). Got ${r}: ${JSON.stringify(t,null,2)}

Expected format:
{
  structuredContent: {
    key: "value",
    nested: { data: "here" }
  }
}`)}}return c}}(p,S,s,d.name);let w={title:d.annotations?.title,description:d.description,inputSchema:m6(g),outputSchema:s?m6(s,{strict:!0}):void 0,annotations:d.annotations,icons:d.icons,_meta:b};t.registerTool(d.name,w,(a={name:d.name,description:w.description,annotations:w.annotations,icons:w.icons,tags:d.tags,_meta:w._meta},c=pS(i),u=Object.freeze({metadata:function t(r,i=new WeakMap){if(null===r||"object"!=typeof r)return r;let n=Object.getPrototypeOf(r);if(!Array.isArray(r)&&n!==Object.prototype&&null!==n)return r;if(i.has(r))return i.get(r);let o=Array.isArray(r)?[]:Object.create(n);for(let[n,a]of(i.set(r,o),Object.entries(r)))Object.defineProperty(o,n,{value:t(a,i),enumerable:!0,configurable:!0,writable:!0});return Object.freeze(o)}(a)}),(t,r)=>c({method:"tools/call",params:{name:u.metadata.name,arguments:t},tool:u},r,()=>l(t,r))))})}(t,hn(r,l),a),hn(i,l).forEach((r,i)=>{let n=hr(i),o={name:n,title:n,description:"No description provided"},a={},{default:s,metadata:l,schema:c}=r;if("object"==typeof l&&null!==l&&Object.assign(o,l),!1===o.enabled)return;let u=function(t,r="assistant"){return async(i,n)=>{let o,a=t(i,n);if(a instanceof Promise&&(a=await a),Array.isArray(a)||null!==a&&"object"==typeof a&&"messages"in a){let t=Array.isArray(a)?{messages:a}:a,r=await uT.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 a||"number"==typeof a)o={type:"text",text:"number"==typeof a?`${a}`:a};else{let t=py(a);if(t.valid)o=a;else{let r=null===a?"null":typeof a,i=void 0===a?"undefined":null===a?"null":"object"==typeof a?JSON.stringify(a,null,2):String(a);throw Error(`Prompt handler must return a PromptContent object, string, number, PromptMessage[], or GetPromptResult. Got ${r}: ${i}

Validation error: ${t.error}

Expected formats:
- String: "your text here"
- Number: 42
- Messages: [{ role: "user", content: { type: "text", text: "your text here" } }]
- Prompt result: { description: "optional description", messages: [...] }
- Text content: { type: "text", text: "your text here" }
- Image content: { type: "image", data: "base64data", mimeType: "image/jpeg" }
- Audio content: { type: "audio", data: "base64data", mimeType: "audio/mpeg" }
- Resource link: { type: "resource_link", name: "resource name", uri: "resource://uri" }
- All content types support an optional "_meta" object property`)}}if("user"!==r&&"assistant"!==r)throw Error(`Invalid role: ${r}`);return{messages:[{role:r,content:o}]}}}(s,o.role||"assistant");ht(c)?Object.assign(a,c):null!=c&&console.warn(`Invalid schema for prompt "${o.name}" at ${i}. Expected Record<string, z.ZodType>`),t.registerPrompt(o.name,{title:o.title,description:o.description,icons:o.icons,_meta:d0(o)._meta,argsSchema:m6(a)},u)}),o=hn(n,l),c=s?.registerResource,[...d1.getAll()].forEach(([r,i])=>{let n=i.mimeType||"text/html;profile=mcp-app",o=i?._meta?m7(i._meta):void 0,a={name:i.name,description:`Auto-generated resource for ${i.name} tool`,mimeType:i.mimeType,_meta:o},s=async(t,r)=>{if(i.mimeType&&i.toolPath)try{var o;let t,r,a=(o=i.toolPath,IS_CLOUDFLARE?function(t){let{normalizedPath:r,baseName:i}=hd(t),n=5381;for(let t=0;t<r.length;t++)n=Math.imul(n,33)+r.charCodeAt(t)>>>0;let o=n.toString(16).slice(0,6).padStart(6,"0");return`${i}_${o}`}(o):function(t){let{normalizedPath:r,baseName:i}=hd(t),n=F(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}`}(o)),s=function(t){if(INJECTED_CLIENT_BUNDLES)return INJECTED_CLIENT_BUNDLES[t]||null;if(!IS_CLOUDFLARE)try{let r=F(Object(function(){var t=Error("Cannot find module 'fs'");throw t.code="MODULE_NOT_FOUND",t}())),i=F(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 o=i.join(n,`${t}.bundle.js`),a=i.join(n,`${t}.bundle.css`);if(r.existsSync(o)){let t,i=r.readFileSync(o,"utf-8");return r.existsSync(a)&&(t=r.readFileSync(a,"utf-8")),{js:i,css:t}}}}catch{}return null}(a);if(!s)throw Error(`React client bundle not found for "${i.name}" (bundle: "${a}").
React tool bundles are generated automatically when you run "xmcp build" (or "xmcp dev").
Please re-run the build so the framework can regenerate the bundle.`);let l=s.js,c=s.css,u=(t=`
  <script type="module">
    const componentSource = ${JSON.stringify(l)};
    const blobUrl = URL.createObjectURL(
      new Blob([componentSource], { type: "text/javascript" })
    );

    await import(blobUrl);

    let nextId = 1;

    window.parent.postMessage({
      jsonrpc: "2.0",
      id: nextId++,
      method: ${JSON.stringify("ui/initialize")},
      params: {
        appCapabilities: {
          availableDisplayModes: ["inline", "fullscreen", "pip"]
        },
        appInfo: { name: "xmcp React Widget", version: "1.0.0" },
        protocolVersion: ${JSON.stringify("2026-01-26")}
      }
    }, "*");

    window.addEventListener("message", (event) => {
      const data = event.data;

      if (event.source !== window.parent) return;

      // handshake ack
      if (data?.result?.hostContext && data?.id === 1) {
        window.parent.postMessage({
          jsonrpc: "2.0",
          method: ${JSON.stringify("ui/notifications/initialized")},
          params: {}
        }, "*");
      }
    });

    requestAnimationFrame(() => {
      URL.revokeObjectURL(blobUrl);
    });
  </script>`,r=c?`<style>${c}</style>`:"",`<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  ${r}
</head>
<body>
  <div id="root"></div>
  ${t}
</body>
</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 a=i.handler({},r);if(a instanceof Promise&&(a=await a),"string"==typeof a)return{contents:[{uri:i.uri,text:a,mimeType:n,_meta:i._meta}]};if(a&&"object"==typeof a&&"_meta"in a&&!("content"in a))return{contents:[{uri:i.uri,text:"",mimeType:n,_meta:i._meta}]};if(a&&"object"==typeof a&&"content"in a&&Array.isArray(a.content)){let t=a.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,a,s)}),o.forEach((r,i)=>{let n={name:hr(i),description:"No description provided"},{default:o,metadata:a,schema:s,complete:l}=r;if("object"==typeof a&&null!==a&&Object.assign(n,a),!1===n.enabled)return;let u={};ht(s)?u=s:null!=s&&console.warn(`Invalid schema for resource "${n.name}" at ${i}. Expected Record<string, z.ZodType>`);let d=hp(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=hp(r);if(!n)throw Error(`Invalid resource file path: ${r}. Must follow (scheme)/path/[param] convention.`);return async(r,o)=>{let a=t(function(t,r,i){let n={},o={};if(0===r.parameters.length)return o;let a=r.uriTemplate.split("://")[1]||"",s=t.split("://")[1]||"",l=a.split("/"),c=s.split("/");for(let t=0;t<l.length&&t<c.length;t++){let r=l[t],i=c[t],o=r.match(/^\{(.+)\}$/);o&&(n[o[1]]=i)}for(let t of r.parameters){let r=n[t],a=i[t];if(void 0===r)throw Error(`Missing required parameter: ${t}`);if(!a){o[t]=r;continue}try{o[t]=a.parse(r)}catch(i){throw Error(`Invalid parameter "${t}": ${r}. Validation error: ${i instanceof Error?i.message:String(i)}`)}}return o}(r.href,n,i),o);if(a instanceof Promise&&(a=await a),c2(a))return a;if("string"==typeof a)return{contents:[{uri:r.href,text:a}]};if(!a||"object"!=typeof a||!Array.isArray(a.contents)){let t=null===a?"null":typeof a,r=void 0===a?"undefined":null===a?"null":"object"==typeof a?JSON.stringify(a,null,2):String(a);throw Error(`Resource handler must return a ReadResourceResult, InputRequiredResult, or string. Got ${t}: ${r}

Expected ReadResourceResult format:
{
  contents: [
    { uri: "resource://uri", text: "content here" },
    { uri: "resource://uri", mimeType: "application/json", text: "json content" },
    { uri: "resource://uri", blob: base64data }
  ]
}`)}return a.contents.forEach(t=>{t.uri||(t.uri=r.href)}),a}}(o,i,u);if("direct"===d.type)c?.(n.name,p),t.registerResource(n.name,p,d0(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 dS(p,{list:void 0,complete:r}),a=async(t,r,i)=>{let n={};for(let t of d.parameters){let i=r[t],o=u[t];if(void 0===i)throw Error(`Missing required parameter: ${t}. Available variables: ${Object.keys(r)}`);o?n[t]=o.parse(i):n[t]=i}let a=o(n,i);return a instanceof Promise&&(a=await a),"string"==typeof a?{contents:[{uri:t.href,text:a}]}:a};c?.(n.name,i),t.registerResource(n.name,i,d0(n),a)}})}),t}async function hS(){let{toolModules:t,skippedTools:r}=await hh(hg);return hf(r),t}async function hw(){let{promptModules:t,skippedPrompts:r}=await ha(hy);return hs(r),t}async function hR(){let{resourceModules:t,skippedResources:r}=await hc(hv);return hu(r),t}async function hk(){let{instructions:t,...r}=h_,i=new db(r,{instructions:t}),n=hS(),o=hw(),a=hR(),[s,l,c]=await Promise.all([n,o,a]);return hb(i,s,l,c)}let hx="This MCP server was bootstrapped with xmcp.",hC={cursor:`
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <g clip-path="url(#cursor)">
        <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" />
      </g>
      <defs>
        <clipPath id="cursor">
          <rect width="20" height="20" fill="white" />
        </clipPath>
      </defs>
    </svg>
  `,claude:`
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <g clip-path="url(#claude)">
        <path d="M3.92841 13.2962L7.85957 11.0903L7.92541 10.8981L7.85957 10.7918H7.66732L7.00957 10.7513L4.76324 10.6906L2.81532 10.6097L0.928158 10.5085L0.452574 10.4072L0.00732422 9.82042L0.0528242 9.52692L0.452574 9.25875L1.02424 9.30942L2.28916 9.39542L4.18641 9.52692L5.56257 9.60792L7.60157 9.82042H7.92541L7.97091 9.68883L7.85957 9.60792L7.77357 9.52692L5.81057 8.19633L3.68557 6.78975L2.57257 5.98025L1.97049 5.57042L1.66691 5.18592L1.53541 4.34608L2.08182 3.744L2.81541 3.79458L3.00257 3.84517L3.74632 4.41683L5.33499 5.64633L7.40941 7.17433L7.71299 7.42725L7.83441 7.34125L7.84957 7.28058L7.71291 7.05283L6.58466 5.01392L5.38049 2.9395L4.84424 2.0795L4.70257 1.56333C4.65199 1.35083 4.61657 1.17383 4.61657 0.95625L5.23891 0.11125L5.58282 0L6.41257 0.111333L6.76174 0.414833L7.27774 1.59375L8.11257 3.45058L9.40782 5.97525L9.78724 6.724L9.98966 7.41717L10.0655 7.62967H10.1971V7.50825L10.3033 6.08658L10.5007 4.341L10.6929 2.09458L10.7587 1.46217L11.0723 0.70325L11.6947 0.293417L12.1803 0.526167L12.5801 1.09783L12.5244 1.46725L12.2867 3.01033L11.8212 5.42875L11.5176 7.04783H11.6947L11.8971 6.84542L12.7167 5.75767L14.0928 4.03742L14.7 3.35442L15.4083 2.60058L15.8637 2.24133H16.7237L17.3562 3.18242L17.0729 4.15383L16.1875 5.277L15.4538 6.22817L14.4015 7.64483L13.7437 8.77817L13.8045 8.86925L13.9613 8.854L16.3392 8.34817L17.6243 8.11533L19.1573 7.85225L19.8505 8.17608L19.9263 8.50492L19.6532 9.17783L18.014 9.58258L16.0913 9.96708L13.2277 10.6451L13.1922 10.6704L13.2327 10.721L14.5229 10.8424L15.0744 10.8728H16.4252L18.9398 11.06L19.5975 11.495L19.9922 12.0263L19.9263 12.4311L18.9145 12.9472L17.5484 12.6233L14.3609 11.8644L13.2682 11.5912H13.1163V11.6822L14.0271 12.5728L15.6967 14.0804L17.7862 16.0232L17.8925 16.5039L17.6243 16.8834L17.341 16.8429L15.5044 15.4617L14.7961 14.8393L13.1922 13.4885H13.086V13.6302L13.4553 14.1715L15.4083 17.106L15.5095 18.0066L15.3678 18.3L14.8619 18.4771L14.3053 18.3759L13.1619 16.7721L11.9831 14.9658L11.0319 13.3468L10.9155 13.4127L10.3538 19.4587L10.0908 19.7672L9.48366 20L8.97774 19.6155L8.70957 18.9932L8.97774 17.7638L9.30157 16.1599L9.56466 14.8849L9.80241 13.3012L9.94407 12.7751L9.93399 12.7397L9.81757 12.7548L8.62357 14.3942L6.80724 16.848L5.37032 18.386L5.02632 18.5227L4.42932 18.214L4.48491 17.6625L4.81891 17.1717L6.80724 14.642L8.00632 13.0737L8.78049 12.168L8.77532 12.0364H8.72982L3.44774 15.4668L2.50666 15.5882L2.10191 15.2087L2.15257 14.5864L2.34482 14.384L3.93349 13.2912L3.92841 13.2962Z" fill="currentColor" />
      </g>
      <defs>
        <clipPath id="claude">
          <rect width="20" height="20" fill="white" />
        </clipPath>
      </defs>
    </svg>
  `,windsurf:`
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <g clip-path="url(#windsurf)">
        <path d="M19.625 4.2225C18.6218 4.22084 17.8078 5.03334 17.8078 6.03625V10.0926C17.8078 10.9026 17.1382 11.5588 16.3414 11.5588C15.8681 11.5588 15.3954 11.3204 15.1149 10.9205L10.9722 5.00359C10.6284 4.51225 10.0691 4.21942 9.46358 4.21942C8.51908 4.21942 7.66917 5.02234 7.66917 6.01359V10.0933C7.66917 10.9033 7.00508 11.5595 6.20283 11.5595C5.72783 11.5595 5.25592 11.3212 4.9755 10.9213L0.339667 4.29984C0.235167 4.14984 0 4.224 0 4.40684V7.9445C0 8.12342 0.0546667 8.29684 0.157 8.44367L4.71933 14.9589C4.98883 15.3439 5.3865 15.6299 5.84508 15.7338C6.99267 15.9946 8.04892 15.1113 8.04892 13.9857V9.90817C8.04892 9.09817 8.70517 8.44209 9.51525 8.44209H9.51775C9.75841 8.44214 9.99552 8.50016 10.209 8.61125C10.4225 8.72233 10.6061 8.8832 10.7442 9.08025L14.8878 14.9964C15.2324 15.4885 15.7628 15.7806 16.3956 15.7806C17.3612 15.7806 18.1885 14.9768 18.1885 13.9864V9.90742C18.1885 9.09742 18.8447 8.44125 19.6548 8.44125H19.8165C19.8406 8.4413 19.8645 8.43658 19.8868 8.42738C19.9091 8.41817 19.9293 8.40466 19.9464 8.38762C19.9635 8.37057 19.977 8.35033 19.9862 8.32804C19.9955 8.30576 20.0002 8.28187 20.0002 8.25775V4.40609C20.0002 4.38197 19.9955 4.35808 19.9863 4.33579C19.977 4.31351 19.9635 4.29326 19.9465 4.2762C19.9294 4.25915 19.9092 4.24563 19.8869 4.23641C19.8646 4.2272 19.8407 4.22247 19.8166 4.2225H19.625Z" fill="currentColor" />
      </g>
      <defs>
        <clipPath id="windsurf">
          <rect width="20" height="20" fill="white" />
        </clipPath>
      </defs>
    </svg>
  `,gemini:`
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <g clip-path="url(#gemini)">
        <path d="M20 10.0195C14.6289 10.3477 10.3477 14.6289 10.0195 20H9.98047C9.65234 14.6289 5.37109 10.3477 0 10.0195V9.98047C5.37109 9.65234 9.65234 5.37109 9.98047 0H10.0195C10.3477 5.37109 14.6289 9.65234 20 9.98047V10.0195Z" fill="currentColor" />
      </g>
      <defs>
        <clipPath id="gemini">
          <rect width="20" height="20" fill="white" />
        </clipPath>
      </defs>
    </svg>
  `,codex:`
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <g clip-path="url(#codex)">
        <path d="M18.5681 8.18423C18.7917 7.51079 18.8691 6.79739 18.795 6.09168C18.7209 5.38596 18.497 4.70419 18.1384 4.0919C17.6067 3.16642 16.7948 2.43369 15.8199 1.99936C14.8449 1.56503 13.7572 1.45153 12.7135 1.67523C12.1206 1.0157 11.3646 0.523789 10.5214 0.248906C9.67823 -0.0259764 8.77756 -0.0741542 7.90986 0.109212C7.04216 0.292578 6.23798 0.701031 5.57809 1.29355C4.91821 1.88607 4.42584 2.64179 4.15046 3.48481C3.45518 3.62739 2.79834 3.91672 2.22384 4.33347C1.64933 4.75023 1.1704 5.28481 0.81904 5.90148C0.281569 6.82542 0.0518576 7.89634 0.163116 8.95943C0.274374 10.0225 0.720837 11.0227 1.43796 11.8153C1.21351 12.4884 1.13539 13.2017 1.20883 13.9074C1.28227 14.6132 1.50557 15.2951 1.86379 15.9076C2.39616 16.8334 3.20872 17.5663 4.18438 18.0006C5.16004 18.4349 6.2484 18.5483 7.29262 18.3243C7.76367 18.8548 8.34248 19.2786 8.99038 19.5676C9.63828 19.8566 10.3404 20.004 11.0498 20C12.1195 20.001 13.1618 19.662 14.0263 19.0321C14.8909 18.4021 15.5329 17.5137 15.8596 16.4951C16.5548 16.3523 17.2116 16.0629 17.786 15.6461C18.3605 15.2294 18.8395 14.6949 19.191 14.0784C19.7222 13.1558 19.9479 12.0889 19.836 11.0303C19.7242 9.97163 19.2804 8.9754 18.5681 8.18423ZM11.0498 18.691C10.1737 18.6924 9.32512 18.3853 8.65279 17.8236L8.77104 17.7566L12.753 15.4581C12.8521 15.4 12.9343 15.3171 12.9917 15.2176C13.0491 15.118 13.0796 15.0053 13.0802 14.8904V9.27631L14.7635 10.2501C14.7719 10.2544 14.7791 10.2605 14.7846 10.268C14.7901 10.2755 14.7937 10.2843 14.7952 10.2935V14.9456C14.7931 15.9383 14.3978 16.8898 13.6959 17.5917C12.9939 18.2936 12.0425 18.6889 11.0498 18.691ZM2.99921 15.2531C2.55985 14.4945 2.4021 13.6052 2.55371 12.7417L2.67204 12.8127L6.65787 15.1112C6.7565 15.1691 6.86877 15.1996 6.98312 15.1996C7.09747 15.1996 7.20975 15.1691 7.30837 15.1112L12.1774 12.3041V14.2478C12.1769 14.2579 12.1742 14.2677 12.1694 14.2766C12.1646 14.2855 12.1579 14.2932 12.1497 14.2991L8.11654 16.6251C7.25581 17.121 6.2335 17.255 5.27405 16.9978C4.3146 16.7405 3.49644 16.1131 2.99921 15.2531ZM1.95054 6.57965C2.39294 5.81612 3.09123 5.23375 3.92179 4.93565V9.66665C3.92029 9.78094 3.94949 9.89355 4.00635 9.99271C4.06321 10.0919 4.14564 10.174 4.24504 10.2304L9.09037 13.0256L7.40696 13.9994C7.39785 14.0042 7.38769 14.0068 7.37737 14.0068C7.36706 14.0068 7.3569 14.0042 7.34779 13.9994L3.32254 11.6773C2.46343 11.1793 1.83666 10.3612 1.57951 9.40204C1.32236 8.44291 1.45577 7.42095 1.95054 6.55998V6.57965ZM15.7808 9.79281L10.9197 6.96998L12.5992 5.99998C12.6083 5.99514 12.6185 5.99261 12.6288 5.99261C12.6391 5.99261 12.6493 5.99514 12.6584 5.99998L16.6836 8.32606C17.2991 8.68119 17.8008 9.20407 18.1303 9.83365C18.4597 10.4632 18.6032 11.1735 18.5441 11.8816C18.485 12.5898 18.2257 13.2664 17.7964 13.8327C17.3672 14.3989 16.7857 14.8314 16.1199 15.0796V10.3486C16.1164 10.2345 16.0833 10.1232 16.0238 10.0258C15.9644 9.92833 15.8807 9.8481 15.7808 9.79281ZM17.4564 7.27356L17.338 7.20256L13.3601 4.8844C13.2609 4.82617 13.1479 4.79547 13.0329 4.79547C12.9178 4.79547 12.8049 4.82617 12.7056 4.8844L7.84071 7.6914V5.74781C7.83967 5.73793 7.84132 5.72795 7.84549 5.71893C7.84965 5.70991 7.85618 5.70218 7.86437 5.69656L11.8896 3.3744C12.5065 3.01899 13.2119 2.84659 13.9232 2.87736C14.6345 2.90813 15.3224 3.14079 15.9063 3.54813C16.4903 3.95548 16.9461 4.52066 17.2206 5.17759C17.4952 5.83452 17.577 6.55602 17.4565 7.25773L17.4564 7.27356ZM6.92196 10.7191L5.23862 9.74931C5.2302 9.74424 5.223 9.73738 5.21753 9.72921C5.21205 9.72105 5.20845 9.71178 5.20696 9.70206V5.06181C5.20788 4.34996 5.41144 3.65308 5.79383 3.05265C6.17622 2.45222 6.72164 1.97305 7.36632 1.67118C8.011 1.3693 8.7283 1.2572 9.43434 1.34796C10.1404 1.43873 10.806 1.72861 11.3534 2.18373L11.235 2.25081L7.25321 4.54915C7.1541 4.60727 7.07182 4.69017 7.01445 4.78971C6.95707 4.88925 6.92658 5.00201 6.92596 5.1169L6.92196 10.7191ZM7.83662 8.74798L10.005 7.49815L12.1774 8.74798V11.2475L10.0129 12.4972L7.84062 11.2475L7.83662 8.74798Z" fill="currentColor" />
      </g>
      <defs>
        <clipPath id="codex">
          <rect width="20" height="20" fill="white" />
        </clipPath>
      </defs>
    </svg>
  `},h$=String.raw`
  :root {
    color-scheme: dark;
    --brand-white: #f7f7f7;
    --brand-neutral-50: #dbdbdb;
    --brand-neutral-100: #a8a8a8;
    --brand-neutral-200: #757575;
    --brand-neutral-300: #595959;
    --brand-neutral-400: #424242;
    --brand-neutral-500: #262626;
    --brand-neutral-600: #171717;
    --brand-black: #000000;
  }

  *,
  *::before,
  *::after {
    box-sizing: border-box;
  }

  body {
    margin: 0;
    min-height: 100vh;
    background: #050505;
    color: var(--brand-white);
    font-family: "Geist Sans", "Inter", "SF Pro Display", "Segoe UI", -apple-system, BlinkMacSystemFont, sans-serif;
    -webkit-font-smoothing: antialiased;
  }

  a {
    color: inherit;
    text-decoration: none;
  }

  main {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 1.5rem;
    display: grid;
    grid-template-columns: repeat(12, minmax(0, 1fr));
    gap: 20px;
  }

  .section {
    grid-column: 1 / -1;
    padding: 2rem 0;
    display: grid;
    grid-template-columns: repeat(12, minmax(0, 1fr));
    gap: 20px;
  }

  .section-content {
    grid-column: 1 / -1;
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
  }

  @media (min-width: 1024px) {
    .section-content {
      grid-column: 2 / span 9;
    }
  }

  .section-header {
    display: grid;
    grid-template-columns: repeat(12, minmax(0, 1fr));
    gap: 1rem;
    width: 100%;
  }

  .display {
    grid-column: span 12;
    font-size: clamp(2rem, 3.5vw, 3rem);
    line-height: 1.1;
    letter-spacing: -0.05em;
    font-weight: 500;
    margin: 0;
  }

  .heading-2 {
    grid-column: span 12;
    font-size: clamp(1.75rem, 3vw, 2.5rem);
    line-height: 1.2;
    letter-spacing: -0.03em;
    font-weight: 500;
    margin: 0;
  }

  .text-gradient {
    background: linear-gradient(
      270deg,
      rgba(247, 247, 247, 0.8) 0%,
      #f7f7f7 50%,
      rgba(247, 247, 247, 0.8) 100%
    );
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
  }

  .lead {
    grid-column: span 12;
    font-size: 1.125rem;
    color: var(--brand-white);
    max-width: 650px;
    margin: 0;
    line-height: 1.6;
  }

  .body-text {
    grid-column: span 12;
    color: var(--brand-neutral-100);
    font-size: 1rem;
    line-height: 1.7;
    margin: 0;
    max-width: 650px;
  }

  .connection-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 12px;
    width: 100%;
    margin-top: 1rem;
  }

  .connection-card {
    position: relative;
    display: flex;
    align-items: center;
    gap: 1rem;
    min-height: 60px;
    border: 1px solid var(--brand-neutral-600);
    background: rgba(5, 5, 5, 0.85);
    padding: 1.25rem 1.5rem;
    border-radius: 2px;
    color: var(--brand-white);
    font-size: 1rem;
    font-weight: 500;
    overflow: hidden;
    cursor: pointer;
    transition: border-color 0.2s ease, background 0.2s ease;
  }

  .connection-card:hover,
  .connection-card:focus-visible {
    border-color: var(--brand-neutral-400);
    background: rgba(15, 15, 15, 0.85);
  }

  .connection-card:focus-visible {
    outline: 2px solid var(--brand-white);
    outline-offset: 3px;
  }

  .icon-badge {
    width: 48px;
    height: 48px;
    border: 1px dashed var(--brand-neutral-400);
    border-radius: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--brand-neutral-600);
    flex-shrink: 0;
  }

  .icon-badge svg {
    width: 24px;
    height: 24px;
    color: var(--brand-white);
  }

  .background-icon {
    position: absolute;
    inset: 0;
    pointer-events: none;
    color: var(--brand-neutral-600);
  }

  .background-icon svg {
    position: absolute;
    width: 120px;
    height: auto;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
    color: currentColor;
  }

  .card-label {
    position: relative;
    z-index: 2;
    color: var(--brand-white);
  }

  .code-block {
    position: relative;
    width: 100%;
    margin-top: 1.25rem;
  }

  .code-block pre {
    margin: 0;
    border-radius: 0;
    border: 1px solid var(--brand-neutral-500);
    background: rgba(8, 8, 8, 0.9);
    padding: 1.5rem;
    overflow-x: auto;
  }

  .code-block code {
    font-family: "Geist Mono", "SFMono-Regular", "Consolas", monospace;
    color: var(--brand-white);
    font-size: 0.85rem;
    line-height: 1.6;
    display: block;
    white-space: pre;
  }

  .copy-snippet-btn {
    position: absolute;
    top: 14px;
    right: 14px;
    width: 32px;
    height: 32px;
    display: grid;
    place-items: center;
    border: none;
    background: rgba(0, 0, 0, 0.8);
    color: var(--brand-neutral-50);
    border-radius: 0;
    cursor: pointer;
    transition: color 0.2s ease, background 0.2s ease;
    z-index: 10;
  }

  .copy-snippet-btn:hover,
  .copy-snippet-btn:focus-visible {
    color: var(--brand-white);
    background: rgba(0, 0, 0, 0.95);
    outline: none;
  }

  .copy-snippet-btn svg {
    width: 16px;
    height: 16px;
    transition: opacity 0.2s ease, transform 0.2s ease;
  }

  .copy-snippet-btn svg.hidden {
    opacity: 0;
    transform: scale(0.8);
  }

  .copy-snippet-btn svg.visible {
    opacity: 1;
    transform: scale(1);
  }

  .card-inner {
    display: flex;
    align-items: center;
    gap: 1rem;
    width: 100%;
  }

  .toast {
    position: fixed;
    bottom: 24px;
    right: 24px;
    background: rgba(8, 8, 8, 0.95);
    border: 1px solid var(--brand-neutral-500);
    border-radius: 0;
    padding: 0.75rem 1.25rem;
    font-size: 0.9rem;
    color: var(--brand-white);
    opacity: 0;
    transform: translateY(12px) scale(0.98);
    transition: opacity 0.3s ease, transform 0.3s ease;
    pointer-events: none;
  }

  .toast.show {
    opacity: 1;
    transform: translateY(0) scale(1);
  }

  .sr-only {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    border: 0;
  }
`;function hT(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 hP=HTTP_CORS_CONFIG;function hE(t,r){let i=new Headers(t.headers);for(let[t,n]of Object.entries(hT(hP,r)))i.set(t,n);return new Response(t.body,{status:t.status,statusText:t.statusText,headers:i})}let hO=HTTP_CONFIG,hI=TEMPLATE_CONFIG,hq=INJECTED_MIDDLEWARE,hj=null;async function hA(){return hq?(hj||(hj=(async()=>{try{var t;let r=await hq();return t=r?.default,Array.isArray(t)?t.filter(hL):hL(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),[]}})()),hj):[]}function hL(t){return"function"==typeof t}async function hN(t){let r=await hA();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 hz(t,...r){hO.debug&&console.log(`[Cloudflare-MCP] ${t}`,...r)}uV();let hM=function(t,r={}){var i;let{legacy:n,onerror:o,responseMode:a}=r,s=dq(r.maxRequestBodySize);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 p=new Set,m=!1,h=t=>{try{o?.(t)}catch{}},f=r.bus??new ds(h),g={toolsChanged:()=>f.publish({kind:"tools_list_changed"}),promptsChanged:()=>f.publish({kind:"prompts_list_changed"}),resourcesChanged:()=>f.publish({kind:"resources_list_changed"}),resourceUpdated:t=>f.publish({kind:"resource_updated",uri:t})},y=function(t){let{bus:r,onerror:i}=t,n=t.maxSubscriptions??1024,o=t.keepAliveMs??15e3,a=new Set;return{serve:function(t,s,l,c){var u,d,p;let m,h,f,g,y,v,_;if(a.size>=n)return i?.(Error(`subscriptions/listen refused: subscription limit reached (${n})`)),dl(t.id,-32603,"Subscription limit reached");let b=(u=t,(y=cZ(cM).validateRequest("subscriptions/listen",u)).ok?y.value.params?.notifications:void 0);if(void 0===b)return dl(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,R=new TextEncoder,k=!1,x=t=>{if(!k)try{m.enqueue(R.encode(t))}catch(t){i?.(t instanceof Error?t:Error(String(t)))}},C=(t,r)=>{x(`event: message
data: ${JSON.stringify({jsonrpc:"2.0",method:t,params:r})}

`)},$=t=>{if(!k){t&&x(`event: message
data: ${JSON.stringify({jsonrpc:"2.0",id:w,result:{resultType:"complete",_meta:{[oQ]:w,[oY]:c}}})}

`),k=!0;try{h?.()}catch(t){i?.(t instanceof Error?t:Error(String(t)))}void 0!==f&&clearInterval(f),g?.(),a.delete($);try{m.close()}catch{}}},T=new ReadableStream({start(t){m=t;let i=dc({method:"notifications/subscriptions/acknowledged",params:{notifications:S}},w);(C(i.method,i.params),0===Object.keys(S).length)?$(!0):(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=dc(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);C(r.method,r.params)}),f=da(o,()=>x(": keepalive\n\n")),a.add($))},cancel(){$(!1)}});if(void 0!==s)if(s.aborted)$(!1);else{let t=()=>$(!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 a)t(!0)},get openCount(){return a.size}}}({bus:f,maxSubscriptions:r.maxSubscriptions??1024,keepAliveMs:r.keepAliveMs??15e3,onerror:h});"json"===a&&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 v="reject"===n?void 0:(i=r.keepAliveMs,async(r,n)=>{if("POST"!==r.method.toUpperCase())return dN(405,-32e3,"Method not allowed.");try{let o=await t({era:"legacy",...n?.authInfo!==void 0&&{authInfo:n.authInfo},requestInfo:r}),a=new dA({sessionIdGenerator:void 0,...void 0!==i&&{keepAliveMs:i},...void 0!==s&&{maxRequestBodySize:s}});await o.connect(a);let l=()=>{a.close().catch(()=>{}),o.close().catch(()=>{})};r.signal?.addEventListener("abort",l,{once:!0});let c=await a.handleRequest(r,{...n?.authInfo!==void 0&&{authInfo:n.authInfo},...n?.parsedBody!==void 0&&{parsedBody:n.parsedBody}});if(null===c.body||"text/event-stream"!==uM(c.headers.get("content-type")))return l(),c;let u=c.body.getReader(),d=!1,p=()=>{d||(d=!0,l())},m=new ReadableStream({pull:async t=>{try{let{done:r,value:i}=await u.read();if(r){p(),t.close();return}void 0!==i&&t.enqueue(i)}catch(r){p(),t.error(r)}},cancel:t=>(p(),u.cancel(t).catch(()=>{}))});return new Response(m,{status:c.status,statusText:c.statusText,headers:c.headers})}catch(t){try{h?.(dM(t))}catch{}return dZ(dL(n?.parsedBody))}});async function _(i,n,o){var s,m;let f=i.classification.revision;if(void 0===f||!l0.includes(f)){let t=new cw({supported:[...l0],requested:f??"unknown"});return h(t),dN(400,t.code,t.message,t.data,dL(i.message))}let g=function(t,r){if("request"!==r.messageKind)return;let i=r.message.method;if(void 0===t.protocolVersionHeader){let t=r.classification.revision;return us("version-header-missing","(missing)",void 0===t?"the body carries a modern per-request envelope but the required MCP-Protocol-Version header is absent":`the body envelope names protocol version ${t} but the required MCP-Protocol-Version header is absent`,"standard-header-validation")}if(void 0===t.mcpMethodHeader)return us("method-header-missing","(missing)",`the body names method ${i} but the required Mcp-Method header is absent`,"standard-header-validation");let n=function(t,r){let i=Object.hasOwn(ul,t)?ul[t]:void 0;if(void 0===i)return;let n=uu(r)?r[i]:void 0;return{field:i,value:"string"==typeof n?n:void 0}}(i,r.message.params);if(void 0===n)return;let{field:o,value:a}=n;if(void 0===t.mcpNameHeader){if(void 0===a)return;return us("name-header-missing","(missing)",`the body carries params.${o}="${a}" but the required Mcp-Name header is absent`,"standard-header-validation")}let s=uc(t.mcpNameHeader),l=ur(s);return void 0===l?us("name-header-invalid-encoding",s,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==a&&l!==a?us("name-header-mismatch",s,`the body carries params.${o}="${a}" but the Mcp-Name header names "${l}"`,"standard-header-validation"):void 0}({httpMethod:n.method,...dF(n)},i);if(void 0!==g)return h(Error(`Rejected inbound request (${g.cell}): ${g.message}`)),dz(g,dL(i.message));let v="request"===i.messageKind?cB(i.message.params):void 0,_=v?.[oX];if("request"===i.messageKind){let t=Object.hasOwn(lK,s=i.message.method)?lK[s]:void 0;if(void 0!==t){let r=lX(t,_);if(void 0!==r){let t=new cR({requiredCapabilities:r});return h(t),dN(uo[t.code]??400,t.code,t.message,t.data,i.message.id)}}}let b=await t({era:"modern",...void 0!==o&&{authInfo:o},requestInfo:n}),S=b instanceof db?b.server:b;if(dU(S),"request"===i.messageKind&&"subscriptions/listen"===i.message.method){let t=S.getCapabilities(),r=d(S);return b.close().catch(h),y.serve(i.message,n.signal,t,r)}if("request"===i.messageKind&&"tools/call"===i.message.method&&b instanceof db){let t=i.message.params,r="string"==typeof t?.name?t.name:void 0,o=void 0===r?void 0:b.toolInputSchemaJson(r);if(void 0!==o){let r=c3(o);if(r.valid&&r.declarations.length>0){let o=function(t,r,i){for(let n of t){let t=`Mcp-Param-${n.headerName}`,o=i.get(t),a=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==a)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)}}(a);if(void 0===s)continue;if(null===o)return ui("param-header-missing",t,`the body carries ${c8(n.path)}=${JSON.stringify(a)} but the ${t} header is absent`);let l=ur(o);if(void 0===l)return ui("param-header-invalid-encoding",t,`the ${t} header carries an invalid Base64 sentinel value`);if(!(("integer"===n.type||"number"===n.type)&&ut.test(l)&&"number"==typeof a?Number(l)===a:l===s))return ui("param-header-mismatch",t,`the ${t} header decodes to ${JSON.stringify(l)} but the body carries ${c8(n.path)}=${JSON.stringify(a)}`)}}(r.declarations,t?.arguments,n.headers);if(void 0!==o)return b.close().catch(h),h(Error(`Rejected inbound request (${o.cell}): ${o.message}`)),dz(o,i.message.id)}}}if("request"===i.messageKind&&b instanceof db)try{let t=await dp([i.message],o,t=>b.resolveScopeChallenge(t));if(void 0!==t)return b.close().catch(h),dh(t,dm(o))}catch(t){return b.close().catch(h),h(dM(t)),dZ(i.message.id)}dU(S),l(S,f),u(S,l0),void 0!==v&&(m={clientInfo:v[oK],clientCapabilities:_},c(S,m));let w=S.onclose;p.add(S);let R=()=>{p.delete(S),S.onclose===R&&(S.onclose=w),w?.()};S.onclose=R;try{let t=await dO(b,i.message,{classification:i.classification,request:n,...void 0!==o&&{authInfo:o},...void 0!==a&&{responseMode:a},...void 0!==r.keepAliveMs&&{keepAliveMs:r.keepAliveMs}});return"notification"===i.messageKind&&queueMicrotask(()=>void S.close().catch(()=>{})),t}catch(t){if(t instanceof lG&&t.code===lW.ConnectionClosed)return new Response(null,{status:499});return await S.close().catch(()=>{}),p.delete(S),h(dM(t)),dZ(dL(i.message))}}async function b(t,r,i,n){if(void 0!==v)return v(r,{...void 0!==i&&{authInfo:i},...void 0!==n&&{parsedBody:n}});let o=function(t,r){switch(t.reason){case"http-method":return ua("http-method","modern-only-method-not-allowed",405,new c_(-32e3,"Method not allowed."),!0);case"batch":return ua("jsonrpc-shape","modern-only-batch-not-supported",400,new c_(cv.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return ua("jsonrpc-shape","modern-only-response-post",400,new c_(cv.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 ua("era-classification","modern-only-missing-envelope",400,void 0===i?new c_(cv.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...r]}):new cw({supported:[...r],requested:i}),!0)}}}(t,l0);return void 0===o?new Response(null,{status:202}):(h(Error(`Rejected 2025-era request on a modern-only endpoint (${o.cell}): ${o.message}`)),dz(o,dL(n)))}async function S(t,r){let i=r?.authInfo;if("POST"===t.method.toUpperCase()&&!uZ(t.headers.get("content-type")))return h(Error("Unsupported Media Type: Content-Type must be application/json")),dN(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let n=await dH(t,r?.parsedBody,!0,s);if("unreadable-body"===n.step)return dN(400,-32700,"Parse error: the request body could not be read");if("body-too-large"===n.step)return dN(413,-32e3,dI(s));if("no-json-body"===n.step)return void 0!==v?v(n.forwardRequest,{...void 0!==i&&{authInfo:i}}):dN(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:o,body:a,parsedBody:l,forwardRequest:c}=n;try{switch(o.kind){case"reject":return h(Error(`Rejected inbound request (${o.cell}): ${o.message}`)),dz(o,dL(a));case"modern":return await _(o,t,i);case"legacy":return await b(o,c,i,l)}}catch(t){return h(dM(t)),dZ(dL(a))}}return{fetch:async(t,r)=>{if(m)throw Error("This MCP handler has been closed");try{return await S(t,r)}catch(t){return h(dM(t)),dZ(dL(r?.parsedBody))}},notify:g,bus:f,close:async()=>{m=!0,y.closeAll();let t=[...p].map(t=>t.close().catch(()=>{}));p.clear(),await Promise.all(t)}}}(hk,{legacy:"stateless",responseMode:"json",maxSubscriptions:hO.maxSubscriptions,onerror:t=>hz("MCP handler error:",t)});async function hZ(t,r,i,n){let o=crypto.randomUUID(),a=await t.clone().json().catch(()=>void 0),s=(t=>{for(let r of Array.isArray(t)?t:[t]){let t=dX(r);if(t)return t}})(a),l={};return t.headers.forEach((t,r)=>{l[r]=t}),dG({id:o,headers:l,clientInfo:s},async()=>{try{let i=await hM.fetch(t,{authInfo:n,parsedBody:a});return hE(i,r)}catch(t){return console.error("[Cloudflare-MCP] Error handling MCP request:",t),hE(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 hU={async fetch(t,r,i){let n=new URL(t.url).pathname,o=t.headers.get("origin");if(hz(`${t.method} ${n}`),"OPTIONS"===t.method)return new Response(null,{status:204,headers:new Headers(hT(hP,o))});let a=hO.endpoint?.startsWith("/")?hO.endpoint:`/${hO.endpoint||"mcp"}`;if("/health"===n)return hE(new Response(JSON.stringify({status:"ok",transport:"cloudflare-workers",mode:"stateless",auth:"none"}),{status:200,headers:{"Content-Type":"application/json"}}),o);if("/"===n&&"GET"===t.method){var s,l;return hE(new Response((s=hI.name,l=hI.description,`
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>${s||"xmcp server"}</title>
    <link
      rel="preconnect"
      href="https://fonts.googleapis.com"
    />
    <link
      rel="preconnect"
      href="https://fonts.gstatic.com"
      crossorigin
    />
    <link
      href="https://fonts.googleapis.com/css2?family=Geist+Sans:wght@400;500;600&family=Geist+Mono:wght@400;500&display=swap"
      rel="stylesheet"
    />
    <style>
${h$}
    </style>
  </head>
  <body>
    <main class="template-layout">
      <section class="section">
        <div class="section-content">
          <div class="section-header">
            <h2 id="server-name" class="display text-gradient">xmcp server</h2>
            <p id="server-description" class="lead">
              ${l||hx}
            </p>
          </div>
        </div>
      </section>

      <section class="section">
        <div class="section-content">
          <div class="section-header">
            <h2 class="heading-2 text-gradient">Connect to a client</h2>
            <p class="body-text">
              Select your preferred way to connect to your MCP server.
            </p>
          </div>
          <div id="connection-grid" class="connection-grid" aria-live="polite"></div>
        </div>
      </section>

      <section class="section">
        <div class="section-content">
          <div class="section-header">
            <h2 class="heading-2 text-gradient">Standard connection</h2>
            <p class="body-text">
              For clients not listed above, you can use the following connection method.
            </p>
          </div>
          <div class="code-block">
            <button
              type="button"
              class="copy-snippet-btn"
              id="copy-remote-snippet"
              aria-label="Copy standard connection method"
            >
              <span class="sr-only">Copy standard connection method</span>
              <svg
                id="copy-icon"
                class="visible"
                width="16"
                height="16"
                viewBox="0 0 16 16"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
                aria-hidden="true"
              >
                <rect
                  x="5.25"
                  y="3"
                  width="7.5"
                  height="9.5"
                  rx="1"
                  stroke="currentColor"
                  stroke-width="1.25"
                />
                <path
                  d="M3.25 10.75V2.75H9.75"
                  stroke="currentColor"
                  stroke-width="1.25"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                />
              </svg>
              <svg
                id="check-icon"
                class="hidden"
                width="16"
                height="16"
                viewBox="0 0 16 16"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
                aria-hidden="true"
                style="position: absolute;"
              >
                <path
                  d="M13.5 4L6 11.5L2.5 8"
                  stroke="currentColor"
                  stroke-width="1.5"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                />
        </svg>
            </button>
            <pre><code id="remote-snippet"></code></pre>
          </div>
    </div>
      </section>
    </main>
    <div id="toast" class="toast" role="status" aria-live="polite"></div>
    <script>
${`
  (() => {
    const templateConfig = ${JSON.stringify({endpoint:a,serverName:s??null,serverDescription:l??null})};

    const elements = {
      name: document.getElementById("server-name"),
      description: document.getElementById("server-description"),
      grid: document.getElementById("connection-grid"),
      remoteSnippet: document.getElementById("remote-snippet"),
      copyRemoteButton: document.getElementById("copy-remote-snippet"),
      copyIcon: document.getElementById("copy-icon"),
      checkIcon: document.getElementById("check-icon"),
      toast: document.getElementById("toast"),
    };

    const resolvedName =
      (templateConfig.serverName && templateConfig.serverName.trim()) || "xmcp server";
    const resolvedDescription =
      (templateConfig.serverDescription && templateConfig.serverDescription.trim()) ||
      "${hx}";
    const endpointPath =
      (templateConfig.endpoint && templateConfig.endpoint.trim()) || "/";
    const normalizedEndpoint = endpointPath.startsWith("/")
      ? endpointPath
      : \`/\${endpointPath}\`;
    const origin = window.location.origin.replace(/\\/$/, "");
    const serverUrl = origin + normalizedEndpoint;
    const identifier =
      resolvedName
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, "-")
        .replace(/(^-|-$)/g, "") || "xmcp-server";

    if (elements.name) {
      elements.name.textContent = resolvedName;
    }

    if (elements.description) {
      elements.description.textContent = resolvedDescription;
    }

    const icons = ${JSON.stringify(hC)};

    const connectionOptions = [
      {
        label: "Cursor",
        type: "copy",
        snippet: \`{
    "\${identifier}": {
      "url": "\${serverUrl}"
    }
  }\`,
        description: "Copy Cursor connection config",
        icon: "cursor",
      },
      {
        label: "Claude Code",
        type: "copy",
        snippet: \`claude mcp add --transport http "\${identifier}" \\\\\\n    "\${serverUrl}"\`,
        description: "Copy CLI snippet for Claude Code",
        icon: "claude",
      },
      {
        label: "Claude Desktop",
        type: "copy",
        snippet: \`{
    "\${identifier}": {
      "command": "npx",
      "args": ["-y", "mcp-remote", "\${serverUrl}"]
    }
  }\`,
        description: "Copy Claude Desktop setup command",
        icon: "claude",
      },
      {
        label: "Windsurf",
        type: "copy",
        snippet: \`"\${identifier}": {
  "command": "npx",
  "args": [
    "mcp-remote",
    "\${serverUrl}"
  ]
}\`,
        description: "Copy Windsurf attach command",
        icon: "windsurf",
      },
      {
        label: "Gemini CLI",
        type: "copy",
        snippet: \`gemini mcp add --transport http "\${identifier}" "\${serverUrl}"\`,
        description: "Copy Gemini CLI link command",
        icon: "gemini",
      },
      {
        label: "Codex",
        type: "copy",
        snippet: \`[mcp_servers.\${identifier}]
command = "npx"
args = ["-y", "mcp-remote", "\${serverUrl}"]\`,
        description: "Copy Codex connect command",
        icon: "codex",
      },
    ];

    if (elements.remoteSnippet) {
      const remoteSnippet = JSON.stringify(
        {
          command: "npx",
          args: ["mcp-remote", serverUrl],
        },
        null,
        2
      );
      elements.remoteSnippet.textContent = remoteSnippet;
    }

    if (elements.copyRemoteButton) {
      elements.copyRemoteButton.addEventListener("click", () => {
        const snippet = elements.remoteSnippet?.textContent || "";
        copyText(snippet)
          .then((success) => {
            if (success) {
              // Animate icon change
              if (elements.copyIcon && elements.checkIcon) {
                elements.copyIcon.classList.remove("visible");
                elements.copyIcon.classList.add("hidden");
                elements.checkIcon.classList.remove("hidden");
                elements.checkIcon.classList.add("visible");

                // Reset after 2 seconds
                setTimeout(() => {
                  elements.copyIcon?.classList.remove("hidden");
                  elements.copyIcon?.classList.add("visible");
                  elements.checkIcon?.classList.remove("visible");
                  elements.checkIcon?.classList.add("hidden");
                }, 2000);
              }
            } else {
              showToast("Unable to copy. Please copy manually.");
            }
          })
          .catch(() => {
            showToast("Unable to copy. Please copy manually.");
          });
      });
    }

    if (elements.grid) {
      elements.grid.innerHTML = "";
      connectionOptions.forEach((option) => {
        const isCopy = option.type === "copy";
        const card = document.createElement(isCopy ? "button" : "a");
        card.className = "connection-card";
        if (isCopy) {
          card.type = "button";
        } else {
          card.href = option.href;
          card.target = "_blank";
          card.rel = "noreferrer";
        }

        const inner = document.createElement("span");
        inner.className = "card-inner";

        const iconBadge = document.createElement("span");
        iconBadge.className = "icon-badge";
        iconBadge.innerHTML = icons[option.icon] || "";

        const label = document.createElement("span");
        label.className = "card-label";
        label.textContent = option.label;

        inner.appendChild(iconBadge);
        inner.appendChild(label);
        card.appendChild(inner);

        const backgroundIcon = document.createElement("span");
        backgroundIcon.className = "background-icon";
        backgroundIcon.innerHTML = icons[option.icon] || "";
        card.appendChild(backgroundIcon);

        if (isCopy) {
          card.addEventListener("click", () => {
            copyText(option.snippet)
              .then((success) => {
                showToast(
                  success
                    ? \`\${option.label} connection method copied to clipboard.\`
                    : "Unable to copy. Please copy manually."
                );
              })
              .catch(() => {
                showToast("Unable to copy. Please copy manually.");
              });
          });
        }

        elements.grid?.appendChild(card);
      });
    }

    function showToast(message) {
      if (!elements.toast) return;
      elements.toast.textContent = message;
      elements.toast.classList.add("show");
      setTimeout(() => {
        elements.toast && elements.toast.classList.remove("show");
      }, 2400);
    }

    async function copyText(text) {
      if (navigator.clipboard && window.isSecureContext) {
        try {
          await navigator.clipboard.writeText(text);
          return true;
        } catch (error) {
          return fallbackCopy(text);
        }
      }
      return fallbackCopy(text);
    }

    function fallbackCopy(text) {
      try {
        const textarea = document.createElement("textarea");
        textarea.value = text;
        textarea.setAttribute("readonly", "");
        textarea.style.position = "absolute";
        textarea.style.left = "-9999px";
        document.body.appendChild(textarea);
        textarea.select();
        const successful = document.execCommand("copy");
        document.body.removeChild(textarea);
        return successful;
      } catch {
        return false;
      }
    }
  })();
`}
    </script>
  </body>
</html>
`),{status:200,headers:{"Content-Type":"text/html"}}),o)}if(n===a)try{let{response:r,authInfo:n}=await hN(t);if(r)return hE(r,o);return hZ(t,o,i,n)}catch(t){return console.error("[Cloudflare-MCP] Middleware error:",t),hE(new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null}),{status:500,headers:{"Content-Type":"application/json"}}),o)}return hE(new Response(JSON.stringify({error:"Not found"}),{status:404,headers:{"Content-Type":"application/json"}}),o)}};var hF=H.A;export{hF as default};