xmcp 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{createRequire as e}from"node:module";let t=e(import.meta.url);var r={6982(e){e.exports=t("crypto")},9896(e){e.exports=t("fs")},6928(e){e.exports=t("path")}},a={};function i(e){var t=a[e];if(void 0!==t)return t.exports;var n=a[e]={exports:{}};return r[e](n,n.exports,i),n.exports}i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var n={};(()=>{let e,r,a,s,o,l,c,u,d,p,m;i.d(n,{r:()=>hu});var h,f,g,y,v,_,b,S,$,w,R,k,x,P=Object.create,E=Object.defineProperty,T=Object.getOwnPropertyDescriptor,j=Object.getOwnPropertyNames,C=Object.getPrototypeOf,O=Object.prototype.hasOwnProperty,I=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),N=(e,t,r)=>(r=null!=e?P(C(e)):{},((e,t,r,a)=>{if(t&&"object"==typeof t||"function"==typeof t)for(var i,n=j(t),s=0,o=n.length;s<o;s++)i=n[s],O.call(e,i)||i===r||E(e,i,{get:(e=>t[e]).bind(null,i),enumerable:!(a=T(t,i))||a.enumerable});return e})(!t&&e&&e.__esModule?r:E(r,"default",{value:e,enumerable:!0}),e));let q=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),A=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),z=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),M=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]),L=Object.freeze({status:"aborted"});function Z(e,t,r){function a(r,a){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:a,constr:s,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,a);let i=s.prototype,n=Object.keys(i);for(let e=0;e<n.length;e++){let t=n[e];t in r||(r[t]=i[t].bind(r))}}let i=r?.Parent??Object;class n extends i{}function s(e){var t;let i=r?.Parent?new n:this;for(let r of(a(i,e),(t=i._zod).deferred??(t.deferred=[]),i._zod.deferred))r();return i}return Object.defineProperty(n,"name",{value:e}),Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!r?.Parent&&t instanceof r.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}Symbol("zod_brand");class V extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class D extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(b=globalThis).__zod_globalConfig??(b.__zod_globalConfig={});let U=globalThis.__zod_globalConfig;function F(e){return e&&Object.assign(U,e),U}let H=/^[cC][0-9a-z]{6,}$/,J=/^[0-9a-z]+$/,B=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,K=/^[0-9a-vA-V]{20}$/,G=/^[A-Za-z0-9]{27}$/,W=/^[a-zA-Z0-9_-]{21}$/,X=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Y=/^([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})$/,Q=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ee=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,et=/^(?:(?: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])$/,er=/^(([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}|:))$/,ea=/^((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])$/,ei=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,en=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,es=/^[A-Za-z0-9_-]*$/,eo=/^https?$/,el=/^\+[1-9]\d{6,14}$/,ec="(?:(?:\\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])))",eu=RegExp(`^${ec}$`);function ed(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}let ep=/^-?\d+$/,em=/^-?\d+(?:\.\d+)?$/,eh=/^(?:true|false)$/i,ef=/^null$/i,eg=/^[^A-Z]*$/,ey=/^[^a-z]*$/;function ev(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function e_(e,t){return"bigint"==typeof t?t.toString():t}function eb(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function eS(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}let e$=Symbol("evaluating");function ew(e,t,r){let a;Object.defineProperty(e,t,{get(){if(a!==e$)return void 0===a&&(a=e$,a=r()),a},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function eR(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ek(...e){let t={};for(let r of e)Object.assign(t,Object.getOwnPropertyDescriptors(r));return Object.defineProperties({},t)}function ex(e){return JSON.stringify(e)}let eP="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function eE(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let eT=eb(()=>{if(U.jitless||"undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function ej(e){if(!1===eE(e))return!1;let t=e.constructor;if(void 0===t||"function"!=typeof t)return!0;let r=t.prototype;return!1!==eE(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function eC(e){return ej(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let eO=new Set(["string","number","symbol"]);function eI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function eN(e,t,r){let a=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(a._zod.parent=e),a}function eq(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}let eA={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]};function ez(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function eM(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function eL(e){return"string"==typeof e?e:e?.message}function eZ(e,t,r){let a=e.message?e.message:eL(e.inst?._zod.def?.error?.(e))??eL(t?.error?.(e))??eL(r.customError?.(e))??eL(r.localeError?.(e))??"Invalid input",{inst:i,continue:n,input:s,...o}=e;return o.path??(o.path=[]),o.message=a,t?.reportInput&&(o.input=s),o}function eV(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function eD(...e){let[t,r,a]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:a}:{...t}}let eU=Z("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),eF={number:"number",bigint:"bigint",object:"date"},eH=Z("$ZodCheckLessThan",(e,t)=>{eU.init(e,t);let r=eF[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,a=(t.inclusive?r.maximum:r.exclusiveMaximum)??1/0;t.value<a&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:r,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),eJ=Z("$ZodCheckGreaterThan",(e,t)=>{eU.init(e,t);let r=eF[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,a=(t.inclusive?r.minimum:r.exclusiveMinimum)??-1/0;t.value>a&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:r,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),eB=Z("$ZodCheckMultipleOf",(e,t)=>{eU.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{let a,i,n;if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0==(i=Math.round(a=r.value/t.value),n=Number.EPSILON*Math.max(Math.abs(a),1),Math.abs(a-i)<n?0:a-i))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),eK=Z("$ZodCheckNumberFormat",(e,t)=>{eU.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),a=r?"int":"number",[i,n]=eA[t.format];e._zod.onattach.push(e=>{let a=e._zod.bag;a.format=t.format,a.minimum=i,a.maximum=n,r&&(a.pattern=ep)}),e._zod.check=s=>{let o=s.value;if(r){if(!Number.isInteger(o))return void s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:o,inst:e});if(!Number.isSafeInteger(o))return void(o>0?s.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}):s.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}))}o<i&&s.issues.push({origin:"number",input:o,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),o>n&&s.issues.push({origin:"number",input:o,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),eG=Z("$ZodCheckMaxLength",(e,t)=>{var r;eU.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return null!=t&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??1/0;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let a=r.value;if(a.length<=t.maximum)return;let i=eV(a);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),eW=Z("$ZodCheckMinLength",(e,t)=>{var r;eU.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return null!=t&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??-1/0;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let a=r.value;if(a.length>=t.minimum)return;let i=eV(a);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),eX=Z("$ZodCheckLengthEquals",(e,t)=>{var r;eU.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return null!=t&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{let a=r.value,i=a.length;if(i===t.length)return;let n=eV(a),s=i>t.length;r.issues.push({origin:n,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),eY=Z("$ZodCheckStringFormat",(e,t)=>{var r,a;eU.init(e,t),e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),eQ=Z("$ZodCheckRegex",(e,t)=>{eY.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),e0=Z("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=eg),eY.init(e,t)}),e1=Z("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ey),eY.init(e,t)}),e2=Z("$ZodCheckIncludes",(e,t)=>{eU.init(e,t);let r=eI(t.includes),a=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=a,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(a)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),e9=Z("$ZodCheckStartsWith",(e,t)=>{eU.init(e,t);let r=RegExp(`^${eI(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),e4=Z("$ZodCheckEndsWith",(e,t)=>{eU.init(e,t);let r=RegExp(`.*${eI(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),e3=Z("$ZodCheckOverwrite",(e,t)=>{eU.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class e6{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){return Function(...this?.args,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}let e5=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,e_,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},e8=Z("$ZodError",e5),e7=Z("$ZodError",e5,{Parent:Error}),te=e=>(t,r,a,i)=>{let n=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new V;if(s.issues.length){let t=new(i?.Err??e)(s.issues.map(e=>eZ(e,n,F())));throw eP(t,i?.callee),t}return s.value},tt=e=>async(t,r,a,i)=>{let n=a?{...a,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise&&(s=await s),s.issues.length){let t=new(i?.Err??e)(s.issues.map(e=>eZ(e,n,F())));throw eP(t,i?.callee),t}return s.value},tr=e=>(t,r,a)=>{let i=a?{...a,async:!1}:{async:!1},n=t._zod.run({value:r,issues:[]},i);if(n instanceof Promise)throw new V;return n.issues.length?{success:!1,error:new(e??e8)(n.issues.map(e=>eZ(e,i,F())))}:{success:!0,data:n.value}},ta=tr(e7),ti=e=>async(t,r,a)=>{let i=a?{...a,async:!0}:{async:!0},n=t._zod.run({value:r,issues:[]},i);return n instanceof Promise&&(n=await n),n.issues.length?{success:!1,error:new e(n.issues.map(e=>eZ(e,i,F())))}:{success:!0,data:n.value}},tn=ti(e7),ts={major:4,minor:4,patch:3},to=Z("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ts;let a=[...e._zod.def.checks??[]];for(let t of(e._zod.traits.has("$ZodCheck")&&a.unshift(e),a))for(let r of t._zod.onattach)r(e);if(0===a.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let a,i=ez(e);for(let n of t){if(n._zod.def.when){if(function(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}(e)||!n._zod.def.when(e))continue}else if(i)continue;let t=e.issues.length,s=n._zod.check(e);if(s instanceof Promise&&r?.async===!1)throw new V;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,e.issues.length!==t&&(i||(i=ez(e,t)))});else{if(e.issues.length===t)continue;i||(i=ez(e,t))}}return a?a.then(()=>e):e},r=(r,i,n)=>{if(ez(r))return r.aborted=!0,r;let s=t(i,a,n);if(s instanceof Promise){if(!1===n.async)throw new V;return s.then(t=>e._zod.parse(t,n))}return e._zod.parse(s,n)};e._zod.run=(i,n)=>{if(n.skipChecks)return e._zod.parse(i,n);if("backward"===n.direction){let t=e._zod.parse({value:i.value,issues:[]},{...n,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,i,n)):r(t,i,n)}let s=e._zod.parse(i,n);if(s instanceof Promise){if(!1===n.async)throw new V;return s.then(e=>t(e,a,n))}return t(s,a,n)}}ew(e,"~standard",()=>({validate:t=>{try{let r=ta(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return tn(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),tl=Z("$ZodString",(e,t)=>{var r;let a;to.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(a=(r=e._zod.bag)?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*",RegExp(`^${a}$`)),e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=String(r.value)}catch(e){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),tc=Z("$ZodStringFormat",(e,t)=>{eY.init(e,t),tl.init(e,t)}),tu=Z("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Y),tc.init(e,t)}),td=Z("$ZodUUID",(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Q(e))}else t.pattern??(t.pattern=Q());tc.init(e,t)}),tp=Z("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ee),tc.init(e,t)}),tm=Z("$ZodURL",(e,t)=>{tc.init(e,t),e._zod.check=r=>{try{let a=r.value.trim();if(!t.normalize&&t.protocol?.source===eo.source&&!/^https?:\/\//i.test(a))return void r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});let i=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=i.href:r.value=a;return}catch(a){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),th=Z("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),tc.init(e,t)}),tf=Z("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=W),tc.init(e,t)}),tg=Z("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=H),tc.init(e,t)}),ty=Z("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=J),tc.init(e,t)}),tv=Z("$ZodULID",(e,t)=>{t.pattern??(t.pattern=B),tc.init(e,t)}),t_=Z("$ZodXID",(e,t)=>{t.pattern??(t.pattern=K),tc.init(e,t)}),tb=Z("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=G),tc.init(e,t)}),tS=Z("$ZodISODateTime",(e,t)=>{let r,a,i;t.pattern??(r=ed({precision:t.precision}),a=["Z"],t.local&&a.push(""),t.offset&&a.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)"),i=`${r}(?:${a.join("|")})`,t.pattern=RegExp(`^${ec}T(?:${i})$`)),tc.init(e,t)}),t$=Z("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=eu),tc.init(e,t)}),tw=Z("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=RegExp(`^${ed(t)}$`)),tc.init(e,t)}),tR=Z("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=X),tc.init(e,t)}),tk=Z("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=et),tc.init(e,t),e._zod.bag.format="ipv4"}),tx=Z("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=er),tc.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),tP=Z("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ea),tc.init(e,t)}),tE=Z("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ei),tc.init(e,t),e._zod.check=r=>{let a=r.value.split("/");try{if(2!==a.length)throw Error();let[e,t]=a;if(!t)throw Error();let r=Number(t);if(`${r}`!==t||r<0||r>128)throw Error();new URL(`http://[${e}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function tT(e){if(""===e)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let tj=Z("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=en),tc.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{tT(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),tC=Z("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=es),tc.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{!function(e){if(!es.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return tT(t.padEnd(4*Math.ceil(t.length/4),"="))}(r.value)&&r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),tO=Z("$ZodE164",(e,t)=>{t.pattern??(t.pattern=el),tc.init(e,t)}),tI=Z("$ZodJWT",(e,t)=>{tc.init(e,t),e._zod.check=r=>{!function(e,t=null){try{let r=e.split(".");if(3!==r.length)return!1;let[a]=r;if(!a)return!1;let i=JSON.parse(atob(a));if("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))return!1;return!0}catch{return!1}}(r.value,t.alg)&&r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),tN=Z("$ZodNumber",(e,t)=>{to.init(e,t),e._zod.pattern=e._zod.bag.pattern??em,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}let i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;let n="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...n?{received:n}:{}}),r}}),tq=Z("$ZodNumberFormat",(e,t)=>{eK.init(e,t),tN.init(e,t)}),tA=Z("$ZodBoolean",(e,t)=>{to.init(e,t),e._zod.pattern=eh,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=!!r.value}catch(e){}let i=r.value;return"boolean"==typeof i||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),tz=Z("$ZodNull",(e,t)=>{to.init(e,t),e._zod.pattern=ef,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{let a=t.value;return null===a||t.issues.push({expected:"null",code:"invalid_type",input:a,inst:e}),t}}),tM=Z("$ZodAny",(e,t)=>{to.init(e,t),e._zod.parse=e=>e}),tL=Z("$ZodUnknown",(e,t)=>{to.init(e,t),e._zod.parse=e=>e}),tZ=Z("$ZodNever",(e,t)=>{to.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function tV(e,t,r){e.issues.length&&t.issues.push(...eM(r,e.issues)),t.value[r]=e.value}let tD=Z("$ZodArray",(e,t)=>{to.init(e,t),e._zod.parse=(r,a)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);let n=[];for(let e=0;e<i.length;e++){let s=i[e],o=t.element._zod.run({value:s,issues:[]},a);o instanceof Promise?n.push(o.then(t=>tV(t,r,e))):tV(o,r,e)}return n.length?Promise.all(n).then(()=>r):r}});function tU(e,t,r,a,i,n){let s=r in a;if(e.issues.length){if(i&&n&&!s)return;t.issues.push(...eM(r,e.issues))}if(!s&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}void 0===e.value?s&&(t.value[r]=void 0):t.value[r]=e.value}function tF(e){var t;let r=Object.keys(e.shape);for(let t of r)if(!e.shape?.[t]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${t}": expected a Zod schema`);let a=Object.keys(t=e.shape).filter(e=>"optional"===t[e]._zod.optin&&"optional"===t[e]._zod.optout);return{...e,keys:r,keySet:new Set(r),numKeys:r.length,optionalKeys:new Set(a)}}function tH(e,t,r,a,i,n){let s=[],o=i.keySet,l=i.catchall._zod,c=l.def.type,u="optional"===l.optin,d="optional"===l.optout;for(let i in t){if("__proto__"===i||o.has(i))continue;if("never"===c){s.push(i);continue}let n=l.run({value:t[i],issues:[]},a);n instanceof Promise?e.push(n.then(e=>tU(e,r,i,t,u,d))):tU(n,r,i,t,u,d)}return(s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:n}),e.length)?Promise.all(e).then(()=>r):r}let tJ=Z("$ZodObject",(e,t)=>{let r;to.init(e,t);let a=Object.getOwnPropertyDescriptor(t,"shape");if(!a?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}let i=eb(()=>tF(t));ew(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let a=e[t]._zod;if(a.values)for(let e of(r[t]??(r[t]=new Set),a.values))r[t].add(e)}return r});let n=t.catchall;e._zod.parse=(t,a)=>{r??(r=i.value);let s=t.value;if(!eE(s))return t.issues.push({expected:"object",code:"invalid_type",input:s,inst:e}),t;t.value={};let o=[],l=r.shape;for(let e of r.keys){let r=l[e],i="optional"===r._zod.optin,n="optional"===r._zod.optout,c=r._zod.run({value:s[e],issues:[]},a);c instanceof Promise?o.push(c.then(r=>tU(r,t,e,s,i,n))):tU(c,t,e,s,i,n)}return n?tH(o,s,t,a,i.value,e):o.length?Promise.all(o).then(()=>t):t}}),tB=Z("$ZodObjectJIT",(e,t)=>{let r,a;tJ.init(e,t);let i=e._zod.parse,n=eb(()=>tF(t)),s=!U.jitless,o=s&&eT.value,l=t.catchall;e._zod.parse=(c,u)=>{a??(a=n.value);let d=c.value;return eE(d)?s&&o&&u?.async===!1&&!0!==u.jitless?(r||(r=(e=>{let t=new e6(["shape","payload","ctx"]),r=n.value,a=e=>{let t=ex(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");let i=Object.create(null),s=0;for(let e of r.keys)i[e]=`key_${s++}`;for(let n of(t.write("const newResult = {};"),r.keys)){let r=i[n],s=ex(n),o=e[n],l=o?._zod?.optin==="optional",c=o?._zod?.optout==="optional";t.write(`const ${r} = ${a(n)};`),l&&c?t.write(`
1
+ import{createRequire as e}from"node:module";let t=e(import.meta.url);var r={6982(e){e.exports=t("crypto")},9896(e){e.exports=t("fs")},6928(e){e.exports=t("path")}},a={};function i(e){var t=a[e];if(void 0!==t)return t.exports;var n=a[e]={exports:{}};return r[e](n,n.exports,i),n.exports}i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var n={};(()=>{let e,r,a,s,o,l,c,u,d,p,m;i.d(n,{r:()=>hd});var h,f,g,y,v,_,b,S,$,w,R,k,x,P=Object.create,E=Object.defineProperty,T=Object.getOwnPropertyDescriptor,j=Object.getOwnPropertyNames,C=Object.getPrototypeOf,O=Object.prototype.hasOwnProperty,I=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),N=(e,t,r)=>(r=null!=e?P(C(e)):{},((e,t,r,a)=>{if(t&&"object"==typeof t||"function"==typeof t)for(var i,n=j(t),s=0,o=n.length;s<o;s++)i=n[s],O.call(e,i)||i===r||E(e,i,{get:(e=>t[e]).bind(null,i),enumerable:!(a=T(t,i))||a.enumerable});return e})(!t&&e&&e.__esModule?r:E(r,"default",{value:e,enumerable:!0}),e));let q=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),A=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),z=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),M=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]),L=Object.freeze({status:"aborted"});function Z(e,t,r){function a(r,a){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:a,constr:s,traits:new Set},enumerable:!1}),r._zod.traits.has(e))return;r._zod.traits.add(e),t(r,a);let i=s.prototype,n=Object.keys(i);for(let e=0;e<n.length;e++){let t=n[e];t in r||(r[t]=i[t].bind(r))}}let i=r?.Parent??Object;class n extends i{}function s(e){var t;let i=r?.Parent?new n:this;for(let r of(a(i,e),(t=i._zod).deferred??(t.deferred=[]),i._zod.deferred))r();return i}return Object.defineProperty(n,"name",{value:e}),Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!r?.Parent&&t instanceof r.Parent||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}Symbol("zod_brand");class V extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class D extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(b=globalThis).__zod_globalConfig??(b.__zod_globalConfig={});let U=globalThis.__zod_globalConfig;function F(e){return e&&Object.assign(U,e),U}let H=/^[cC][0-9a-z]{6,}$/,J=/^[0-9a-z]+$/,B=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,K=/^[0-9a-vA-V]{20}$/,G=/^[A-Za-z0-9]{27}$/,W=/^[a-zA-Z0-9_-]{21}$/,X=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Y=/^([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})$/,Q=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ee=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,et=/^(?:(?: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])$/,er=/^(([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}|:))$/,ea=/^((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])$/,ei=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,en=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,es=/^[A-Za-z0-9_-]*$/,eo=/^https?$/,el=/^\+[1-9]\d{6,14}$/,ec="(?:(?:\\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])))",eu=RegExp(`^${ec}$`);function ed(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}let ep=/^-?\d+$/,em=/^-?\d+(?:\.\d+)?$/,eh=/^(?:true|false)$/i,ef=/^null$/i,eg=/^[^A-Z]*$/,ey=/^[^a-z]*$/;function ev(e){let t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,r])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function e_(e,t){return"bigint"==typeof t?t.toString():t}function eb(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function eS(e){let t=+!!e.startsWith("^"),r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}let e$=Symbol("evaluating");function ew(e,t,r){let a;Object.defineProperty(e,t,{get(){if(a!==e$)return void 0===a&&(a=e$,a=r()),a},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function eR(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ek(...e){let t={};for(let r of e)Object.assign(t,Object.getOwnPropertyDescriptors(r));return Object.defineProperties({},t)}function ex(e){return JSON.stringify(e)}let eP="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function eE(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}let eT=eb(()=>{if(U.jitless||"undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return Function(""),!0}catch(e){return!1}});function ej(e){if(!1===eE(e))return!1;let t=e.constructor;if(void 0===t||"function"!=typeof t)return!0;let r=t.prototype;return!1!==eE(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function eC(e){return ej(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let eO=new Set(["string","number","symbol"]);function eI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function eN(e,t,r){let a=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(a._zod.parent=e),a}function eq(e){if(!e)return{};if("string"==typeof e)return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");e.error=e.message}return(delete e.message,"string"==typeof e.error)?{...e,error:()=>e.error}:e}let eA={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]};function ez(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function eM(e,t){return t.map(t=>(t.path??(t.path=[]),t.path.unshift(e),t))}function eL(e){return"string"==typeof e?e:e?.message}function eZ(e,t,r){let a=e.message?e.message:eL(e.inst?._zod.def?.error?.(e))??eL(t?.error?.(e))??eL(r.customError?.(e))??eL(r.localeError?.(e))??"Invalid input",{inst:i,continue:n,input:s,...o}=e;return o.path??(o.path=[]),o.message=a,t?.reportInput&&(o.input=s),o}function eV(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function eD(...e){let[t,r,a]=e;return"string"==typeof t?{message:t,code:"custom",input:r,inst:a}:{...t}}let eU=Z("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),eF={number:"number",bigint:"bigint",object:"date"},eH=Z("$ZodCheckLessThan",(e,t)=>{eU.init(e,t);let r=eF[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,a=(t.inclusive?r.maximum:r.exclusiveMaximum)??1/0;t.value<a&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:r,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),eJ=Z("$ZodCheckGreaterThan",(e,t)=>{eU.init(e,t);let r=eF[typeof t.value];e._zod.onattach.push(e=>{let r=e._zod.bag,a=(t.inclusive?r.minimum:r.exclusiveMinimum)??-1/0;t.value>a&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:r,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),eB=Z("$ZodCheckMultipleOf",(e,t)=>{eU.init(e,t),e._zod.onattach.push(e=>{var r;(r=e._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=r=>{let a,i,n;if(typeof r.value!=typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%t.value===BigInt(0):0==(i=Math.round(a=r.value/t.value),n=Number.EPSILON*Math.max(Math.abs(a),1),Math.abs(a-i)<n?0:a-i))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),eK=Z("$ZodCheckNumberFormat",(e,t)=>{eU.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),a=r?"int":"number",[i,n]=eA[t.format];e._zod.onattach.push(e=>{let a=e._zod.bag;a.format=t.format,a.minimum=i,a.maximum=n,r&&(a.pattern=ep)}),e._zod.check=s=>{let o=s.value;if(r){if(!Number.isInteger(o))return void s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:o,inst:e});if(!Number.isSafeInteger(o))return void(o>0?s.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}):s.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}))}o<i&&s.issues.push({origin:"number",input:o,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),o>n&&s.issues.push({origin:"number",input:o,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),eG=Z("$ZodCheckMaxLength",(e,t)=>{var r;eU.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return null!=t&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.maximum??1/0;t.maximum<r&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{let a=r.value;if(a.length<=t.maximum)return;let i=eV(a);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),eW=Z("$ZodCheckMinLength",(e,t)=>{var r;eU.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return null!=t&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag.minimum??-1/0;t.minimum>r&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{let a=r.value;if(a.length>=t.minimum)return;let i=eV(a);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),eX=Z("$ZodCheckLengthEquals",(e,t)=>{var r;eU.init(e,t),(r=e._zod.def).when??(r.when=e=>{let t=e.value;return null!=t&&void 0!==t.length}),e._zod.onattach.push(e=>{let r=e._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=r=>{let a=r.value,i=a.length;if(i===t.length)return;let n=eV(a),s=i>t.length;r.issues.push({origin:n,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),eY=Z("$ZodCheckStringFormat",(e,t)=>{var r,a;eU.init(e,t),e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),eQ=Z("$ZodCheckRegex",(e,t)=>{eY.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,t.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),e0=Z("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=eg),eY.init(e,t)}),e1=Z("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ey),eY.init(e,t)}),e2=Z("$ZodCheckIncludes",(e,t)=>{eU.init(e,t);let r=eI(t.includes),a=new RegExp("number"==typeof t.position?`^.{${t.position}}${r}`:r);t.pattern=a,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(a)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),e9=Z("$ZodCheckStartsWith",(e,t)=>{eU.init(e,t);let r=RegExp(`^${eI(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),e4=Z("$ZodCheckEndsWith",(e,t)=>{eU.init(e,t);let r=RegExp(`.*${eI(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),e3=Z("$ZodCheckOverwrite",(e,t)=>{eU.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class e6{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let t=e.split("\n").filter(e=>e),r=Math.min(...t.map(e=>e.length-e.trimStart().length));for(let e of t.map(e=>e.slice(r)).map(e=>" ".repeat(2*this.indent)+e))this.content.push(e)}compile(){return Function(...this?.args,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}let e5=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,e_,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},e8=Z("$ZodError",e5),e7=Z("$ZodError",e5,{Parent:Error}),te=e=>(t,r,a,i)=>{let n=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new V;if(s.issues.length){let t=new(i?.Err??e)(s.issues.map(e=>eZ(e,n,F())));throw eP(t,i?.callee),t}return s.value},tt=e=>async(t,r,a,i)=>{let n=a?{...a,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},n);if(s instanceof Promise&&(s=await s),s.issues.length){let t=new(i?.Err??e)(s.issues.map(e=>eZ(e,n,F())));throw eP(t,i?.callee),t}return s.value},tr=e=>(t,r,a)=>{let i=a?{...a,async:!1}:{async:!1},n=t._zod.run({value:r,issues:[]},i);if(n instanceof Promise)throw new V;return n.issues.length?{success:!1,error:new(e??e8)(n.issues.map(e=>eZ(e,i,F())))}:{success:!0,data:n.value}},ta=tr(e7),ti=e=>async(t,r,a)=>{let i=a?{...a,async:!0}:{async:!0},n=t._zod.run({value:r,issues:[]},i);return n instanceof Promise&&(n=await n),n.issues.length?{success:!1,error:new e(n.issues.map(e=>eZ(e,i,F())))}:{success:!0,data:n.value}},tn=ti(e7),ts={major:4,minor:4,patch:3},to=Z("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ts;let a=[...e._zod.def.checks??[]];for(let t of(e._zod.traits.has("$ZodCheck")&&a.unshift(e),a))for(let r of t._zod.onattach)r(e);if(0===a.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,r)=>{let a,i=ez(e);for(let n of t){if(n._zod.def.when){if(function(e,t=0){if(!0===e.aborted)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}(e)||!n._zod.def.when(e))continue}else if(i)continue;let t=e.issues.length,s=n._zod.check(e);if(s instanceof Promise&&r?.async===!1)throw new V;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,e.issues.length!==t&&(i||(i=ez(e,t)))});else{if(e.issues.length===t)continue;i||(i=ez(e,t))}}return a?a.then(()=>e):e},r=(r,i,n)=>{if(ez(r))return r.aborted=!0,r;let s=t(i,a,n);if(s instanceof Promise){if(!1===n.async)throw new V;return s.then(t=>e._zod.parse(t,n))}return e._zod.parse(s,n)};e._zod.run=(i,n)=>{if(n.skipChecks)return e._zod.parse(i,n);if("backward"===n.direction){let t=e._zod.parse({value:i.value,issues:[]},{...n,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,i,n)):r(t,i,n)}let s=e._zod.parse(i,n);if(s instanceof Promise){if(!1===n.async)throw new V;return s.then(e=>t(e,a,n))}return t(s,a,n)}}ew(e,"~standard",()=>({validate:t=>{try{let r=ta(e,t);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return tn(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),tl=Z("$ZodString",(e,t)=>{var r;let a;to.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(a=(r=e._zod.bag)?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*",RegExp(`^${a}$`)),e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=String(r.value)}catch(e){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),tc=Z("$ZodStringFormat",(e,t)=>{eY.init(e,t),tl.init(e,t)}),tu=Z("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Y),tc.init(e,t)}),td=Z("$ZodUUID",(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Q(e))}else t.pattern??(t.pattern=Q());tc.init(e,t)}),tp=Z("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ee),tc.init(e,t)}),tm=Z("$ZodURL",(e,t)=>{tc.init(e,t),e._zod.check=r=>{try{let a=r.value.trim();if(!t.normalize&&t.protocol?.source===eo.source&&!/^https?:\/\//i.test(a))return void r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});let i=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=i.href:r.value=a;return}catch(a){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),th=Z("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),tc.init(e,t)}),tf=Z("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=W),tc.init(e,t)}),tg=Z("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=H),tc.init(e,t)}),ty=Z("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=J),tc.init(e,t)}),tv=Z("$ZodULID",(e,t)=>{t.pattern??(t.pattern=B),tc.init(e,t)}),t_=Z("$ZodXID",(e,t)=>{t.pattern??(t.pattern=K),tc.init(e,t)}),tb=Z("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=G),tc.init(e,t)}),tS=Z("$ZodISODateTime",(e,t)=>{let r,a,i;t.pattern??(r=ed({precision:t.precision}),a=["Z"],t.local&&a.push(""),t.offset&&a.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)"),i=`${r}(?:${a.join("|")})`,t.pattern=RegExp(`^${ec}T(?:${i})$`)),tc.init(e,t)}),t$=Z("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=eu),tc.init(e,t)}),tw=Z("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=RegExp(`^${ed(t)}$`)),tc.init(e,t)}),tR=Z("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=X),tc.init(e,t)}),tk=Z("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=et),tc.init(e,t),e._zod.bag.format="ipv4"}),tx=Z("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=er),tc.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),tP=Z("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ea),tc.init(e,t)}),tE=Z("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ei),tc.init(e,t),e._zod.check=r=>{let a=r.value.split("/");try{if(2!==a.length)throw Error();let[e,t]=a;if(!t)throw Error();let r=Number(t);if(`${r}`!==t||r<0||r>128)throw Error();new URL(`http://[${e}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function tT(e){if(""===e)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let tj=Z("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=en),tc.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{tT(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),tC=Z("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=es),tc.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{!function(e){if(!es.test(e))return!1;let t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return tT(t.padEnd(4*Math.ceil(t.length/4),"="))}(r.value)&&r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),tO=Z("$ZodE164",(e,t)=>{t.pattern??(t.pattern=el),tc.init(e,t)}),tI=Z("$ZodJWT",(e,t)=>{tc.init(e,t),e._zod.check=r=>{!function(e,t=null){try{let r=e.split(".");if(3!==r.length)return!1;let[a]=r;if(!a)return!1;let i=JSON.parse(atob(a));if("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))return!1;return!0}catch{return!1}}(r.value,t.alg)&&r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),tN=Z("$ZodNumber",(e,t)=>{to.init(e,t),e._zod.pattern=e._zod.bag.pattern??em,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=Number(r.value)}catch(e){}let i=r.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return r;let n="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...n?{received:n}:{}}),r}}),tq=Z("$ZodNumberFormat",(e,t)=>{eK.init(e,t),tN.init(e,t)}),tA=Z("$ZodBoolean",(e,t)=>{to.init(e,t),e._zod.pattern=eh,e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=!!r.value}catch(e){}let i=r.value;return"boolean"==typeof i||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),tz=Z("$ZodNull",(e,t)=>{to.init(e,t),e._zod.pattern=ef,e._zod.values=new Set([null]),e._zod.parse=(t,r)=>{let a=t.value;return null===a||t.issues.push({expected:"null",code:"invalid_type",input:a,inst:e}),t}}),tM=Z("$ZodAny",(e,t)=>{to.init(e,t),e._zod.parse=e=>e}),tL=Z("$ZodUnknown",(e,t)=>{to.init(e,t),e._zod.parse=e=>e}),tZ=Z("$ZodNever",(e,t)=>{to.init(e,t),e._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function tV(e,t,r){e.issues.length&&t.issues.push(...eM(r,e.issues)),t.value[r]=e.value}let tD=Z("$ZodArray",(e,t)=>{to.init(e,t),e._zod.parse=(r,a)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);let n=[];for(let e=0;e<i.length;e++){let s=i[e],o=t.element._zod.run({value:s,issues:[]},a);o instanceof Promise?n.push(o.then(t=>tV(t,r,e))):tV(o,r,e)}return n.length?Promise.all(n).then(()=>r):r}});function tU(e,t,r,a,i,n){let s=r in a;if(e.issues.length){if(i&&n&&!s)return;t.issues.push(...eM(r,e.issues))}if(!s&&!i){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}void 0===e.value?s&&(t.value[r]=void 0):t.value[r]=e.value}function tF(e){var t;let r=Object.keys(e.shape);for(let t of r)if(!e.shape?.[t]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${t}": expected a Zod schema`);let a=Object.keys(t=e.shape).filter(e=>"optional"===t[e]._zod.optin&&"optional"===t[e]._zod.optout);return{...e,keys:r,keySet:new Set(r),numKeys:r.length,optionalKeys:new Set(a)}}function tH(e,t,r,a,i,n){let s=[],o=i.keySet,l=i.catchall._zod,c=l.def.type,u="optional"===l.optin,d="optional"===l.optout;for(let i in t){if("__proto__"===i||o.has(i))continue;if("never"===c){s.push(i);continue}let n=l.run({value:t[i],issues:[]},a);n instanceof Promise?e.push(n.then(e=>tU(e,r,i,t,u,d))):tU(n,r,i,t,u,d)}return(s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:n}),e.length)?Promise.all(e).then(()=>r):r}let tJ=Z("$ZodObject",(e,t)=>{let r;to.init(e,t);let a=Object.getOwnPropertyDescriptor(t,"shape");if(!a?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let r={...e};return Object.defineProperty(t,"shape",{value:r}),r}})}let i=eb(()=>tF(t));ew(e._zod,"propValues",()=>{let e=t.shape,r={};for(let t in e){let a=e[t]._zod;if(a.values)for(let e of(r[t]??(r[t]=new Set),a.values))r[t].add(e)}return r});let n=t.catchall;e._zod.parse=(t,a)=>{r??(r=i.value);let s=t.value;if(!eE(s))return t.issues.push({expected:"object",code:"invalid_type",input:s,inst:e}),t;t.value={};let o=[],l=r.shape;for(let e of r.keys){let r=l[e],i="optional"===r._zod.optin,n="optional"===r._zod.optout,c=r._zod.run({value:s[e],issues:[]},a);c instanceof Promise?o.push(c.then(r=>tU(r,t,e,s,i,n))):tU(c,t,e,s,i,n)}return n?tH(o,s,t,a,i.value,e):o.length?Promise.all(o).then(()=>t):t}}),tB=Z("$ZodObjectJIT",(e,t)=>{let r,a;tJ.init(e,t);let i=e._zod.parse,n=eb(()=>tF(t)),s=!U.jitless,o=s&&eT.value,l=t.catchall;e._zod.parse=(c,u)=>{a??(a=n.value);let d=c.value;return eE(d)?s&&o&&u?.async===!1&&!0!==u.jitless?(r||(r=(e=>{let t=new e6(["shape","payload","ctx"]),r=n.value,a=e=>{let t=ex(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");let i=Object.create(null),s=0;for(let e of r.keys)i[e]=`key_${s++}`;for(let n of(t.write("const newResult = {};"),r.keys)){let r=i[n],s=ex(n),o=e[n],l=o?._zod?.optin==="optional",c=o?._zod?.optout==="optional";t.write(`const ${r} = ${a(n)};`),l&&c?t.write(`
2
2
  if (${r}.issues.length) {
3
3
  if (${s} in input) {
4
4
  payload.issues = payload.issues.concat(${r}.issues.map(iss => ({
@@ -85,13 +85,13 @@ data:
85
85
  ]))`;continue}else if("$"===a[e]){i+=`($|(?=[\r
86
86
  ]))`;continue}}if(r.s&&"."===a[e]){i+=s?`${a[e]}\r
87
87
  `:`[${a[e]}\r
88
- ]`;continue}i+=a[e],"\\"===a[e]?n=!0:s&&"]"===a[e]?s=!1:s||"["!==a[e]||(s=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function p8(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===x.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,a)=>({...r,[a]:mt(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??pV(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:mt(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===x.ZodString&&e.keyType._def.checks?.length){let{type:a,...i}=p2(e.keyType._def,t);return{...r,propertyNames:i}}if(e.keyType?._def.typeName===x.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===x.ZodBranded&&e.keyType._def.type._def.typeName===x.ZodString&&e.keyType._def.type._def.checks?.length){let{type:a,...i}=pF(e.keyType._def,t);return{...r,propertyNames:i}}return r}let p7={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},me=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>mt(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function mt(e,t,r=!1){let a=t.seen.get(e);if(t.override){let i=t.override?.(e,t,a,r);if(i!==dC)return i}if(a&&!r){let e=mr(a,t);if(void 0!==e)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let n=((e,t,r)=>{switch(t){case x.ZodString:return p2(e,r);case x.ZodNumber:let a={type:"number"};if(!e.checks)return a;for(let t of e.checks)switch(t.kind){case"int":a.type="integer",pD(a,"type",t.message,r);break;case"min":"jsonSchema7"===r.target?t.inclusive?pU(a,"minimum",t.value,t.message,r):pU(a,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(a.exclusiveMinimum=!0),pU(a,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?pU(a,"maximum",t.value,t.message,r):pU(a,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(a.exclusiveMaximum=!0),pU(a,"maximum",t.value,t.message,r));break;case"multipleOf":pU(a,"multipleOf",t.value,t.message,r)}return a;case x.ZodObject:return function(e,t){let r="openAi"===t.target,a={type:"object",properties:{}},i=[],n=e.shape();for(let e in n){let s=n[e];if(void 0===s||void 0===s._def)continue;let o=function(e){try{return e.isOptional()}catch{return!0}}(s);o&&r&&("ZodOptional"===s._def.typeName&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),o=!1);let l=mt(s._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==l&&(a.properties[e]=l,o||i.push(e))}i.length&&(a.required=i);let s=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return mt(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==s&&(a.additionalProperties=s),a}(e,r);case x.ZodBigInt:let i={type:"integer",format:"int64"};if(!e.checks)return i;for(let t of e.checks)switch(t.kind){case"min":"jsonSchema7"===r.target?t.inclusive?pU(i,"minimum",t.value,t.message,r):pU(i,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(i.exclusiveMinimum=!0),pU(i,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?pU(i,"maximum",t.value,t.message,r):pU(i,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(i.exclusiveMaximum=!0),pU(i,"maximum",t.value,t.message,r));break;case"multipleOf":pU(i,"multipleOf",t.value,t.message,r)}return i;case x.ZodBoolean:return{type:"boolean"};case x.ZodDate:return function e(t,r,a){let i=a??r.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((a,i)=>e(t,r,a))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var n=t,s=r;let o={type:"integer",format:"unix-time"};if("openApi3"===s.target)return o;for(let e of n.checks)switch(e.kind){case"min":pU(o,"minimum",e.value,e.message,s);break;case"max":pU(o,"maximum",e.value,e.message,s)}return o}}(e,r);case x.ZodUndefined:return{not:pV(r)};case x.ZodNull:return"openApi3"===r.target?{enum:["null"],nullable:!0}:{type:"null"};case x.ZodArray:let n;return n={type:"array"},e.type?._def&&e.type?._def?.typeName!==x.ZodAny&&(n.items=mt(e.type._def,{...r,currentPath:[...r.currentPath,"items"]})),e.minLength&&pU(n,"minItems",e.minLength.value,e.minLength.message,r),e.maxLength&&pU(n,"maxItems",e.maxLength.value,e.maxLength.message,r),e.exactLength&&(pU(n,"minItems",e.exactLength.value,e.exactLength.message,r),pU(n,"maxItems",e.exactLength.value,e.exactLength.message,r)),n;case x.ZodUnion:case x.ZodDiscriminatedUnion:if("openApi3"===r.target)return me(e,r);let s=e.options instanceof Map?Array.from(e.options.values()):e.options;if(s.every(e=>e._def.typeName in p7&&(!e._def.checks||!e._def.checks.length))){let e=s.reduce((e,t)=>{let r=p7[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(s.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=s.reduce((e,t)=>{let r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===s.length){let t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:s.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(s.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:s.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return me(e,r);case x.ZodIntersection:let o,l,c;return o=[mt(e.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),mt(e.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(e=>!!e),l="jsonSchema2019-09"===r.target?{unevaluatedProperties:!1}:void 0,c=[],o.forEach(e=>{if((!("type"in e)||"string"!==e.type)&&"allOf"in e)c.push(...e.allOf),void 0===e.unevaluatedProperties&&(l=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...a}=e;t=a}else l=void 0;c.push(t)}}),c.length?{allOf:c,...l}:void 0;case x.ZodTuple:return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,t)=>mt(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:mt(e.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,t)=>mt(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])};case x.ZodRecord:return p8(e,r);case x.ZodLiteral:let u;return"bigint"!=(u=typeof e.value)&&"number"!==u&&"boolean"!==u&&"string"!==u?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===r.target?{type:"bigint"===u?"integer":u,enum:[e.value]}:{type:"bigint"===u?"integer":u,const:e.value};case x.ZodEnum:return{type:"string",enum:Array.from(e.values)};case x.ZodNativeEnum:let d,p,m;return d=e.values,{type:1===(m=Array.from(new Set((p=Object.keys(e.values).filter(e=>"number"!=typeof d[d[e]]).map(e=>d[e])).map(e=>typeof e)))).length?"string"===m[0]?"string":"number":["string","number"],enum:p};case x.ZodNullable:if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===r.target?{type:p7[e.innerType._def.typeName],nullable:!0}:{type:[p7[e.innerType._def.typeName],"null"]};if("openApi3"===r.target){let t=mt(e.innerType._def,{...r,currentPath:[...r.currentPath]});return t&&"$ref"in t?{allOf:[t],nullable:!0}:t&&{...t,nullable:!0}}let h=mt(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return h&&{anyOf:[h,{type:"null"}]};case x.ZodOptional:if(r.currentPath.toString()===r.propertyPath?.toString())return mt(e.innerType._def,r);let f=mt(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return f?{anyOf:[{not:pV(r)},f]}:pV(r);case x.ZodMap:if("record"===r.mapStrategy)return p8(e,r);return{type:"array",maxItems:125,items:{type:"array",items:[mt(e.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||pV(r),mt(e.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||pV(r)],minItems:2,maxItems:2}};case x.ZodSet:let g;return g={type:"array",uniqueItems:!0,items:mt(e.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})},e.minSize&&pU(g,"minItems",e.minSize.value,e.minSize.message,r),e.maxSize&&pU(g,"maxItems",e.maxSize.value,e.maxSize.message,r),g;case x.ZodLazy:return()=>e.getter()._def;case x.ZodPromise:return mt(e.type._def,r);case x.ZodNaN:case x.ZodNever:return"openAi"===r.target?void 0:{not:pV({...r,currentPath:[...r.currentPath,"not"]})};case x.ZodEffects:return"input"===r.effectStrategy?mt(e.schema._def,r):pV(r);case x.ZodAny:case x.ZodUnknown:return pV(r);case x.ZodDefault:return{...mt(e.innerType._def,r),default:e.defaultValue()};case x.ZodBranded:return pF(e,r);case x.ZodReadonly:case x.ZodCatch:return mt(e.innerType._def,r);case x.ZodPipeline:if("input"===r.pipeStrategy)return mt(e.in._def,r);if("output"===r.pipeStrategy)return mt(e.out._def,r);let y=mt(e.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),v=mt(e.out._def,{...r,currentPath:[...r.currentPath,"allOf",y?"1":"0"]});return{allOf:[y,v].filter(e=>void 0!==e)};case x.ZodFunction:case x.ZodVoid:case x.ZodSymbol:default:return}})(e,e.typeName,t),s="function"==typeof n?mt(n(),t):n;if(s&&ma(e,t,s),t.postProcess){let r=t.postProcess(s,e,t);return i.jsonSchema=s,r}return i.jsonSchema=s,s}let mr=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:pZ(t.currentPath,e.path)};case"none":case"seen":if(e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),pV(t);return"seen"===t.$refStrategy?pV(t):void 0}},ma=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);function mi(e,t={}){let{strict:r=!1}=t,a=Object.entries(e),i=e=>({target:t})=>{let i={},n=[];for(let[r,s]of a)i[r]=function(e,t,r){let a=e["~standard"];if(a.jsonSchema)return a.jsonSchema[r]({target:t});if("zod"===e["~standard"].vendor&&!("_zod"in e)&&"_def"in e){let r=((e,t)=>{let r,a,i=(a=void 0!==(r="string"==typeof t?{...dO,name:t}:{...dO,...t}).name?[...r.basePath,r.definitionPath,r.name]:r.basePath,{...r,flags:{hasReferencedOpenAiAnyType:!1},currentPath:a,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([e,t])=>[t._def,{def:t._def,path:[...r.basePath,r.definitionPath,e],jsonSchema:void 0}]))}),n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:mt(r._def,{...i,currentPath:[...i.basePath,i.definitionPath,t]},!0)??pV(i)}),{}):void 0,s="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,o=mt(e._def,void 0===s?i:{...i,currentPath:[...i.basePath,i.definitionPath,s]},!1)??pV(i),l="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==l&&(o.title=l),i.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[i.openAiAnyTypeName]||(n[i.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===i.$refStrategy?"1":[...i.basePath,i.definitionPath,i.openAiAnyTypeName].join("/")}}));let c=void 0===s?n?{...o,[i.definitionPath]:n}:o:{$ref:[..."relative"===i.$refStrategy?[]:i.basePath,i.definitionPath,s].join("/"),[i.definitionPath]:{...n,[s]:o}};return"jsonSchema7"===i.target?c.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===i.target||"openAi"===i.target)&&(c.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===i.target&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c})(e,{$refStrategy:"none",target:"openapi-3.0"===t?"openApi3":"jsonSchema7"});return delete r.$schema,r}if("zod"===a.vendor&&"_zod"in e)try{let t=r2(e);return delete t.$schema,t}catch(e){throw Error(`Failed to convert a zod schema to JSON Schema (zod v4 without "~standard.jsonSchema"). Upgrade to zod >= 4.2.0. Original error: ${e instanceof Error?e.message:String(e)}`)}throw Error(`Schema library "${a.vendor}" cannot be converted to JSON Schema. Use zod v3 (>= 3.25.76), zod >= 4.2.0, or a Standard Schema library implementing "~standard.jsonSchema".`)}(s,t,e),!function(e,t){if("function"!=typeof e.safeParse)return!1;try{let r=e.safeParse(void 0);return r.success&&("input"===t||void 0===r.data)}catch{return!1}}(s,e)&&n.push(r);let s={type:"object",properties:i};return n.length>0&&(s.required=n),r&&(s.additionalProperties=!1),s},n=async t=>{if("object"!=typeof t||null===t||Array.isArray(t))return{issues:[{message:"Expected an object."}]};let i={},n=[];for(let[e,r]of a){let a=await r["~standard"].validate(t[e]);if(a.issues)for(let t of a.issues)n.push({message:t.message,path:[e,...t.path??[]]});else(e in t||void 0!==a.value)&&(i[e]=a.value)}if(r)for(let r of Object.keys(t))r in e||n.push({message:`Unrecognized key: "${r}"`,path:[r]});return n.length>0?{issues:n}:{value:i}};return{shape:e,"~standard":{version:1,vendor:"xmcp",validate:n,jsonSchema:{input:i("input"),output:i("output")}}}}let mn=t("async_hooks"),ms=(e,t)=>{globalThis[e]=t},mo=e=>globalThis[e];function ml({name:e,fallback:t=!0}){let r=Symbol.for(`xmcp-context-${e}`),a=Symbol.for(`xmcp-context-${e}-fallback-store`);if(mo(r))return mo(r);let i=new mn.AsyncLocalStorage,n=globalThis[a]??{current:null};ms(a,n);let s={provider:(e,r)=>(t&&(n.current=e),i.run(e,r)),getContext:()=>{let r=i.getStore();if(r)return r;if(t&&n.current)return n.current;throw Error(`getContext() can only be used within the ${e} context.`)},setContext:r=>{let a=i.getStore()??(t?n.current:null);if(!a)throw Error(`setContext() can only be used within the ${e} context.`);Object.assign(a,r)}};return ms(r,s),s}let mc=ml({name:"http-request-context"});mc.setContext;let mu=mc.getContext,md=mc.provider,mp=ml({name:"client-info-context"});mp.setContext;let mm=mp.getContext;mp.provider;let mh=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),mf=e=>{if(!mh(e)||"string"!=typeof e.name||"string"!=typeof e.version)return;let t={name:e.name,version:e.version};return"string"==typeof e.title&&(t.title=e.title),"string"==typeof e.websiteUrl&&(t.websiteUrl=e.websiteUrl),"string"==typeof e.description&&(t.description=e.description),t},mg=e=>{if(e&&"initialize"===e.method&&mh(e.params))return mf(e.params.clientInfo)},my=(e,t)=>{let r=t.toLowerCase();for(let[t,a]of Object.entries(e)){if(t.toLowerCase()!==r)continue;let e=Array.isArray(a)?a[0]:a;if("string"!=typeof e)break;let i=e.trim();return i.length>0?i:void 0}},mv=new Set(["message","mode","requestedSchema"]),m_=new Set(["elicitationId","message","mode","url"]),mb=new Set(["properties","required","type"]),mS=new Set(["default","description","format","maxLength","minLength","title","type"]),m$=new Set(["default","description","enum","enumNames","title","type"]),mw=new Set(["default","description","title","type"]),mR=new Set(["default","description","maximum","minimum","title","type"]),mk=new Set(["date","date-time","email","uri"]);async function mx(e,t,r){let a=function(e){let t=e.mode??"form";if("url"===t)return function(e){let t;mE(e,"Elicitation request must be a plain object."),mP(e,m_,"URL elicitation"),mT(e.message,"URL elicitation requires a string message."),mj(e.elicitationId,"URL elicitation requires a non-empty elicitationId."),mj(e.url,"URL elicitation requires a non-empty URL.");try{t=new URL(e.url)}catch{throw Error("URL elicitation requires a valid http or https URL.")}if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error("URL elicitation requires a valid http or https URL.")}(e),e;if("form"!==t)throw Error(`Unsupported elicitation mode "${String(e.mode)}". Expected "form" or "url".`);return function(e){mE(e,"Elicitation request must be a plain object."),mP(e,mv,"Form elicitation"),mT(e.message,"Form elicitation requires a string message.");let t=e.requestedSchema;if(mE(t,"Form elicitation requires a flat object schema."),mP(t,mb,"Form elicitation schema"),"object"!==t.type)throw Error('Form elicitation schema must use type "object".');for(let[e,r]of(mE(t.properties,"Form elicitation schema requires a properties object."),Object.entries(t.properties)))!function(e,t){if(mE(t,`Form elicitation field "${e}" must be a plain object.`),mC(t.title,`Form elicitation field "${e}" title must be a string.`),mC(t.description,`Form elicitation field "${e}" description must be a string.`),"string"===t.type&&"enum"in t){var r,a;if(mP(t,m$,`Form elicitation field "${e}"`),mI(t.enum,`Form elicitation field "${e}" enum values must be strings.`),r=t.enumNames,a=`Form elicitation field "${e}" enumNames must be strings.`,void 0!==r&&mI(r,a),void 0!==t.enumNames&&t.enumNames.length!==t.enum.length)throw Error(`Form elicitation field "${e}" enumNames length must match enum length.`);if(mC(t.default,`Form elicitation field "${e}" default must be a string.`),void 0!==t.default&&!t.enum.includes(t.default))throw Error(`Form elicitation field "${e}" default must be one of its enum values.`);return}if("string"===t.type&&!("enum"in t)){mP(t,mS,`Form elicitation field "${e}"`),mO(t.minLength,`Form elicitation field "${e}" minLength must be a number.`),mO(t.maxLength,`Form elicitation field "${e}" maxLength must be a number.`),mC(t.default,`Form elicitation field "${e}" default must be a string.`);let r=t.format;if(mC(r,`Form elicitation field "${e}" format must be a string.`),void 0!==r&&!mk.has(r))throw Error(`Form elicitation field "${e}" format must be one of: ${Array.from(mk).join(", ")}.`);return}if("boolean"===t.type){if(mP(t,mw,`Form elicitation field "${e}"`),void 0!==t.default&&"boolean"!=typeof t.default)throw Error(`Form elicitation field "${e}" default must be a boolean.`);return}if("number"===t.type||"integer"===t.type){mP(t,mR,`Form elicitation field "${e}"`),mO(t.minimum,`Form elicitation field "${e}" minimum must be a number.`),mO(t.maximum,`Form elicitation field "${e}" maximum must be a number.`),mO(t.default,`Form elicitation field "${e}" default must be a number.`);return}throw Error(`Form elicitation field "${e}" uses unsupported type "${String(t.type)}". Supported types are string, boolean, number, integer, and string enums.`)}(e,r);if(void 0!==t.required){if(!Array.isArray(t.required)||t.required.some(e=>"string"!=typeof e))throw Error("Form elicitation schema required fields must be a string array.");for(let e of t.required)if(!(e in t.properties))throw Error(`Form elicitation schema required field "${e}" is not defined in properties.`)}}(e),{...e,mode:"form"}}(t);try{let t=await e.mcpReq.elicitInput(a,r);return{...t,content:t.content??void 0}}catch(e){if(e instanceof oR&&e.code===ow.MethodNotSupportedByProtocolVersion)throw Error("extra.elicit() is not available on protocol revision 2026-07-28: server-initiated elicitation was replaced by multi round-trip requests. Return inputRequired({ ... }) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw e}}function mP(e,t,r){let a=Object.keys(e).filter(e=>!t.has(e));if(0!==a.length)throw Error(`${r} includes unsupported key(s): ${a.join(", ")}.`)}function mE(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}function mT(e,t){if("string"!=typeof e)throw Error(t)}function mj(e,t){if("string"!=typeof e||0===e.trim().length)throw Error(t)}function mC(e,t){if(void 0!==e&&"string"!=typeof e)throw Error(t)}function mO(e,t){if(void 0!==e&&"number"!=typeof e)throw Error(t)}function mI(e,t){if(!Array.isArray(e)||e.some(e=>"string"!=typeof e))throw Error(t)}let mN=new Set(["_meta","includeContext","maxTokens","messages","metadata","modelPreferences","stopSequences","systemPrompt","temperature"]),mq=new Set(["task","toolChoice","tools"]),mA=new Set(["text","image","audio"]);async function mz(e,t,r){let a=function(e){mM(e,"Sampling request must be a plain object.");let t=Object.keys(e),r=t.filter(e=>mq.has(e));if(r.length>0)throw Error(`Sampling request key(s) not supported by xmcp yet: ${r.join(", ")}.`);let a=t.filter(e=>!mN.has(e));if(a.length>0)throw Error(`Sampling request includes unsupported key(s): ${a.join(", ")}.`);if(!Array.isArray(e.messages)||0===e.messages.length)throw Error("Sampling requires at least one message.");for(let[t,r]of e.messages.entries())!function(e,t){if(mM(t,`Sampling message at index ${e} must be a plain object.`),"user"!==t.role&&"assistant"!==t.role)throw Error(`Sampling message at index ${e} requires role "user" or "assistant".`);let r=t.content;mM(r,`Sampling message at index ${e} requires a content object.`);let a=r.type;if("string"!=typeof a||!mA.has(a))throw Error(`Sampling message at index ${e} uses unsupported content type "${String(a)}". Supported types are text, image, and audio.`);if("text"===a&&"string"!=typeof r.text)throw Error(`Sampling message at index ${e} requires string text content.`);if(("image"===a||"audio"===a)&&("string"!=typeof r.data||"string"!=typeof r.mimeType))throw Error(`Sampling message at index ${e} requires base64 data and a mimeType.`)}(t,r);if("number"!=typeof e.maxTokens)throw Error("Sampling requires a numeric maxTokens.");return e}(t);try{return await e.mcpReq.requestSampling(a,r)}catch(e){if(e instanceof oR&&e.code===ow.MethodNotSupportedByProtocolVersion)throw Error("extra.sample() is not available on protocol revision 2026-07-28: server-initiated sampling was replaced by multi round-trip requests. Return inputRequired({ ... }) with inputRequired.createMessage(...) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw e}}function mM(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}let mL={text:e=>"string"!=typeof e.text?{valid:!1,error:'Text content must have a "text" property of type string'}:{valid:!0},image:e=>"string"!=typeof e.data?{valid:!1,error:'Image content must have a "data" property of type string (base64-encoded image)'}:"string"!=typeof e.mimeType?{valid:!1,error:'Image content must have a "mimeType" property of type string'}:{valid:!0},audio:e=>"string"!=typeof e.data?{valid:!1,error:'Audio content must have a "data" property of type string (base64-encoded audio)'}:"string"!=typeof e.mimeType?{valid:!1,error:'Audio content must have a "mimeType" property of type string'}:{valid:!0},resource_link:e=>"string"!=typeof e.name?{valid:!1,error:'Resource link content must have a "name" property of type string'}:"string"!=typeof e.uri?{valid:!1,error:'Resource link content must have a "uri" property of type string'}:void 0!==e.title&&"string"!=typeof e.title?{valid:!1,error:'Resource link "title" property must be a string if provided'}:void 0!==e.description&&"string"!=typeof e.description?{valid:!1,error:'Resource link "description" property must be a string if provided'}:void 0!==e.mimeType&&"string"!=typeof e.mimeType?{valid:!1,error:'Resource link "mimeType" property must be a string if provided'}:{valid:!0}};function mZ(e){if(!e||"object"!=typeof e)return{valid:!1,error:"Content must be an object"};if("string"!=typeof e.type)return{valid:!1,error:'Content must have a "type" property of type string'};if(void 0!==e._meta&&(null===e._meta||"object"!=typeof e._meta))return{valid:!1,error:'Content "_meta" property must be an object if provided'};let t=mL[e.type];return t?t(e):{valid:!0}}function mV(e,t,r,a){if(null===e||"object"!=typeof e||Array.isArray(e))throw Error(`Tool "${r}" ${a}: expected a plain object.`);let i=new Set(Object.keys(t)),n=Object.keys(e).filter(e=>!i.has(e));if(n.length>0)throw Error(`Tool "${r}" ${a}: unrecognized key(s): ${n.join(", ")}`);for(let[i,n]of Object.entries(t))try{n.parse(e[i])}catch(e){throw Error(`Tool "${r}" ${a}: ${e?.message??`invalid field "${i}"`}`)}}function mD(e){return!!(e&&"object"==typeof e&&Object.keys(e).some(e=>e.startsWith("ui/")))}function mU(e){let t=e.mcpReq.envelope,r=mf(t?.[iP]);if(!r)try{let e,t=mu();r=t.clientInfo??(e=t.headers,mf({name:my(e,"x-mcp-client-name"),version:my(e,"x-mcp-client-version"),title:my(e,"x-mcp-client-title"),websiteUrl:my(e,"x-mcp-client-website-url"),description:my(e,"x-mcp-client-description")}))}catch{}if(!r)try{r=mm().clientInfo}catch{}return r}function mF(e){return e.endsWith(".tsx")}let mH=new class{add(e,t){this.resources.set(e,t)}getAll(){return this.resources}clear(){this.resources.clear()}has(e){return this.resources.has(e)}constructor(){var e,t;e="resources",t=new Map,e in this?Object.defineProperty(this,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):this[e]=t}};function mJ(e){let t={};return!function e(r,a=""){if(r&&"object"==typeof r)for(let[i,n]of Object.entries(r)){let r=a?`${a}/${i}`:i;!n||"object"!=typeof n||Array.isArray(n)||n instanceof Date||n instanceof RegExp?t[r]=n:e(n,r)}}(e),t}let mB=["ui/resourceUri","resourceUri","visibility"],mK=["prefersBorder","domain","csp","permissions","connectDomains","resourceDomains","frameDomains","baseUriDomains"],mG=ml({name:"request-context",fallback:!1});function mW(e){let t=[...e];return(e,r,a)=>(function(e,t,r){let a,i=new Map;if(e.http){let e=mu(),t=Object.fromEntries(Object.entries(e.headers).map(([e,t])=>[e,Array.isArray(t)?Object.freeze([...t]):t]));a=Object.freeze({id:e.id,headers:Object.freeze(t)})}return mG.provider(Object.freeze({clientInfo:t?Object.freeze({...t}):void 0,http:a,signal:e.mcpReq.signal,set(e,t){i.set(e,t)},get:e=>i.get(e),async progress(t,r){let a=e.mcpReq._meta?.progressToken;void 0!==a&&await e.mcpReq.notify({method:"notifications/progress",params:{progressToken:a,progress:t,...void 0===r?{}:{total:r}}})},log:(t,r)=>e.mcpReq.log(t,r)}),r)})(r,mU(r),async()=>{if(0===t.length)return a();let r=Object.freeze({...function(){try{return mG.getContext()}catch{throw Error("getRequestContext() can only be used while handling an MCP request.")}}(),method:e.method,params:Object.freeze({...e.params})}),i=-1,n=async e=>{if(e<=i)throw Error("MCP middleware next() can only be called once");i=e;let s=t[e];return s?s(r,()=>n(e+1)):a()};return n(0)})}let mX=new Set(["tools/list","prompts/get","prompts/list","resources/read","resources/list","resources/templates/list","completion/complete"]);function mY(e){return"object"==typeof e&&null!==e&&Object.entries(e).every(([e,t])=>"string"==typeof e&&"object"==typeof t&&null!==t&&"parse"in t&&"function"==typeof t.parse)}function mQ(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}function m0(e){let t=e.split("/").filter(e=>""!==e),r=t.findIndex(e=>e.match(/^\(.+\)$/));if(-1===r)return null;let a=t[t.length-1];if(a&&a.match(/^\[.+\]\.ts$/))return null;let i=t[r].slice(1,-1),n=t.slice(r+1),s=n[n.length-1];if(s&&s.includes(".")){let e=s.split(".")[0];"index"!==e?n[n.length-1]=e:n.pop()}let o=[],l=[],c=n.map(e=>{if(!e.match(/^\[.+\]$/))return l.push(e),e;{let t=e.slice(1,-1);return o.push(t),`{${t}}`}}),u=`${i}://${c.join("/")}`,d=o.length>0?"template":"direct";return{filePath:e,uriTemplate:u,scheme:i,parameters:o,pathSegments:l,type:d}}function m1(e){let t=e.replace(/\\/g,"/");if(!t)throw Error("Invalid tool path: path is empty");let r=t.replace(/\.[^/.]+$/,"").replace(/\//g,"_");return{normalizedPath:t,baseName:r}}function m2(e){return Error(`[xmcp] Invalid prompt file: ${e}
89
- -> Default export must be a prompt handler function.`)}async function m9(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw m2(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw m2(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default prompt handler."}}:{skipped:!1,path:e,promptModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.promptModule)}return{promptModules:t,skippedPrompts:r}}let m4=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load prompt file: ${t}
90
- -> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} prompt${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function m3(e){return Error(`[xmcp] Invalid resource file: ${e}
91
- -> Default export must be a resource handler function.`)}async function m6(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw m3(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw m3(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default resource handler."}}:{skipped:!1,path:e,resourceModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.resourceModule)}return{resourceModules:t,skippedResources:r}}let m5=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load resource file: ${t}
92
- -> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} resource${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function m8(e){return Error(`[xmcp] Invalid tool file: ${e}
93
- -> Default export must be a tool handler function.`)}async function m7(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw m8(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw m8(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default tool handler."}}:{skipped:!1,path:e,toolModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.toolModule)}return{toolModules:t,skippedTools:r}}let he=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load tool file: ${t}
94
- -> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} tool${1===i?"":"s"} skipped due to empty files or missing default exports`)}}(),ht=INJECTED_TOOLS,hr=INJECTED_PROMPTS,ha=INJECTED_RESOURCES,hi=SERVER_INFO;async function hn(e,t,r,a){let n=await INJECTED_MIDDLEWARE?.(),s=function(e){if(void 0===e)return[];let t=Array.isArray(e)?[...e]:[e];if(!t.every(e=>"function"==typeof e))throw Error("src/middleware.ts must export mcp as a function or an array of functions");return t}(n?.mcp);return mH.clear(),!function(e,t,r){let a=e.server,i=a.setRequestHandler,n=mW(t);a.setRequestHandler=(e,...t)=>{if(mX.has(e)&&1===t.length&&"function"==typeof t[0]){let e=t[0];t[0]=(t,r)=>n({method:t.method,params:t.params??{}},r,()=>e(t,r))}Reflect.apply(i,a,[e,...t])};try{r()}finally{a.setRequestHandler=i}}(e,s,()=>{!function(e,t,r=[]){t.forEach((t,a)=>{var i,n;let s,o,l,c={name:mQ(a),description:"No description provided"},{default:u,metadata:d,schema:p,outputSchema:m}=t;if("object"==typeof d&&null!==d&&Object.assign(c,d),"function"==typeof u&&"__x402"in u){let e=global.__XMCP_X402_REGISTRY;e&&e.set(c.name,u.__x402)}let h={};if(mY(p)?h=p:null!=p&&console.warn(`Invalid schema for tool "${c.name}" at ${a}. Expected Record<string, z.ZodType>`),null!=m)if(mY(m))s=m;else throw Error(`Invalid outputSchema for tool "${c.name}" at ${a}. Expected Record<string, z.ZodType>`);c.annotations={...c.annotations??{}},void 0===c.annotations.title&&(c.annotations.title=c.name),void 0===c._meta&&(c._meta={});let f=mF(a),g=!!(i=c._meta)&&"object"==typeof i&&"ui"in i&&"object"==typeof i.ui||f,y=c._meta;if(g){let e=`ui://app/${c.name}.html`;c._meta.ui||(c._meta.ui={}),c._meta.ui.resourceUri||(c._meta.ui.resourceUri=e);let t=function(e){let t={},r={};if(e.ui&&"object"==typeof e.ui){let a=e.ui,i={},n={};for(let[e,t]of Object.entries(a))mB.includes(e)?i[e]=t:mK.includes(e)?n[e]=t:i[e]=t;Object.keys(i).length>0&&(t.ui=i),Object.keys(n).length>0&&(r.ui=n)}for(let[r,a]of Object.entries(e))"ui"!==r&&(t[r]=a);return{toolMeta:t,resourceMeta:r}}(y);y=t.toolMeta;let r=t.resourceMeta;r.ui=r.ui||{},r.ui.csp=r.ui.csp||{},r.ui.csp.resourceDomains=r.ui.csp.resourceDomains||[],r.ui.csp.resourceDomains.includes("https://esm.sh")||r.ui.csp.resourceDomains.push("https://esm.sh"),mH.add(c.name,{name:c.name,uri:e,handler:u,mimeType:"text/html;profile=mcp-app",_meta:r,toolPath:f?a:void 0})}let v=mJ(y),_=g?v:void 0;o=mF(a)&&g?async(e,t)=>({content:[{type:"text",text:""}],_meta:_,structuredContent:{args:e}}):function(e,t,r,a="unknown-tool"){return async(i,n)=>{let s,o,l=e(i,(s=mU(n),o=function(e){if(!e)return;let t={};return e.headers.forEach((e,r)=>{t[r]=e}),t}(n.http?.req),{signal:n.mcpReq.signal,authInfo:n.http?.authInfo,sessionId:n.sessionId,_meta:n.mcpReq._meta,requestId:n.mcpReq.id,requestInfo:o?{headers:o}:void 0,clientInfo:s,sendNotification:e=>n.mcpReq.notify(e),sendRequest:(e,t,r)=>n.mcpReq.send(e,t,r),elicit:(e,t)=>mx(n,e,t),sample:(e,t)=>mz(n,e,t),inputResponses:n.mcpReq.inputResponses,requestState:n.mcpReq.requestState}));if(l instanceof Promise&&(l=await l),lT(l))return l;if("string"==typeof l||"number"==typeof l){if(r){let e=Object.entries(r);if(1===e.length){let[t,r]=e[0];try{return r.parse(l),{content:[{type:"text",text:"number"==typeof l?`${l}`:l}],structuredContent:{[t]:l}}}catch{}}}return mD(t)?{content:[{type:"text",text:""}],structuredContent:{args:i},_meta:t}:{content:[{type:"text",text:"number"==typeof l?`${l}`:l}]}}if(!r||!l||"object"!=typeof l||Array.isArray(l)||"structuredContent"in l||"content"in l&&Array.isArray(l.content)||"_meta"in l||"isError"in l||(mV(l,r,a,"returned data that does not match outputSchema"),l={structuredContent:l}),l&&"object"==typeof l&&"_meta"in l&&!("content"in l)&&!("structuredContent"in l)){let e=l._meta;if(mD(e))return{content:[{type:"text",text:""}],_meta:e}}if(!l||"object"!=typeof l){let e=null===l?"null":typeof l,t=void 0===l?"undefined":null===l?"null":"object"==typeof l?JSON.stringify(l,null,2):String(l);throw Error(`Tool handler must return a CallToolResult, string, or number. Got ${e}: ${t}
88
+ ]`;continue}i+=a[e],"\\"===a[e]?n=!0:s&&"]"===a[e]?s=!1:s||"["!==a[e]||(s=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function p8(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===x.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,a)=>({...r,[a]:mt(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??pV(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:mt(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===x.ZodString&&e.keyType._def.checks?.length){let{type:a,...i}=p2(e.keyType._def,t);return{...r,propertyNames:i}}if(e.keyType?._def.typeName===x.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===x.ZodBranded&&e.keyType._def.type._def.typeName===x.ZodString&&e.keyType._def.type._def.checks?.length){let{type:a,...i}=pF(e.keyType._def,t);return{...r,propertyNames:i}}return r}let p7={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},me=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>mt(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function mt(e,t,r=!1){let a=t.seen.get(e);if(t.override){let i=t.override?.(e,t,a,r);if(i!==dC)return i}if(a&&!r){let e=mr(a,t);if(void 0!==e)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let n=((e,t,r)=>{switch(t){case x.ZodString:return p2(e,r);case x.ZodNumber:let a={type:"number"};if(!e.checks)return a;for(let t of e.checks)switch(t.kind){case"int":a.type="integer",pD(a,"type",t.message,r);break;case"min":"jsonSchema7"===r.target?t.inclusive?pU(a,"minimum",t.value,t.message,r):pU(a,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(a.exclusiveMinimum=!0),pU(a,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?pU(a,"maximum",t.value,t.message,r):pU(a,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(a.exclusiveMaximum=!0),pU(a,"maximum",t.value,t.message,r));break;case"multipleOf":pU(a,"multipleOf",t.value,t.message,r)}return a;case x.ZodObject:return function(e,t){let r="openAi"===t.target,a={type:"object",properties:{}},i=[],n=e.shape();for(let e in n){let s=n[e];if(void 0===s||void 0===s._def)continue;let o=function(e){try{return e.isOptional()}catch{return!0}}(s);o&&r&&("ZodOptional"===s._def.typeName&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),o=!1);let l=mt(s._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==l&&(a.properties[e]=l,o||i.push(e))}i.length&&(a.required=i);let s=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return mt(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==s&&(a.additionalProperties=s),a}(e,r);case x.ZodBigInt:let i={type:"integer",format:"int64"};if(!e.checks)return i;for(let t of e.checks)switch(t.kind){case"min":"jsonSchema7"===r.target?t.inclusive?pU(i,"minimum",t.value,t.message,r):pU(i,"exclusiveMinimum",t.value,t.message,r):(t.inclusive||(i.exclusiveMinimum=!0),pU(i,"minimum",t.value,t.message,r));break;case"max":"jsonSchema7"===r.target?t.inclusive?pU(i,"maximum",t.value,t.message,r):pU(i,"exclusiveMaximum",t.value,t.message,r):(t.inclusive||(i.exclusiveMaximum=!0),pU(i,"maximum",t.value,t.message,r));break;case"multipleOf":pU(i,"multipleOf",t.value,t.message,r)}return i;case x.ZodBoolean:return{type:"boolean"};case x.ZodDate:return function e(t,r,a){let i=a??r.dateStrategy;if(Array.isArray(i))return{anyOf:i.map((a,i)=>e(t,r,a))};switch(i){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":var n=t,s=r;let o={type:"integer",format:"unix-time"};if("openApi3"===s.target)return o;for(let e of n.checks)switch(e.kind){case"min":pU(o,"minimum",e.value,e.message,s);break;case"max":pU(o,"maximum",e.value,e.message,s)}return o}}(e,r);case x.ZodUndefined:return{not:pV(r)};case x.ZodNull:return"openApi3"===r.target?{enum:["null"],nullable:!0}:{type:"null"};case x.ZodArray:let n;return n={type:"array"},e.type?._def&&e.type?._def?.typeName!==x.ZodAny&&(n.items=mt(e.type._def,{...r,currentPath:[...r.currentPath,"items"]})),e.minLength&&pU(n,"minItems",e.minLength.value,e.minLength.message,r),e.maxLength&&pU(n,"maxItems",e.maxLength.value,e.maxLength.message,r),e.exactLength&&(pU(n,"minItems",e.exactLength.value,e.exactLength.message,r),pU(n,"maxItems",e.exactLength.value,e.exactLength.message,r)),n;case x.ZodUnion:case x.ZodDiscriminatedUnion:if("openApi3"===r.target)return me(e,r);let s=e.options instanceof Map?Array.from(e.options.values()):e.options;if(s.every(e=>e._def.typeName in p7&&(!e._def.checks||!e._def.checks.length))){let e=s.reduce((e,t)=>{let r=p7[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(s.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){let e=s.reduce((e,t)=>{let r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}},[]);if(e.length===s.length){let t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:s.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(s.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:s.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return me(e,r);case x.ZodIntersection:let o,l,c;return o=[mt(e.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),mt(e.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(e=>!!e),l="jsonSchema2019-09"===r.target?{unevaluatedProperties:!1}:void 0,c=[],o.forEach(e=>{if((!("type"in e)||"string"!==e.type)&&"allOf"in e)c.push(...e.allOf),void 0===e.unevaluatedProperties&&(l=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){let{additionalProperties:r,...a}=e;t=a}else l=void 0;c.push(t)}}),c.length?{allOf:c,...l}:void 0;case x.ZodTuple:return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,t)=>mt(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:mt(e.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,t)=>mt(e._def,{...r,currentPath:[...r.currentPath,"items",`${t}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])};case x.ZodRecord:return p8(e,r);case x.ZodLiteral:let u;return"bigint"!=(u=typeof e.value)&&"number"!==u&&"boolean"!==u&&"string"!==u?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===r.target?{type:"bigint"===u?"integer":u,enum:[e.value]}:{type:"bigint"===u?"integer":u,const:e.value};case x.ZodEnum:return{type:"string",enum:Array.from(e.values)};case x.ZodNativeEnum:let d,p,m;return d=e.values,{type:1===(m=Array.from(new Set((p=Object.keys(e.values).filter(e=>"number"!=typeof d[d[e]]).map(e=>d[e])).map(e=>typeof e)))).length?"string"===m[0]?"string":"number":["string","number"],enum:p};case x.ZodNullable:if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===r.target?{type:p7[e.innerType._def.typeName],nullable:!0}:{type:[p7[e.innerType._def.typeName],"null"]};if("openApi3"===r.target){let t=mt(e.innerType._def,{...r,currentPath:[...r.currentPath]});return t&&"$ref"in t?{allOf:[t],nullable:!0}:t&&{...t,nullable:!0}}let h=mt(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return h&&{anyOf:[h,{type:"null"}]};case x.ZodOptional:if(r.currentPath.toString()===r.propertyPath?.toString())return mt(e.innerType._def,r);let f=mt(e.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return f?{anyOf:[{not:pV(r)},f]}:pV(r);case x.ZodMap:if("record"===r.mapStrategy)return p8(e,r);return{type:"array",maxItems:125,items:{type:"array",items:[mt(e.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||pV(r),mt(e.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||pV(r)],minItems:2,maxItems:2}};case x.ZodSet:let g;return g={type:"array",uniqueItems:!0,items:mt(e.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})},e.minSize&&pU(g,"minItems",e.minSize.value,e.minSize.message,r),e.maxSize&&pU(g,"maxItems",e.maxSize.value,e.maxSize.message,r),g;case x.ZodLazy:return()=>e.getter()._def;case x.ZodPromise:return mt(e.type._def,r);case x.ZodNaN:case x.ZodNever:return"openAi"===r.target?void 0:{not:pV({...r,currentPath:[...r.currentPath,"not"]})};case x.ZodEffects:return"input"===r.effectStrategy?mt(e.schema._def,r):pV(r);case x.ZodAny:case x.ZodUnknown:return pV(r);case x.ZodDefault:return{...mt(e.innerType._def,r),default:e.defaultValue()};case x.ZodBranded:return pF(e,r);case x.ZodReadonly:case x.ZodCatch:return mt(e.innerType._def,r);case x.ZodPipeline:if("input"===r.pipeStrategy)return mt(e.in._def,r);if("output"===r.pipeStrategy)return mt(e.out._def,r);let y=mt(e.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),v=mt(e.out._def,{...r,currentPath:[...r.currentPath,"allOf",y?"1":"0"]});return{allOf:[y,v].filter(e=>void 0!==e)};case x.ZodFunction:case x.ZodVoid:case x.ZodSymbol:default:return}})(e,e.typeName,t),s="function"==typeof n?mt(n(),t):n;if(s&&ma(e,t,s),t.postProcess){let r=t.postProcess(s,e,t);return i.jsonSchema=s,r}return i.jsonSchema=s,s}let mr=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:pZ(t.currentPath,e.path)};case"none":case"seen":if(e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),pV(t);return"seen"===t.$refStrategy?pV(t):void 0}},ma=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);function mi(e,t={}){let{strict:r=!1}=t,a=Object.entries(e),i=e=>({target:t})=>{let i={},n=[];for(let[r,s]of a)i[r]=function(e,t,r){let a=e["~standard"];if(a.jsonSchema)return a.jsonSchema[r]({target:t});if("zod"===e["~standard"].vendor&&!("_zod"in e)&&"_def"in e){let r=((e,t)=>{let r,a,i=(a=void 0!==(r="string"==typeof t?{...dO,name:t}:{...dO,...t}).name?[...r.basePath,r.definitionPath,r.name]:r.basePath,{...r,flags:{hasReferencedOpenAiAnyType:!1},currentPath:a,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([e,t])=>[t._def,{def:t._def,path:[...r.basePath,r.definitionPath,e],jsonSchema:void 0}]))}),n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:mt(r._def,{...i,currentPath:[...i.basePath,i.definitionPath,t]},!0)??pV(i)}),{}):void 0,s="string"==typeof t?t:t?.nameStrategy==="title"?void 0:t?.name,o=mt(e._def,void 0===s?i:{...i,currentPath:[...i.basePath,i.definitionPath,s]},!1)??pV(i),l="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==l&&(o.title=l),i.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[i.openAiAnyTypeName]||(n[i.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===i.$refStrategy?"1":[...i.basePath,i.definitionPath,i.openAiAnyTypeName].join("/")}}));let c=void 0===s?n?{...o,[i.definitionPath]:n}:o:{$ref:[..."relative"===i.$refStrategy?[]:i.basePath,i.definitionPath,s].join("/"),[i.definitionPath]:{...n,[s]:o}};return"jsonSchema7"===i.target?c.$schema="http://json-schema.org/draft-07/schema#":("jsonSchema2019-09"===i.target||"openAi"===i.target)&&(c.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===i.target&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c})(e,{$refStrategy:"none",target:"openapi-3.0"===t?"openApi3":"jsonSchema7"});return delete r.$schema,r}if("zod"===a.vendor&&"_zod"in e)try{let t=r2(e);return delete t.$schema,t}catch(e){throw Error(`Failed to convert a zod schema to JSON Schema (zod v4 without "~standard.jsonSchema"). Upgrade to zod >= 4.2.0. Original error: ${e instanceof Error?e.message:String(e)}`)}throw Error(`Schema library "${a.vendor}" cannot be converted to JSON Schema. Use zod v3 (>= 3.25.76), zod >= 4.2.0, or a Standard Schema library implementing "~standard.jsonSchema".`)}(s,t,e),!function(e,t){if("function"!=typeof e.safeParse)return!1;try{let r=e.safeParse(void 0);return r.success&&("input"===t||void 0===r.data)}catch{return!1}}(s,e)&&n.push(r);let s={type:"object",properties:i};return n.length>0&&(s.required=n),r&&(s.additionalProperties=!1),s},n=async t=>{if("object"!=typeof t||null===t||Array.isArray(t))return{issues:[{message:"Expected an object."}]};let i={},n=[];for(let[e,r]of a){let a=await r["~standard"].validate(t[e]);if(a.issues)for(let t of a.issues)n.push({message:t.message,path:[e,...t.path??[]]});else(e in t||void 0!==a.value)&&(i[e]=a.value)}if(r)for(let r of Object.keys(t))r in e||n.push({message:`Unrecognized key: "${r}"`,path:[r]});return n.length>0?{issues:n}:{value:i}};return{shape:e,"~standard":{version:1,vendor:"xmcp",validate:n,jsonSchema:{input:i("input"),output:i("output")}}}}let mn=t("async_hooks"),ms=(e,t)=>{globalThis[e]=t},mo=e=>globalThis[e];function ml({name:e,fallback:t=!0}){let r=Symbol.for(`xmcp-context-${e}`),a=Symbol.for(`xmcp-context-${e}-fallback-store`);if(mo(r))return mo(r);let i=new mn.AsyncLocalStorage,n=globalThis[a]??{current:null};ms(a,n);let s={provider:(e,r)=>(t&&(n.current=e),i.run(e,r)),getContext:()=>{let r=i.getStore();if(r)return r;if(t&&n.current)return n.current;throw Error(`getContext() can only be used within the ${e} context.`)},setContext:r=>{let a=i.getStore()??(t?n.current:null);if(!a)throw Error(`setContext() can only be used within the ${e} context.`);Object.assign(a,r)}};return ms(r,s),s}let mc=ml({name:"http-request-context"});mc.setContext;let mu=mc.getContext,md=mc.provider,mp=ml({name:"client-info-context"});mp.setContext;let mm=mp.getContext;mp.provider;let mh=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),mf=e=>{if(!mh(e)||"string"!=typeof e.name||"string"!=typeof e.version)return;let t={name:e.name,version:e.version};return"string"==typeof e.title&&(t.title=e.title),"string"==typeof e.websiteUrl&&(t.websiteUrl=e.websiteUrl),"string"==typeof e.description&&(t.description=e.description),t},mg=e=>{if(e&&"initialize"===e.method&&mh(e.params))return mf(e.params.clientInfo)},my=(e,t)=>{let r=t.toLowerCase();for(let[t,a]of Object.entries(e)){if(t.toLowerCase()!==r)continue;let e=Array.isArray(a)?a[0]:a;if("string"!=typeof e)break;let i=e.trim();return i.length>0?i:void 0}},mv=new Set(["message","mode","requestedSchema"]),m_=new Set(["elicitationId","message","mode","url"]),mb=new Set(["properties","required","type"]),mS=new Set(["default","description","format","maxLength","minLength","title","type"]),m$=new Set(["default","description","enum","enumNames","title","type"]),mw=new Set(["default","description","title","type"]),mR=new Set(["default","description","maximum","minimum","title","type"]),mk=new Set(["date","date-time","email","uri"]);async function mx(e,t,r){let a=function(e){let t=e.mode??"form";if("url"===t)return function(e){let t;mE(e,"Elicitation request must be a plain object."),mP(e,m_,"URL elicitation"),mT(e.message,"URL elicitation requires a string message."),mj(e.elicitationId,"URL elicitation requires a non-empty elicitationId."),mj(e.url,"URL elicitation requires a non-empty URL.");try{t=new URL(e.url)}catch{throw Error("URL elicitation requires a valid http or https URL.")}if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error("URL elicitation requires a valid http or https URL.")}(e),e;if("form"!==t)throw Error(`Unsupported elicitation mode "${String(e.mode)}". Expected "form" or "url".`);return function(e){mE(e,"Elicitation request must be a plain object."),mP(e,mv,"Form elicitation"),mT(e.message,"Form elicitation requires a string message.");let t=e.requestedSchema;if(mE(t,"Form elicitation requires a flat object schema."),mP(t,mb,"Form elicitation schema"),"object"!==t.type)throw Error('Form elicitation schema must use type "object".');for(let[e,r]of(mE(t.properties,"Form elicitation schema requires a properties object."),Object.entries(t.properties)))!function(e,t){if(mE(t,`Form elicitation field "${e}" must be a plain object.`),mC(t.title,`Form elicitation field "${e}" title must be a string.`),mC(t.description,`Form elicitation field "${e}" description must be a string.`),"string"===t.type&&"enum"in t){var r,a;if(mP(t,m$,`Form elicitation field "${e}"`),mI(t.enum,`Form elicitation field "${e}" enum values must be strings.`),r=t.enumNames,a=`Form elicitation field "${e}" enumNames must be strings.`,void 0!==r&&mI(r,a),void 0!==t.enumNames&&t.enumNames.length!==t.enum.length)throw Error(`Form elicitation field "${e}" enumNames length must match enum length.`);if(mC(t.default,`Form elicitation field "${e}" default must be a string.`),void 0!==t.default&&!t.enum.includes(t.default))throw Error(`Form elicitation field "${e}" default must be one of its enum values.`);return}if("string"===t.type&&!("enum"in t)){mP(t,mS,`Form elicitation field "${e}"`),mO(t.minLength,`Form elicitation field "${e}" minLength must be a number.`),mO(t.maxLength,`Form elicitation field "${e}" maxLength must be a number.`),mC(t.default,`Form elicitation field "${e}" default must be a string.`);let r=t.format;if(mC(r,`Form elicitation field "${e}" format must be a string.`),void 0!==r&&!mk.has(r))throw Error(`Form elicitation field "${e}" format must be one of: ${Array.from(mk).join(", ")}.`);return}if("boolean"===t.type){if(mP(t,mw,`Form elicitation field "${e}"`),void 0!==t.default&&"boolean"!=typeof t.default)throw Error(`Form elicitation field "${e}" default must be a boolean.`);return}if("number"===t.type||"integer"===t.type){mP(t,mR,`Form elicitation field "${e}"`),mO(t.minimum,`Form elicitation field "${e}" minimum must be a number.`),mO(t.maximum,`Form elicitation field "${e}" maximum must be a number.`),mO(t.default,`Form elicitation field "${e}" default must be a number.`);return}throw Error(`Form elicitation field "${e}" uses unsupported type "${String(t.type)}". Supported types are string, boolean, number, integer, and string enums.`)}(e,r);if(void 0!==t.required){if(!Array.isArray(t.required)||t.required.some(e=>"string"!=typeof e))throw Error("Form elicitation schema required fields must be a string array.");for(let e of t.required)if(!(e in t.properties))throw Error(`Form elicitation schema required field "${e}" is not defined in properties.`)}}(e),{...e,mode:"form"}}(t);try{let t=await e.mcpReq.elicitInput(a,r);return{...t,content:t.content??void 0}}catch(e){if(e instanceof oR&&e.code===ow.MethodNotSupportedByProtocolVersion)throw Error("extra.elicit() is not available on protocol revision 2026-07-28: server-initiated elicitation was replaced by multi round-trip requests. Return inputRequired({ ... }) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw e}}function mP(e,t,r){let a=Object.keys(e).filter(e=>!t.has(e));if(0!==a.length)throw Error(`${r} includes unsupported key(s): ${a.join(", ")}.`)}function mE(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}function mT(e,t){if("string"!=typeof e)throw Error(t)}function mj(e,t){if("string"!=typeof e||0===e.trim().length)throw Error(t)}function mC(e,t){if(void 0!==e&&"string"!=typeof e)throw Error(t)}function mO(e,t){if(void 0!==e&&"number"!=typeof e)throw Error(t)}function mI(e,t){if(!Array.isArray(e)||e.some(e=>"string"!=typeof e))throw Error(t)}let mN=new Set(["_meta","includeContext","maxTokens","messages","metadata","modelPreferences","stopSequences","systemPrompt","temperature"]),mq=new Set(["task","toolChoice","tools"]),mA=new Set(["text","image","audio"]);async function mz(e,t,r){let a=function(e){mM(e,"Sampling request must be a plain object.");let t=Object.keys(e),r=t.filter(e=>mq.has(e));if(r.length>0)throw Error(`Sampling request key(s) not supported by xmcp yet: ${r.join(", ")}.`);let a=t.filter(e=>!mN.has(e));if(a.length>0)throw Error(`Sampling request includes unsupported key(s): ${a.join(", ")}.`);if(!Array.isArray(e.messages)||0===e.messages.length)throw Error("Sampling requires at least one message.");for(let[t,r]of e.messages.entries())!function(e,t){if(mM(t,`Sampling message at index ${e} must be a plain object.`),"user"!==t.role&&"assistant"!==t.role)throw Error(`Sampling message at index ${e} requires role "user" or "assistant".`);let r=t.content;mM(r,`Sampling message at index ${e} requires a content object.`);let a=r.type;if("string"!=typeof a||!mA.has(a))throw Error(`Sampling message at index ${e} uses unsupported content type "${String(a)}". Supported types are text, image, and audio.`);if("text"===a&&"string"!=typeof r.text)throw Error(`Sampling message at index ${e} requires string text content.`);if(("image"===a||"audio"===a)&&("string"!=typeof r.data||"string"!=typeof r.mimeType))throw Error(`Sampling message at index ${e} requires base64 data and a mimeType.`)}(t,r);if("number"!=typeof e.maxTokens)throw Error("Sampling requires a numeric maxTokens.");return e}(t);try{return await e.mcpReq.requestSampling(a,r)}catch(e){if(e instanceof oR&&e.code===ow.MethodNotSupportedByProtocolVersion)throw Error("extra.sample() is not available on protocol revision 2026-07-28: server-initiated sampling was replaced by multi round-trip requests. Return inputRequired({ ... }) with inputRequired.createMessage(...) from the tool handler instead (re-exported from xmcp); the client fulfils the embedded requests and retries the tool call.");throw e}}function mM(e,t){if("object"!=typeof e||null===e||Array.isArray(e))throw Error(t)}let mL={text:e=>"string"!=typeof e.text?{valid:!1,error:'Text content must have a "text" property of type string'}:{valid:!0},image:e=>"string"!=typeof e.data?{valid:!1,error:'Image content must have a "data" property of type string (base64-encoded image)'}:"string"!=typeof e.mimeType?{valid:!1,error:'Image content must have a "mimeType" property of type string'}:{valid:!0},audio:e=>"string"!=typeof e.data?{valid:!1,error:'Audio content must have a "data" property of type string (base64-encoded audio)'}:"string"!=typeof e.mimeType?{valid:!1,error:'Audio content must have a "mimeType" property of type string'}:{valid:!0},resource_link:e=>"string"!=typeof e.name?{valid:!1,error:'Resource link content must have a "name" property of type string'}:"string"!=typeof e.uri?{valid:!1,error:'Resource link content must have a "uri" property of type string'}:void 0!==e.title&&"string"!=typeof e.title?{valid:!1,error:'Resource link "title" property must be a string if provided'}:void 0!==e.description&&"string"!=typeof e.description?{valid:!1,error:'Resource link "description" property must be a string if provided'}:void 0!==e.mimeType&&"string"!=typeof e.mimeType?{valid:!1,error:'Resource link "mimeType" property must be a string if provided'}:{valid:!0}};function mZ(e){if(!e||"object"!=typeof e)return{valid:!1,error:"Content must be an object"};if("string"!=typeof e.type)return{valid:!1,error:'Content must have a "type" property of type string'};if(void 0!==e._meta&&(null===e._meta||"object"!=typeof e._meta))return{valid:!1,error:'Content "_meta" property must be an object if provided'};let t=mL[e.type];return t?t(e):{valid:!0}}function mV(e,t,r,a){if(null===e||"object"!=typeof e||Array.isArray(e))throw Error(`Tool "${r}" ${a}: expected a plain object.`);let i=new Set(Object.keys(t)),n=Object.keys(e).filter(e=>!i.has(e));if(n.length>0)throw Error(`Tool "${r}" ${a}: unrecognized key(s): ${n.join(", ")}`);for(let[i,n]of Object.entries(t))try{n.parse(e[i])}catch(e){throw Error(`Tool "${r}" ${a}: ${e?.message??`invalid field "${i}"`}`)}}function mD(e){return!!(e&&"object"==typeof e&&Object.keys(e).some(e=>e.startsWith("ui/")))}function mU(e){let t=e.mcpReq.envelope,r=mf(t?.[iP]);if(!r)try{let e,t=mu();r=t.clientInfo??(e=t.headers,mf({name:my(e,"x-mcp-client-name"),version:my(e,"x-mcp-client-version"),title:my(e,"x-mcp-client-title"),websiteUrl:my(e,"x-mcp-client-website-url"),description:my(e,"x-mcp-client-description")}))}catch{}if(!r)try{r=mm().clientInfo}catch{}return r}function mF(e){return e.endsWith(".tsx")}let mH=new class{add(e,t){this.resources.set(e,t)}getAll(){return this.resources}clear(){this.resources.clear()}has(e){return this.resources.has(e)}constructor(){var e,t;e="resources",t=new Map,e in this?Object.defineProperty(this,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):this[e]=t}};function mJ(e){let t={};return!function e(r,a=""){if(r&&"object"==typeof r)for(let[i,n]of Object.entries(r)){let r=a?`${a}/${i}`:i;!n||"object"!=typeof n||Array.isArray(n)||n instanceof Date||n instanceof RegExp?t[r]=n:e(n,r)}}(e),t}let mB=["ui/resourceUri","resourceUri","visibility"],mK=["prefersBorder","domain","csp","permissions","connectDomains","resourceDomains","frameDomains","baseUriDomains"],mG=ml({name:"request-context",fallback:!1});function mW(e){let t=[...e];return(e,r,a)=>(function(e,t,r){let a,i=new Map;if(e.http){let e=mu(),t=Object.fromEntries(Object.entries(e.headers).map(([e,t])=>[e,Array.isArray(t)?Object.freeze([...t]):t]));a=Object.freeze({id:e.id,headers:Object.freeze(t)})}return mG.provider(Object.freeze({clientInfo:t?Object.freeze({...t}):void 0,http:a,signal:e.mcpReq.signal,set(e,t){i.set(e,t)},get:e=>i.get(e),async progress(t,r){let a=e.mcpReq._meta?.progressToken;void 0!==a&&await e.mcpReq.notify({method:"notifications/progress",params:{progressToken:a,progress:t,...void 0===r?{}:{total:r}}})},log:(t,r)=>e.mcpReq.log(t,r)}),r)})(r,mU(r),async()=>{if(0===t.length)return a();let r=Object.freeze({...function(){try{return mG.getContext()}catch{throw Error("getRequestContext() can only be used while handling an MCP request.")}}(),method:e.method,params:Object.freeze({...e.params})}),i=-1,n=async e=>{if(e<=i)throw Error("MCP middleware next() can only be called once");i=e;let s=t[e];return s?s(r,()=>n(e+1)):a()};return n(0)})}let mX=new Set(["tools/list","prompts/get","prompts/list","resources/read","resources/list","resources/templates/list","completion/complete"]);function mY(e){let{tags:t,enabled:r,...a}=e;return{...a,_meta:void 0===t?a._meta:{...a._meta,"xmcp/tags":t}}}function mQ(e){return"object"==typeof e&&null!==e&&Object.entries(e).every(([e,t])=>"string"==typeof e&&"object"==typeof t&&null!==t&&"parse"in t&&"function"==typeof t.parse)}function m0(e){return(e.split("/").pop()||e).replace(/\.[^/.]+$/,"")}function m1(e){let t=e.split("/").filter(e=>""!==e),r=t.findIndex(e=>e.match(/^\(.+\)$/));if(-1===r)return null;let a=t[t.length-1];if(a&&a.match(/^\[.+\]\.ts$/))return null;let i=t[r].slice(1,-1),n=t.slice(r+1),s=n[n.length-1];if(s&&s.includes(".")){let e=s.split(".")[0];"index"!==e?n[n.length-1]=e:n.pop()}let o=[],l=[],c=n.map(e=>{if(!e.match(/^\[.+\]$/))return l.push(e),e;{let t=e.slice(1,-1);return o.push(t),`{${t}}`}}),u=`${i}://${c.join("/")}`,d=o.length>0?"template":"direct";return{filePath:e,uriTemplate:u,scheme:i,parameters:o,pathSegments:l,type:d}}function m2(e){let t=e.replace(/\\/g,"/");if(!t)throw Error("Invalid tool path: path is empty");let r=t.replace(/\.[^/.]+$/,"").replace(/\//g,"_");return{normalizedPath:t,baseName:r}}function m9(e){return Error(`[xmcp] Invalid prompt file: ${e}
89
+ -> Default export must be a prompt handler function.`)}async function m4(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw m9(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw m9(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default prompt handler."}}:{skipped:!1,path:e,promptModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.promptModule)}return{promptModules:t,skippedPrompts:r}}let m3=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load prompt file: ${t}
90
+ -> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} prompt${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function m6(e){return Error(`[xmcp] Invalid resource file: ${e}
91
+ -> Default export must be a resource handler function.`)}async function m5(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw m6(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw m6(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default resource handler."}}:{skipped:!1,path:e,resourceModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.resourceModule)}return{resourceModules:t,skippedResources:r}}let m8=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load resource file: ${t}
92
+ -> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} resource${1===i?"":"s"} skipped due to empty files or missing default exports`)}}();function m7(e){return Error(`[xmcp] Invalid tool file: ${e}
93
+ -> Default export must be a tool handler function.`)}async function he(e){let t=new Map,r=[];for(let a of(await Promise.all(Object.entries(e).map(async([e,t])=>{let r=await t(),a=function(e,t){if("object"!=typeof e||null===e)throw m7(t);let r=Object.keys(e),a=e.default,i=r.filter(e=>"__esModule"!==e);if(0===r.length||1===i.length&&"default"===i[0]&&"object"==typeof a&&null!==a&&0===Object.keys(a).length)return"empty";if(!("default"in e)||void 0===e.default)return"missing-default";if("function"!=typeof e.default)throw m7(t);return"valid"}(r,e);return"empty"===a?{skipped:!0,issue:{path:e,message:"File is empty."}}:"missing-default"===a?{skipped:!0,issue:{path:e,message:"File does not export a default tool handler."}}:{skipped:!1,path:e,toolModule:r}})))){if(a.skipped){r.push(a.issue);continue}t.set(a.path,a.toolModule)}return{toolModules:t,skippedTools:r}}let ht=function(e=console){let t="";return r=>{let a=r.map(({path:e,message:t})=>`${e}:${t}`).sort().join("|");if(a===t||(t=a,0===r.length))return;r.forEach(({path:t,message:r})=>{e.warn(`[xmcp] Failed to load tool file: ${t}
94
+ -> ${r}`)});let i=r.length;e.warn(`[xmcp] ${i} tool${1===i?"":"s"} skipped due to empty files or missing default exports`)}}(),hr=INJECTED_TOOLS,ha=INJECTED_PROMPTS,hi=INJECTED_RESOURCES,hn=SERVER_INFO;async function hs(e,t,r,a){let n=await INJECTED_MIDDLEWARE?.(),s=function(e){if(void 0===e)return[];let t=Array.isArray(e)?[...e]:[e];if(!t.every(e=>"function"==typeof e))throw Error("src/middleware.ts must export mcp as a function or an array of functions");return t}(n?.mcp);return mH.clear(),!function(e,t,r){let a=e.server,i=a.setRequestHandler,n=mW(t);a.setRequestHandler=(e,...t)=>{if(mX.has(e)&&1===t.length&&"function"==typeof t[0]){let e=t[0];t[0]=(t,r)=>n({method:t.method,params:t.params??{}},r,()=>e(t,r))}Reflect.apply(i,a,[e,...t])};try{r()}finally{a.setRequestHandler=i}}(e,s,()=>{!function(e,t,r=[]){t.forEach((t,a)=>{var i,n;let s,o,l,c={name:m0(a),description:"No description provided"},{default:u,metadata:d,schema:p,outputSchema:m}=t;if("object"==typeof d&&null!==d&&Object.assign(c,d),!1===c.enabled)return;if("function"==typeof u&&"__x402"in u){let e=global.__XMCP_X402_REGISTRY;e&&e.set(c.name,u.__x402)}let h={};if(mQ(p)?h=p:null!=p&&console.warn(`Invalid schema for tool "${c.name}" at ${a}. Expected Record<string, z.ZodType>`),null!=m)if(mQ(m))s=m;else throw Error(`Invalid outputSchema for tool "${c.name}" at ${a}. Expected Record<string, z.ZodType>`);c.annotations={...c.annotations??{}},void 0===c.annotations.title&&(c.annotations.title=c.name),c._meta={...mY(c)._meta};let f=mF(a),g=!!(i=c._meta)&&"object"==typeof i&&"ui"in i&&"object"==typeof i.ui||f,y=c._meta;if(g){let e=`ui://app/${c.name}.html`;c._meta.ui||(c._meta.ui={}),c._meta.ui.resourceUri||(c._meta.ui.resourceUri=e);let t=function(e){let t={},r={};if(e.ui&&"object"==typeof e.ui){let a=e.ui,i={},n={};for(let[e,t]of Object.entries(a))mB.includes(e)?i[e]=t:mK.includes(e)?n[e]=t:i[e]=t;Object.keys(i).length>0&&(t.ui=i),Object.keys(n).length>0&&(r.ui=n)}for(let[r,a]of Object.entries(e))"ui"!==r&&(t[r]=a);return{toolMeta:t,resourceMeta:r}}(y);y=t.toolMeta;let r=t.resourceMeta;r.ui=r.ui||{},r.ui.csp=r.ui.csp||{},r.ui.csp.resourceDomains=r.ui.csp.resourceDomains||[],r.ui.csp.resourceDomains.includes("https://esm.sh")||r.ui.csp.resourceDomains.push("https://esm.sh"),mH.add(c.name,{name:c.name,uri:e,handler:u,mimeType:"text/html;profile=mcp-app",_meta:r,toolPath:f?a:void 0})}let v=mJ(y),_=g?v:void 0;o=mF(a)&&g?async(e,t)=>({content:[{type:"text",text:""}],_meta:_,structuredContent:{args:e}}):function(e,t,r,a="unknown-tool"){return async(i,n)=>{let s,o,l=e(i,(s=mU(n),o=function(e){if(!e)return;let t={};return e.headers.forEach((e,r)=>{t[r]=e}),t}(n.http?.req),{signal:n.mcpReq.signal,authInfo:n.http?.authInfo,sessionId:n.sessionId,_meta:n.mcpReq._meta,requestId:n.mcpReq.id,requestInfo:o?{headers:o}:void 0,clientInfo:s,sendNotification:e=>n.mcpReq.notify(e),sendRequest:(e,t,r)=>n.mcpReq.send(e,t,r),elicit:(e,t)=>mx(n,e,t),sample:(e,t)=>mz(n,e,t),inputResponses:n.mcpReq.inputResponses,requestState:n.mcpReq.requestState}));if(l instanceof Promise&&(l=await l),lT(l))return l;if("string"==typeof l||"number"==typeof l){if(r){let e=Object.entries(r);if(1===e.length){let[t,r]=e[0];try{return r.parse(l),{content:[{type:"text",text:"number"==typeof l?`${l}`:l}],structuredContent:{[t]:l}}}catch{}}}return mD(t)?{content:[{type:"text",text:""}],structuredContent:{args:i},_meta:t}:{content:[{type:"text",text:"number"==typeof l?`${l}`:l}]}}if(!r||!l||"object"!=typeof l||Array.isArray(l)||"structuredContent"in l||"content"in l&&Array.isArray(l.content)||"_meta"in l||"isError"in l||(mV(l,r,a,"returned data that does not match outputSchema"),l={structuredContent:l}),l&&"object"==typeof l&&"_meta"in l&&!("content"in l)&&!("structuredContent"in l)){let e=l._meta;if(mD(e))return{content:[{type:"text",text:""}],_meta:e}}if(!l||"object"!=typeof l){let e=null===l?"null":typeof l,t=void 0===l?"undefined":null===l?"null":"object"==typeof l?JSON.stringify(l,null,2):String(l);throw Error(`Tool handler must return a CallToolResult, string, or number. Got ${e}: ${t}
95
95
 
96
96
  Expected CallToolResult format:
97
97
  {
@@ -158,7 +158,7 @@ Expected format:
158
158
  key: "value",
159
159
  nested: { data: "here" }
160
160
  }
161
- }`)}}return l}}(u,_,s,c.name);let b={title:c.annotations?.title,description:c.description,inputSchema:mi(h),outputSchema:s?mi(s,{strict:!0}):void 0,annotations:c.annotations,_meta:v};e.registerTool(c.name,b,(n=c.name,l=mW(r),(e,t)=>l({method:"tools/call",params:{name:n,arguments:e}},t,()=>o(e,t))))})}(e,t,s),r.forEach((t,r)=>{let a=mQ(r),i={name:a,title:a,description:"No description provided"},n={},{default:s,metadata:o,schema:l}=t;"object"==typeof o&&null!==o&&Object.assign(i,o);let c=function(e,t="assistant"){return async(r,a)=>{let i,n=e(r,a);if(n instanceof Promise&&(n=await n),Array.isArray(n)||null!==n&&"object"==typeof n&&"messages"in n){let e=Array.isArray(n)?{messages:n}:n,t=await ct.GetPromptResult["~standard"].validate(e);if(t.issues){let e=t.issues.map(e=>{let t=e.path?.map(e=>"object"==typeof e?e.key:e).join(".");return`${t||"result"}: ${e.message}`});throw Error(`Invalid prompt result: ${e.join("; ")}`)}return e}if("string"==typeof n||"number"==typeof n)i={type:"text",text:"number"==typeof n?`${n}`:n};else{let e=mZ(n);if(e.valid)i=n;else{let t=null===n?"null":typeof n,r=void 0===n?"undefined":null===n?"null":"object"==typeof n?JSON.stringify(n,null,2):String(n);throw Error(`Prompt handler must return a PromptContent object, string, number, PromptMessage[], or GetPromptResult. Got ${t}: ${r}
161
+ }`)}}return l}}(u,_,s,c.name);let b={title:c.annotations?.title,description:c.description,inputSchema:mi(h),outputSchema:s?mi(s,{strict:!0}):void 0,annotations:c.annotations,icons:c.icons,_meta:v};e.registerTool(c.name,b,(n=c.name,l=mW(r),(e,t)=>l({method:"tools/call",params:{name:n,arguments:e}},t,()=>o(e,t))))})}(e,t,s),r.forEach((t,r)=>{let a=m0(r),i={name:a,title:a,description:"No description provided"},n={},{default:s,metadata:o,schema:l}=t;if("object"==typeof o&&null!==o&&Object.assign(i,o),!1===i.enabled)return;let c=function(e,t="assistant"){return async(r,a)=>{let i,n=e(r,a);if(n instanceof Promise&&(n=await n),Array.isArray(n)||null!==n&&"object"==typeof n&&"messages"in n){let e=Array.isArray(n)?{messages:n}:n,t=await ct.GetPromptResult["~standard"].validate(e);if(t.issues){let e=t.issues.map(e=>{let t=e.path?.map(e=>"object"==typeof e?e.key:e).join(".");return`${t||"result"}: ${e.message}`});throw Error(`Invalid prompt result: ${e.join("; ")}`)}return e}if("string"==typeof n||"number"==typeof n)i={type:"text",text:"number"==typeof n?`${n}`:n};else{let e=mZ(n);if(e.valid)i=n;else{let t=null===n?"null":typeof n,r=void 0===n?"undefined":null===n?"null":"object"==typeof n?JSON.stringify(n,null,2):String(n);throw Error(`Prompt handler must return a PromptContent object, string, number, PromptMessage[], or GetPromptResult. Got ${t}: ${r}
162
162
 
163
163
  Validation error: ${e.error}
164
164
 
@@ -171,7 +171,7 @@ Expected formats:
171
171
  - Image content: { type: "image", data: "base64data", mimeType: "image/jpeg" }
172
172
  - Audio content: { type: "audio", data: "base64data", mimeType: "audio/mpeg" }
173
173
  - Resource link: { type: "resource_link", name: "resource name", uri: "resource://uri" }
174
- - All content types support an optional "_meta" object property`)}}if("user"!==t&&"assistant"!==t)throw Error(`Invalid role: ${t}`);return{messages:[{role:t,content:i}]}}}(s,i.role||"assistant");mY(l)?Object.assign(n,l):null!=l&&console.warn(`Invalid schema for prompt "${i.name}" at ${r}. Expected Record<string, z.ZodType>`),e.registerPrompt(i.name,{title:i.title,description:i.description,argsSchema:mi(n)},c)}),[...mH.getAll()].forEach(([t,r])=>{let a=r.mimeType||"text/html;profile=mcp-app",n=r?._meta?mJ(r._meta):void 0,s={name:r.name,description:`Auto-generated resource for ${r.name} tool`,mimeType:r.mimeType,_meta:n},o=async(e,t)=>{if(r.mimeType&&r.toolPath)try{var n;let e,t,s=(n=r.toolPath,IS_CLOUDFLARE?function(e){let{normalizedPath:t,baseName:r}=m1(e),a=5381;for(let e=0;e<t.length;e++)a=Math.imul(a,33)+t.charCodeAt(e)>>>0;let i=a.toString(16).slice(0,6).padStart(6,"0");return`${r}_${i}`}(n):function(e){let{normalizedPath:t,baseName:r}=m1(e),a=i(6982).createHash("md5").update(t).digest("hex").slice(0,6);return`${r}_${a}`}(n)),o=function(e){if(INJECTED_CLIENT_BUNDLES)return INJECTED_CLIENT_BUNDLES[e]||null;if(!IS_CLOUDFLARE)try{let t=i(9896),r=i(6928);for(let a of[r.join(process.cwd(),"dist","client"),r.join(process.cwd(),"client")]){let i=r.join(a,`${e}.bundle.js`),n=r.join(a,`${e}.bundle.css`);if(t.existsSync(i)){let e,r=t.readFileSync(i,"utf-8");return t.existsSync(n)&&(e=t.readFileSync(n,"utf-8")),{js:r,css:e}}}}catch{}return null}(s);if(!o)throw Error(`React client bundle not found for "${r.name}" (bundle: "${s}").
174
+ - All content types support an optional "_meta" object property`)}}if("user"!==t&&"assistant"!==t)throw Error(`Invalid role: ${t}`);return{messages:[{role:t,content:i}]}}}(s,i.role||"assistant");mQ(l)?Object.assign(n,l):null!=l&&console.warn(`Invalid schema for prompt "${i.name}" at ${r}. Expected Record<string, z.ZodType>`),e.registerPrompt(i.name,{title:i.title,description:i.description,icons:i.icons,_meta:mY(i)._meta,argsSchema:mi(n)},c)}),[...mH.getAll()].forEach(([t,r])=>{let a=r.mimeType||"text/html;profile=mcp-app",n=r?._meta?mJ(r._meta):void 0,s={name:r.name,description:`Auto-generated resource for ${r.name} tool`,mimeType:r.mimeType,_meta:n},o=async(e,t)=>{if(r.mimeType&&r.toolPath)try{var n;let e,t,s=(n=r.toolPath,IS_CLOUDFLARE?function(e){let{normalizedPath:t,baseName:r}=m2(e),a=5381;for(let e=0;e<t.length;e++)a=Math.imul(a,33)+t.charCodeAt(e)>>>0;let i=a.toString(16).slice(0,6).padStart(6,"0");return`${r}_${i}`}(n):function(e){let{normalizedPath:t,baseName:r}=m2(e),a=i(6982).createHash("md5").update(t).digest("hex").slice(0,6);return`${r}_${a}`}(n)),o=function(e){if(INJECTED_CLIENT_BUNDLES)return INJECTED_CLIENT_BUNDLES[e]||null;if(!IS_CLOUDFLARE)try{let t=i(9896),r=i(6928);for(let a of[r.join(process.cwd(),"dist","client"),r.join(process.cwd(),"client")]){let i=r.join(a,`${e}.bundle.js`),n=r.join(a,`${e}.bundle.css`);if(t.existsSync(i)){let e,r=t.readFileSync(i,"utf-8");return t.existsSync(n)&&(e=t.readFileSync(n,"utf-8")),{js:r,css:e}}}}catch{}return null}(s);if(!o)throw Error(`React client bundle not found for "${r.name}" (bundle: "${s}").
175
175
  React tool bundles are generated automatically when you run "xmcp build" (or "xmcp dev").
176
176
  Please re-run the build so the framework can regenerate the bundle.`);let l=o.js,c=o.css,u=(e=`
177
177
  <script type="module">
@@ -226,7 +226,7 @@ Please re-run the build so the framework can regenerate the bundle.`);let l=o.js
226
226
  <div id="root"></div>
227
227
  ${e}
228
228
  </body>
229
- </html>`);return{contents:[{uri:r.uri,text:u,mimeType:a,_meta:r._meta}]}}catch(e){throw console.error(`React failed for ${r.name}:`,e),e}let s=r.handler({},t);if(s instanceof Promise&&(s=await s),"string"==typeof s)return{contents:[{uri:r.uri,text:s,mimeType:a,_meta:r._meta}]};if(s&&"object"==typeof s&&"_meta"in s&&!("content"in s))return{contents:[{uri:r.uri,text:"",mimeType:a,_meta:r._meta}]};if(s&&"object"==typeof s&&"content"in s&&Array.isArray(s.content)){let e=s.content.find(e=>"text"===e.type);if(e&&"text"===e.type&&"string"==typeof e.text)return{contents:[{uri:r.uri,text:e.text,mimeType:a,_meta:r._meta}]}}return{contents:[{uri:r.uri,text:"",mimeType:a,_meta:r._meta}]}};e.registerResource(r.name,r.uri,s,o)}),a.forEach((t,r)=>{let a={name:mQ(r),description:"No description provided"},{default:i,metadata:n,schema:s,complete:o}=t;"object"==typeof n&&null!==n&&Object.assign(a,n);let l={};mY(s)?l=s:null!=s&&console.warn(`Invalid schema for resource "${a.name}" at ${r}. Expected Record<string, z.ZodType>`);let c=m0(r);if(!c)return void console.warn(`Skipping resource "${a.name}" at ${r}: Invalid file path format`);let u=c.uriTemplate;a.mimeType&&a.mimeType.includes("html")&&(u=u.endsWith(".html")?u:`${u}.html`);let d=function(e,t,r={}){let a=m0(t);if(!a)throw Error(`Invalid resource file path: ${t}. Must follow (scheme)/path/[param] convention.`);return async(t,i)=>{let n=e(function(e,t,r){let a={},i={};if(0===t.parameters.length)return i;let n=t.uriTemplate.split("://")[1]||"",s=e.split("://")[1]||"",o=n.split("/"),l=s.split("/");for(let e=0;e<o.length&&e<l.length;e++){let t=o[e],r=l[e],i=t.match(/^\{(.+)\}$/);i&&(a[i[1]]=r)}for(let e of t.parameters){let t=a[e],n=r[e];if(void 0===t)throw Error(`Missing required parameter: ${e}`);if(!n){i[e]=t;continue}try{i[e]=n.parse(t)}catch(r){throw Error(`Invalid parameter "${e}": ${t}. Validation error: ${r instanceof Error?r.message:String(r)}`)}}return i}(t.href,a,r),i);if(n instanceof Promise&&(n=await n),"string"==typeof n)return{contents:[{uri:t.href,text:n}]};if(!n||"object"!=typeof n||!Array.isArray(n.contents)){let e=null===n?"null":typeof n,t=void 0===n?"undefined":null===n?"null":"object"==typeof n?JSON.stringify(n,null,2):String(n);throw Error(`Resource handler must return a ReadResourceResult or string. Got ${e}: ${t}
229
+ </html>`);return{contents:[{uri:r.uri,text:u,mimeType:a,_meta:r._meta}]}}catch(e){throw console.error(`React failed for ${r.name}:`,e),e}let s=r.handler({},t);if(s instanceof Promise&&(s=await s),"string"==typeof s)return{contents:[{uri:r.uri,text:s,mimeType:a,_meta:r._meta}]};if(s&&"object"==typeof s&&"_meta"in s&&!("content"in s))return{contents:[{uri:r.uri,text:"",mimeType:a,_meta:r._meta}]};if(s&&"object"==typeof s&&"content"in s&&Array.isArray(s.content)){let e=s.content.find(e=>"text"===e.type);if(e&&"text"===e.type&&"string"==typeof e.text)return{contents:[{uri:r.uri,text:e.text,mimeType:a,_meta:r._meta}]}}return{contents:[{uri:r.uri,text:"",mimeType:a,_meta:r._meta}]}};e.registerResource(r.name,r.uri,s,o)}),a.forEach((t,r)=>{let a={name:m0(r),description:"No description provided"},{default:i,metadata:n,schema:s,complete:o}=t;if("object"==typeof n&&null!==n&&Object.assign(a,n),!1===a.enabled)return;let l={};mQ(s)?l=s:null!=s&&console.warn(`Invalid schema for resource "${a.name}" at ${r}. Expected Record<string, z.ZodType>`);let c=m1(r);if(!c)return void console.warn(`Skipping resource "${a.name}" at ${r}: Invalid file path format`);let u=c.uriTemplate;a.mimeType&&a.mimeType.includes("html")&&(u=u.endsWith(".html")?u:`${u}.html`);let d=function(e,t,r={}){let a=m1(t);if(!a)throw Error(`Invalid resource file path: ${t}. Must follow (scheme)/path/[param] convention.`);return async(t,i)=>{let n=e(function(e,t,r){let a={},i={};if(0===t.parameters.length)return i;let n=t.uriTemplate.split("://")[1]||"",s=e.split("://")[1]||"",o=n.split("/"),l=s.split("/");for(let e=0;e<o.length&&e<l.length;e++){let t=o[e],r=l[e],i=t.match(/^\{(.+)\}$/);i&&(a[i[1]]=r)}for(let e of t.parameters){let t=a[e],n=r[e];if(void 0===t)throw Error(`Missing required parameter: ${e}`);if(!n){i[e]=t;continue}try{i[e]=n.parse(t)}catch(r){throw Error(`Invalid parameter "${e}": ${t}. Validation error: ${r instanceof Error?r.message:String(r)}`)}}return i}(t.href,a,r),i);if(n instanceof Promise&&(n=await n),"string"==typeof n)return{contents:[{uri:t.href,text:n}]};if(!n||"object"!=typeof n||!Array.isArray(n.contents)){let e=null===n?"null":typeof n,t=void 0===n?"undefined":null===n?"null":"object"==typeof n?JSON.stringify(n,null,2):String(n);throw Error(`Resource handler must return a ReadResourceResult or string. Got ${e}: ${t}
230
230
 
231
231
  Expected ReadResourceResult format:
232
232
  {
@@ -235,10 +235,10 @@ Expected ReadResourceResult format:
235
235
  { uri: "resource://uri", mimeType: "application/json", text: "json content" },
236
236
  { uri: "resource://uri", blob: base64data }
237
237
  ]
238
- }`)}return n.contents.forEach(e=>{e.uri||(e.uri=t.href)}),n}}(i,r,l);if("direct"===c.type)e.registerResource(a.name,u,a,d);else{let t=Object.create(null);for(let e of c.parameters)o&&Object.hasOwn(o,e)&&(t[e]=o[e]);let r=new dm(u,{list:void 0,complete:t}),n=async(e,t,r)=>{let a={};for(let e of c.parameters){let r=t[e],i=l[e];if(void 0===r)throw Error(`Missing required parameter: ${e}. Available variables: ${Object.keys(t)}`);i?a[e]=i.parse(r):a[e]=r}let n=i(a,r);return n instanceof Promise&&(n=await n),"string"==typeof n?{contents:[{uri:e.href,text:n}]}:n};e.registerResource(a.name,r,a,n)}})}),e}async function hs(){let{toolModules:e,skippedTools:t}=await m7(ht);return he(t),e}async function ho(){let{promptModules:e,skippedPrompts:t}=await m9(hr);return m4(t),e}async function hl(){let{resourceModules:e,skippedResources:t}=await m6(ha);return m5(t),e}let hc=function(e,t={}){var r;let{legacy:a,onerror:i,responseMode:n}=t;if("function"==typeof a)throw TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.");let s=new Set,o=!1,p=e=>{try{i?.(e)}catch{}},m=t.bus??new da(p),h={toolsChanged:()=>m.publish({kind:"tools_list_changed"}),promptsChanged:()=>m.publish({kind:"prompts_list_changed"}),resourcesChanged:()=>m.publish({kind:"resources_list_changed"}),resourceUpdated:e=>m.publish({kind:"resource_updated",uri:e})},f=function(e){let{bus:t,onerror:r}=e,a=e.maxSubscriptions??1024,i=e.keepAliveMs??15e3,n=new Set;return{serve:function(e,s,o,l){var c,u,d;let p,m,h,f,g,y,v;if(n.size>=a)return r?.(Error(`subscriptions/listen refused: subscription limit reached (${a})`)),di(e.id,-32603,"Subscription limit reached");let _=(c=e,(g=lh(lm).validateRequest("subscriptions/listen",c)).ok?g.value.params?.notifications:void 0);if(void 0===_)return di(e.id,-32602,"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter");let b=(u=_,d=o,y={},v=e=>void 0===d||!0===e,!0===u.toolsListChanged&&v(d?.tools?.listChanged)&&(y.toolsListChanged=!0),!0===u.promptsListChanged&&v(d?.prompts?.listChanged)&&(y.promptsListChanged=!0),!0===u.resourcesListChanged&&v(d?.resources?.listChanged)&&(y.resourcesListChanged=!0),void 0!==u.resourceSubscriptions&&u.resourceSubscriptions.length>0&&v(d?.resources?.subscribe)&&(y.resourceSubscriptions=[...u.resourceSubscriptions]),y),S=e.id,$=new TextEncoder,w=!1,R=e=>{if(!w)try{p.enqueue($.encode(e))}catch(e){r?.(e instanceof Error?e:Error(String(e)))}},k=(e,t)=>{R(`event: message
238
+ }`)}return n.contents.forEach(e=>{e.uri||(e.uri=t.href)}),n}}(i,r,l);if("direct"===c.type)e.registerResource(a.name,u,mY(a),d);else{let t=Object.create(null);for(let e of c.parameters)o&&Object.hasOwn(o,e)&&(t[e]=o[e]);let r=new dm(u,{list:void 0,complete:t}),n=async(e,t,r)=>{let a={};for(let e of c.parameters){let r=t[e],i=l[e];if(void 0===r)throw Error(`Missing required parameter: ${e}. Available variables: ${Object.keys(t)}`);i?a[e]=i.parse(r):a[e]=r}let n=i(a,r);return n instanceof Promise&&(n=await n),"string"==typeof n?{contents:[{uri:e.href,text:n}]}:n};e.registerResource(a.name,r,mY(a),n)}})}),e}async function ho(){let{toolModules:e,skippedTools:t}=await he(hr);return ht(t),e}async function hl(){let{promptModules:e,skippedPrompts:t}=await m4(ha);return m3(t),e}async function hc(){let{resourceModules:e,skippedResources:t}=await m5(hi);return m8(t),e}let hu=function(e,t={}){var r;let{legacy:a,onerror:i,responseMode:n}=t;if("function"==typeof a)throw TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler.");let s=new Set,o=!1,p=e=>{try{i?.(e)}catch{}},m=t.bus??new da(p),h={toolsChanged:()=>m.publish({kind:"tools_list_changed"}),promptsChanged:()=>m.publish({kind:"prompts_list_changed"}),resourcesChanged:()=>m.publish({kind:"resources_list_changed"}),resourceUpdated:e=>m.publish({kind:"resource_updated",uri:e})},f=function(e){let{bus:t,onerror:r}=e,a=e.maxSubscriptions??1024,i=e.keepAliveMs??15e3,n=new Set;return{serve:function(e,s,o,l){var c,u,d;let p,m,h,f,g,y,v;if(n.size>=a)return r?.(Error(`subscriptions/listen refused: subscription limit reached (${a})`)),di(e.id,-32603,"Subscription limit reached");let _=(c=e,(g=lh(lm).validateRequest("subscriptions/listen",c)).ok?g.value.params?.notifications:void 0);if(void 0===_)return di(e.id,-32602,"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter");let b=(u=_,d=o,y={},v=e=>void 0===d||!0===e,!0===u.toolsListChanged&&v(d?.tools?.listChanged)&&(y.toolsListChanged=!0),!0===u.promptsListChanged&&v(d?.prompts?.listChanged)&&(y.promptsListChanged=!0),!0===u.resourcesListChanged&&v(d?.resources?.listChanged)&&(y.resourcesListChanged=!0),void 0!==u.resourceSubscriptions&&u.resourceSubscriptions.length>0&&v(d?.resources?.subscribe)&&(y.resourceSubscriptions=[...u.resourceSubscriptions]),y),S=e.id,$=new TextEncoder,w=!1,R=e=>{if(!w)try{p.enqueue($.encode(e))}catch(e){r?.(e instanceof Error?e:Error(String(e)))}},k=(e,t)=>{R(`event: message
239
239
  data: ${JSON.stringify({jsonrpc:"2.0",method:e,params:t})}
240
240
 
241
241
  `)},x=e=>{if(!w){e&&R(`event: message
242
242
  data: ${JSON.stringify({jsonrpc:"2.0",id:S,result:{resultType:"complete",_meta:{[ij]:S,[iE]:l}}})}
243
243
 
244
- `),w=!0;try{m?.()}catch(e){r?.(e instanceof Error?e:Error(String(e)))}void 0!==h&&clearInterval(h),f?.(),n.delete(x);try{p.close()}catch{}}},P=new ReadableStream({start(e){p=e;let r=dn({method:"notifications/subscriptions/acknowledged",params:{notifications:b}},S);k(r.method,r.params),m=t.subscribe(e=>{if(w||!function(e,t){switch(t.kind){case"tools_list_changed":return!0===e.toolsListChanged;case"prompts_list_changed":return!0===e.promptsListChanged;case"resources_list_changed":return!0===e.resourcesListChanged;case"resource_updated":return void 0!==e.resourceSubscriptions&&e.resourceSubscriptions.includes(t.uri)}}(b,e))return;let t=dn(function(e){switch(e.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:e.uri}}}}(e),S);k(t.method,t.params)}),h=dr(i,()=>R(": keepalive\n\n")),n.add(x)},cancel(){x(!1)}});if(void 0!==s)if(s.aborted)x(!1);else{let e=()=>x(!1);s.addEventListener("abort",e,{once:!0}),f=()=>s.removeEventListener("abort",e)}return new Response(P,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let e of n)e(!0)},get openCount(){return n.size}}}({bus:m,maxSubscriptions:t.maxSubscriptions??1024,keepAliveMs:t.keepAliveMs??15e3,onerror:p});"json"===n&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let g="reject"===a?void 0:(r=t.keepAliveMs,async(t,a)=>{if("POST"!==t.method.toUpperCase())return dx(405,-32e3,"Method not allowed.");try{let i=await e({era:"legacy",...a?.authInfo!==void 0&&{authInfo:a.authInfo},requestInfo:t}),n=new dR({sessionIdGenerator:void 0,...void 0!==r&&{keepAliveMs:r}});await i.connect(n);let s=()=>{n.close().catch(()=>{}),i.close().catch(()=>{})};t.signal?.addEventListener("abort",s,{once:!0});let o=await n.handleRequest(t,{...a?.authInfo!==void 0&&{authInfo:a.authInfo},...a?.parsedBody!==void 0&&{parsedBody:a.parsedBody}});if(null===o.body||"text/event-stream"!==cp(o.headers.get("content-type")))return s(),o;let l=o.body.getReader(),c=!1,u=()=>{c||(c=!0,s())},d=new ReadableStream({pull:async e=>{try{let{done:t,value:r}=await l.read();if(t){u(),e.close();return}void 0!==r&&e.enqueue(r)}catch(t){u(),e.error(t)}},cancel:e=>(u(),l.cancel(e).catch(()=>{}))});return new Response(d,{status:o.status,statusText:o.statusText,headers:o.headers})}catch(e){try{p?.(dE(e))}catch{}return dT(dk(a?.parsedBody))}});async function y(r,a,i){var o,m;let h=r.classification.revision;if(void 0===h||!oT.includes(h)){let e=new o5({supported:[...oT],requested:h??"unknown"});return p(e),dx(400,e.code,e.message,e.data,dk(r.message))}let g=function(e,t){if("request"!==t.messageKind)return;let r=t.message.method;if(void 0===e.mcpMethodHeader)return lF("method-header-missing","(missing)",`the body names method ${r} but the required Mcp-Method header is absent`,"standard-header-validation");let a=Object.hasOwn(lH,r)?lH[r]:void 0;if(void 0===a)return;let i=t.message.params?.[a],n="string"==typeof i?i:void 0;if(void 0===e.mcpNameHeader){if(void 0===n)return;return lF("name-header-missing","(missing)",`the body carries params.${a}="${n}" but the required Mcp-Name header is absent`,"standard-header-validation")}let s=lJ(e.mcpNameHeader),o=lL(s);return void 0===o?lF("name-header-invalid-encoding",s,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==n&&o!==n?lF("name-header-mismatch",s,`the body carries params.${a}="${n}" but the Mcp-Name header names "${o}"`,"standard-header-validation"):void 0}({httpMethod:a.method,mcpMethodHeader:a.headers.get("mcp-method")??void 0,mcpNameHeader:a.headers.get("mcp-name")??void 0},r);if(void 0!==g)return p(Error(`Rejected inbound request (${g.cell}): ${g.message}`)),dP(g,dk(r.message));let y="request"===r.messageKind?lb(r.message.params):void 0,v=y?.[iT];if("request"===r.messageKind){let e=Object.hasOwn(ok,o=r.message.method)?ok[o]:void 0;if(void 0!==e){let t=oP(e,v);if(void 0!==t){let e=new o8({requiredCapabilities:t});return p(e),dx(lD[e.code]??400,e.code,e.message,e.data,r.message.id)}}}let _=await e({era:"modern",...void 0!==i&&{authInfo:i},requestInfo:a}),b=_ instanceof dp?_.server:_;if("request"===r.messageKind&&"subscriptions/listen"===r.message.method){let e=b.getCapabilities(),t=d(b);return _.close().catch(p),f.serve(r.message,a.signal,e,t)}if("request"===r.messageKind&&"tools/call"===r.message.method&&_ instanceof dp){let e=r.message.params,t="string"==typeof e?.name?e.name:void 0,i=void 0===t?void 0:_.toolInputSchemaJson(t);if(void 0!==i){let t=lI(i);if(t.valid&&t.declarations.length>0){let i=function(e,t,r){for(let a of e){let e=`Mcp-Param-${a.headerName}`,i=r.get(e),n=function(e,t){let r=e;for(let e of t){if(null===r||"object"!=typeof r)return;r=r[e]}return r}(t,a.path);if(null==n)continue;let s=function(e){if("string"==typeof e)return e;if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}(n);if(void 0===s)continue;if(null===i)return lZ("param-header-missing",e,`the body carries ${lA(a.path)}=${JSON.stringify(n)} but the ${e} header is absent`);let o=lL(i);if(void 0===o)return lZ("param-header-invalid-encoding",e,`the ${e} header carries an invalid Base64 sentinel value`);if(!(("integer"===a.type||"number"===a.type)&&lM.test(o)&&"number"==typeof n?Number(o)===n:o===s))return lZ("param-header-mismatch",e,`the ${e} header decodes to ${JSON.stringify(o)} but the body carries ${lA(a.path)}=${JSON.stringify(n)}`)}}(t.declarations,e?.arguments,a.headers);if(void 0!==i)return _.close().catch(p),p(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),dP(i,r.message.id)}}}l(b,h),u(b,oT),void 0!==y&&(m={clientInfo:y[iP],clientCapabilities:v},c(b,m));let S=b.onclose;s.add(b),b.onclose=()=>{s.delete(b),S?.()};try{let e=await dw(_,r.message,{classification:r.classification,request:a,...void 0!==i&&{authInfo:i},...void 0!==n&&{responseMode:n},...void 0!==t.keepAliveMs&&{keepAliveMs:t.keepAliveMs}});return"notification"===r.messageKind&&queueMicrotask(()=>void b.close().catch(()=>{})),e}catch(e){if(e instanceof oR&&e.code===ow.ConnectionClosed)return new Response(null,{status:499});return await b.close().catch(()=>{}),s.delete(b),p(dE(e)),dT(dk(r.message))}}async function v(e,t,r,a){if(void 0!==g)return g(t,{...void 0!==r&&{authInfo:r},...void 0!==a&&{parsedBody:a}});let i=function(e,t){switch(e.reason){case"http-method":return lU("http-method","modern-only-method-not-allowed",405,new o4(-32e3,"Method not allowed."),!0);case"batch":return lU("jsonrpc-shape","modern-only-batch-not-supported",400,new o4(o9.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return lU("jsonrpc-shape","modern-only-response-post",400,new o4(o9.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let r=e.requestedVersion;return lU("era-classification","modern-only-missing-envelope",400,void 0===r?new o4(o9.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...t]}):new o5({supported:[...t],requested:r}),!0)}}}(e,oT);return void 0===i?new Response(null,{status:202}):(p(Error(`Rejected 2025-era request on a modern-only endpoint (${i.cell}): ${i.message}`)),dP(i,dk(a)))}async function _(e,t){let r=t?.authInfo;if("POST"===e.method.toUpperCase()&&!cm(e.headers.get("content-type")))return p(Error("Unsupported Media Type: Content-Type must be application/json")),dx(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let a=await dj(e,t?.parsedBody);if("unreadable-body"===a.step)return dx(400,-32700,"Parse error: the request body could not be read");if("no-json-body"===a.step)return void 0!==g?g(a.forwardRequest,{...void 0!==r&&{authInfo:r}}):dx(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:i,body:n,parsedBody:s,forwardRequest:o}=a;try{switch(i.kind){case"reject":return p(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),dP(i,dk(n));case"modern":return await y(i,e,r);case"legacy":return await v(i,o,r,s)}}catch(e){return p(dE(e)),dT(dk(n))}}return{fetch:async(e,t)=>{if(o)throw Error("This MCP handler has been closed");try{return await _(e,t)}catch(e){return p(dE(e)),dT(dk(t?.parsedBody))}},notify:h,bus:m,close:async()=>{o=!0,f.closeAll();let e=[...s].map(e=>e.close().catch(()=>{}));s.clear(),await Promise.all(e)}}}(async function(){let{instructions:e,...t}=hi,r=new dp(t,{instructions:e}),a=hs(),i=ho(),n=hl(),[s,o,l]=await Promise.all([a,i,n]);return hn(r,s,o,l)},{legacy:"stateless"});async function hu(e,t={}){let r="POST"===e.method?await e.clone().json().catch(()=>void 0):void 0;return md({id:crypto.randomUUID(),headers:Object.fromEntries(e.headers.entries()),clientInfo:(e=>{for(let t of Array.isArray(e)?e:[e]){let e=mg(t);if(e)return e}})(r)},()=>hc.fetch(e,{parsedBody:r,authInfo:t.authInfo}))}})();var s=n.r;export{s as xmcpHandler};
244
+ `),w=!0;try{m?.()}catch(e){r?.(e instanceof Error?e:Error(String(e)))}void 0!==h&&clearInterval(h),f?.(),n.delete(x);try{p.close()}catch{}}},P=new ReadableStream({start(e){p=e;let r=dn({method:"notifications/subscriptions/acknowledged",params:{notifications:b}},S);k(r.method,r.params),m=t.subscribe(e=>{if(w||!function(e,t){switch(t.kind){case"tools_list_changed":return!0===e.toolsListChanged;case"prompts_list_changed":return!0===e.promptsListChanged;case"resources_list_changed":return!0===e.resourcesListChanged;case"resource_updated":return void 0!==e.resourceSubscriptions&&e.resourceSubscriptions.includes(t.uri)}}(b,e))return;let t=dn(function(e){switch(e.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:e.uri}}}}(e),S);k(t.method,t.params)}),h=dr(i,()=>R(": keepalive\n\n")),n.add(x)},cancel(){x(!1)}});if(void 0!==s)if(s.aborted)x(!1);else{let e=()=>x(!1);s.addEventListener("abort",e,{once:!0}),f=()=>s.removeEventListener("abort",e)}return new Response(P,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})},closeAll(){for(let e of n)e(!0)},get openCount(){return n.size}}}({bus:m,maxSubscriptions:t.maxSubscriptions??1024,keepAliveMs:t.keepAliveMs??15e3,onerror:p});"json"===n&&console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped.");let g="reject"===a?void 0:(r=t.keepAliveMs,async(t,a)=>{if("POST"!==t.method.toUpperCase())return dx(405,-32e3,"Method not allowed.");try{let i=await e({era:"legacy",...a?.authInfo!==void 0&&{authInfo:a.authInfo},requestInfo:t}),n=new dR({sessionIdGenerator:void 0,...void 0!==r&&{keepAliveMs:r}});await i.connect(n);let s=()=>{n.close().catch(()=>{}),i.close().catch(()=>{})};t.signal?.addEventListener("abort",s,{once:!0});let o=await n.handleRequest(t,{...a?.authInfo!==void 0&&{authInfo:a.authInfo},...a?.parsedBody!==void 0&&{parsedBody:a.parsedBody}});if(null===o.body||"text/event-stream"!==cp(o.headers.get("content-type")))return s(),o;let l=o.body.getReader(),c=!1,u=()=>{c||(c=!0,s())},d=new ReadableStream({pull:async e=>{try{let{done:t,value:r}=await l.read();if(t){u(),e.close();return}void 0!==r&&e.enqueue(r)}catch(t){u(),e.error(t)}},cancel:e=>(u(),l.cancel(e).catch(()=>{}))});return new Response(d,{status:o.status,statusText:o.statusText,headers:o.headers})}catch(e){try{p?.(dE(e))}catch{}return dT(dk(a?.parsedBody))}});async function y(r,a,i){var o,m;let h=r.classification.revision;if(void 0===h||!oT.includes(h)){let e=new o5({supported:[...oT],requested:h??"unknown"});return p(e),dx(400,e.code,e.message,e.data,dk(r.message))}let g=function(e,t){if("request"!==t.messageKind)return;let r=t.message.method;if(void 0===e.mcpMethodHeader)return lF("method-header-missing","(missing)",`the body names method ${r} but the required Mcp-Method header is absent`,"standard-header-validation");let a=Object.hasOwn(lH,r)?lH[r]:void 0;if(void 0===a)return;let i=t.message.params?.[a],n="string"==typeof i?i:void 0;if(void 0===e.mcpNameHeader){if(void 0===n)return;return lF("name-header-missing","(missing)",`the body carries params.${a}="${n}" but the required Mcp-Name header is absent`,"standard-header-validation")}let s=lJ(e.mcpNameHeader),o=lL(s);return void 0===o?lF("name-header-invalid-encoding",s,"the Mcp-Name header carries an invalid Base64 sentinel value","standard-header-validation"):void 0!==n&&o!==n?lF("name-header-mismatch",s,`the body carries params.${a}="${n}" but the Mcp-Name header names "${o}"`,"standard-header-validation"):void 0}({httpMethod:a.method,mcpMethodHeader:a.headers.get("mcp-method")??void 0,mcpNameHeader:a.headers.get("mcp-name")??void 0},r);if(void 0!==g)return p(Error(`Rejected inbound request (${g.cell}): ${g.message}`)),dP(g,dk(r.message));let y="request"===r.messageKind?lb(r.message.params):void 0,v=y?.[iT];if("request"===r.messageKind){let e=Object.hasOwn(ok,o=r.message.method)?ok[o]:void 0;if(void 0!==e){let t=oP(e,v);if(void 0!==t){let e=new o8({requiredCapabilities:t});return p(e),dx(lD[e.code]??400,e.code,e.message,e.data,r.message.id)}}}let _=await e({era:"modern",...void 0!==i&&{authInfo:i},requestInfo:a}),b=_ instanceof dp?_.server:_;if("request"===r.messageKind&&"subscriptions/listen"===r.message.method){let e=b.getCapabilities(),t=d(b);return _.close().catch(p),f.serve(r.message,a.signal,e,t)}if("request"===r.messageKind&&"tools/call"===r.message.method&&_ instanceof dp){let e=r.message.params,t="string"==typeof e?.name?e.name:void 0,i=void 0===t?void 0:_.toolInputSchemaJson(t);if(void 0!==i){let t=lI(i);if(t.valid&&t.declarations.length>0){let i=function(e,t,r){for(let a of e){let e=`Mcp-Param-${a.headerName}`,i=r.get(e),n=function(e,t){let r=e;for(let e of t){if(null===r||"object"!=typeof r)return;r=r[e]}return r}(t,a.path);if(null==n)continue;let s=function(e){if("string"==typeof e)return e;if("boolean"==typeof e)return e?"true":"false";if("number"==typeof e){if(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}(n);if(void 0===s)continue;if(null===i)return lZ("param-header-missing",e,`the body carries ${lA(a.path)}=${JSON.stringify(n)} but the ${e} header is absent`);let o=lL(i);if(void 0===o)return lZ("param-header-invalid-encoding",e,`the ${e} header carries an invalid Base64 sentinel value`);if(!(("integer"===a.type||"number"===a.type)&&lM.test(o)&&"number"==typeof n?Number(o)===n:o===s))return lZ("param-header-mismatch",e,`the ${e} header decodes to ${JSON.stringify(o)} but the body carries ${lA(a.path)}=${JSON.stringify(n)}`)}}(t.declarations,e?.arguments,a.headers);if(void 0!==i)return _.close().catch(p),p(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),dP(i,r.message.id)}}}l(b,h),u(b,oT),void 0!==y&&(m={clientInfo:y[iP],clientCapabilities:v},c(b,m));let S=b.onclose;s.add(b),b.onclose=()=>{s.delete(b),S?.()};try{let e=await dw(_,r.message,{classification:r.classification,request:a,...void 0!==i&&{authInfo:i},...void 0!==n&&{responseMode:n},...void 0!==t.keepAliveMs&&{keepAliveMs:t.keepAliveMs}});return"notification"===r.messageKind&&queueMicrotask(()=>void b.close().catch(()=>{})),e}catch(e){if(e instanceof oR&&e.code===ow.ConnectionClosed)return new Response(null,{status:499});return await b.close().catch(()=>{}),s.delete(b),p(dE(e)),dT(dk(r.message))}}async function v(e,t,r,a){if(void 0!==g)return g(t,{...void 0!==r&&{authInfo:r},...void 0!==a&&{parsedBody:a}});let i=function(e,t){switch(e.reason){case"http-method":return lU("http-method","modern-only-method-not-allowed",405,new o4(-32e3,"Method not allowed."),!0);case"batch":return lU("jsonrpc-shape","modern-only-batch-not-supported",400,new o4(o9.InvalidRequest,"Bad Request: JSON-RPC batches are not supported by this endpoint"),!0);case"response":return lU("jsonrpc-shape","modern-only-response-post",400,new o4(o9.InvalidRequest,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"),!0);case"notification":return;case"initialize":case"no-claim":{let r=e.requestedVersion;return lU("era-classification","modern-only-missing-envelope",400,void 0===r?new o4(o9.UnsupportedProtocolVersion,"Unsupported protocol version: the request did not name a protocol version",{supported:[...t]}):new o5({supported:[...t],requested:r}),!0)}}}(e,oT);return void 0===i?new Response(null,{status:202}):(p(Error(`Rejected 2025-era request on a modern-only endpoint (${i.cell}): ${i.message}`)),dP(i,dk(a)))}async function _(e,t){let r=t?.authInfo;if("POST"===e.method.toUpperCase()&&!cm(e.headers.get("content-type")))return p(Error("Unsupported Media Type: Content-Type must be application/json")),dx(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let a=await dj(e,t?.parsedBody);if("unreadable-body"===a.step)return dx(400,-32700,"Parse error: the request body could not be read");if("no-json-body"===a.step)return void 0!==g?g(a.forwardRequest,{...void 0!==r&&{authInfo:r}}):dx(400,-32700,"Parse error: the request body is not valid JSON");let{outcome:i,body:n,parsedBody:s,forwardRequest:o}=a;try{switch(i.kind){case"reject":return p(Error(`Rejected inbound request (${i.cell}): ${i.message}`)),dP(i,dk(n));case"modern":return await y(i,e,r);case"legacy":return await v(i,o,r,s)}}catch(e){return p(dE(e)),dT(dk(n))}}return{fetch:async(e,t)=>{if(o)throw Error("This MCP handler has been closed");try{return await _(e,t)}catch(e){return p(dE(e)),dT(dk(t?.parsedBody))}},notify:h,bus:m,close:async()=>{o=!0,f.closeAll();let e=[...s].map(e=>e.close().catch(()=>{}));s.clear(),await Promise.all(e)}}}(async function(){let{instructions:e,...t}=hn,r=new dp(t,{instructions:e}),a=ho(),i=hl(),n=hc(),[s,o,l]=await Promise.all([a,i,n]);return hs(r,s,o,l)},{legacy:"stateless"});async function hd(e,t={}){let r="POST"===e.method?await e.clone().json().catch(()=>void 0):void 0;return md({id:crypto.randomUUID(),headers:Object.fromEntries(e.headers.entries()),clientInfo:(e=>{for(let t of Array.isArray(e)?e:[e]){let e=mg(t);if(e)return e}})(r)},()=>hu.fetch(e,{parsedBody:r,authInfo:t.authInfo}))}})();var s=n.r;export{s as xmcpHandler};