@hyperframes/studio 0.9.52 → 0.9.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{hyperframes-player-D7LhzIg1.js → hyperframes-player-Oju91F6x.js} +2 -2
- package/dist/assets/{index-D3WxJaqm.js → index-B0VEzzD2.js} +180 -180
- package/dist/assets/index-Dv67Vrl6.js +74 -0
- package/dist/assets/{index-CQ7o0CBU.js → index-XEm_N45R.js} +1 -1
- package/dist/assets/{pausedVideoDecoder-BVUmBgn0.js → pausedVideoDecoder-p6zibxVM.js} +1 -1
- package/dist/{chunk-F6EHWNZU.js → chunk-K3IOYISK.js} +121 -94
- package/dist/{chunk-VHV2ZDKY.js → chunk-OOGQ5KCC.js} +7 -0
- package/dist/{chunk-GVW7AU57.js → chunk-UM4CLD4M.js} +1 -1
- package/dist/chunk-USW3YBOG.js +70 -0
- package/dist/{domEditingLayers-SA5KLSSS.js → domEditingLayers-IHYA42AJ.js} +2 -2
- package/dist/index.d.ts +14 -7
- package/dist/index.html +1 -1
- package/dist/index.js +110 -98
- package/dist/keys.d.ts +72 -1
- package/dist/keys.js +5 -4
- package/dist/player.d.ts +1 -0
- package/dist/player.js +2 -2
- package/package.json +9 -9
- package/src/captions/keyboard.ts +1 -1
- package/src/components/RightPanelTabs.test.tsx +1 -1
- package/src/components/StudioHeader.dom.test.tsx +1 -1
- package/src/components/TimelineHistoryButtons.dom.test.tsx +1 -1
- package/src/components/TimelineToolbar.tsx +1 -1
- package/src/components/editor/SnapToolbar.tsx +1 -1
- package/src/components/editor/gsapLivePreview.test.ts +19 -0
- package/src/components/editor/gsapLivePreview.ts +2 -0
- package/src/components/editor/manualEditingAvailability.ts +7 -0
- package/src/components/editor/useDomEditNudge.ts +1 -1
- package/src/components/nle/NLEPreview.test.ts +25 -0
- package/src/components/nle/NLEPreview.tsx +5 -0
- package/src/components/nle/PreviewPane.tsx +2 -0
- package/src/components/panels/SlideshowPanel.tsx +1 -1
- package/src/components/renders/RenderQueue.test.tsx +1 -1
- package/src/components/sidebar/CompositionsTab.tsx +4 -8
- package/src/components/ui/Button.test.tsx +1 -1
- package/src/components/ui/Menu.test.tsx +1 -1
- package/src/components/ui/valueControls.test.tsx +1 -1
- package/src/hooks/appHotkeysDispatch.ts +1 -1
- package/src/hooks/gsapParsedTween.test.ts +19 -0
- package/src/hooks/gsapParsedTween.ts +3 -1
- package/src/hooks/linkShortcuts.ts +1 -1
- package/src/hooks/useAutomationSelectionKeyboard.ts +1 -1
- package/src/hooks/useConsoleErrorCapture.test.tsx +69 -1
- package/src/hooks/useConsoleErrorCapture.ts +47 -11
- package/src/hooks/useKeyframeKeyboard.ts +1 -1
- package/src/index.ts +3 -2
- package/src/keys.test.ts +5 -7
- package/src/keys.ts +1 -6
- package/src/player/components/Player.test.ts +49 -0
- package/src/player/components/Player.tsx +13 -4
- package/src/player/components/ShortcutsPanel.tsx +1 -1
- package/src/player/components/studioCombo.test.ts +1 -1
- package/src/player/components/studioShortcuts.ts +1 -1
- package/src/player/lib/frameToken.ts +20 -0
- package/src/player/lib/playbackShortcuts.ts +3 -28
- package/src/player/lib/previewChannel.ts +10 -0
- package/src/utils/studioHelpers.ts +1 -1
- package/src/utils/studioPendingEdits.ts +1 -1
- package/src/utils/timelineDiscovery.ts +1 -1
- package/src/utils/typingTarget.test.ts +1 -1
- package/src/webmcp/polyfill.transport.test.ts +13 -3
- package/src/webmcp/types.ts +3 -3
- package/src/webmcp/useStudioAgentTools.polyfill.test.tsx +89 -121
- package/src/webmcp/useStudioAgentTools.test.tsx +2 -2
- package/src/webmcp/useStudioAgentTools.ts +2 -3
- package/dist/assets/index-BX3KHhGX.js +0 -71
- package/dist/chunk-5ZHKYODQ.js +0 -149
- package/dist/keys-B163OjLN.d.ts +0 -87
- package/src/player/components/studioCombo.ts +0 -108
- package/src/utils/typingTarget.ts +0 -56
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
var _m=Object.defineProperty;var $a=e=>{throw TypeError(e)};var vm=(e,t,n)=>t in e?_m(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var T=(e,t,n)=>vm(e,typeof t!="symbol"?t+"":t,n),Rs=(e,t,n)=>t.has(e)||$a("Cannot "+n);var E=(e,t,n)=>(Rs(e,t,"read from private field"),n?n.call(e):t.get(e)),ye=(e,t,n)=>t.has(e)?$a("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),rt=(e,t,n,o)=>(Rs(e,t,"write to private field"),o?o.call(e,n):t.set(e,n),n),G=(e,t,n)=>(Rs(e,t,"access private method"),n);function Fs(e){const t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,r])=>t.indexOf(+o)===-1).map(([o,r])=>r)}function Ea(e,t="|"){return e.map(n=>sl(n)).join(t)}function Vs(e,t){return typeof t=="bigint"?t.toString():t}class bm{constructor(t){this._getter=t,this._value=void 0}get value(){const t=this._getter;return t!==void 0&&(this._value=t(),this._getter=void 0),this._value}}function ts(e){return new bm(e)}function wm(e){return e==null}function _i(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Rm(e,t){const n=e/t,o=Math.round(n),r=4*Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-o)<r?0:n-o}const Pa=Symbol("evaluating");function Tm(e,t,n){let o;Object.defineProperty(e,t,{get(){if(o!==Pa)return o===void 0&&(o=Pa,o=n()),o},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function yt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function vi(e){const t=Object.getOwnPropertyDescriptor(e,"shape");return t!=null&&t.get?t.get.raw:t==null?void 0:t.value}function Pt(e){return vi(e._zod.def)??e._zod.def.shape}function tl(e,t,n){Object.defineProperty(e,t,{get(){const o=n();return yt(this,t,o),o},enumerable:!0,configurable:!0})}function nl(e,t,n){t in e?yt(e,t,n):e[t]=n}function fn(e,t,n,o){const r=Pt(t);for(const s of n){const i=Object.getOwnPropertyDescriptor(r,s);i.enumerable&&(i.get?tl(e,s,()=>{const a=t._zod.def.shape[s];return o?o(a,s):a}):nl(e,s,o?o(i.value,s):i.value))}}function $m(e,t){for(const n of Reflect.ownKeys(t)){const o=Object.getOwnPropertyDescriptor(t,n);o.enumerable&&(o.get?tl(e,n,()=>t[n]):nl(e,n,o.value))}}function Je(...e){const t={};for(const n of e){const o=Object.getOwnPropertyDescriptors(n);Object.assign(t,o)}return Object.defineProperties({},t)}function Em(e){return JSON.stringify(e)}function Pm(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ol="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ho(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const km=ts(()=>{var e;if(at.jitless||typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Dn(e){if(Ho(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Ho(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function rl(e){return Dn(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Cm=new Set(["string","number","symbol"]);function Un(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Jt(e,t,n){const o=new e._zod.constr(t??e._zod.def);return(!t||n!=null&&n.parent)&&(o._zod.parent=e),o}function x(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function sl(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Om(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}const il={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Im={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function qm(e,t){const n=e._zod.def,o=n.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const s={};return fn(s,e,ns(e,t)),Jt(e,Je(n,{shape:s,checks:[]}))}function ns(e,t){var r;const n=Pt(e),o=[];for(const s of Reflect.ownKeys(t)){if(!((r=Object.getOwnPropertyDescriptor(n,s))!=null&&r.enumerable))throw new Error(`Unrecognized key: "${String(s)}"`);t[s]&&o.push(s)}return o}function Nm(e,t){const n=e._zod.def,o=n.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=new Set(ns(e,t)),i={};return fn(i,e,Reflect.ownKeys(Pt(e)).filter(a=>!s.has(a))),Jt(e,Je(n,{shape:i,checks:[]}))}function Mm(e,t){if(!Dn(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const r=Pt(e);for(const s of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(r,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Jt(e,Je(e._zod.def,{shape:al(e,t)}))}function al(e,t){const n={};return fn(n,e,Reflect.ownKeys(Pt(e))),$m(n,t),n}function Am(e,t){if(!Dn(t))throw new Error("Invalid input to safeExtend: expected a plain object");return Jt(e,Je(e._zod.def,{shape:al(e,t)}))}function xm(e,t){var r,s;if(!((r=t==null?void 0:t._zod)!=null&&r.def))throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if((s=e._zod.def.checks)!=null&&s.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n={};fn(n,e,Reflect.ownKeys(Pt(e))),fn(n,t,Reflect.ownKeys(Pt(t)));const o=Je(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Jt(e,o)}function ka(e,t,n,o="partial"){const s=t._zod.def.checks;if(s&&s.length>0)throw new Error(`.${o}() cannot be used on object schemas containing refinements`);const a=n?new Set(ns(t,n)):void 0,c={};return fn(c,t,Reflect.ownKeys(Pt(t)),e&&((d,u)=>a&&!a.has(u)?d:new e({type:"optional",innerType:d}))),Jt(t,Je(t._zod.def,{shape:c,checks:[]}))}function zm(e,t,n){const o=n?new Set(ns(t,n)):void 0,r={};return fn(r,t,Reflect.ownKeys(Pt(t)),(s,i)=>o&&!o.has(i)?s:new e({type:"nonoptional",innerType:s})),Jt(t,Je(t._zod.def,{shape:r}))}function Et(e,t=0){var n;if(e.aborted===!0)return!0;for(let o=t;o<e.issues.length;o++)if(((n=e.issues[o])==null?void 0:n.continue)!==!0)return!0;return!1}function Lm(e,t=0){var n;if(e.aborted===!0)return!0;for(let o=t;o<e.issues.length;o++)if(((n=e.issues[o])==null?void 0:n.continue)===!1)return!0;return!1}function In(e,t){return t.map(n=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(e),n})}function Oo(e){return typeof e=="string"?e:e==null?void 0:e.message}function Ca(e){const t=[];for(const n of e??[]){const o=n._zod.def;if(!/_(length|size)$|_equals$/.test(o.check))break;const r=o.maximum??o.length??o.size;r>=0&&t.push([r,n])}return t}function Js(e,t,n){var o;for(let r=t;r<e.length;r++)(o=e[r]).schema??(o.schema=n)}function Ft(e,t,n){var c,d,u,p,m,h,f,_,S,b;var o;const r=(d=(c=e.inst)==null?void 0:c._zod)==null?void 0:d.traits;r!=null&&r.has("$ZodType")&&(r.has("$ZodCheck")?(o=e).schema??(o.schema=e.inst):e.schema=e.inst);const s=e.schema!==e.inst?(p=(u=e.schema)==null?void 0:u._zod.def)==null?void 0:p.error:void 0,i=e.message?e.message:Oo((f=(h=(m=e.inst)==null?void 0:m._zod.def)==null?void 0:h.error)==null?void 0:f.call(h,e))??Oo(s==null?void 0:s(e))??Oo((_=t==null?void 0:t.error)==null?void 0:_.call(t,e))??Oo((S=n.customError)==null?void 0:S.call(n,e))??Oo((b=n.localeError)==null?void 0:b.call(n,e))??"Invalid input",a={};for(const R of Object.keys(e))R==="inst"||R==="schema"||R==="continue"||R==="input"||R==="__proto__"||(a[R]=e[R]);return a.path??(a.path=[]),a.message=i,t!=null&&t.reportInput&&(a.input=e.input),a}const jm=/[\uD800-\uDBFF]/;function bi(e){const t=e.length;if(!jm.test(e))return t;let n=t;for(let o=0;o<t-1;o++)(e.charCodeAt(o)&64512)===55296&&(e.charCodeAt(o+1)&64512)===56320&&(n--,o++);return n}function wi(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Dm(e){const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";const n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function Fo(...e){const[t,n,o]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:o}:{...t}}function Um(e,t){for(const n in t){const o=Object.getOwnPropertyDescriptor(t,n);o.get?Object.defineProperty(e,n,{...o,enumerable:!1}):Zm(e,n,o.value)}}function Vt(e,t,n,o=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:o,value:n}),n}function cl(e,t,n){return Vt(e,t,n,!1)}function ll(e,t){for(const n in e){const o=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return Vt(this,n,o(this))},set(r){Vt(this,n,r)}})}return t}function Zm(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:Vt(this,t,n.bind(this))},set(o){Vt(this,t,o)}})}function Hm(e,t){const n=Object.getPrototypeOf(e);return t in n?void 0:n}let Ts,Nt=!1;const Fm={configurable:!0,get(){Nt=!0}};function ee(e,t,n){const o=Object.getPrototypeOf(e._zod);if(t in o&&Ts!==e._zod){Ts=void 0;return}Ts=e._zod,Object.defineProperty(o,t,{configurable:!0,get(){Object.defineProperty(this,t,Fm);const r=Nt;Nt=!1;try{const s=n(this);return Nt?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s}),Nt=Nt||r,s}catch(s){throw delete this[t],Nt=Nt||r,s}},set(r){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r})}})}function Vm(e,t,n,o){const r=Hm(e,t);r&&Object.defineProperty(r,t,{configurable:!0,get(){const s={configurable:!0,writable:!0,enumerable:o,value:void 0};return Object.defineProperty(this,t,s),s.value=n(this),Object.defineProperty(this,t,s),s.value},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:o,value:s})}})}const Jm="~constantCatch";function Bm(e){const t=()=>e;return t[Jm]=!0,t}var Oa;const Wm=Object.freeze({status:"aborted"}),$s={value:void 0,enumerable:!1};let Ia="captureStackTrace"in Error?Error:null;function Km(e){const t=Ia;if(t){const n=t.stackTraceLimit;if(typeof n=="number"){try{t.stackTraceLimit=0}catch{return Ia=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function w(e,t,n,o){const r={};function s(m){this.def=m,this.constr=p,this.traits=new Set}s.prototype=r;const i=n,a=i&&new WeakSet;function c(m,h){if(m._zod){if(m._zod.traits.has(e))return}else{$s.value=new s(h);try{Object.defineProperty(m,"_zod",$s)}finally{$s.value=void 0}}if(m._zod.traits.add(e),t(m,h),a){const _=Object.getPrototypeOf(m),S=m._zod.constr.prototype;let b=_;for(;b&&b!==S;)b=Object.getPrototypeOf(b);const R=b??_;a.has(R)||(a.add(R),Um(R,i))}const f=p.prototype;for(const _ in f)Object.prototype.hasOwnProperty.call(f,_)&&(_ in m||(m[_]=f[_].bind(m)))}const d=(o==null?void 0:o.Parent)??Object;class u extends d{}Object.defineProperty(u,"name",{value:e});function p(m){var S;const h=o!=null&&o.Parent?Km(u):this;c(h,m);const f=h._zod.deferred;if(f){for(const b of f)b();h._zod.deferred=void 0}const _=(S=globalThis.__zod_globalConfig)==null?void 0:S.postProcessor;return _&&_(h),h}return Object.defineProperty(p,"init",{value:c}),Object.defineProperty(p,Symbol.hasInstance,{value:m=>{var h,f;return o!=null&&o.Parent&&m instanceof o.Parent?!0:(f=(h=m==null?void 0:m._zod)==null?void 0:h.traits)==null?void 0:f.has(e)}}),Object.defineProperty(p,"name",{value:e}),p}class mn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ul extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Oa=globalThis).__zod_globalConfig??(Oa.__zod_globalConfig={});const at=globalThis.__zod_globalConfig;function St(e){return e&&Object.assign(at,e),at}function Gm(){const e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Vs,2)),e.message}function Ym(e){this._zod.message=e}const Xm={get:Gm,set:Ym,enumerable:!0,configurable:!0},Es={value:void 0,enumerable:!1},qa=new WeakSet([Object.prototype,Error.prototype]),Qm=(e,t)=>{e.name="$ZodError",Es.value=t,Object.defineProperty(e,"issues",Es),Es.value=void 0,Object.defineProperty(e,"message",Xm);const n=Object.getPrototypeOf(e);qa.has(n)||(qa.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){const o=()=>this.message;return Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,"toString",{value:o,configurable:!0,writable:!0})}}))},eh=w("$ZodError",Qm);function th(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t==="__proto__"?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function nh(e,t=n=>n.message){const n={},o=[];for(const r of e.issues)r.path.length>0?th(n,r.path[0],()=>[]).push(t(r)):o.push(t(r));return{formErrors:o,fieldErrors:n}}function oh(e,t=n=>n.message){const n={_errors:[]},o=(r,s=[])=>{for(const i of r.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")o({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")o({issues:i.issues},[...s,...i.path]);else{const a=[...s,...i.path];if(a.length===0)n._errors.push(t(i));else{let c=n,d=0;for(;d<a.length;){const u=a[d],p=d===a.length-1;if(u==="_errors"){p&&c._errors.push(t(i)),d++;continue}Object.prototype.hasOwnProperty.call(c,u)||Object.defineProperty(c,u,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});const m=c[u];p&&m._errors.push(t(i)),c=m,d++}}}};return o(e),n}function os(e,t){return{callee:(t==null?void 0:t.callee)??e,Err:t==null?void 0:t.Err}}const Ri=e=>{const t=(n,o,r,s)=>{const i=r?{...r,async:!1}:{async:!1},a=n._zod.run({value:o,issues:[]},i);if(a instanceof Promise)throw new mn;if(a.issues.length){const c=new((s==null?void 0:s.Err)??e)(a.issues.map(d=>Ft(d,i,St())));throw ol(c,(s==null?void 0:s.callee)??t),c}return a.value};return t},Ti=e=>{const t=async(n,o,r,s)=>{const i=r?{...r,async:!0}:{async:!0};let a=n._zod.run({value:o,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){const c=new((s==null?void 0:s.Err)??e)(a.issues.map(d=>Ft(d,i,St())));throw ol(c,(s==null?void 0:s.callee)??t),c}return a.value};return t},$i=e=>(t,n,o)=>{const r=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)throw new mn;return s.issues.length?dl(e,s.issues,r):{success:!0,data:s.value}};function dl(e,t,n){let o;return{success:!1,get error(){return o||(o=new e(t.map(r=>Ft(r,n,St()))),t=void 0,n=void 0),o},set error(r){o=r,t=void 0,n=void 0}}}const Ei=e=>async(t,n,o)=>{const r=o?{...o,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},r);return s instanceof Promise&&(s=await s),s.issues.length?dl(e,s.issues,r):{success:!0,data:s.value}},rh=Symbol.for("zod.compile.invalid"),sh=Symbol.for("zod.compile.fallback"),ih=((e,t,n)=>{const o=e._zod.bag.validator;if(o!==void 0){if(o(t)!==rh)return!0;if(o.definite===!0&&n===void 0)return!1}return ah(e,t,n)});function ah(e,t,n){const o=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},r=e._zod.bag.fallbackRun;let s;if(r?(o[sh]=!0,s=r({value:t,issues:[]},o)):s=e._zod.run({value:t,issues:[]},o),s instanceof Promise)throw new mn;return s.issues.length===0}const ch=async(e,t,n)=>{const o=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0};let r=e._zod.run({value:t,issues:[]},o);return r instanceof Promise&&(r=await r),r.issues.length===0},lh=e=>{const t=Ri(e),n=(o,r,s,i)=>{const a=s?{...s,direction:"backward"}:{direction:"backward"};return t(o,r,a,os(n,i))};return n},uh=e=>{const t=Ri(e),n=(o,r,s,i)=>t(o,r,s,os(n,i));return n},dh=e=>{const t=Ti(e),n=async(o,r,s,i)=>{const a=s?{...s,direction:"backward"}:{direction:"backward"};return await t(o,r,a,os(n,i))};return n},ph=e=>{const t=Ti(e),n=async(o,r,s,i)=>await t(o,r,s,os(n,i));return n},mh=e=>(t,n,o)=>{const r=o?{...o,direction:"backward"}:{direction:"backward"};return $i(e)(t,n,r)},hh=e=>(t,n,o)=>$i(e)(t,n,o),fh=e=>async(t,n,o)=>{const r=o?{...o,direction:"backward"}:{direction:"backward"};return Ei(e)(t,n,r)},gh=e=>async(t,n,o)=>Ei(e)(t,n,o),Sh=/^[cC][0-9a-z]{6,}$/,yh=/^[0-9a-z]+$/,_h=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,vh=/^[0-9a-vA-V]{20}$/,bh=/^[A-Za-z0-9]{27}$/,wh=/^[a-zA-Z0-9_-]{21}$/;function Rh(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const Th=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,$h=/^([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})$/,Na=e=>e?new 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)$/,Eh=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Ph="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function kh(){return new RegExp(Ph,"u")}const Ch=/^(?:(?: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])$/,Oh=/^(([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}|:))$/,Ih=/^((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])$/,qh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Nh=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Mh=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Ah=/^https?$/,xh=/^\+[1-9]\d{6,14}$/,pl="(?:(?:\\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])))";function zh(e){return new RegExp(`^${e}$`)}const Lh=zh(pl);function Bs(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function jh(e){return new RegExp(`^${Bs(e)}$`)}function Dh(e){const t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${Bs({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,o=e.local?`${n}|${Bs({precision:e.precision})}`:n;return new RegExp(`^${pl}T(?:${o})$`)}const Uh=/^[\s\S]{0,}$/,Zh=/^-?\d+$/,Pi=/^-?\d+(?:\.\d+)?$/,Hh=/^(?:true|false)$/i,Fh=/^null$/i,Vh=/^[^A-Z]*$/,Jh=/^[^a-z]*$/,Le=w("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ki=e=>{const t=e.value;return!wm(t)&&t.length!==void 0},Ur={number:"number",bigint:"bigint",object:"date"},ml=w("$ZodCheckLessThan",(e,t)=>{Le.init(e,t);const n=Ur[typeof t.value];e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:Ur[typeof o.value]??n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),hl=w("$ZodCheckGreaterThan",(e,t)=>{Le.init(e,t);const n=Ur[typeof t.value];e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:Ur[typeof o.value]??n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Bh=w("$ZodCheckMultipleOf",(e,t)=>{Le.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Rm(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Wh=w("$ZodCheckNumberFormat",(e,t)=>{var i;Le.init(e,t),t.format=t.format||"float64";const n=(i=t.format)==null?void 0:i.includes("int"),o=n?"int":"number",[r,s]=il[t.format];e._zod.check=a=>{const c=a.value;if(n){if(!Number.isInteger(c)){a.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?a.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort}):a.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}c<r&&a.issues.push({origin:"number",input:c,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),c>s&&a.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),Kh=w("$ZodCheckMaxLength",(e,t)=>{var n;Le.init(e,t),(n=e._zod.def).when??(n.when=ki),e._zod.check=o=>{const r=o.value,s=r.length;if((typeof r=="string"&&s>t.maximum?bi(r):s)<=t.maximum)return;const a=wi(r);o.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Gh=w("$ZodCheckMinLength",(e,t)=>{var n;Le.init(e,t),(n=e._zod.def).when??(n.when=ki),e._zod.check=o=>{const r=o.value,s=r.length;if((typeof r=="string"&&s>=t.minimum&&s<t.minimum*2?bi(r):s)>=t.minimum)return;const a=wi(r);o.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Yh=w("$ZodCheckLengthEquals",(e,t)=>{var n;Le.init(e,t),(n=e._zod.def).when??(n.when=ki),e._zod.check=o=>{const r=o.value,s=r.length,i=typeof r=="string"&&s>=t.length&&s<=t.length*2?bi(r):s;if(i===t.length)return;const a=wi(r),c=i>t.length;o.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),rs=w("$ZodCheckStringFormat",(e,t)=>{var n,o;Le.init(e,t),t.pattern?(n=e._zod).check??(n.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})}):(o=e._zod).check??(o.check=()=>{})}),Xh=w("$ZodCheckRegex",(e,t)=>{rs.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Qh=w("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Vh),rs.init(e,t)}),ef=w("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Jh),rs.init(e,t)}),tf=w("$ZodCheckIncludes",(e,t)=>{Le.init(e,t);const n=Un(t.includes),o=new RegExp(typeof t.position=="number"?`^.{${t.position},}${n}`:n);t.pattern=o,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})}}),nf=w("$ZodCheckStartsWith",(e,t)=>{Le.init(e,t);const n=new RegExp(`^${Un(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=o=>{o.value.startsWith(t.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),of=w("$ZodCheckEndsWith",(e,t)=>{Le.init(e,t);const n=new RegExp(`.*${Un(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=o=>{o.value.endsWith(t.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}}),rf=w("$ZodCheckOverwrite",(e,t)=>{Le.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class sf{constructor(t=[],n={}){this.content=[],this.indent=0,this.args=t,this.closed=n}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const o=t.split(`
|
|
2
|
+
`).filter(i=>i),r=Math.min(...o.map(i=>i.length-i.trimStart().length)),s=o.map(i=>i.slice(r)).map(i=>" ".repeat(this.indent*2)+i);for(const i of s)this.content.push(i)}compile(){const t=Function,n=(this==null?void 0:this.content)??[""];return new t(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
|
3
|
+
${n.join(`
|
|
4
|
+
`)}
|
|
5
|
+
};`)(...Object.values(this.closed))}}const af={major:4,minor:6,patch:7},ae=w("$ZodType",(e,t)=>{var s;var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=af;const o=e._zod.def.checks,r=e._zod.traits.has("$ZodCheck")?[e,...o??[]]:o!=null&&o.length?[...o]:[];for(const i of r)for(const a of i._zod.onattach)a(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),(s=e._zod.deferred)==null||s.push(()=>{e._zod.run=e._zod.parse});else{const i=(c,d,u)=>{if(c.memo)return c;let p=Et(c),m;for(const h of d){if(h._zod.def.when){if(Lm(c)||!h._zod.def.when(c))continue}else if(p)continue;const f=c.issues.length,_=h._zod.check(c);if(_ instanceof Promise&&(u==null?void 0:u.async)===!1)throw new mn;if(m||_ instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await _,c.issues.length!==f&&(Js(c.issues,f,e),p||(p=Et(c,f)))});else{if(c.issues.length===f)continue;Js(c.issues,f,e),p||(p=Et(c,f))}}return m?m.then(()=>c):c},a=(c,d,u)=>{if(Et(c))return c.aborted=!0,c;const p=i(d,r,u);if(p instanceof Promise){if(u.async===!1)throw new mn;return p.then(m=>e._zod.parse(m,u))}return e._zod.parse(p,u)};e._zod.run=(c,d)=>{if(d.skipChecks)return e._zod.parse(c,d);if(d.direction==="backward"){const p=e._zod.parse({value:c.value,issues:[]},{...d,skipChecks:!0});return p instanceof Promise?p.then(m=>a(m,c,d)):a(p,c,d)}const u=e._zod.parse(c,d);if(u instanceof Promise){if(d.async===!1)throw new mn;return u.then(p=>i(p,r,d))}return i(u,r,d)}}},{get"~standard"(){return cl(this,"~standard",gl(this))},set"~standard"(e){Vt(this,"~standard",e)}}),fl=(e,t)=>e.issues.length?{issues:e.issues.map(n=>Ft(n,t,St()))}:{value:e.value};async function cf(e,t){const n={async:!0};return fl(await e._zod.run({value:t,issues:[]},n),n)}function gl(e){return{validate:t=>{const n={async:!1};try{const o=e._zod.run({value:t,issues:[]},n);if(!(o instanceof Promise))return fl(o,n)}catch{}return cf(e,t)},vendor:"zod",version:1}}const Ci=w("$ZodString",(e,t)=>{ae.init(e,t),e._zod.pattern=t.pattern??Uh,e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),le=w("$ZodStringFormat",(e,t)=>{rs.init(e,t),Ci.init(e,t)}),lf=w("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=$h),le.init(e,t)}),uf=w("$ZodUUID",(e,t)=>{if(t.version){const o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Na(o))}else t.pattern??(t.pattern=Na());le.init(e,t)}),df=w("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Eh),le.init(e,t)}),Sl=1,Zr=2;function yl(e){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function pf(e,t){return!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t)?yl(e)||Zr:mf(e,t)}function mf(e,t){var n;if(!t.normalize&&((n=t.protocol)==null?void 0:n.source)===Ah.source&&!/^https?:\/\//i.test(e))return Sl;try{if(typeof URL<"u"){const o=URL;if(typeof o.parse=="function")return o.parse(e)??Zr}return new URL(e)}catch{return Zr}}const hf=/[\t\n\r]/g;function Ma(e){return e.replace(hf,"")}function ff(e,t){return t.lastIndex=0,t.test(e.hostname)}function gf(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}const Sf=w("$ZodURL",(e,t)=>{le.init(e,t),e._zod.check=n=>{try{const o=n.value.trim(),r=pf(o,t);if(r===Sl){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(r===Zr){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(r===!0){n.value=Ma(o);return}t.hostname&&!ff(r,t.hostname)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!gf(r,t.protocol)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?r.href:Ma(o);return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),yf=w("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=kh()),le.init(e,t)}),_f=w("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw new Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?wh:Rh(t.length)),le.init(e,t)}),vf=w("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Sh),le.init(e,t)}),bf=w("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=yh),le.init(e,t)}),wf=w("$ZodULID",(e,t)=>{t.pattern??(t.pattern=_h),le.init(e,t)}),Rf=w("$ZodXID",(e,t)=>{t.pattern??(t.pattern=vh),le.init(e,t)}),Tf=w("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=bh),le.init(e,t)}),$f=w("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Dh(t)),le.init(e,t)}),Ef=w("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Lh),le.init(e,t)}),Pf=w("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=jh(t)),le.init(e,t)}),kf=w("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Th),le.init(e,t)}),Cf=w("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Ch),le.init(e,t)}),Of=/^[0-9a-fA-F:.]+$/;function _l(e){return Of.test(e)?yl(`http://[${e}]`):!1}const If=w("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Oh),le.init(e,t),e._zod.check=n=>{_l(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),qf=w("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Ih),le.init(e,t)});function Nf(e){const t=e.split("/");if(t.length!==2)return!1;const[n,o]=t;if(!o)return!1;const r=Number(o);return`${r}`!==o||r<0||r>128?!1:_l(n)}const Mf=w("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=qh),le.init(e,t),e._zod.check=n=>{Nf(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function vl(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const bl=/^[0-9a-zA-Z+/]*={0,2}$/,Af=w("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=bl),le.init(e,t),e._zod.check=n=>{vl(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Oi=/^[A-Za-z0-9_-]*$/;function xf(e){if(!Oi.test(e))return!1;const t=e.replace(/[-_]/g,o=>o==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return vl(n)}const zf=w("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Oi),le.init(e,t),e._zod.check=n=>{xf(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Lf=w("$ZodE164",(e,t)=>{t.pattern??(t.pattern=xh),le.init(e,t)});function jf(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[o]=n;if(!o)return!1;const r=JSON.parse(atob(o));return!("typ"in r&&(r==null?void 0:r.typ)!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const Df=w("$ZodJWT",(e,t)=>{le.init(e,t),e._zod.check=n=>{jf(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),wl=w("$ZodNumber",(e,t)=>{ae.init(e,t),e._zod.pattern=Pi,e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;const s=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:String(r):void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...s?{received:s}:{}}),n}}),Uf=w("$ZodNumberFormat",(e,t)=>{Wh.init(e,t),wl.init(e,t)}),Zf=w("$ZodBoolean",(e,t)=>{ae.init(e,t),e._zod.pattern=Hh,e._zod.parse=(n,o)=>{if(t.coerce)try{n.value=!!n.value}catch{}const r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),Hf=w("$ZodNull",(e,t)=>{ae.init(e,t),e._zod.pattern=Fh,e._zod.values=new Set([null]),e._zod.parse=(n,o)=>{const r=n.value;return r===null||n.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),n}}),Ff=w("$ZodAny",(e,t)=>{ae.init(e,t),e._zod.parse=n=>n}),Vf=w("$ZodUnknown",(e,t)=>{ae.init(e,t),e._zod.parse=n=>n}),Jf=w("$ZodNever",(e,t)=>{ae.init(e,t),e._zod.parse=(n,o)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Bf(e,t){const n=Ca(e._zod.def.checks);if(!n.length)return;const o=Math.min(...n.map(s=>s[0])),r=e._zod.parse;e._zod.parse=(s,i)=>{const a=t(s.value);if(a>o&&!(i!=null&&i.skipChecks)&&(i==null?void 0:i.direction)!=="backward"){for(const[c,d]of Ca(e._zod.def.checks))if(a>c&&d._zod.def.when(s)){const u=s.issues.length;return d._zod.check(s),s.issues[u].continue=!1,Js(s.issues,u,e),s}}return r(s,i)}}const Wf=e=>Array.isArray(e)?e.length:-1;function Aa(e,t,n){e.issues.length&&t.issues.push(...In(n,e.issues)),t.value[n]=e.value}const Kf=w("$ZodArray",(e,t)=>{ae.init(e,t);const n=at.memoizer;n==null||n.attach(e),e._zod.parse=(o,r)=>{const s=o.value;if(!Array.isArray(s))return o.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),o;o.value=n?n.alloc(e,o,Array(s.length),r):Array(s.length);const i=[],a=r==null?void 0:r.abortEarly;for(let c=0;c<s.length;c++){const d=s[c],u=t.element._zod.run({value:d,issues:[]},r);if(u instanceof Promise)i.push(u.then(p=>Aa(p,o,c)));else if(Aa(u,o,c),a&&u.issues.length!==0&&Et(u))break}return i.length?Promise.all(i).then(()=>o):o},Bf(e,Wf)});function Hr(e,t,n,o,r,s){const i=n in o,a=s==="optional";if(!(!i&&a&&r==="optional")){if(e.issues.length){if(r!==void 0&&a&&!i)return;t.issues.push(...In(n,e.issues))}if(!i&&r===void 0){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?(i||r==="defaulted"&&!a)&&(t.value[n]=void 0):t.value[n]=e.value}}const Gf=[];function Rl(e){var i,a,c,d;const t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),o=n.length?n:Gf,r=o.length?[...t,...o]:t;for(const u of r)if(!((d=(c=(a=(i=e.shape)==null?void 0:i[u])==null?void 0:a._zod)==null?void 0:c.traits)!=null&&d.has("$ZodType")))throw new Error(`Invalid element at key "${String(u)}": expected a Zod schema`);const s=Om(e.shape);return{...e,allKeys:r,symbolKeys:o,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function Tl(e,t,n,o,r,s,i){const a=[],c=r.keySet,d=r.catchall._zod,u=d.def.type,p=d.optin,m=d.optout;let h=0;for(const f in t){if(i&&n.issues.length!==h){if(Et(n,h))break;h=n.issues.length}if(c.has(f))continue;if(f==="__proto__"){u==="never"&&a.push(f);continue}if(u==="never"){a.push(f);continue}const _=d.run({value:t[f],issues:[]},o);_ instanceof Promise?e.push(_.then(S=>Hr(S,n,f,t,p,m))):Hr(_,n,f,t,p,m)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const Yf=w("$ZodObject",(e,t)=>{ae.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape"),o=n!=null&&n.get?n.get.raw:t.shape??{};if(o){const d=()=>{const u={...o};return Object.defineProperty(t,"shape",{value:u}),d.raw=u,u};d.raw=o,Object.defineProperty(t,"shape",{get:d})}const r=ts(()=>Rl(t));ee(e,"propValues",d=>{const u=d.def.shape,p={};for(const m in u){const h=u[m]._zod;if(h.values){Object.prototype.hasOwnProperty.call(p,m)||yt(p,m,new Set);for(const f of h.values)p[m].add(f);h.optin!==void 0&&p[m].add(void 0)}}return p});const s=Ho,i=t.catchall;let a;const c=at.memoizer;c==null||c.attach(e),e._zod.parse=(d,u)=>{a??(a=r.value);const p=d.value;if(!s(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d;d.value=c?c.alloc(e,d,{},u):{};const m=[],h=a.shape,f=u==null?void 0:u.abortEarly;let _=d.issues.length;for(const S of a.allKeys){if(f&&d.issues.length!==_){if(Et(d,_))break;_=d.issues.length}if(S==="__proto__")continue;const b=h[S],R=b._zod.optin,M=b._zod.optout,L=b._zod.run({value:p[S],issues:[]},u);L instanceof Promise?m.push(L.then(te=>Hr(te,d,S,p,R,M))):Hr(L,d,S,p,R,M)}return i?Tl(m,p,d,u,r.value,e,f===!0):m.length?Promise.all(m).then(()=>d):d}}),Xf=w("$ZodObjectJIT",(e,t)=>{Yf.init(e,t);const n=e._zod.parse,o=ts(()=>Rl(t)),r=at.memoizer,s=h=>{var te,oe;const f=o.value,_=f.symbolKeys,S=new sf(["payload","ctx"],{shape:h,inst:e,memo:r,syms:_}),b=Y=>`shape[${Y}]._zod.run({ value: input[${Y}], issues: [] }, ctx)`,R=(Y,H)=>`
|
|
6
|
+
let ${Y}_ab = false;
|
|
7
|
+
for (let i = 0; i < ${Y}.issues.length; i++) {
|
|
8
|
+
const iss = ${Y}.issues[i];
|
|
9
|
+
iss.path = iss.path ? [${H}, ...iss.path] : [${H}];
|
|
10
|
+
payload.issues.push(iss);
|
|
11
|
+
if (iss.continue !== true) ${Y}_ab = true;
|
|
12
|
+
}
|
|
13
|
+
if (${Y}_ab && ctx && ctx.abortEarly) {
|
|
14
|
+
payload.value = newResult;
|
|
15
|
+
return payload;
|
|
16
|
+
}`;S.write("const input = payload.value;");const M=Object.create(null);let L=0;for(const Y of f.allKeys)M[Y]=`key_${L++}`;S.write(r?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(const Y of f.allKeys){if(Y==="__proto__")continue;const H=M[Y],ne=typeof Y=="symbol"?`syms[${_.indexOf(Y)}]`:Em(Y),Q=`${ne} in input`,re=h[Y],we=(te=re==null?void 0:re._zod)==null?void 0:te.optin,Me=we!==void 0,pe=((oe=re==null?void 0:re._zod)==null?void 0:oe.optout)==="optional";if(S.write(`const ${H} = ${b(ne)};`),Me&&pe){const _e=we==="optional"?`${H}_present`:`${H}.value !== undefined || ${H}_present`;S.write(`
|
|
17
|
+
const ${H}_present = ${Q};
|
|
18
|
+
if (!${H}.issues.length || ${H}_present) {
|
|
19
|
+
if (${H}.issues.length) {${R(H,ne)}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (${_e}) {
|
|
23
|
+
newResult[${ne}] = ${H}.value;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
`)}else Me?(S.write(`
|
|
28
|
+
if (${H}.issues.length) {${R(H,ne)}
|
|
29
|
+
}
|
|
30
|
+
`),we==="defaulted"?S.write(`newResult[${ne}] = ${H}.value;`):S.write(`
|
|
31
|
+
if (${H}.value !== undefined || ${Q}) {
|
|
32
|
+
newResult[${ne}] = ${H}.value;
|
|
33
|
+
}
|
|
34
|
+
`)):S.write(`
|
|
35
|
+
const ${H}_present = ${Q};
|
|
36
|
+
if (${H}.issues.length) {${R(H,ne)}
|
|
37
|
+
}
|
|
38
|
+
if (!${H}_present && !${H}.issues.length) {
|
|
39
|
+
payload.issues.push({
|
|
40
|
+
code: "invalid_type",
|
|
41
|
+
expected: "nonoptional",
|
|
42
|
+
input: undefined,
|
|
43
|
+
path: [${ne}]
|
|
44
|
+
});
|
|
45
|
+
if (ctx && ctx.abortEarly) {
|
|
46
|
+
payload.value = newResult;
|
|
47
|
+
return payload;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (${H}_present) {
|
|
52
|
+
newResult[${ne}] = ${H}.value;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
`)}return S.write("payload.value = newResult;"),S.write("return payload;"),S.compile()};let i;const a=Ho,c=!at.jitless,u=c&&km.value,p=t.catchall;let m;e._zod.parse=(h,f)=>{m??(m=o.value);const _=h.value;return a(_)?c&&u&&(f==null?void 0:f.async)===!1&&f.jitless!==!0?(i||(i=s(t.shape)),h=i(h,f),p?Tl([],_,h,f,m,e,(f==null?void 0:f.abortEarly)===!0):h):n(h,f):(h.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),h)}});function xa(e,t,n,o){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const r=e.filter(s=>!Et(s));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(i=>Ft(i,o,St())))}),t)}const $l=w("$ZodUnion",(e,t)=>{ae.init(e,t),ee(e,"optin",o=>o.def.options.some(r=>r._zod.optin==="defaulted")?"defaulted":o.def.options.some(r=>r._zod.optin!==void 0)?"optional":void 0),ee(e,"optout",o=>o.def.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ee(e,"values",o=>{if(o.def.options.every(r=>r._zod.values))return new Set(o.def.options.flatMap(r=>Array.from(r._zod.values)))}),ee(e,"pattern",o=>{if(o.def.options.every(r=>r._zod.pattern)){const r=o.def.options.map(s=>s._zod.pattern);return new RegExp(`^(${r.map(s=>_i(s.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,r)=>{if(n)return n(o,r);let s=!1;const i=[];for(const a of t.options){const c=a._zod.run({value:o.value,issues:[]},r);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>xa(a,o,e,r)):xa(i,o,e,r)}});function Qf(e){var n;const t=new Map;for(const o of e.options){const r=(n=o._zod.propValues)==null?void 0:n[e.discriminator];if(!r||r.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const s of r)if(t.has(s)){if(s!==void 0)throw new Error(`Duplicate discriminator value "${String(s)}"`);t.set(s,null)}else t.set(s,o)}return t}const eg=w("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,$l.init(e,t);const n=e._zod.parse;ee(e,"propValues",r=>{var a,c;const s={};let i=0;for(const d of r.def.options){const u=d._zod.propValues;if(!u||Object.keys(u).length===0)throw new Error(`Invalid discriminated union option at index "${r.def.options.indexOf(d)}"`);(a=u[r.def.discriminator])!=null&&a.has(void 0)&&i++;for(const[p,m]of Object.entries(u)){Object.prototype.hasOwnProperty.call(s,p)||yt(s,p,new Set);for(const h of m)s[p].add(h)}}return!r.def.unionFallback&&i>1&&((c=s[r.def.discriminator])==null||c.delete(void 0)),s}),t.options.forEach((r,s)=>{const i=vi(r._zod.def);if(i&&!Object.prototype.hasOwnProperty.call(i,t.discriminator))throw new Error(`Invalid discriminated union option at index "${s}"`)});const o=ts(()=>Qf(t));e._zod.parse=(r,s)=>{const i=r.value;if(!Ho(i))return r.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),r;const a=i==null?void 0:i[t.discriminator],c=o.value.get(a);return c&&(a!==void 0||s.direction!=="backward")?c._zod.run(r,s):t.unionFallback||s.direction==="backward"?n(r,s):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(o.value.keys()).filter(d=>o.value.get(d)!==null),input:i,path:[t.discriminator],inst:e}),r)}}),tg=w("$ZodIntersection",(e,t)=>{ae.init(e,t),e._zod.parse=(n,o)=>{const r=n.value,s=t.left._zod.run({value:r,issues:[]},o),i=t.right._zod.run({value:r,issues:[]},o);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,d])=>za(n,c,d)):za(n,s,i)}});function Ws(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Dn(e)&&Dn(t)){const n=Object.keys(t),o=Object.keys(e).filter(s=>n.indexOf(s)!==-1),r={...e,...t};Object.prototype.hasOwnProperty.call(r,"__proto__")&&delete r.__proto__;for(const s of o){if(s==="__proto__")continue;const i=Ws(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};r[s]=i.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let o=0;o<e.length;o++){const r=e[o],s=t[o],i=Ws(r,s);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function za(e,t,n){const o=new Map;let r;const s=new Map,i=(d,u)=>{var m,h;let p;if(d.code==="unrecognized_keys"&&!((m=d.path)!=null&&m.length))r??(r=d),p=d.keys;else if(d.code==="invalid_key"&&d.origin==="record"&&((h=d.path)==null?void 0:h.length)===1){const f=String(d.path[0]);s.has(f)||s.set(f,d),p=[f]}else return!1;for(const f of p)o.has(f)||o.set(f,{}),o.get(f)[u]=!0;return!0};for(const d of t.issues)i(d,"l")||e.issues.push(d);for(const d of n.issues)i(d,"r")||e.issues.push(d);const a=[...o].filter(([,d])=>d.l&&d.r).map(([d])=>d);if(a.length){const d=r?a.filter(u=>r.keys.includes(u)):[];d.length&&e.issues.push({...r,keys:d});for(const u of a)!d.includes(u)&&s.has(u)&&e.issues.push(s.get(u))}const c=Ws(t.value,n.value);if(!c.valid){if(Et(e))return e;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}const ng=w("$ZodRecord",(e,t)=>{ae.init(e,t);const n=at.memoizer;n==null||n.attach(e),e._zod.parse=(o,r)=>{const s=o.value;if(!Dn(s))return o.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),o;const i=[],a=t.keyType._zod.values;if(a&&!t.partial){o.value=n?n.alloc(e,o,{},r):{};const c=new Set;for(const u of a)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){if(c.add(typeof u=="number"?u.toString():u),u==="__proto__")continue;const p=t.keyType._zod.run({value:u,issues:[]},r);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(p.issues.length){o.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(f=>Ft(f,r,St())),input:u,path:[u],inst:e});continue}const m=p.value;if(m==="__proto__")continue;const h=t.valueType._zod.run({value:s[u],issues:[]},r);h instanceof Promise?i.push(h.then(f=>{f.issues.length&&o.issues.push(...In(u,f.issues)),o.value[m]=f.value})):(h.issues.length&&o.issues.push(...In(u,h.issues)),o.value[m]=h.value)}let d;for(const u in s)if(!c.has(u))if(t.mode==="loose"){if(u==="__proto__")continue;o.value[u]=s[u]}else d=d??[],d.push(u);d&&d.length>0&&o.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:d,continue:!0})}else{o.value=n?n.alloc(e,o,{},r):{};let c;for(const d of Reflect.ownKeys(s)){if(d==="__proto__"||!Object.prototype.propertyIsEnumerable.call(s,d))continue;let u=t.keyType._zod.run({value:d,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof d=="string"&&Pi.test(d)&&u.issues.length){const f=t.keyType._zod.run({value:Number(d),issues:[]},r);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");f.issues.length===0&&(u=f)}if(u.issues.length){t.mode==="loose"?o.value[d]=s[d]:a?(c=c??[],c.push(d)):o.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(f=>Ft(f,r,St())),input:d,path:[d],inst:e});continue}const m=u.value;if(m==="__proto__")continue;const h=t.valueType._zod.run({value:s[d],issues:[]},r);h instanceof Promise?i.push(h.then(f=>{f.issues.length&&o.issues.push(...In(d,f.issues)),o.value[m]=f.value})):(h.issues.length&&o.issues.push(...In(d,h.issues)),o.value[m]=h.value)}c&&c.length>0&&o.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c,continue:!0})}return i.length?Promise.all(i).then(()=>o):o}}),og=w("$ZodEnum",(e,t)=>{ae.init(e,t);const n=Fs(t.entries),o=new Set(n);e._zod.values=o,ee(e,"pattern",r=>{const s=Fs(r.def.entries).filter(i=>Cm.has(typeof i));return new RegExp(s.length?`^(${s.map(i=>Un(i.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,s)=>{const i=r.value;return o.has(i)||r.issues.push({code:"invalid_value",values:n,input:i,inst:e}),r}}),rg=w("$ZodLiteral",(e,t)=>{ae.init(e,t);const n=new Set(t.values);e._zod.values=n,ee(e,"pattern",o=>{const r=o.def.values;return new RegExp(r.length?`^(${r.map(s=>typeof s=="string"?Un(s):s?Un(s.toString()):String(s)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,r)=>{const s=o.value;return n.has(s)||o.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),o}}),sg=w("$ZodTransform",(e,t)=>{var n;ae.init(e,t),e._zod.optin="optional",(n=at.memoizer)==null||n.guard(e),e._zod.parse=(o,r)=>{if(r.direction==="backward")throw new ul(e.constructor.name);const s=t.transform(o.value,o);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(a=>(o.value=a,o));if(s instanceof Promise)throw new mn;return o.value=s,o}});function La(e,t){return e.value=t.issues.length?void 0:t.value,e}const El=w("$ZodOptional",(e,t)=>{ae.init(e,t),ee(e,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",ee(e,"values",n=>{const o=n.def.innerType._zod.values;return o?new Set([...o,void 0]):void 0}),ee(e,"pattern",n=>{const o=n.def.innerType._zod.pattern;return o?new RegExp(`^(${_i(o.source)})?$`):void 0}),e._zod.parse=(n,o)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;const r=t.innerType._zod.run({value:n.value,issues:[]},o);return r instanceof Promise?r.then(s=>La(n,s)):La(n,r)}return t.innerType._zod.run(n,o)}}),ig=w("$ZodExactOptional",(e,t)=>{El.init(e,t),ee(e,"values",n=>n.def.innerType._zod.values),ee(e,"pattern",n=>n.def.innerType._zod.pattern),e._zod.parse=(n,o)=>t.innerType._zod.run(n,o)}),ag=w("$ZodNullable",(e,t)=>{ae.init(e,t),ee(e,"optin",n=>n.def.innerType._zod.optin),ee(e,"optout",n=>n.def.innerType._zod.optout),ee(e,"pattern",n=>{const o=n.def.innerType._zod.pattern;return o?new RegExp(`^(${_i(o.source)}|null)$`):void 0}),ee(e,"values",n=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,o)=>n.value===null?n:t.innerType._zod.run(n,o)}),cg=w("$ZodDefault",(e,t)=>{ae.init(e,t),e._zod.optin="defaulted",ee(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);if(n.value===void 0)return n.value=t.defaultValue,n;const r=t.innerType._zod.run(n,o);return r instanceof Promise?r.then(s=>ja(s,t)):ja(r,t)}});function ja(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const lg=w("$ZodPrefault",(e,t)=>{ae.init(e,t),e._zod.optin="defaulted",ee(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,o)=>(o.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,o))}),ug=w("$ZodNonOptional",(e,t)=>{ae.init(e,t),ee(e,"values",n=>{const o=n.def.innerType._zod.values;return o?new Set([...o].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,o)=>{const r=t.innerType._zod.run(n,o);return r instanceof Promise?r.then(s=>Da(s,e)):Da(r,e)}});function Da(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function Ua(e,t,n,o){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(r=>Ft(r,o,St()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const dg=w("$ZodCatch",(e,t)=>{ae.init(e,t),ee(e,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),ee(e,"optout",n=>n.def.innerType._zod.optout),ee(e,"values",n=>n.def.innerType._zod.values),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);const r=t.innerType._zod.run({value:n.value,issues:[]},o);return r instanceof Promise?r.then(s=>Ua(n,s,t,o)):Ua(n,r,t,o)}}),Pl=w("$ZodPipe",(e,t)=>{ae.init(e,t),ee(e,"values",n=>n.def.in._zod.values),ee(e,"optin",n=>n.def.in._zod.optin),ee(e,"optout",n=>n.def.out._zod.optout),ee(e,"propValues",n=>n.def.in._zod.propValues),e._zod.parse=(n,o)=>{if(o.direction==="backward"){const s=t.out._zod.run(n,o);return s instanceof Promise?s.then(i=>br(i,t.in,o)):br(s,t.in,o)}const r=t.in._zod.run(n,o);return r instanceof Promise?r.then(s=>br(s,t.out,o)):br(r,t.out,o)}});function br(e,t,n){return e.issues.some(o=>o.code!=="unrecognized_keys")?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const pg=w("$ZodPreprocess",(e,t)=>{Pl.init(e,t)}),mg=w("$ZodReadonly",(e,t)=>{ae.init(e,t),ee(e,"propValues",n=>n.def.innerType._zod.propValues),ee(e,"values",n=>n.def.innerType._zod.values),ee(e,"optin",n=>{var o,r;return(r=(o=n.def.innerType)==null?void 0:o._zod)==null?void 0:r.optin}),ee(e,"optout",n=>{var o,r;return(r=(o=n.def.innerType)==null?void 0:o._zod)==null?void 0:r.optout}),e._zod.parse=(n,o)=>{if(o.direction==="backward")return t.innerType._zod.run(n,o);const r=t.innerType._zod.run(n,o);return r instanceof Promise?r.then(Za):Za(r)}});function Za(e){return e.memo||(e.value=Object.freeze(e.value)),e}const hg=w("$ZodLazy",(e,t)=>{ae.init(e,t),Tm(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),ee(e,"pattern",n=>{var o,r;return(r=(o=n.innerType)==null?void 0:o._zod)==null?void 0:r.pattern}),ee(e,"propValues",n=>{var o,r;return(r=(o=n.innerType)==null?void 0:o._zod)==null?void 0:r.propValues}),ee(e,"optin",n=>{var o,r;return((r=(o=n.innerType)==null?void 0:o._zod)==null?void 0:r.optin)??void 0}),ee(e,"optout",n=>{var o,r;return((r=(o=n.innerType)==null?void 0:o._zod)==null?void 0:r.optout)??void 0}),e._zod.parse=(n,o)=>e._zod.innerType._zod.run(n,o)}),fg=w("$ZodCustom",(e,t)=>{Le.init(e,t),ae.init(e,t),e._zod.parse=(n,o)=>n,e._zod.check=n=>{const o=n.value,r=t.fn(o);if(r instanceof Promise)return r.then(s=>Ha(s,n,o,e));Ha(r,n,o,e)}});function Ha(e,t,n,o){if(!e){const r={code:"custom",input:n,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(r.params=o._zod.def.params),t.issues.push(Fo(r))}}class gg extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}const Ks="~memo",Fa=[];function kl(e){return e!==null&&typeof e=="object"}function Ps(e){return e.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}const Cl=new WeakMap,Mo=0,Mr=1,zo=2;function Ar(e,t,n){const o=Cl.get(e);if(o!==void 0)return o?zo:Mo;if(t.has(e))return zo;t.add(e);let r=Mo;const s=u=>{if(r!==zo&&(u!=null&&u._zod)){const p=Ar(u,t);p>r&&(r=p)}},i=(u,p)=>{var h;let m=Mo;for(const f of Reflect.ownKeys(u)){const _=Object.getOwnPropertyDescriptor(u,f);if(!_.enumerable)continue;const S=_.get?Mr:(h=_.value)!=null&&h._zod?Ar(_.value,t):Mo;S>m&&(m=S)}return m},a=u=>{u>r&&(r=u)},c=e._zod.def;switch(c.type){case"object":{const u=vi(c);a(u?i(u):Mr),s(c.catchall);break}case"array":s(c.element);break;case"tuple":for(const u of c.items)s(u);s(c.rest);break;case"record":case"map":s(c.keyType),s(c.valueType);break;case"set":s(c.valueType);break;case"union":for(const u of c.options)s(u);break;case"intersection":s(c.left),s(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(c.innerType);break;case"pipe":s(c.in),s(c.out);break;case"function":s(c.input),s(c.output);break;case"lazy":{const u=c._cachedInner??void 0;a(u?Ar(u,t):Mr);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(const u in c){const p=Object.getOwnPropertyDescriptor(c,u);if(!p||p.get)continue;const m=p.value;if(!(!m||typeof m!="object")){if(m._zod)s(m);else if(Array.isArray(m))for(const h of m)s(h)}}}return t.delete(e),Sg(e,r)}function Sg(e,t){return t!==Mr&&Cl.set(e,t===zo),t}function yg(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}let wr;const Rr=[],_g={alloc(e,t,n){const o=wr;if(!o)return n;wr=void 0;const r={value:n,issues:null};return o.set(t.value,r),Rr.push(r),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const n=e._zod.parse,o=(r,s)=>{if(s.direction!=="backward"&&bg(s,r.value))throw new gg;return n(r,s)};e._zod.parse=o,e._zod.run===n&&(e._zod.run=o)})},attach(e){var t;let n,o=!1,r,s;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const i=e._zod.parse,a=(c,d)=>{if(n===void 0){const b=Ar(e,new Set);if(b===Mo)return e._zod.parse=i,e._zod.run===a&&(e._zod.run=i),i(c,d);b===zo||o?n=!0:o=!0}const u=c.value;if(!kl(u))return i(c,d);let p=d[Ks];p||(p={buckets:new WeakMap,backEdges:void 0},d[Ks]=p);let m;r===d?m=s:(m=yg(p,e),r=d,s=m);const h=m.get(u);if(h)return c.value=h.value,h.issues?h.issues.length&&c.issues.push(...Ps(h.issues)):(c.memo=!0,p.backEdges??(p.backEdges=new WeakSet),p.backEdges.add(h.value)),c;wr=m;const f=Rr.length,_=i(c,d);wr=void 0;const S=Rr.length>f?Rr.pop():void 0;return _ instanceof Promise?_.then(b=>(S&&(S.issues=b.issues.length?Ps(b.issues):Fa),b)):(S&&(S.issues=_.issues.length?Ps(_.issues):Fa),_)};e._zod.parse=a,e._zod.run===i&&(e._zod.run=a)})}};function vg(){return _g}function bg(e,t){var o;const n=(o=e[Ks])==null?void 0:o.backEdges;return n!==void 0&&kl(t)&&n.has(t)}const wg=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(s){return e[s]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};function r(s,i){return s==="number"&&typeof i=="number"&&!Number.isFinite(i)?String(i):o[s]??s}return s=>{switch(s.code){case"invalid_type":{const i=r(s.expected),a=Dm(s.input),c=r(a,s.input);return`Invalid input: expected ${i}, received ${c}`}case"invalid_value":return s.values.length===1?`Invalid input: expected ${sl(s.values[0])}`:`Invalid option: expected one of ${Ea(s.values,"|")}`;case"too_big":{const i=s.exact?"exactly ":s.inclusive?"<=":"<",a=t(s.origin);return a?`Too big: expected ${s.origin??"value"} to have ${i}${s.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${s.origin??"value"} to be ${i}${s.maximum.toString()}`}case"too_small":{const i=s.exact?"exactly ":s.inclusive?">=":">",a=t(s.origin);return a?`Too small: expected ${s.origin} to have ${i}${s.minimum.toString()} ${a.unit}`:`Too small: expected ${s.origin} to be ${i}${s.minimum.toString()}`}case"invalid_format":{const i=s;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${n[i.format]??s.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${s.divisor}`;case"unrecognized_keys":return`Unrecognized key${s.keys.length>1?"s":""}: ${Ea(s.keys,", ")}`;case"invalid_key":return`Invalid key in ${s.origin}`;case"invalid_union":return s.options&&Array.isArray(s.options)&&s.options.length>0?`Invalid discriminator value. Expected ${s.options.map(a=>`'${a}'`).join(" | ")}`:s.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${s.origin}`;default:return"Invalid input"}}};function Rg(){return{localeError:wg()}}var Va;class Tg{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const o=n[0];return this._map.set(t,o),o&&typeof o=="object"&&"id"in o&&this._idmap.set(o.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const o={...this.get(n)??{}};delete o.id;const r={...o,...this._map.get(t)};return Object.keys(r).length?r:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function $g(){return new Tg}(Va=globalThis).__zod_globalRegistry??(Va.__zod_globalRegistry=$g());const Ao=globalThis.__zod_globalRegistry;function Ii(e){return e.checks&&(e.checks=[...e.checks]),e}function Eg(e,t){return new e(Ii({type:"string",...x(t)}))}function Ol(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...x(t)})}function Pg(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...x(t)})}function kg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...x(t)})}function Cg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...x(t)})}function Og(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...x(t)})}function Ig(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...x(t)})}function Il(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...x(t)})}function qg(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...x(t)})}function Ng(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...x(t)})}function Mg(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...x(t)})}function Ag(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...x(t)})}function xg(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...x(t)})}function zg(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...x(t)})}function Lg(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...x(t)})}function jg(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...x(t)})}function Dg(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...x(t)})}function Ug(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...x(t)})}function Zg(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...x(t)})}function Hg(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...x(t)})}function Fg(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...x(t)})}function Vg(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...x(t)})}function Jg(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...x(t)})}function ql(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...x(t)})}function Nl(e,t){return new e({type:"string",format:"date",check:"string_format",...x(t)})}function Bg(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...x(t)})}function Wg(e,t){return new e({type:"string",format:"duration",check:"string_format",...x(t)})}function Kg(e,t){return new e(Ii({type:"number",checks:[],...x(t)}))}function Gg(e,t){return new e(Ii({type:"number",coerce:!0,checks:[],...x(t)}))}function Yg(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...x(t)})}function Xg(e,t){return new e({type:"boolean",...x(t)})}function Qg(e,t){return new e({type:"null",...x(t)})}function eS(e){return new e({type:"any"})}function tS(e){return new e({type:"unknown"})}function nS(e,t){return new e({type:"never",...x(t)})}function Ja(e,t){return new ml({check:"less_than",...x(t),value:e,inclusive:!1})}function ks(e,t){return new ml({check:"less_than",...x(t),value:e,inclusive:!0})}function Ba(e,t){return new hl({check:"greater_than",...x(t),value:e,inclusive:!1})}function Cs(e,t){return new hl({check:"greater_than",...x(t),value:e,inclusive:!0})}function Wa(e,t){return new Bh({check:"multiple_of",...x(t),value:e})}function Ml(e,t){return new Kh({check:"max_length",...x(t),maximum:e})}function Fr(e,t){return new Gh({check:"min_length",...x(t),minimum:e})}function Al(e,t){return new Yh({check:"length_equals",...x(t),length:e})}function oS(e,t){return new Xh({check:"string_format",format:"regex",...x(t),pattern:e})}function rS(e){return new Qh({check:"string_format",format:"lowercase",...x(e)})}function sS(e){return new ef({check:"string_format",format:"uppercase",...x(e)})}function iS(e,t){return new tf({check:"string_format",format:"includes",...x(t),includes:e})}function aS(e,t){return new nf({check:"string_format",format:"starts_with",...x(t),prefix:e})}function cS(e,t){return new of({check:"string_format",format:"ends_with",...x(t),suffix:e})}function Wn(e){return new rf({check:"overwrite",tx:e})}function lS(e){return Wn(t=>t.normalize(e))}function uS(){return Wn(e=>e.trim())}function dS(){return Wn(e=>e.toLowerCase())}function pS(){return Wn(e=>e.toUpperCase())}function mS(){return Wn(e=>Pm(e))}function hS(e,t,n){return new e({type:"array",element:t,...x(n)})}function fS(e,t,n){return new e({type:"custom",check:"custom",fn:t,...x(n)})}function gS(e,t){const n=SS(o=>(o.addIssue=r=>{if(typeof r=="string")o.issues.push(Fo(r,o.value,n._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=o.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),o.issues.push(Fo(s))}},e(o.value,o)),t);return n}function SS(e,t){const n=new Le({check:"custom",...x(t)});return n._zod.check=e,n}function Lo(e,...t){for(const n of t)for(const o of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,o)&&yt(e,o,n[o]);return e}function Vr(e){let t=(e==null?void 0:e.target)??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:(e==null?void 0:e.metadata)??Ao,target:t,unrepresentable:(e==null?void 0:e.unrepresentable)??"throw",override:(e==null?void 0:e.override)??(()=>{}),io:(e==null?void 0:e.io)??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:(e==null?void 0:e.cycles)??"ref",reused:(e==null?void 0:e.reused)??"inline",intersections:[],deferred:[],external:(e==null?void 0:e.external)??void 0}}function be(e,t,n,o,r){const s=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:o.path,message:r}):t.unrepresentable;if(s==="any")return!1;if(s===void 0||s==="throw")throw new Error(r);return Object.assign(n,s),!0}function ie(e,t,n={path:[],schemaPath:[]}){var u,p;var o;const r=e._zod.def,s=t.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;const i={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,i),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;const a=(p=(u=e._zod).toJSONSchema)==null?void 0:p.call(u);if(a)i.schema=a;else{const m={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,m);else{const f=i.schema,_=t.processors[r.type];if(!_)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);_(e,t,f,m)}const h=e._zod.parent;h&&(i.ref||(i.ref=h),ie(h,t,m),t.seen.get(h).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Lo(i.schema,c),t.io==="input"&&qe(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((o=i.schema).default??(o.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function Ka(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Jr(e,t){var i,a,c,d;const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;const o=new Map;for(const u of e.seen.entries()){const p=(i=e.metadataRegistry.get(u[0]))==null?void 0:i.id;if(p){const m=o.get(p);if(m&&m!==u[0])throw new Error(`Duplicate schema id "${p}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(p,u[0])}}const r=u=>{var _;const p=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const S=(_=e.external.registry.get(u[0]))==null?void 0:_.id,b=e.external.uri??(M=>M);if(S)return{ref:b(S)};const R=u[1].defId??u[1].schema.id??`schema${e.counter++}`;return u[1].defId=R,{defId:R,ref:`${b("__shared")}#/${p}/${Ka(R)}`}}const m="#",h=`${m}/${p}/`;if(u[1]===n&&!u[1].schema.id)return{ref:m};const f=u[1].schema.id??`__schema${e.counter++}`;return{defId:f,ref:h+Ka(f)}},s=u=>{if(u[1].schema.$ref)return;const p=u[1],{ref:m,defId:h}=r(u);p.def={...p.schema},h&&(p.defId=h);const f=p.schema;for(const _ in f)delete f[_];f.$ref=m};if(e.cycles==="throw")for(const u of e.seen.entries()){const p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${(a=p.cycle)==null?void 0:a.join("/")}/<root>
|
|
56
|
+
|
|
57
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of e.seen.entries()){const p=u[1];if(t===u[0]){s(u);continue}if(e.external){const h=(c=e.external.registry.get(u[0]))==null?void 0:c.id;if(t!==u[0]&&h){s(u);continue}}if((d=e.metadataRegistry.get(u[0]))==null?void 0:d.id){s(u);continue}if(p.cycle){s(u);continue}p.count>1&&e.reused==="ref"&&s(u)}e.external&&(e.sharedDefsExtractedFor=e.external)}function xl(e){const t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;const n=[];for(const o of t){if(!o||typeof o!="object")return;xl(o);const r=Object.keys(o);if(r.length!==1||r[0]!=="type")return;const s=o.type;for(const i of Array.isArray(s)?s:[s]){if(typeof i!="string")return;n.includes(i)||n.push(i)}}delete e.anyOf,e.type=n.length===1?n[0]:n}const zl=new Set(["type","properties","required","additionalProperties"]),Ga=["oneOf","anyOf"];function Ya(e){const t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function Gs(e){var s;const t=[];for(const i of e){if(typeof i!="object"||i.type!=="object")return null;for(const a in i)if(!zl.has(a))return null;t.push(i)}const n={},o=new Set;for(const i of t){for(const a in i.properties){if(Object.prototype.hasOwnProperty.call(n,a))continue;const c=[];for(const u of t){const p=((s=u.properties)==null?void 0:s[a])??Ya(u);p!=null&&(c.some(m=>JSON.stringify(m)===JSON.stringify(p))||c.push(p))}const d=c.length===1?c[0]:Gs(c)??{allOf:c};yt(n,a,d)}for(const a of i.required??[])o.add(a)}const r={type:"object",properties:n};if(o.size&&(r.required=[...o]),t.every(i=>i.additionalProperties===!1))r.additionalProperties=!1;else{const i=[];for(const a of t){const c=Ya(a);c&&!i.some(d=>JSON.stringify(d)===JSON.stringify(c))&&i.push(c)}i.length===1?r.additionalProperties=i[0]:i.length>1&&(r.additionalProperties={allOf:i})}return r}function yS(e){const t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(const r of zl)if(r in e)return;const n=t.filter(r=>Ga.some(s=>Array.isArray(r[s])));let o=null;if(!n.length)o=Gs(t);else{const r=n[0],s=Ga.find(c=>Array.isArray(r[c]));if(Object.keys(r).length!==1)return;const i=t.filter(c=>c!==r),a=r[s].map(c=>Gs([...i,c]));if(a.some(c=>!c))return;o={[s]:a}}o&&(delete e.allOf,Lo(e,o))}function Br(e,t){var a,c,d,u;const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const o=p=>{const m=e.seen.get(p);if(m.ref===null)return;const h=m.def??m.schema,f={...h},_=m.ref;if(m.ref=null,_){o(_);const b=e.seen.get(_),R=b.schema;if(R.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(h.allOf=h.allOf??[],h.allOf.push(R)):Lo(h,R),Lo(h,f),p._zod.parent===_)for(const L in h)L==="$ref"||L==="allOf"||L in f||delete h[L];if(R.$ref&&b.def)for(const L in h)L==="$ref"||L==="allOf"||L in b.def&&JSON.stringify(h[L])===JSON.stringify(b.def[L])&&delete h[L]}const S=p._zod.parent;if(S&&S!==_){o(S);const b=e.seen.get(S);if(b!=null&&b.schema.$ref&&(h.$ref=b.schema.$ref,b.def))for(const R in h)R==="$ref"||R==="allOf"||R in b.def&&JSON.stringify(h[R])===JSON.stringify(b.def[R])&&delete h[R]}e.override({zodSchema:p,jsonSchema:h,path:m.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(const p of[...e.seen.entries()].reverse())o(p[0]);if(e.target!=="openapi-3.0")for(const p of e.seen.entries())xl(p[1].def??p[1].schema);for(const p of e.deferred)p();if(e.intersections.length){const p=new Map;for(const m of e.seen.values())for(const h of[m.schema,m.def]){const f=h==null?void 0:h.allOf;if(!Array.isArray(f))continue;const _=p.get(f);_?_.push(h):p.set(f,[h])}for(const m of e.intersections)for(const h of p.get(m)??[])yS(h)}}const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,(a=e.external)!=null&&a.uri){const p=(c=e.external.registry.get(t))==null?void 0:c.id;if(!p)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(p)}Lo(r,n.defId?n.schema:n.def??n.schema);const s=(d=e.metadataRegistry.get(t))==null?void 0:d.id;s!==void 0&&r.id===s&&delete r.id;const i=((u=e.external)==null?void 0:u.defs)??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(const p of e.seen.entries()){const m=p[1];m.def&&m.defId&&(m.def.id===m.defId&&delete m.def.id,yt(i,m.defId,m.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?r.$defs=i:r.definitions=i);try{const p=JSON.parse(JSON.stringify(r));return Object.defineProperty(p,"~standard",{value:{...t["~standard"],jsonSchema:{input:Wr(t,"input",e.processors),output:Wr(t,"output",e.processors)}},enumerable:!1,writable:!1}),p}catch{throw new Error("Error converting schema to JSON.")}}function qe(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return qe(o.element,n);if(o.type==="set")return qe(o.valueType,n);if(o.type==="lazy")return qe(o.getter(),n);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault"||o.type==="catch")return qe(o.innerType,n);if(o.type==="intersection")return qe(o.left,n)||qe(o.right,n);if(o.type==="record"||o.type==="map")return qe(o.keyType,n)||qe(o.valueType,n);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:qe(o.in,n)||qe(o.out,n);if(o.type==="object"){for(const r in o.shape)if(qe(o.shape[r],n))return!0;return!1}if(o.type==="union"){for(const r of o.options)if(qe(r,n))return!0;return!1}if(o.type==="tuple"){for(const r of o.items)if(qe(r,n))return!0;return!!(o.rest&&qe(o.rest,n))}return!1}const _S=(e,t={})=>n=>{const o=Vr({...n,processors:t});return ie(e,o),Jr(o,e),Br(o,e)},Wr=(e,t,n={})=>o=>{const{libraryOptions:r,target:s}=o??{},i=Vr({...r??{},target:s,io:t,processors:n});return ie(e,i),Jr(i,e),Br(i,e)},Zn=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},Hn=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Xa=(e,t)=>{Zn(e,"minimum",t),Hn(e,"maximum",t)},Ll=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},jl=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Dl=(e,t)=>{e.mime=e.mime?e.mime.filter(n=>t.includes(n)):[...t]},Ul=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},Qa=(e,t)=>Zn(e,"minimum",t.minimum),ec=(e,t)=>Hn(e,"maximum",t.maximum),tc=e=>(t,n)=>{Ul(t,n.format);const[o,r]=e[n.format];Zn(t,"minimum",o),Hn(t,"maximum",r)},Os={greater_than:(e,t)=>Zn(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Hn(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Ll(e,t.value),number_format:tc(il),bigint_format:tc(Im),min_length:Qa,max_length:ec,length_equals:(e,t)=>Xa(e,t.length),min_size:Qa,max_size:ec,size_equals:(e,t)=>Xa(e,t.size),string_format:(e,t)=>{Ul(e,t.format),t.pattern&&jl(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Dl(e,t.mime)};function Be(e){var s;const t={},n=e._zod.def,o=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(const i of o)(s=Os[i._zod.def.check])==null||s.call(Os,t,i._zod.def);const r=e._zod.bag;r.minimum!==void 0&&Zn(t,"minimum",r.minimum),r.exclusiveMinimum!==void 0&&Zn(t,"exclusiveMinimum",r.exclusiveMinimum),r.maximum!==void 0&&Hn(t,"maximum",r.maximum),r.exclusiveMaximum!==void 0&&Hn(t,"exclusiveMaximum",r.exclusiveMaximum),r.multipleOf!==void 0&&Ll(t,r.multipleOf),r.format!==void 0&&(t.format??(t.format=r.format),r.format.includes("int")&&(t.isInt=!0)),r.mime&&Dl(t,r.mime);for(const i of r.patterns??[])jl(t,i);return t}const vS={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},bS=new Map([[bl,Nh],[Oi,Mh]]),Zl=e=>bS.get(e)??e,Hl=(e,t,n,o)=>{const r=n;r.type="string";const{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:d,laxFormat:u}=Be(e);if(typeof s=="number"&&(r.minLength=s),typeof i=="number"&&(r.maxLength=i),a&&(r.format=vS[a]??a,r.format===""&&delete r.format,(a==="time"||u)&&delete r.format),d&&(r.contentEncoding=d),c&&c.size>0){const p=[...c].map(Zl);p.length===1?r.pattern=p[0].source:p.length>1&&(r.allOf=[...p.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},Fl=(e,t,n,o)=>{const r=n,{minimum:s,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:d,isInt:u}=Be(e);r.type=u?"integer":"number";const p=typeof d=="number"&&d>=(s??Number.NEGATIVE_INFINITY),m=typeof c=="number"&&c<=(i??Number.POSITIVE_INFINITY),h=t.target==="draft-04"||t.target==="openapi-3.0";if(p?h?(r.minimum=d,r.exclusiveMinimum=!0):r.exclusiveMinimum=d:typeof s=="number"&&(r.minimum=s),m?h?(r.maximum=c,r.exclusiveMaximum=!0):r.exclusiveMaximum=c:typeof i=="number"&&(r.maximum=i),a){const f=new Set;for(const b of a)Number.isFinite(b)&&b!==0?f.add(Math.abs(b)):be(e,t,r,o,`A multipleOf divisor of ${b} cannot be represented in JSON Schema`);const[_,...S]=f;_!==void 0&&(r.multipleOf=_),S.length&&(r.allOf=[...r.allOf??[],...S.map(b=>({multipleOf:b}))])}},Vl=(e,t,n,o)=>{n.type="boolean"},wS=(e,t,n,o)=>{be(e,t,n,o,"BigInt cannot be represented in JSON Schema")},RS=(e,t,n,o)=>{be(e,t,n,o,"Symbols cannot be represented in JSON Schema")},Jl=(e,t,n,o)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},TS=(e,t,n,o)=>{be(e,t,n,o,"Undefined cannot be represented in JSON Schema")},$S=(e,t,n,o)=>{be(e,t,n,o,"Void cannot be represented in JSON Schema")},Bl=(e,t,n,o)=>{n.not={}},Wl=(e,t,n,o)=>{},Kl=(e,t,n,o)=>{},ES=(e,t,n,o)=>{be(e,t,n,o,"Date cannot be represented in JSON Schema")},Gl=(e,t,n,o)=>{const r=e._zod.def,s=Fs(r.entries);if(s.length===0){n.not={};return}s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},Yl=(e,t,n,o)=>{const r=e._zod.def;if(r.values.length===0){n.not={};return}const s=[];for(const i of r.values)if(i===void 0){if(be(e,t,n,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i=="bigint"){if(be(e,t,n,o,"BigInt literals cannot be represented in JSON Schema"))return;s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){const i=s[0];n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[i]:n.const=i}else s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),s.every(i=>typeof i=="boolean")&&(n.type="boolean"),s.every(i=>i===null)&&(n.type="null"),n.enum=s},PS=(e,t,n,o)=>{be(e,t,n,o,"NaN cannot be represented in JSON Schema")},kS=(e,t,n,o)=>{const r=n,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=s.source},CS=(e,t,n,o)=>{const r=n;r.type="string",r.format="binary",r.contentEncoding="binary";const{minimum:s,maximum:i,mime:a}=Be(e);s!==void 0&&(r.minLength=s),i!==void 0&&(r.maxLength=i),a&&(a.length===0?r.not={}:a.length===1?r.contentMediaType=a[0]:r.anyOf=a.map(c=>({contentMediaType:c})))},OS=(e,t,n,o)=>{n.type="boolean"},Xl=(e,t,n,o)=>{be(e,t,n,o,"Custom types cannot be represented in JSON Schema")},IS=(e,t,n,o)=>{be(e,t,n,o,"Function types cannot be represented in JSON Schema")},Ql=(e,t,n,o)=>{be(e,t,n,o,"Transforms cannot be represented in JSON Schema")},qS=(e,t,n,o)=>{be(e,t,n,o,"Map cannot be represented in JSON Schema")},NS=(e,t,n,o)=>{be(e,t,n,o,"Set cannot be represented in JSON Schema")},eu=(e,t,n,o)=>{const r=n,s=e._zod.def,{minimum:i,maximum:a}=Be(e);typeof i=="number"&&(r.minItems=i),typeof a=="number"&&(r.maxItems=a),r.type="array",r.items=ie(s.element,t,{...o,path:[...o.path,"items"]})};function Vo(e){const t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Vo(t.out):t.type==="catch"?Vo(t.innerType):e._zod.optin}const tu=(e,t,n,o)=>{var d;const r=n,s=e._zod.def,i=s.shape;if(Object.getOwnPropertySymbols(i).length&&be(e,t,r,o,"Symbol keys cannot be represented in JSON Schema"))return;r.type="object",r.properties={};for(const u in i)yt(r.properties,u,ie(i[u],t,{...o,path:[...o.path,"properties",u]}));const c=[];for(const u of Object.keys(i)){const p=s.shape[u];(t.io==="input"?Vo(p)===void 0:p._zod.optout===void 0)&&c.push(u)}c.length>0&&(r.required=c),((d=s.catchall)==null?void 0:d._zod.def.type)==="never"?r.additionalProperties=!1:s.catchall?s.catchall&&(r.additionalProperties=ie(s.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},nu=(e,t,n,o)=>{const r=e._zod.def,s=r.inclusive===!1,i=r.options.map((a,c)=>ie(a,t,{...o,path:[...o.path,s?"oneOf":"anyOf",c]}));s?n.oneOf=i:n.anyOf=i},ou=(e,t,n,o)=>{const r=e._zod.def,s=ie(r.left,t,{...o,path:[...o.path,"allOf",0]}),i=ie(r.right,t,{...o,path:[...o.path,"allOf",1]}),a=d=>"allOf"in d&&Object.keys(d).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=c,t.intersections.push(c)},MS=(e,t,n,o)=>{const r=n,s=e._zod.def;r.type="array";const i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((_,S)=>ie(_,t,{...o,path:[...o.path,i,S]})),d=s.rest?ie(s.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;let u=s.items.length;for(;u>0;){const _=s.items[u-1];if(!(t.io==="input"?Vo(_)!==void 0:_._zod.optout==="optional"))break;u--}const p=s.items.length,m=!s.rest;t.target==="draft-2020-12"?(r.prefixItems=c,m?r.items=!1:d&&(r.items=d),u>0&&(r.minItems=u),m&&(r.maxItems=p)):t.target==="openapi-3.0"?(r.items={anyOf:c},d&&r.items.anyOf.push(d),u>0&&(r.minItems=u),m&&(r.maxItems=p)):(r.items=c,m?r.additionalItems=!1:d&&(r.additionalItems=d),u>0&&(r.minItems=u),m&&(r.maxItems=p));const{minimum:h,maximum:f}=Be(e);typeof h=="number"&&(r.minItems=h),typeof f=="number"&&(r.maxItems=f)};function Ys(e,t,n){var f;if(t.$ref){if(n.has(t))return t;n.add(t);const _=(f=e.get(t))==null?void 0:f.def;if(!_)return t;const S=Ys(e,_,n);return S===_?t:S}for(const _ of["anyOf","oneOf"]){const S=t[_];if(!Array.isArray(S))continue;const b=S.map(R=>Ys(e,R,n));b.some((R,M)=>R!==S[M])&&(t={...t,[_]:b})}const o=Array.isArray(t.type)?t.type:[t.type],r=!o.includes("string")&&o.some(_=>_==="number"||_==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!r&&!(s!=null&&s.some(_=>typeof _=="number")))return t;const{minimum:i,maximum:a,exclusiveMinimum:c,exclusiveMaximum:d,multipleOf:u,format:p,id:m,...h}=t;return h.enum?h.enum=h.enum.map(_=>typeof _=="number"?String(_):_):typeof h.const=="number"&&(h.const=String(h.const)),r&&(h.type="string",s||(h.pattern=(o.includes("number")?Pi:Zh).source)),h}const Xs=new WeakMap;function AS(e){var o;const t=new Map;for(const r of e.seen.values())r.def&&!t.has(r.schema)&&t.set(r.schema,r);const n=new Map;for(const r of Xs.get(e)??[]){const s=e.seen.get(r),i=(o=(s==null?void 0:s.def)??(s==null?void 0:s.schema))==null?void 0:o.propertyNames;if(!i||i===!0||n.has(i))continue;const a=Ys(t,i,new Set);a!==i&&n.set(i,a)}if(n.size)for(const r of e.seen.values())for(const s of[r.schema,r.def]){const i=s&&n.get(s.propertyNames);i&&(s.propertyNames=i)}}const ru=(e,t,n,o)=>{const r=n,s=e._zod.def;r.type="object";const i=s.keyType,a=Be(i).patterns;if(s.mode==="loose"&&a&&a.size>0){const u=ie(s.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});r.patternProperties={};for(const p of a)yt(r.patternProperties,Zl(p).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){r.propertyNames=ie(s.keyType,t,{...o,path:[...o.path,"propertyNames"]});let u=Xs.get(t);u||(u=[],Xs.set(t,u),t.deferred.push(()=>AS(t))),u.push(e)}r.additionalProperties=ie(s.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}const c=i._zod.values,d=t.io==="input"&&Vo(s.valueType)!==void 0;if(c&&!s.partial&&!d){const u=[...c].filter(p=>typeof p=="string"||typeof p=="number");u.length>0&&(r.required=u.map(String))}},su=(e,t,n,o)=>{const r=e._zod.def,s=ie(r.innerType,t,o),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=r.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},iu=(e,t,n,o)=>{const r=e._zod.def;ie(r.innerType,t,o);const s=t.seen.get(e);s.ref=r.innerType},qi=Symbol();function au(e,t,n,o,r){let s=!1;const i=JSON.stringify(e,(a,c)=>typeof c!="bigint"?c:(s=!0,null));return s?(be(t,n,o,r,"BigInt defaults cannot be represented in JSON Schema"),qi):JSON.parse(i)}const cu=(e,t,n,o)=>{const r=e._zod.def;ie(r.innerType,t,o);const s=t.seen.get(e);s.ref=r.innerType;const i=au(r.defaultValue,e,t,n,o);i!==qi&&(n.default=i)},lu=(e,t,n,o)=>{const r=e._zod.def;ie(r.innerType,t,o);const s=t.seen.get(e);if(s.ref=r.innerType,t.io!=="input")return;const i=au(r.defaultValue,e,t,n,o);i!==qi&&(n._prefault=i)},uu=(e,t,n,o)=>{const r=e._zod.def;ie(r.innerType,t,o);const s=t.seen.get(e);s.ref=r.innerType;let i;try{i=r.catchValue(void 0)}catch{be(e,t,n,o,"Dynamic catch values are not supported in JSON Schema");return}n.default=i},du=(e,t,n,o)=>{const r=e._zod.def,s=r.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?r.out:r.in:r.out;ie(i,t,o);const a=t.seen.get(e);a.ref=i},pu=(e,t,n,o)=>{const r=e._zod.def;ie(r.innerType,t,o);const s=t.seen.get(e);s.ref=r.innerType,n.readOnly=!0},xS=(e,t,n,o)=>{const r=e._zod.def;ie(r.innerType,t,o);const s=t.seen.get(e);s.ref=r.innerType},Ni=(e,t,n,o)=>{const r=e._zod.def;ie(r.innerType,t,o);const s=t.seen.get(e);s.ref=r.innerType},mu=(e,t,n,o)=>{const r=e._zod.innerType;ie(r,t,o);const s=t.seen.get(e);s.ref=r},nc={string:Hl,number:Fl,boolean:Vl,bigint:wS,symbol:RS,null:Jl,undefined:TS,void:$S,never:Bl,any:Wl,unknown:Kl,date:ES,enum:Gl,literal:Yl,nan:PS,template_literal:kS,file:CS,success:OS,custom:Xl,function:IS,transform:Ql,map:qS,set:NS,array:eu,object:tu,union:nu,intersection:ou,tuple:MS,record:ru,nullable:su,nonoptional:iu,default:cu,prefault:lu,catch:uu,pipe:du,readonly:pu,promise:xS,optional:Ni,lazy:mu};function hu(e,t){if("_idmap"in e){const o=e,r=Vr({...t,processors:nc}),s={};for(const c of o._idmap.entries()){const[d,u]=c;ie(u,r)}const i={},a={registry:o,uri:t==null?void 0:t.uri,defs:s};r.external=a;for(const c of o._idmap.entries()){const[d,u]=c;Jr(r,u),yt(i,d,Br(r,u))}if(Object.keys(s).length>0){const c=r.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[c]:s}}return{schemas:i}}const n=Vr({...t,processors:nc});return ie(e,n),Jr(n,e),Br(n,e)}const oc=new WeakSet([Object.prototype,Error.prototype]);function Tr(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){const o=n(this);return Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0}),o},set(o){Object.defineProperty(this,t,{value:o,configurable:!0,writable:!0})}})}const zS=(e,t)=>{eh.init(e,t),e.name="ZodError";const n=Object.getPrototypeOf(e);oc.has(n)||(oc.add(n),Tr(n,"format",o=>r=>oh(o,r)),Tr(n,"flatten",o=>r=>nh(o,r)),Tr(n,"addIssue",o=>r=>{o.issues.push(r),o.message=JSON.stringify(o.issues,Vs,2)}),Tr(n,"addIssues",o=>r=>{o.issues.push(...r),o.message=JSON.stringify(o.issues,Vs,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},tt=w("ZodError",zS,void 0,{Parent:Error}),LS=Ri(tt),jS=Ti(tt),fu=$i(tt),DS=Ei(tt),US=lh(tt),ZS=uh(tt),HS=dh(tt),FS=ph(tt),VS=mh(tt),JS=hh(tt),BS=fh(tt),WS=gh(tt);function KS(){at.localeError||St(Rg())}function ss(){at.memoizer||St({memoizer:vg()})}const ce=w("ZodType",(e,t)=>(KS(),ae.init(e,t),e.def=t,e.type=t.type,e),{check(...e){const t=this.def;return this.clone(Je(t,{checks:[...t.checks??[],...e.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Jt(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Hy(e,t))},superRefine(e,t){return this.check(Fy(e,t))},overwrite(e){return this.check(Wn(e))},optional(){return z(this)},exactOptional(){return Cy(this)},nullable(){return ic(this)},nullish(){return z(ic(this))},nonoptional(e){return Ay(this,e)},array(){return y(this)},or(e){return N([this,e])},and(e){return gn(this,e)},transform(e){return ac(this,Tu(e))},default(e){return qy(this,e)},prefault(e){return My(this,e)},catch(e){return zy(this,e)},pipe(e){return ac(this,e)},readonly(){return Dy(this)},describe(e){const t=this.clone();return Ao.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ao.get(this);const t=this.clone();return Ao.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return cl(this,"~standard",{...gl(this),jsonSchema:{input:Wr(this,"input"),output:Wr(this,"output")}})},set"~standard"(e){Vt(this,"~standard",e)},parse:function e(t,n){return LS(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await jS(this,t,n,{callee:e})},safeParse(e,t){return fu(this,e,t)},async safeParseAsync(e,t){return DS(this,e,t)},get spa(){return this==null?void 0:this.safeParseAsync},set spa(e){Vt(this,"spa",e)},validate(e,t){return ih(this,e,t)},validateAsync(e,t){return ch(this,e,t)},encode:function e(t,n){return US(this,t,n,{callee:e})},decode:function e(t,n){return ZS(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await HS(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await FS(this,t,n,{callee:e})},safeEncode(e,t){return VS(this,e,t)},safeDecode(e,t){return JS(this,e,t)},async safeEncodeAsync(e,t){return BS(this,e,t)},async safeDecodeAsync(e,t){return WS(this,e,t)},toJSONSchema(e){return _S(this,{})(e)},get description(){var e;return(e=Ao.get(this))==null?void 0:e.description},get _def(){return this._zod.def}}),gu=w("_ZodString",(e,t)=>{Ci.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Hl(e,n,o)},ll({format:e=>Be(e).format??null,minLength:e=>Be(e).minimum??null,maxLength:e=>Be(e).maximum??null},{regex(...e){return this.check(oS(...e))},includes(...e){return this.check(iS(...e))},startsWith(...e){return this.check(aS(...e))},endsWith(...e){return this.check(cS(...e))},min(...e){return this.check(Fr(...e))},max(...e){return this.check(Ml(...e))},length(...e){return this.check(Al(...e))},nonempty(...e){return this.check(Fr(1,...e))},lowercase(e){return this.check(rS(e))},uppercase(e){return this.check(sS(e))},trim(){return this.check(uS())},normalize(...e){return this.check(lS(...e))},toLowerCase(){return this.check(dS())},toUpperCase(){return this.check(pS())},slugify(){return this.check(mS())}})),GS=w("ZodString",(e,t)=>{Ci.init(e,t),gu.init(e,t)},{email(e){return this.check(Ol(_u,e))},url(e){return this.check(Il(vu,e))},jwt(e){return this.check(Jg(fy,e))},emoji(e){return this.check(qg(ty,e))},guid(e){return this.check(Pg(ey,e))},uuid(e){return this.check(kg($r,e))},uuidv4(e){return this.check(Cg($r,e))},uuidv6(e){return this.check(Og($r,e))},uuidv7(e){return this.check(Ig($r,e))},nanoid(e){return this.check(Ng(ny,e))},cuid(e){return this.check(Mg(oy,e))},cuid2(e){return this.check(Ag(ry,e))},ulid(e){return this.check(xg(sy,e))},base64(e){return this.check(Hg(py,e))},base64url(e){return this.check(Fg(my,e))},xid(e){return this.check(zg(iy,e))},ksuid(e){return this.check(Lg(ay,e))},ipv4(e){return this.check(jg(cy,e))},ipv6(e){return this.check(Dg(ly,e))},cidrv4(e){return this.check(Ug(uy,e))},cidrv6(e){return this.check(Zg(dy,e))},e164(e){return this.check(Vg(hy,e))},datetime(e){return this.check(ql(Su,e))},date(e){return this.check(Nl(yu,e))},time(e){return this.check(Bg(YS,e))},duration(e){return this.check(Wg(XS,e))}});function l(e){return Eg(GS,e)}const de=w("ZodStringFormat",(e,t)=>{le.init(e,t),gu.init(e,t)}),Su=w("ZodISODateTime",(e,t)=>{$f.init(e,t),de.init(e,t)}),yu=w("ZodISODate",(e,t)=>{Ef.init(e,t),de.init(e,t)}),YS=w("ZodISOTime",(e,t)=>{Pf.init(e,t),de.init(e,t)}),XS=w("ZodISODuration",(e,t)=>{kf.init(e,t),de.init(e,t)}),_u=w("ZodEmail",(e,t)=>{df.init(e,t),de.init(e,t)});function QS(e){return Ol(_u,e)}const ey=w("ZodGUID",(e,t)=>{lf.init(e,t),de.init(e,t)}),$r=w("ZodUUID",(e,t)=>{uf.init(e,t),de.init(e,t)}),vu=w("ZodURL",(e,t)=>{Sf.init(e,t),de.init(e,t)});function bu(e){return Il(vu,e)}const ty=w("ZodEmoji",(e,t)=>{yf.init(e,t),de.init(e,t)}),ny=w("ZodNanoID",(e,t)=>{_f.init(e,t),de.init(e,t)}),oy=w("ZodCUID",(e,t)=>{vf.init(e,t),de.init(e,t)}),ry=w("ZodCUID2",(e,t)=>{bf.init(e,t),de.init(e,t)}),sy=w("ZodULID",(e,t)=>{wf.init(e,t),de.init(e,t)}),iy=w("ZodXID",(e,t)=>{Rf.init(e,t),de.init(e,t)}),ay=w("ZodKSUID",(e,t)=>{Tf.init(e,t),de.init(e,t)}),cy=w("ZodIPv4",(e,t)=>{Cf.init(e,t),de.init(e,t)}),ly=w("ZodIPv6",(e,t)=>{If.init(e,t),de.init(e,t)}),uy=w("ZodCIDRv4",(e,t)=>{qf.init(e,t),de.init(e,t)}),dy=w("ZodCIDRv6",(e,t)=>{Mf.init(e,t),de.init(e,t)}),py=w("ZodBase64",(e,t)=>{Af.init(e,t),de.init(e,t)}),my=w("ZodBase64URL",(e,t)=>{zf.init(e,t),de.init(e,t)}),hy=w("ZodE164",(e,t)=>{Lf.init(e,t),de.init(e,t)}),fy=w("ZodJWT",(e,t)=>{Df.init(e,t),de.init(e,t)}),Mi=w("ZodNumber",(e,t)=>{wl.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Fl(e,n,o,r),e.isFinite=!0},ll({minValue:e=>{const{minimum:t,exclusiveMinimum:n}=Be(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:e=>{const{maximum:t,exclusiveMaximum:n}=Be(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:e=>{const{isInt:t,multipleOf:n}=Be(e);return!!t||!!(n!=null&&n.some(Number.isSafeInteger))},format:e=>Be(e).format??null},{gt(e,t){return this.check(Ba(e,t))},gte(e,t){return this.check(Cs(e,t))},min(e,t){return this.check(Cs(e,t))},lt(e,t){return this.check(Ja(e,t))},lte(e,t){return this.check(ks(e,t))},max(e,t){return this.check(ks(e,t))},int(e){return this.check(rc(e))},safe(e){return this.check(rc(e))},positive(e){return this.check(Ba(0,e))},nonnegative(e){return this.check(Cs(0,e))},negative(e){return this.check(Ja(0,e))},nonpositive(e){return this.check(ks(0,e))},multipleOf(e,t){return this.check(Wa(e,t))},step(e,t){return this.check(Wa(e,t))},finite(){return this}}));function $(e){return Kg(Mi,e)}const gy=w("ZodNumberFormat",(e,t)=>{Uf.init(e,t),Mi.init(e,t)});function rc(e){return Yg(gy,e)}const Sy=w("ZodBoolean",(e,t)=>{Zf.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Vl(e,n,o)});function q(e){return Xg(Sy,e)}const yy=w("ZodNull",(e,t)=>{Hf.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Jl(e,n,o)});function Jo(e){return Qg(yy,e)}const _y=w("ZodAny",(e,t)=>{Ff.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Wl()});function vy(){return eS(_y)}const by=w("ZodUnknown",(e,t)=>{Vf.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Kl()});function j(){return tS(by)}const wy=w("ZodNever",(e,t)=>{Jf.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Bl(e,n,o)});function Ry(e){return nS(wy,e)}const Ty=w("ZodArray",(e,t)=>{ss(),Kf.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>eu(e,n,o,r),e.element=t.element},{min(e,t){return this.check(Fr(e,t))},nonempty(e){return this.check(Fr(1,e))},max(e,t){return this.check(Ml(e,t))},length(e,t){return this.check(Al(e,t))},unwrap(){return this.element}});function y(e,t){return hS(Ty,e,t)}const wu=w("ZodObject",(e,t)=>{ss(),Xf.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>tu(e,n,o,r),Vm(e,"shape",n=>n._zod.def.shape,!1)},{keyof(){return B(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Je(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Je(this._zod.def,{catchall:j()}))},loose(){return this.clone(Je(this._zod.def,{catchall:j()}))},strict(){return this.clone(Je(this._zod.def,{catchall:Ry()}))},strip(){return this.clone(Je(this._zod.def,{catchall:void 0}))},extend(e){return Mm(this,e)},safeExtend(e){return Am(this,e)},merge(e){return xm(this,e)},pick(e){return qm(this,e)},omit(e){return Nm(this,e)},partial(...e){return ka($u,this,e[0])},exactPartial(...e){return ka(Eu,this,e[0],"exactPartial")},required(...e){return zm(Pu,this,e[0])}});function g(e,t){const n={type:"object",shape:e??{},...x(t)};return new wu(n)}function U(e,t){return new wu({type:"object",shape:e,catchall:j(),...x(t)})}const Ru=w("ZodUnion",(e,t)=>{$l.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>nu(e,n,o,r),e.options=t.options});function N(e,t){return new Ru({type:"union",options:e,...x(t)})}const $y=w("ZodDiscriminatedUnion",(e,t)=>{Ru.init(e,t),eg.init(e,t)});function Kr(e,t,n){return new $y({type:"union",options:t,discriminator:e,...x(n)})}const Ey=w("ZodIntersection",(e,t)=>{tg.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ou(e,n,o,r)});function gn(e,t){return new Ey({type:"intersection",left:e,right:t})}const sc=w("ZodRecord",(e,t)=>{ss(),ng.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ru(e,n,o,r),e.keyType=t.keyType,e.valueType=t.valueType});function C(e,t,n){return!t||!t._zod?new sc({type:"record",keyType:l(),valueType:e,...x(t)}):new sc({type:"record",keyType:e,valueType:t,...x(n)})}const Qs=w("ZodEnum",(e,t)=>{og.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(o,r,s)=>Gl(e,o,r),e.enum=t.entries,e.options=[...e._zod.values];const n=new Set(Object.keys(t.entries));e.extract=(o,r)=>{const s={};for(const i of o)if(n.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Qs({...t,checks:[],...x(r),entries:s})},e.exclude=(o,r)=>{const s={...t.entries};for(const i of o)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Qs({...t,checks:[],...x(r),entries:s})}});function B(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new Qs({type:"enum",entries:n,...x(t)})}const Py=w("ZodLiteral",(e,t)=>{rg.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Yl(e,n,o,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function v(e,t){return new Py({type:"literal",values:Array.isArray(e)?e:[e],...x(t)})}const ky=w("ZodTransform",(e,t)=>{ss(),sg.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Ql(e,n,o,r),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new ul(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(Fo(s,n.value,t));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=n.value),i.inst??(i.inst=e),n.issues.push(Fo(i))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(s=>(n.value=s,n)):(n.value=r,n)}});function Tu(e){return new ky({type:"transform",transform:e})}const $u=w("ZodOptional",(e,t)=>{El.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Ni(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function z(e){return new $u({type:"optional",innerType:e})}const Eu=w("ZodExactOptional",(e,t)=>{ig.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Ni(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function Cy(e){return new Eu({type:"optional",innerType:e})}const Oy=w("ZodNullable",(e,t)=>{ag.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>su(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function ic(e){return new Oy({type:"nullable",innerType:e})}const Iy=w("ZodDefault",(e,t)=>{cg.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>cu(e,n,o,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function qy(e,t){return new Iy({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():rl(t)}})}const Ny=w("ZodPrefault",(e,t)=>{lg.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>lu(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function My(e,t){return new Ny({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():rl(t)}})}const Pu=w("ZodNonOptional",(e,t)=>{ug.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>iu(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function Ay(e,t){return new Pu({type:"nonoptional",innerType:e,...x(t)})}const xy=w("ZodCatch",(e,t)=>{dg.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>uu(e,n,o,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function zy(e,t){return new xy({type:"catch",innerType:e,catchValue:typeof t=="function"?t:Bm(t)})}const ku=w("ZodPipe",(e,t)=>{Pl.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>du(e,n,o,r),e.in=t.in,e.out=t.out});function ac(e,t){return new ku({type:"pipe",in:e,out:t})}const Ly=w("ZodPreprocess",(e,t)=>{ku.init(e,t),pg.init(e,t)}),jy=w("ZodReadonly",(e,t)=>{mg.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>pu(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function Dy(e){return new jy({type:"readonly",innerType:e})}const Uy=w("ZodLazy",(e,t)=>{hg.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>mu(e,n,o,r),e.unwrap=()=>e._zod.def.getter()});function Ai(e){return new Uy({type:"lazy",getter:e})}const Zy=w("ZodCustom",(e,t)=>{fg.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Xl(e,n,o,r)});function Hy(e,t={}){return fS(Zy,e,t)}function Fy(e,t){return gS(e,t)}function Bo(e,t){return new Ly({type:"pipe",in:Tu(e),out:t})}const Vy={custom:"custom"};function is(e){return ql(Su,e)}function Jy(e){return Nl(yu,e)}function By(e){return Gg(Mi,e)}const ei="2025-11-25",Wy=[ei,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ky="io.modelcontextprotocol/related-task",as="io.modelcontextprotocol/protocolVersion",xi="io.modelcontextprotocol/clientInfo",jo="io.modelcontextprotocol/serverInfo",nr="io.modelcontextprotocol/clientCapabilities",Gy="io.modelcontextprotocol/subscriptionId",cs="io.modelcontextprotocol/logLevel",ls="2.0",Fn=Ai(()=>N([l(),$(),q(),Jo(),C(l(),Fn),y(Fn)])),fe=C(l(),Fn),Yy=y(Fn),zi=N([l(),$().int()]),Li=l(),Cu=g({ttl:$().optional()}),Ou=g({taskId:l()}),ji=U({progressToken:zi.optional(),[Ky]:Ou.optional()}),Pe=g({_meta:ji.optional()}),or=Pe.extend({task:Cu.optional()}),ge=g({method:l(),params:Pe.loose().optional()}),je=g({_meta:ji.optional()}),De=g({method:l(),params:je.loose().optional()}),Di=U({get[jo](){return ps.optional().catch(void 0)}}),Se=U({_meta:Di.optional()}),Kn=N([l(),$().int()]),Ui=g({jsonrpc:v(ls),id:Kn,...ge.shape}).strict(),Zi=g({jsonrpc:v(ls),...De.shape}).strict(),us=g({jsonrpc:v(ls),id:Kn,result:Se}).strict(),ds=g({jsonrpc:v(ls),id:Kn.optional(),error:g({code:$().int(),message:l(),data:j().optional()})}).strict(),Hi=N([Ui,Zi,us,ds]),Xy=N([us,ds]),Fi=Se.strict(),Iu=je.extend({requestId:Kn.optional(),reason:l().optional()}),Vi=De.extend({method:v("notifications/cancelled"),params:Iu}),qu=g({src:l(),mimeType:l().optional(),sizes:y(l()).optional(),theme:B(["light","dark"]).optional()}),Gn=g({icons:y(qu).optional()}),Sn=g({name:l(),title:l().optional()}),ps=Sn.extend({...Sn.shape,...Gn.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),Qy=gn(g({applyDefaults:q().optional()}),fe),e_=Bo(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,gn(g({form:Qy.optional(),url:fe.optional()}),fe.optional())),Nu=U({list:fe.optional(),cancel:fe.optional(),requests:U({sampling:U({createMessage:fe.optional()}).optional(),elicitation:U({create:fe.optional()}).optional()}).optional()}),Mu=U({list:fe.optional(),cancel:fe.optional(),requests:U({tools:U({call:fe.optional()}).optional()}).optional()}),Au=g({experimental:C(l(),fe).optional(),sampling:g({context:fe.optional(),tools:fe.optional()}).optional(),elicitation:e_.optional(),roots:g({listChanged:q().optional()}).optional(),tasks:Nu.optional(),extensions:C(l(),fe).optional()}),xu=Pe.extend({protocolVersion:l(),capabilities:Au,clientInfo:ps}),zu=ge.extend({method:v("initialize"),params:xu}),Ji=g({experimental:C(l(),fe).optional(),logging:fe.optional(),completions:fe.optional(),prompts:g({listChanged:q().optional()}).optional(),resources:g({subscribe:q().optional(),listChanged:q().optional()}).optional(),tools:g({listChanged:q().optional()}).optional(),tasks:Mu.optional(),extensions:C(l(),fe).optional()}),Lu=Se.extend({protocolVersion:l(),capabilities:Ji,serverInfo:ps,instructions:l().optional()}),ju=De.extend({method:v("notifications/initialized"),params:je.optional()}),Du=ge.extend({method:v("server/discover"),params:Pe.optional()}),Uu=Se.extend({supportedVersions:y(l()),capabilities:Ji,instructions:l().optional()}),Bi=ge.extend({method:v("ping"),params:Pe.optional()}),Zu=g({progress:$(),total:z($()),message:z(l())}),Hu=g({...je.shape,...Zu.shape,progressToken:zi}),Wi=De.extend({method:v("notifications/progress"),params:Hu}),Fu=Pe.extend({cursor:Li.optional()}),Yn=ge.extend({params:Fu.optional()}),Xn=Se.extend({nextCursor:Li.optional()}),Ki=g({uri:l(),mimeType:z(l()),_meta:C(l(),j()).optional()}),Gi=Ki.extend({text:l()}),Yi=l().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Xi=Ki.extend({blob:Yi}),Qn=B(["user","assistant"]),yn=g({audience:y(Qn).optional(),priority:$().min(0).max(1).optional(),lastModified:is({offset:!0}).optional()}),Qi=g({...Sn.shape,...Gn.shape,uri:l(),description:z(l()),mimeType:z(l()),size:z($()),annotations:yn.optional(),_meta:z(U({}))}),Vu=g({...Sn.shape,...Gn.shape,uriTemplate:l(),description:z(l()),mimeType:z(l()),annotations:yn.optional(),_meta:z(U({}))}),Ju=Yn.extend({method:v("resources/list")}),Bu=Xn.extend({resources:y(Qi)}),Wu=Yn.extend({method:v("resources/templates/list")}),Ku=Xn.extend({resourceTemplates:y(Vu)}),ms=Pe.extend({uri:l()}),Gu=ms,Yu=ge.extend({method:v("resources/read"),params:Gu}),Xu=Se.extend({contents:y(N([Gi,Xi]))}),Qu=De.extend({method:v("notifications/resources/list_changed"),params:je.optional()}),ed=ms,td=ge.extend({method:v("resources/subscribe"),params:ed}),nd=ms,od=ge.extend({method:v("resources/unsubscribe"),params:nd}),ea=g({toolsListChanged:q().optional(),promptsListChanged:q().optional(),resourcesListChanged:q().optional(),resourceSubscriptions:y(l()).optional()}),rd=Pe.extend({notifications:ea}),sd=ge.extend({method:v("subscriptions/listen"),params:rd}),id=je.extend({notifications:ea}),ad=De.extend({method:v("notifications/subscriptions/acknowledged"),params:id}),cd=Di.extend({[Gy]:Kn}),ld=Se.extend({_meta:cd}),ud=je.extend({uri:l()}),dd=De.extend({method:v("notifications/resources/updated"),params:ud}),pd=g({name:l(),description:z(l()),required:z(q())}),md=g({...Sn.shape,...Gn.shape,description:z(l()),arguments:z(y(pd)),_meta:z(U({}))}),hd=Yn.extend({method:v("prompts/list")}),fd=Xn.extend({prompts:y(md)}),gd=Pe.extend({name:l(),arguments:C(l(),l()).optional()}),Sd=ge.extend({method:v("prompts/get"),params:gd}),hs=g({type:v("text"),text:l(),annotations:yn.optional(),_meta:C(l(),j()).optional()}),fs=g({type:v("image"),data:Yi,mimeType:l(),annotations:yn.optional(),_meta:C(l(),j()).optional()}),gs=g({type:v("audio"),data:Yi,mimeType:l(),annotations:yn.optional(),_meta:C(l(),j()).optional()}),yd=g({type:v("tool_use"),name:l(),id:l(),input:C(l(),j()),_meta:C(l(),j()).optional()}),_d=g({type:v("resource"),resource:N([Gi,Xi]),annotations:yn.optional(),_meta:C(l(),j()).optional()}),vd=Qi.extend({type:v("resource_link")}),Ss=N([hs,fs,gs,vd,_d]),bd=g({role:Qn,content:Ss}),wd=Se.extend({description:l().optional(),messages:y(bd)}),Rd=De.extend({method:v("notifications/prompts/list_changed"),params:je.optional()}),Td=g({title:l().optional(),readOnlyHint:q().optional(),destructiveHint:q().optional(),idempotentHint:q().optional(),openWorldHint:q().optional()}),$d=g({taskSupport:B(["required","optional","forbidden"]).optional()}),ta=g({...Sn.shape,...Gn.shape,description:l().optional(),inputSchema:g({type:v("object"),properties:C(l(),Fn).optional(),required:y(l()).optional()}).catchall(j()),outputSchema:U({$schema:l().optional()}).optional(),annotations:Td.optional(),execution:$d.optional(),_meta:C(l(),j()).optional()}),Ed=Yn.extend({method:v("tools/list")}),Pd=Xn.extend({tools:y(ta)}),na=Se.extend({content:y(Ss).default([]),structuredContent:j().optional(),isError:q().optional()}),t_=na.or(Se.extend({toolResult:j()})),kd=or.extend({name:l(),arguments:C(l(),j()).optional()}),Cd=ge.extend({method:v("tools/call"),params:kd}),Od=De.extend({method:v("notifications/tools/list_changed"),params:je.optional()}),n_=g({autoRefresh:q().default(!0),debounceMs:$().int().nonnegative().default(300)}),Wo=B(["debug","info","notice","warning","error","critical","alert","emergency"]),Id=Pe.extend({level:Wo}),qd=ge.extend({method:v("logging/setLevel"),params:Id}),Nd=je.extend({level:Wo,logger:l().optional(),data:j()}),Md=De.extend({method:v("notifications/message"),params:Nd}),Ad=g({name:l().optional()}),xd=g({hints:y(Ad).optional(),costPriority:$().min(0).max(1).optional(),speedPriority:$().min(0).max(1).optional(),intelligencePriority:$().min(0).max(1).optional()}),zd=g({mode:B(["auto","required","none"]).optional()}),Ld=g({type:v("tool_result"),toolUseId:l().describe("The unique identifier for the corresponding tool call."),content:y(Ss),structuredContent:j().optional(),isError:q().optional(),_meta:C(l(),j()).optional()}),jd=Kr("type",[hs,fs,gs]),Ko=Kr("type",[hs,fs,gs,yd,Ld]),Dd=g({role:Qn,content:N([Ko,y(Ko)]),_meta:C(l(),j()).optional()}),Ud=or.extend({messages:y(Dd),modelPreferences:xd.optional(),systemPrompt:l().optional(),includeContext:B(["none","thisServer","allServers"]).optional(),temperature:$().optional(),maxTokens:$().int(),stopSequences:y(l()).optional(),metadata:fe.optional(),tools:y(ta).optional(),toolChoice:zd.optional()}),Zd=ge.extend({method:v("sampling/createMessage"),params:Ud}),Hd=Se.extend({model:l(),stopReason:z(B(["endTurn","stopSequence","maxTokens"]).or(l())),role:Qn,content:jd}),Fd=Se.extend({model:l(),stopReason:z(B(["endTurn","stopSequence","maxTokens","toolUse"]).or(l())),role:Qn,content:N([Ko,y(Ko)])}),oa=g({type:v("boolean"),title:l().optional(),description:l().optional(),default:q().optional()}),ys=g({type:v("string"),title:l().optional(),description:l().optional(),minLength:$().optional(),maxLength:$().optional(),format:B(["email","uri","date","date-time"]).optional(),default:l().optional()}),Gr=g({type:B(["number","integer"]),title:l().optional(),description:l().optional(),minimum:$().optional(),maximum:$().optional(),default:$().optional()}),ra=g({type:v("string"),title:l().optional(),description:l().optional(),enum:y(l()),default:l().optional()}),sa=g({type:v("string"),title:l().optional(),description:l().optional(),oneOf:y(g({const:l(),title:l()})),default:l().optional()}),ia=g({type:v("string"),title:l().optional(),description:l().optional(),enum:y(l()),enumNames:y(l()).optional(),default:l().optional()}),Vd=N([ra,sa]),aa=g({type:v("array"),title:l().optional(),description:l().optional(),minItems:$().optional(),maxItems:$().optional(),items:g({type:v("string"),enum:y(l())}),default:y(l()).optional()}),ca=g({type:v("array"),title:l().optional(),description:l().optional(),minItems:$().optional(),maxItems:$().optional(),items:g({anyOf:y(g({const:l(),title:l()}))}),default:y(l()).optional()}),Jd=N([aa,ca]),Bd=N([ia,Vd,Jd]),la=N([Bd,oa,ys,Gr]),_s=or.extend({mode:v("form").optional(),message:l(),requestedSchema:g({type:v("object"),properties:C(l(),la),required:y(l()).optional()}).catchall(j())}),Wd=or.extend({mode:v("url"),message:l(),elicitationId:l(),url:l().url()}),Kd=N([_s,Wd]),Gd=ge.extend({method:v("elicitation/create"),params:Kd}),Yd=je.extend({elicitationId:l()}),Xd=De.extend({method:v("notifications/elicitation/complete"),params:Yd}),Qd=Se.extend({action:B(["accept","decline","cancel"]),content:Bo(e=>e===null?void 0:e,C(l(),N([l(),$(),q(),y(l())])).optional())}),ep=g({type:v("ref/resource"),uri:l()}),tp=g({type:v("ref/prompt"),name:l()}),np=Pe.extend({ref:N([tp,ep]),argument:g({name:l(),value:l()}),context:g({arguments:C(l(),l()).optional()}).optional()}),op=ge.extend({method:v("completion/complete"),params:np}),rp=Se.extend({completion:U({values:y(l()).max(100),total:z($().int()),hasMore:z(q())})}),sp=g({uri:l().startsWith("file://"),name:l().optional(),_meta:C(l(),j()).optional()}),ip=ge.extend({method:v("roots/list"),params:Pe.optional()}),ap=Se.extend({roots:y(sp)}),cp=De.extend({method:v("notifications/roots/list_changed"),params:je.optional()}),o_=U({ttl:$().optional(),pollInterval:$().optional()}),lp=B(["working","input_required","completed","failed","cancelled"]),eo=g({taskId:l(),status:lp,ttl:N([$(),Jo()]),createdAt:l(),lastUpdatedAt:l(),pollInterval:z($()),statusMessage:z(l())}),r_=Se.extend({task:eo}),up=je.merge(eo),s_=De.extend({method:v("notifications/tasks/status"),params:up}),i_=ge.extend({method:v("tasks/get"),params:Pe.extend({taskId:l()})}),a_=Se.merge(eo),c_=ge.extend({method:v("tasks/result"),params:Pe.extend({taskId:l()})}),l_=Se.loose(),u_=Yn.extend({method:v("tasks/list")}),d_=Xn.extend({tasks:y(eo)}),p_=ge.extend({method:v("tasks/cancel"),params:Pe.extend({taskId:l()})}),m_=Se.merge(eo),h_=N([Bi,zu,Du,op,qd,Sd,hd,Ju,Wu,Yu,td,od,sd,Cd,Ed]),f_=N([Vi,Wi,ju,cp]),g_=N([Fi,Hd,Fd,Qd,ap]),S_=N([Bi,Zd,Gd,ip]),y_=N([Vi,Wi,Md,dd,Qu,Od,Rd,ad,Xd]),__=N([Fi,Lu,Uu,rp,wd,fd,Bu,Ku,Xu,na,Pd,ld]),ve=bu().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Vy.custom,message:"URL must be parseable",fatal:!0}),Wm}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),v_=U({resource:l().url(),authorization_servers:y(ve).optional(),jwks_uri:l().url().optional(),scopes_supported:y(l()).optional(),bearer_methods_supported:y(l()).optional(),resource_signing_alg_values_supported:y(l()).optional(),resource_name:l().optional(),resource_documentation:l().optional(),resource_policy_uri:l().url().optional(),resource_tos_uri:l().url().optional(),tls_client_certificate_bound_access_tokens:q().optional(),authorization_details_types_supported:y(l()).optional(),dpop_signing_alg_values_supported:y(l()).optional(),dpop_bound_access_tokens_required:q().optional()}),dp=U({issuer:l(),authorization_endpoint:ve,token_endpoint:ve,registration_endpoint:ve.optional(),scopes_supported:y(l()).optional(),response_types_supported:y(l()),response_modes_supported:y(l()).optional(),grant_types_supported:y(l()).optional(),token_endpoint_auth_methods_supported:y(l()).optional(),token_endpoint_auth_signing_alg_values_supported:y(l()).optional(),service_documentation:ve.optional(),revocation_endpoint:ve.optional(),revocation_endpoint_auth_methods_supported:y(l()).optional(),revocation_endpoint_auth_signing_alg_values_supported:y(l()).optional(),introspection_endpoint:l().optional(),introspection_endpoint_auth_methods_supported:y(l()).optional(),introspection_endpoint_auth_signing_alg_values_supported:y(l()).optional(),code_challenge_methods_supported:y(l()).optional(),client_id_metadata_document_supported:q().optional(),authorization_response_iss_parameter_supported:q().optional().catch(void 0),dpop_signing_alg_values_supported:y(l()).optional()}),pp=U({issuer:l(),authorization_endpoint:ve,token_endpoint:ve,userinfo_endpoint:ve.optional(),jwks_uri:ve,registration_endpoint:ve.optional(),scopes_supported:y(l()).optional(),response_types_supported:y(l()),response_modes_supported:y(l()).optional(),grant_types_supported:y(l()).optional(),acr_values_supported:y(l()).optional(),subject_types_supported:y(l()),id_token_signing_alg_values_supported:y(l()),id_token_encryption_alg_values_supported:y(l()).optional(),id_token_encryption_enc_values_supported:y(l()).optional(),userinfo_signing_alg_values_supported:y(l()).optional(),userinfo_encryption_alg_values_supported:y(l()).optional(),userinfo_encryption_enc_values_supported:y(l()).optional(),request_object_signing_alg_values_supported:y(l()).optional(),request_object_encryption_alg_values_supported:y(l()).optional(),request_object_encryption_enc_values_supported:y(l()).optional(),token_endpoint_auth_methods_supported:y(l()).optional(),token_endpoint_auth_signing_alg_values_supported:y(l()).optional(),display_values_supported:y(l()).optional(),claim_types_supported:y(l()).optional(),claims_supported:y(l()).optional(),service_documentation:l().optional(),claims_locales_supported:y(l()).optional(),ui_locales_supported:y(l()).optional(),claims_parameter_supported:q().optional(),request_parameter_supported:q().optional(),request_uri_parameter_supported:q().optional(),require_request_uri_registration:q().optional(),op_policy_uri:ve.optional(),op_tos_uri:ve.optional(),client_id_metadata_document_supported:q().optional(),authorization_response_iss_parameter_supported:q().optional().catch(void 0)}),b_=g({...pp.shape,...dp.pick({code_challenge_methods_supported:!0}).shape}),w_=g({access_token:l(),id_token:l().optional(),token_type:l(),expires_in:By().optional(),scope:l().optional(),refresh_token:l().optional(),issuer:l().optional().catch(void 0)}).strip(),R_=g({issued_token_type:v("urn:ietf:params:oauth:token-type:id-jag"),access_token:l(),token_type:l().optional(),expires_in:$().optional(),scope:l().optional()}).strip(),T_=g({error:l(),error_description:l().optional(),error_uri:l().optional()}),cc=ve.optional().or(v("").transform(()=>{})),mp=g({redirect_uris:y(ve),token_endpoint_auth_method:l().optional(),grant_types:y(l()).optional(),response_types:y(l()).optional(),application_type:l().optional(),client_name:l().optional(),client_uri:ve.optional(),logo_uri:cc,scope:l().optional(),contacts:y(l()).optional(),tos_uri:cc,policy_uri:l().optional(),jwks_uri:ve.optional(),jwks:vy().optional(),software_id:l().optional(),software_version:l().optional(),software_statement:l().optional()}).strip(),hp=g({client_id:l(),client_secret:l().optional(),client_id_issued_at:$().optional(),client_secret_expires_at:$().optional(),issuer:l().optional().catch(void 0)}).strip(),$_=mp.merge(hp),E_=g({error:l(),error_description:l().optional()}).strip(),P_=g({token:l(),token_type_hint:l().optional()}).strip();function fp(e,t,n){return typeof e=="object"&&!!e&&"channel"in e&&e.channel===t&&"type"in e&&e.type==="mcp"&&"direction"in e&&e.direction===n&&"payload"in e}function an(e,t,n,o,r){e.postMessage({channel:n,type:"mcp",direction:o,payload:r},t)}var k_=class{constructor(e){T(this,"_started",!1);T(this,"_closed",!1);T(this,"_allowedOrigins");T(this,"_channelId");T(this,"_messageHandler");T(this,"_clientOrigin");T(this,"onclientorigin");T(this,"onclose");T(this,"onerror");T(this,"onmessage");var t;if(!((t=e.allowedOrigins)!=null&&t.length))throw Error("At least one allowed origin must be specified");this._allowedOrigins=new Set(e.allowedOrigins),this._channelId=e.channelId??"mcp-iframe"}get clientOrigin(){return this._clientOrigin}async start(){if(this._closed)throw Error("IframeChildTransport cannot be restarted after it closes");if(this._started)throw Error("Transport already started");this._messageHandler=e=>{var n,o,r;if(e.source!==window.parent||!this._allowedOrigins.has("*")&&!this._allowedOrigins.has(e.origin)||!fp(e.data,this._channelId,"client-to-server"))return;this._clientOrigin!==e.origin&&(this._clientOrigin=e.origin,(n=this.onclientorigin)==null||n.call(this,e.origin));let{payload:t}=e.data;if(t==="mcp-check-ready"){this._broadcastServerReady();return}try{let s=Hi.parse(t);(o=this.onmessage)==null||o.call(this,s)}catch(s){(r=this.onerror)==null||r.call(this,Error(`Invalid message: ${s instanceof Error?s.message:String(s)}`))}},window.addEventListener("message",this._messageHandler),this._started=!0,this._broadcastServerReady()}async send(e,t){if(this._closed)throw Error("Transport is closed");if(!this._started)throw Error("Transport not started");if(!this._clientOrigin){console.debug("[IframeChildTransport] No client connected, message not sent");return}if(window.parent===window){console.debug("[IframeChildTransport] Not running in an iframe, message not sent");return}an(window.parent,this._clientOrigin,this._channelId,"server-to-client",e)}async close(){var e;this._closed||(this._closed=!0,this._started=!1,this._messageHandler&&(this._messageHandler=(window.removeEventListener("message",this._messageHandler),void 0)),this._clientOrigin&&window.parent!==window&&an(window.parent,this._clientOrigin,this._channelId,"server-to-client","mcp-server-stopped"),(e=this.onclose)==null||e.call(this))}_broadcastServerReady(){window.parent!==window&&an(window.parent,"*",this._channelId,"server-to-client","mcp-server-ready")}},C_=class{constructor(e){T(this,"_started",!1);T(this,"_closed",!1);T(this,"_allowedOrigins");T(this,"_channelId");T(this,"_messageHandler");T(this,"onclose");T(this,"onerror");T(this,"onmessage");var t;if(!((t=e.allowedOrigins)!=null&&t.length))throw Error("At least one allowed origin must be specified");this._allowedOrigins=new Set(e.allowedOrigins),this._channelId=e.channelId??"mcp-default"}async start(){if(this._closed)throw Error("TabServerTransport cannot be restarted after it closes");if(this._started)throw Error("Transport already started");this._messageHandler=e=>{var n,o;if(e.source!==window||!this._allowedOrigins.has("*")&&!this._allowedOrigins.has(e.origin)||!fp(e.data,this._channelId,"client-to-server"))return;let{payload:t}=e.data;if(t==="mcp-check-ready"){an(window,"*",this._channelId,"server-to-client","mcp-server-ready");return}try{let r=Hi.parse(t);(n=this.onmessage)==null||n.call(this,r)}catch(r){(o=this.onerror)==null||o.call(this,Error(`Invalid message: ${r instanceof Error?r.message:String(r)}`))}},window.addEventListener("message",this._messageHandler),this._started=!0,an(window,"*",this._channelId,"server-to-client","mcp-server-ready")}async send(e,t){if(this._closed)throw Error("Transport is closed");if(!this._started)throw Error("Transport not started");an(window,"*",this._channelId,"server-to-client",e)}async close(){var e;this._closed||(this._closed=!0,this._messageHandler&&(this._messageHandler=(window.removeEventListener("message",this._messageHandler),void 0)),this._started&&an(window,"*",this._channelId,"server-to-client","mcp-server-stopped"),this._started=!1,(e=this.onclose)==null||e.call(this))}};const gp=["consequentialHint","debugging","readOnlyHint","untrustedContentHint"],rn="webmcp-polyfill",Er=500,Sp=globalThis.DOMException;var un,se,Rt,et,Mt,Tt,dn,At,pn,xt,V,xo,yp,_p,vp,bp,xr,ti,ni,bt,oi,ri,zr,Lr,wp,si;class O_{constructor(t,n){ye(this,V);ye(this,un);ye(this,se);ye(this,Rt);ye(this,et,new Set);ye(this,Mt,new Set);ye(this,Tt,Promise.withResolvers());ye(this,dn,new Map);ye(this,At,new Set);ye(this,pn);ye(this,xt,!1);rt(this,se,t),rt(this,un,t.document),rt(this,Rt,n),E(this,se).addEventListener("message",o=>G(this,V,yp).call(this,o),!0),E(this,se).addEventListener("pagehide",()=>{rt(this,xt,!0);for(const o of E(this,At))o.end()}),E(this,se).addEventListener("pageshow",o=>{o.persisted&&(rt(this,xt,!1),G(this,V,zr).call(this))});for(const o of G(this,V,zr).call(this))E(this,Mt).add(o);E(this,Mt).size===0?E(this,Tt).resolve():setTimeout(()=>{E(this,Mt).clear(),E(this,Tt).resolve()},Er)}async allowed(){return E(this,xt)?!1:G(this,V,xr).call(this,E(this,un))}async getTools(t){await E(this,Tt).promise;const n=E(this,se).origin,o=[n,...t];return(await Promise.all(G(this,V,ri).call(this).map(async s=>{if(s===E(this,se))return E(this,Rt).getTools(n).map(i=>uc(i,E(this,se),n));try{const i=await G(this,V,xo).call(this,s,o,{kind:"getTools"});if(!Array.isArray(i.value))throw new TypeError("Expected a tool list from the frame");return i.value.map(a=>uc(q_(a),s,i.origin))}catch(i){return i instanceof Sp&&i.name==="UnknownError"||console.warn("WebMCP: could not read tools from a frame.",i),[]}}))).flat()}async execute(t,n,o,r,s){const i=await G(this,V,xo).call(this,t,[n],{kind:"execute",name:o,input:r},s);if(typeof i.value!="string")throw wt();return i.value}async notify(t){await E(this,Tt).promise;const n=[E(this,se).origin,...t];for(const o of G(this,V,ri).call(this)){if(o===E(this,se)){await E(this,Rt).changed();continue}try{await G(this,V,xo).call(this,o,n,{kind:"changed"})}catch{}}}}un=new WeakMap,se=new WeakMap,Rt=new WeakMap,et=new WeakMap,Mt=new WeakMap,Tt=new WeakMap,dn=new WeakMap,At=new WeakMap,pn=new WeakMap,xt=new WeakMap,V=new WeakSet,xo=function(t,n,o,r){return new Promise((s,i)=>{if(r==null||r.throwIfAborted(),E(this,xt)||!G(this,V,bt).call(this,t)){i(wt());return}const a=crypto.randomUUID(),{port1:c,port2:d}=new MessageChannel;let u;const p=()=>{clearTimeout(S),b(),r==null||r.removeEventListener("abort",h),E(this,dn).delete(a),c.close()},m=(R=wt())=>{c.postMessage({kind:"cancel"}),p(),i(R)},h=()=>m(r==null?void 0:r.reason),f=()=>{u===void 0&&G(this,V,wp).call(this,t),m()},_=R=>{if(R.source===t){if(E(this,dn).delete(a),n&&!n.includes(R.origin)){m();return}u=R.origin,clearTimeout(S),o.kind!=="execute"&&o.kind!=="changed"&&(S=setTimeout(f,Er)),c.postMessage(o)}};let S=setTimeout(f,Er);const b=G(this,V,si).call(this,t,m);c.onmessage=R=>{const M=Go(R.data);if((M==null?void 0:M.kind)==="error"){m();return}(M==null?void 0:M.kind)!=="result"||u===void 0||(p(),s({value:M.value,origin:u}))},c.onmessageerror=()=>m(),r==null||r.addEventListener("abort",h,{once:!0}),E(this,dn).set(a,_);try{t.postMessage(`${rn}:connect:${a}`,"*",[d])}catch{d.close(),m()}})},yp=function(t){var s;const n=N_(t.data);if(!n)return;t.stopImmediatePropagation();const o=t.source;if(!t.isTrusted||!o||!M_(o)||!G(this,V,bt).call(this,o)||t.origin==="null"||E(this,xt))return;if(n.kind==="announce"){const i=!E(this,et).has(o);if(G(this,V,Lr).call(this,o),o.postMessage(`${rn}:present`,t.origin),!i||E(this,se)!==E(this,se).top)return;for(const a of E(this,et))a!==o&&a.postMessage(`${rn}:refresh`,"*");return}if(n.kind==="present"){G(this,V,Lr).call(this,o);return}if(n.kind==="refresh"){o===E(this,se).top&&G(this,V,zr).call(this);return}if(n.kind==="ready"){(s=E(this,dn).get(n.id))==null||s(t);return}const[r]=t.ports;n.kind!=="connect"||!n.id||!r||t.ports.length!==1||(G(this,V,Lr).call(this,o),G(this,V,_p).call(this,o,t.origin,n.id,r))},_p=function(t,n,o,r){const s=new AbortController;let i=!1;const a=()=>{clearTimeout(u),p(),r.close()},c=()=>{s.abort(),a()},d=()=>{r.postMessage({kind:"error"}),c()},u=setTimeout(d,Er),p=G(this,V,si).call(this,t,d);r.onmessageerror=d,r.onmessage=async m=>{const h=Go(m.data);if((h==null?void 0:h.kind)==="cancel"){c();return}if(!i){i=!0,clearTimeout(u);try{const f=await G(this,V,vp).call(this,t,n,h,s.signal);r.postMessage({kind:"result",value:f}),a()}catch{d()}}},t.postMessage(`${rn}:ready:${o}`,n)},vp=async function(t,n,o,r){if(!o||!G(this,V,bt).call(this,t))throw wt();if(o.kind==="permission"){const{childIndex:s,childOrigin:i}=o;if(typeof s!="number"||!Number.isInteger(s)||s<0||typeof i!="string")throw wt();return G(this,V,bp).call(this,s,i)}if(!await this.allowed()||!await G(this,V,ti).call(this,t,n)||!G(this,V,bt).call(this,t))throw wt();if(r.throwIfAborted(),o.kind==="getTools")return E(this,Rt).getTools(n);if(o.kind==="execute"&&typeof o.name=="string"&&typeof o.input=="string")return E(this,Rt).execute(n,o.name,o.input,r);if(o.kind==="changed"){await E(this,Rt).changed();return}throw wt()},bp=async function(t,n){const o=E(this,se)[t];return o!==void 0&&await this.allowed()&&Is(E(this,un),o,n)},xr=async function(t){var i;const n=ua(t);if(!n)return!1;const o=Tp(t);if(o!==void 0)return o;if(n===n.parent)return!0;const r=(i=n.location.ancestorOrigins)==null?void 0:i[0],s=lc(n.parent,r===void 0||r===n.origin);return s?Is(s,n,n.origin)&&await G(this,V,xr).call(this,s):G(this,V,ni).call(this,n,n.origin)},ti=async function(t,n){const o=lc(t,n===E(this,se).origin);return o?G(this,V,xr).call(this,o):G(this,V,ni).call(this,t,n)},ni=async function(t,n){const o=t.parent;if(o===t)return!0;let r=-1;for(let s=0;s<o.length;s++)if(o[s]===t){r=s;break}if(r<0)return!1;if(o===E(this,se))return await this.allowed()&&Is(E(this,un),t,n);if(await E(this,Tt).promise,!E(this,et).has(o))return!1;try{const s=await G(this,V,xo).call(this,o,void 0,{kind:"permission",childIndex:r,childOrigin:n});return s.value===!0&&await G(this,V,ti).call(this,o,s.origin)}catch{return!1}},bt=function(t){try{return!t.closed&&t!==E(this,se)&&t.top===E(this,se).top}catch{return!1}},oi=function(){if(E(this,se).closed)return[];for(const r of E(this,et))G(this,V,bt).call(this,r)||E(this,et).delete(r);const t=[E(this,se),...E(this,et)];for(let r=E(this,se).parent;r!==r.parent;r=r.parent)t.push(r);const n=new Set,o=[E(this,se).top];for(;o.length;){const r=o.pop();if(n.has(r))continue;n.add(r);const s=[];for(let i=0;i<r.length;i++){const a=r[i];a&&s.push(a)}for(const i of t)i!==r&&i.parent===r&&!s.includes(i)&&s.push(i);o.push(...s.reverse())}return Array.from(n).filter(r=>r===E(this,se)||G(this,V,bt).call(this,r))},ri=function(){return G(this,V,oi).call(this).filter(t=>t===E(this,se)||E(this,et).has(t))},zr=function(){const t=G(this,V,oi).call(this).filter(n=>n!==E(this,se));for(const n of t)n.postMessage(`${rn}:announce`,"*");return t},Lr=function(t){E(this,et).add(t),E(this,Mt).delete(t),E(this,Mt).size===0&&E(this,Tt).resolve()},wp=function(t){E(this,et).delete(t),G(this,V,bt).call(this,t)&&t.postMessage(`${rn}:announce`,"*")},si=function(t,n){const o={peer:t,end:n};return E(this,At).add(o),E(this,pn)===void 0&&rt(this,pn,E(this,se).setInterval(()=>{for(const r of E(this,At))G(this,V,bt).call(this,r.peer)||r.end()},100)),()=>{E(this,At).delete(o),E(this,At).size===0&&(E(this,se).clearInterval(E(this,pn)),rt(this,pn,void 0))}};function Is(e,t,n){var u;const o=(u=e.defaultView)==null?void 0:u.origin,r=I_(e,t,n===o);if(!r)return!1;const s=(r.getAttribute("allow")??"").split(";").map(p=>p.trim().split(/\s+/u)).find(([p])=>p==="tools");if(!s)return n===o;const i=s.length===1?["'src'"]:s.slice(1);if(i.includes("'none'"))return!1;const a=r.hasAttribute("srcdoc")?null:r.getAttribute("src"),c=a?URL.parse(a,e.baseURI):null,d=!a||(c==null?void 0:c.protocol)==="about:"?o:c==null?void 0:c.origin;return i.some(p=>p==="*"||p==="'self'"&&n===o||p==="'src'"&&n===d||p===n)}function lc(e,t){if(t)try{return e.document}catch{return}}function I_(e,t,n){if(n)try{const o=t.frameElement;if((o==null?void 0:o.ownerDocument)===e)return o}catch{}return Rp(e,t)}function Rp(e,t){const n=e.querySelectorAll("iframe, frame");for(const o of n)if(o.contentWindow===t)return o;for(const o of e.querySelectorAll("*")){if(!o.shadowRoot)continue;const r=Rp(o.shadowRoot,t);if(r)return r}}function ua(e){const t=e.defaultView;return t&&!t.closed&&t.document===e?t:void 0}function Tp(e){const t=e,n=Go(t.permissionsPolicy??t.featurePolicy);if(typeof(n==null?void 0:n.features)!="function"||typeof n.allowsFeature!="function")return;const o=n.features();return Array.isArray(o)&&o.includes("tools")?!!n.allowsFeature("tools"):void 0}function uc(e,t,n){const o=e.serializedSchema===void 0?void 0:JSON.parse(e.serializedSchema);return{...e.annotations!==void 0&&{annotations:{...e.annotations}},description:e.description,...o!==void 0&&{inputSchema:o},name:e.name,origin:n,title:e.title,window:t}}function q_(e){const t=Go(e);if(!t||typeof t.name!="string"||typeof t.title!="string"||typeof t.description!="string"||t.serializedSchema!==void 0&&typeof t.serializedSchema!="string")throw new TypeError("Invalid tool metadata from the frame");const n={name:t.name,title:t.title,description:t.description,annotations:void 0,serializedSchema:t.serializedSchema};if(t.annotations===void 0)return n;const o=Go(t.annotations);if(!o)throw new TypeError("Invalid tool annotations from the frame");const r={};for(const s of gp){const i=o[s];if(i!==void 0){if(typeof i!="boolean")throw new TypeError(`Invalid ${s} annotation from the frame`);r[s]=i}}return n.annotations=r,n}function N_(e){if(typeof e!="string")return;const[t,n="",o="",r]=e.split(":");return t===rn&&r===void 0?{kind:n,id:o}:void 0}function Go(e){if(!(typeof e!="object"||e===null||Array.isArray(e)))return e}function M_(e){try{return"postMessage"in e&&"window"in e}catch{return!1}}function wt(){return new Sp("Tool execution failed","UnknownError")}/*!
|
|
58
|
+
* Copyright (c) 2026 World Wide Web Consortium
|
|
59
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
60
|
+
*/const $t=globalThis.DOMException;var Gc;const A_=(Gc=Object.getOwnPropertyDescriptor(globalThis,"window"))==null?void 0:Gc.get,dc=new WeakMap;function x_(){if(typeof document>"u"||!globalThis.isSecureContext||"modelContext"in document)return;const e=Document.prototype,t=Object.getOwnPropertyDescriptor(e,"defaultView").get,n=Object.getOwnPropertyDescriptor(globalThis,"ModelContext");if(!Object.isExtensible(e)||n&&!n.configurable||!n&&!Object.isExtensible(globalThis))throw new TypeError("Cannot install WebMCP on this realm");Object.defineProperty(globalThis,"ModelContext",{value:rr,configurable:!0,writable:!0});const{getModelContext:o}={getModelContext(){t.call(this);let r=dc.get(this);return r||(r=new da(this),dc.set(this,r)),r}};Object.defineProperty(o,"name",{value:"get modelContext"}),Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,get:o})}var gt,zt,er,Lt,tr,We,ii,jr,$p,Ep;class da extends EventTarget{constructor(n){super();ye(this,We);ye(this,gt);ye(this,zt,new Map);ye(this,er);ye(this,Lt,null);ye(this,tr,n=>{const o=E(this,Lt);if(typeof o!="function")return;Reflect.apply(o,this,[n])===!1&&Event.prototype.preventDefault.call(n)});rt(this,gt,n);const o=ua(n);o&&rt(this,er,new O_(o,{getTools:r=>G(this,We,$p).call(this,r),execute:(r,s,i,a)=>{const c=qt(n).origin;return G(this,We,ii).call(this,s,i,c,r,a)},changed:()=>G(this,We,Ep).call(this)}))}get ontoolchange(){return E(this,Lt)}set ontoolchange(n){const o=Dt(n)?n:null;!E(this,Lt)&&o&&this.addEventListener("toolchange",E(this,tr)),E(this,Lt)&&!o&&this.removeEventListener("toolchange",E(this,tr)),rt(this,Lt,o)}async registerTool(n,o={}){const r=E(this,gt),{name:s,title:i,description:a,annotations:c,inputSchema:d,execute:u}=z_(n),p=Ut(o),m=hc(p.exposedTo),h=mc(p.signal);qt(r);const f=()=>{if(E(this,zt).has(s))throw new $t(`A tool named ${s} is already registered`,"InvalidStateError")};if(f(),!/^[A-Za-z0-9_.-]{1,128}$/u.test(s))throw new $t(`Tool names are 1 to 128 characters of ASCII alphanumerics, "_", "-" or ".": ${s}`,"InvalidStateError");if(!a)throw new $t("A tool description cannot be empty","InvalidStateError");const _=d===void 0?void 0:qs(d);h==null||h.throwIfAborted();const S=fc(m),b={metadata:{name:s,title:i,description:a,annotations:c,serializedSchema:_},execute:u,exposedTo:S},R=await G(this,We,jr).call(this);return h==null||h.throwIfAborted(),f(),new Promise((M,L)=>{h==null||h.addEventListener("abort",()=>{E(this,zt).delete(s),R.notify(S),L(h.reason)},{once:!0}),E(this,zt).set(s,b),R.notify(S).then(M,L)})}async getTools(n={}){const o=E(this,gt),r=Ut(n),s=hc(r.fromOrigins);qt(o);const i=await G(this,We,jr).call(this),a=fc(s),c=await i.getTools(a);return c.sort((d,u)=>d.name===u.name?0:d.name<u.name?-1:1),new Promise(d=>{On(()=>d(c))})}async executeTool(n,o={},r={}){var h;const s=E(this,gt),i=L_(n),a=Ut(r),c=mc(a.signal);qt(s);const d=(h=URL.parse(i.origin))==null?void 0:h.origin;if(!d||d==="null")throw new $t("Invalid or opaque origin","NotSupportedError");if(!Dt(o))throw new TypeError("inputObject must be an object");const u=qs(o);c==null||c.throwIfAborted();const p=await G(this,We,jr).call(this);c==null||c.throwIfAborted();const m=qt(s);return i.window!==m?p.execute(i.window,d,i.name,u,c):G(this,We,ii).call(this,i.name,u,d,m.origin,c)}}gt=new WeakMap,zt=new WeakMap,er=new WeakMap,Lt=new WeakMap,tr=new WeakMap,We=new WeakSet,ii=function(n,o,r,s,i){return new Promise((a,c)=>{i==null||i.throwIfAborted();const d=new AbortController;let u=!1;const p=()=>{c(i.reason),On(()=>{u||d.abort()})},m=()=>{u=!0,On(()=>{i==null||i.removeEventListener("abort",p),c(wt())})},h=_=>{if(u=!0,!(i!=null&&i.aborted))try{const S=qs(_);On(()=>{i==null||i.removeEventListener("abort",p),a(S)})}catch{m()}},f=()=>{if(!(i!=null&&i.aborted))try{const _=qt(E(this,gt)),S=E(this,zt).get(n);if(!S||r!==_.origin||!pc(S,_.origin,s)){m();return}const b=JSON.parse(o);if(!Dt(b)){m();return}const R=S.execute,M=R(b,{signal:d.signal});Promise.resolve(M).then(h,m)}catch{m()}};i==null||i.addEventListener("abort",p,{once:!0}),On(f)})},jr=async function(){const n=E(this,er);if(!n||!await n.allowed())throw new $t("WebMCP is disabled by Permissions Policy","NotAllowedError");return qt(E(this,gt)),n},$p=function(n){const o=qt(E(this,gt)).origin,r=[];for(const s of E(this,zt).values())pc(s,o,n)&&r.push(s.metadata);return r},Ep=function(){return new Promise(n=>{On(()=>{this.dispatchEvent(new Event("toolchange")),n()})})};function pc(e,t,n){return t===n||e.exposedTo.includes(n)}const rr=function(){throw new TypeError("Illegal constructor")};Object.defineProperty(rr,"name",{value:"ModelContext"});Object.defineProperty(rr,"prototype",{value:da.prototype,writable:!1});Object.setPrototypeOf(rr,EventTarget);Object.defineProperties(da.prototype,{constructor:{value:rr,configurable:!0,writable:!0},[Symbol.toStringTag]:{value:"ModelContext",configurable:!0},registerTool:{enumerable:!0},getTools:{enumerable:!0},executeTool:{enumerable:!0},ontoolchange:{enumerable:!0}});function z_(e){const t=Ut(e),n=kp(t.annotations),o=qn(cn(t.description,"description")),r=cn(t.execute,"execute");if(typeof r!="function")throw new TypeError("execute must be a function");const s=r,i=Pp(t.inputSchema),a=qn(cn(t.name,"name")),c=t.title,d=c===void 0?"":pa(c);return{name:a,title:d,description:o,annotations:n,inputSchema:i,execute:s}}function L_(e){const t=Ut(e);kp(t.annotations),qn(cn(t.description,"description")),Pp(t.inputSchema);const n=qn(cn(t.name,"name")),o=pa(cn(t.origin,"origin")),r=t.title;r!==void 0&&qn(r);const s=cn(t.window,"window");if(!Dt(s))throw new TypeError("window must be a Window");return A_.call(s),{name:n,origin:o,window:s}}function Pp(e){if(e!==void 0&&!Dt(e))throw new TypeError("inputSchema must be an object");return e}function Dt(e){return typeof e=="object"&&e!==null||typeof e=="function"}function Ut(e){if(e==null)return{};if(!Dt(e))throw new TypeError("Expected a dictionary");return e}function kp(e){if(e===void 0)return;const t=Ut(e),n={};for(const o of gp)n[o]=!!t[o];return n}function qn(e){if(typeof e=="symbol")throw new TypeError("Cannot convert a Symbol to a string");return String(e)}function pa(e){return qn(e).toWellFormed()}function cn(e,t){if(e===void 0)throw new TypeError(`${t} is required`);return e}function qs(e){const t=JSON.stringify(e);if(t===void 0)throw new TypeError("Value is not JSON-serializable");return t}function mc(e){if(e!==void 0)return AbortSignal.any([e])}function hc(e){if(e===void 0)return[];if(!Dt(e))throw new TypeError("Origins must be a sequence");const t=Ut(e)[Symbol.iterator];if(typeof t!="function")throw new TypeError("Origins must be a sequence");return Array.from({[Symbol.iterator](){const o=Reflect.apply(t,e,[]);if(!Dt(o))throw new TypeError("Iterator must be an object");const r=Ut(o).next;if(typeof r!="function")throw new TypeError("Iterator next must be a function");return{next(){return Reflect.apply(r,o,[])}}}},pa)}function fc(e){return e.map(t=>{var r;const n=(r=URL.parse(t))==null?void 0:r.origin;if(n===void 0)throw new $t("Invalid origin","SecurityError");const o=URL.parse(n);if(!o||!j_(o))throw new $t("Origin is not potentially trustworthy","SecurityError");return n})}function j_({protocol:e,hostname:t}){if(["https:","wss:"].includes(e))return!0;const n=t==="[::1]"||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t),o=t==="localhost"||t==="localhost."||t.endsWith(".localhost")||t.endsWith(".localhost.");return["http:","ws:"].includes(e)&&(n||o)}function qt(e){const t=ua(e);if(!t)throw new $t("The document is not fully active","InvalidStateError");if(Tp(e)===!1)throw new $t("WebMCP is disabled by Permissions Policy","NotAllowedError");return t}let Ns;const gc=[];function On(e){if(!Ns){const t=new MessageChannel;t.port1.onmessage=()=>{var n;return(n=gc.shift())==null?void 0:n()},Ns=t.port2}gc.push(e),Ns.postMessage(void 0)}const ma=new WeakSet,ai=new WeakMap,Vn=new WeakMap;function Cp(e){return e.isTrusted&&(ma.has(e)||e.eventPhase!==Event.NONE&&e.target instanceof HTMLFormElement&&Vn.has(e.target))}function D_(e,t){var o;if(!Cp(e))throw new DOMException("respondWith() is only available during an agent-invoked submit event","InvalidStateError");if(!e.defaultPrevented)throw new DOMException("respondWith() requires preventDefault() during an agent-invoked submit event","InvalidStateError");if(e.eventPhase===Event.NONE)throw new DOMException("respondWith() is only available while the submit event is being dispatched","InvalidStateError");ma.add(e);const n=Promise.resolve(t);ai.set(e,n),e.target instanceof HTMLFormElement&&((o=Vn.get(e.target))==null||o.respond(e))}const Op=new Set(["email","password","search","tel","text","url"]),U_=new Set([...Op,"date","datetime-local","month","number","time","week"]);function Z_(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement}function Ip(e){var t,n;return(n=(t=Object.getOwnPropertyDescriptor(HTMLFormElement.prototype,"elements"))==null?void 0:t.get)==null?void 0:n.call(e)}function Ms(e,t){return Element.prototype.getAttribute.call(e,t)}function ci(e,t){return Element.prototype.hasAttribute.call(e,t)}function Sc(e){var t,n;return(n=(t=Object.getOwnPropertyDescriptor(Node.prototype,"isConnected"))==null?void 0:t.get)==null?void 0:n.call(e)}function H_(e){var t,n;return(n=(t=Object.getOwnPropertyDescriptor(Element.prototype,"shadowRoot"))==null?void 0:t.get)==null?void 0:n.call(e)}function F_(e){return HTMLFormElement.prototype.checkValidity.call(e)}function V_(e,t){HTMLFormElement.prototype.requestSubmit.call(e,t)}function J_(e){return[...Ip(e)].filter(t=>Z_(t)&&!t.matches(":disabled")&&!("readOnly"in t&&t.readOnly&&(t instanceof HTMLTextAreaElement||U_.has(t.type))))}function qp(e){const t=new Map;for(const n of J_(e)){const o=n.name.trim(),r=t.get(o);r?r.push(n):t.set(o,[n])}return t}function Np(e){return[...e.labels??[]].map(t=>{var o;const n=t.cloneNode(!0);return n instanceof HTMLElement?(n.querySelectorAll("button, input, meter, output, progress, select, textarea").forEach(r=>r.remove()),((o=n.textContent)==null?void 0:o.trim())??""):""}).filter(Boolean).join("; ")}function B_(e,t){var n;for(let o=(n=t[0])==null?void 0:n.parentElement;o&&o!==e;o=o.parentElement)if(o instanceof HTMLFieldSetElement&&t.every(r=>o.contains(r)))return o}function W_(e,t){var n;if(t.length===1){const o=t[0];return o&&(o.getAttribute("toolparamdescription")||Np(o)||o.getAttribute("aria-description"))||void 0}return((n=B_(e,t))==null?void 0:n.getAttribute("toolparamdescription"))||void 0}function K_(e,t,n,o){const r=W_(t,n),s=r&&o?`${r} (${o})`:r||o;return s?{...e,description:s}:e}function yc(e,t){const n=e.getAttribute(t);if(n===null||n.trim()==="")return;const o=Number(n);return Number.isFinite(o)?o:void 0}function Mp(e,t){const n=Number(e.getAttribute("step"));return Number.isFinite(n)&&n>0?n:t}function G_(e,t){const n=e/t;return Math.abs(n-Math.round(n))<Number.EPSILON*16}function _c(e,t){const n=t.getAttribute("pattern");if(n===null)return e;try{new RegExp(n,"v")}catch{return e}return{...e,pattern:n}}function vc(e){const t={type:"number"},n=yc(e,"min"),o=yc(e,"max");if(n!==void 0&&(t.minimum=n),o!==void 0&&(t.maximum=o),e.getAttribute("step")!=="any"){const r=Mp(e,1),s=Number(e.getAttribute("value"));G_(n??(Number.isFinite(s)?s:0),r)&&(t.multipleOf=r)}return t}function bc(e,t){const n=Mp(e,60);return n<1?`${t}(:[0-5][0-9](\\.[0-9]{1,3})?)?$`:n<60?`${t}(:[0-5][0-9])?$`:`${t}$`}function Y_(e){return{anyOf:e.map(t=>({type:"string",const:t.value,title:t.textContent??""})),enum:e.map(t=>t.value)}}function wc(e){return{anyOf:e.map(t=>{const n=Np(t),o={type:"string",const:t.value};return n&&(o.title=n),o}),enum:e.map(t=>t.value)}}function Yo(e,t){return e instanceof HTMLInputElement&&e.type===t}function X_(e){if(Op.has(e.type))return _c({type:"string"},e);switch(e.type){case"hidden":return e.getAttribute("toolparamdescription")?{type:"string"}:void 0;case"number":return _c(vc(e),e);case"range":{const t=vc(e);return t.minimum??(t.minimum=0),t.maximum??(t.maximum=100),t}case"checkbox":return{type:"boolean"};case"date":return{type:"string",format:"date"};case"month":return{type:"string",format:"^[0-9]{4}-(0[1-9]|1[0-2])$"};case"week":return{type:"string",format:"^[0-9]{4}-W(0[1-9]|[1-4][0-9]|5[0-3])$"};case"time":return{type:"string",format:bc(e,"^([01][0-9]|2[0-3]):[0-5][0-9]")};case"datetime-local":return{type:"string",format:bc(e,"^[0-9]{4}-(0[1-9]|1[0-2])-[0-9]{2}T([01][0-9]|2[0-3]):[0-5][0-9]")};case"color":return{type:"string",format:"^#[0-9a-zA-Z]{6}$"};default:return}}function Ap(e,t){const[n]=t;if(!n)return;let o;if(t.every(s=>Yo(s,"radio")))o={type:"string",...wc(t)};else if(t.length>1)t.every(s=>Yo(s,"checkbox"))&&(o={type:"array",items:{type:"string",...wc(t)},uniqueItems:!0});else if(n instanceof HTMLTextAreaElement)o={type:"string"};else if(n instanceof HTMLSelectElement){const s=Y_([...n.options]);o=n.multiple?{type:"array",items:{type:"string",...s},uniqueItems:!0}:{type:"string",...s}}else o=X_(n);const r=n.type==="date"?"Dates MUST be provided in 'YYYY-MM-DD' format.":void 0;return o&&K_(o,e,t,r)}function Q_(e){const t={},n=[];for(const[o,r]of qp(e)){if(!o)continue;const s=Ap(e,r);s&&(Object.defineProperty(t,o,{configurable:!0,enumerable:!0,value:s,writable:!0}),r.some(i=>i.required)&&n.push(o))}return{type:"object",properties:t,required:n}}function ev(e){return{name:Ms(e,"toolname")??"",title:Ms(e,"tooltitle")??"",description:Ms(e,"tooldescription")??"",inputSchema:Q_(e),autosubmit:ci(e,"toolautosubmit")}}function Yr(e){if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return String(e)}function xp(e){if(typeof e=="boolean")return e;if(typeof e=="number"&&Number.isInteger(e))return e!==0;if(typeof e=="string"){if(e==="1"||e.toLowerCase()==="true")return!0;if(e==="0"||e.toLowerCase()==="false")return!1}}function Rc(e,t){if(!Array.isArray(e))return!1;const n=new Set(t);for(const o of e){const r=Yr(o);if(r===void 0||!n.delete(r))return!1}return!0}function tv(e,t){if(t==="")return e.type!=="number"&&e.type!=="range";const n=e.ownerDocument.createElement("input");return n.type=e.type,n.value=t,n.value!==""}function nv(e,t,n){const[o]=t;if(!o||!Ap(e,t))return!1;const r=Yr(n);if(t.every(s=>Yo(s,"radio")))return t.some(s=>s.value===r);if(t.length>1)return Rc(n,new Set(t.map(s=>s.value)));if(o instanceof HTMLSelectElement){const s=new Set([...o.options].map(i=>i.value));return o.multiple?Rc(n,s):r!==void 0&&s.has(r)}return o instanceof HTMLTextAreaElement?r!==void 0:o.type==="checkbox"?xp(n)!==void 0:r!==void 0&&tv(o,r)}function Xr(e){e.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}function ov(e,t){var o,r;if(e.value===t)return;const n=e instanceof HTMLInputElement?HTMLInputElement.prototype:HTMLTextAreaElement.prototype;(r=(o=Object.getOwnPropertyDescriptor(n,"value"))==null?void 0:o.set)==null||r.call(e,t),Xr(e)}function As(e,t){var n,o;e.checked!==t&&((o=(n=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"))==null?void 0:n.set)==null||o.call(e,t),Xr(e))}function rv(e,t){const[n]=e,o=Yr(t),r=new Set(Array.isArray(t)?t.map(Yr):[]);if(e.every(s=>Yo(s,"radio"))){const s=e.find(i=>i.value===o);s&&As(s,!0)}else if(e.length>1)for(const s of e)s instanceof HTMLInputElement&&As(s,r.has(s.value));else if(n instanceof HTMLSelectElement)if(n.multiple){let s=!1;for(const i of n.options){const a=r.has(i.value);i.selected!==a&&(i.selected=a,s=!0)}s&&Xr(n)}else o!==void 0&&n.value!==o&&(n.value=o,Xr(n));else if(n&&Yo(n,"checkbox")){const s=xp(t);s!==void 0&&As(n,s)}else n&&o!==void 0&&ov(n,o)}function sv(e,t){if(Array.isArray(t))throw Zt();const n=qp(e),o=[];for(const[r,s]of Object.entries(t)){const i=n.get(r);if(!i||!nv(e,i,s))throw Zt();o.push({controls:i,value:s})}for(const{controls:r,value:s}of o)rv(r,s)}function iv(e){return[...Ip(e)].find(t=>!t.matches(":disabled")&&(t instanceof HTMLButtonElement&&t.type==="submit"||t instanceof HTMLInputElement&&["image","submit"].includes(t.type)))}function Zt(){return new DOMException("Tool execution failed","UnknownError")}function xs(e,t){const n=new Event(e);return Object.defineProperty(n,"toolName",{enumerable:!0,value:t}),n}function av(e,t,n,o,r){var i;const{form:s}=t;return(i=t.cancelPending)==null||i.call(t,Zt()),new Promise((a,c)=>{let d=!1;const u=()=>{EventTarget.prototype.removeEventListener.call(s,"invalid",f,!0),r.removeEventListener("abort",_),Vn.delete(s),t.cancelPending===m&&delete t.cancelPending},p=S=>{d||(d=!0,u(),S())},m=S=>p(()=>c(S)),h=S=>{t.cancelPending===m&&delete t.cancelPending,S.then(b=>p(()=>a(b??null)),b=>p(()=>c(b)))},f=S=>{S.isTrusted&&queueMicrotask(()=>{F_(s)||m(Zt())})},_=()=>{p(()=>{e.dispatchEvent(xs("toolcancel",n.name)),c(r.reason)})};if(Vn.set(s,{complete(S){setTimeout(()=>{const b=ai.get(S);b?h(b):S.defaultPrevented?m(Zt()):p(()=>a(null))})},direct(){p(()=>a(null))},respond(S){queueMicrotask(()=>{const b=ai.get(S);b&&h(b)})}}),t.cancelPending=m,EventTarget.prototype.addEventListener.call(s,"invalid",f,!0),r.addEventListener("abort",_,{once:!0}),!n.autosubmit){o==null||o.focus(),e.dispatchEvent(xs("toolactivated",n.name));return}try{V_(s,o),e.dispatchEvent(xs("toolactivated",n.name))}catch(S){m(S)}})}function cv(e){const t=SubmitEvent.prototype;if("agentInvoked"in t&&"respondWith"in t)return;"agentInvoked"in t||Object.defineProperty(t,"agentInvoked",{configurable:!0,enumerable:!0,get(){return Cp(this)}}),"respondWith"in t||Object.defineProperty(t,"respondWith",{configurable:!0,enumerable:!0,writable:!0,value(m){D_(this,m)}});const n=new Map,o=new Map,r=new Map,s=m=>{if(!(m instanceof SubmitEvent)||!m.isTrusted||!(m.target instanceof HTMLFormElement))return;const h=Vn.get(m.target);h&&(ma.add(m),h.complete(m))},i=m=>{if(!m.isTrusted||!(m.target instanceof HTMLFormElement))return;const h=m.target;setTimeout(()=>{var f,_;m.defaultPrevented||(_=(f=n.get(h))==null?void 0:f.cancelPending)==null||_.call(f,Zt())})};function a(m){var h;(h=r.get(m))==null||h.disconnect(),r.delete(m),m.removeEventListener("reset",i,!0),m.removeEventListener("submit",s,!0)}function c(m){if(r.has(m))return;const h=new MutationObserver(d);r.set(m,h),h.observe(m,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),m.addEventListener("reset",i,!0),m.addEventListener("submit",s,!0)}function d(){var _,S;c(document);for(const b of r.keys())b instanceof ShadowRoot&&!b.host.isConnected&&a(b);const m=new Set,h=new Map,f=new Map;for(const b of r.keys())for(const R of b.querySelectorAll("*")){const M=H_(R);if(M&&c(M),!(R instanceof HTMLFormElement)||!ci(R,"toolname")||!ci(R,"tooldescription")||!Sc(R))continue;const L=R;m.add(L);const te=ev(L),oe=JSON.stringify(te);if(o.get(L)===oe)continue;o.delete(L);const Y=f.get(te.name);if(Y){const H=Q=>{var re;return((re=n.get(Q))==null?void 0:re.name)===te.name};if(!H(L)||H(Y)){o.set(L,oe);continue}const ne=h.get(Y);ne&&o.set(Y,ne.fingerprint),h.delete(Y)}f.set(te.name,L),h.set(L,{definition:te,fingerprint:oe})}for(const b of o.keys())m.has(b)||o.delete(b);for(const[b,R]of n)((_=h.get(b))==null?void 0:_.fingerprint)!==R.fingerprint&&((S=R.cancelPending)==null||S.call(R,Zt()),R.controller.abort(),n.delete(b));for(const[b,{definition:R,fingerprint:M}]of h){if(n.has(b))continue;const L=new AbortController,te={controller:L,fingerprint:M,form:b,name:R.name};n.set(b,te),e.registerTool({name:R.name,title:R.title,description:R.description,inputSchema:R.inputSchema,execute(oe,Y){const H=iv(b);if(!R.autosubmit&&!H)throw Zt();return sv(b,oe),av(e,te,R,H,Y.signal)}},{signal:L.signal}).catch(oe=>{L.abort(),!(oe instanceof DOMException&&oe.name==="AbortError")&&console.error(`[webmcp] declarative form tool "${R.name}" was not registered:`,oe)})}}const u=Object.getOwnPropertyDescriptor(Element.prototype,"attachShadow");if(u!=null&&u.configurable){const m=Element.prototype.attachShadow,h=function(f){var S,b;const _=m.call(this,f);return _.mode==="open"&&((b=(S=Object.getOwnPropertyDescriptor(Node.prototype,"ownerDocument"))==null?void 0:S.get)==null?void 0:b.call(this))===document&&Sc(this)&&c(_),_};Object.defineProperty(Element.prototype,"attachShadow",{...u,value:h})}const p=Object.getOwnPropertyDescriptor(HTMLFormElement.prototype,"submit");if(p!=null&&p.configurable){const m=HTMLFormElement.prototype.submit,h=function(){var f;m.call(this),(f=Vn.get(this))==null||f.direct()};Object.defineProperty(HTMLFormElement.prototype,"submit",{...p,value:h})}d()}function zp(){if(typeof document>"u"||!globalThis.isSecureContext||typeof Promise.withResolvers!="function"||typeof AbortSignal.any!="function"||typeof String.prototype.toWellFormed!="function"||typeof URL.parse!="function")return;x_();const e=document.modelContext;e&&cv(e)}const lv=/^[A-Za-z0-9_.-]{1,128}$/u;function Ee(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function uv(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function Pr(e){if(typeof e=="symbol")throw new TypeError("Symbol values cannot be converted to a DOMString");return String(e)}function dv(e){const{name:t,description:n,title:o}=e;if(t===void 0)throw new TypeError('Tool "name" is required');if(n===void 0)throw new TypeError('Tool "description" is required');const{annotations:r,inputSchema:s,outputSchema:i,execute:a}=e,c=Pr(t),d=o===void 0?void 0:Pr(o).toWellFormed(),u={name:c,description:Pr(n),execute:a};if(d!==void 0&&(u.title=d),s!==void 0&&(u.inputSchema=s),i!==void 0&&(u.outputSchema=i),r!==void 0){const p=Ee(r)?r:{},m={readOnlyHint:!!p.readOnlyHint,untrustedContentHint:!!p.untrustedContentHint};p.title!==void 0&&(m.title=Pr(p.title).toWellFormed());for(const h of["destructiveHint","idempotentHint","openWorldHint","consequentialHint","debugging"]){const f=p[h];f!==void 0&&(m[h]=!!f)}u.annotations=m}return pv(u),u}function Ne(e){return new DOMException(e,"InvalidStateError")}function pv(e){if(e.name==="")throw Ne('Tool "name" must be a non-empty string');if(!lv.test(e.name))throw Ne('Tool "name" must be 1–128 characters and contain only ASCII alphanumeric, underscore, hyphen, or period');if(e.description.length===0)throw Ne('Tool "description" must be a non-empty string');if(typeof e.execute!="function")throw new TypeError('Tool "execute" must be a function')}function Qr(e){if(!uv(e))throw new TypeError("inputSchema must be an object");const t=JSON.stringify(e);if(t===void 0)throw new TypeError("inputSchema must be JSON-serializable");return t}const Tc={type:"object",properties:{}},mv=["draft-2020-12","draft-07"];function hv(e){if(!Ee(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ha(e,t=new WeakSet){var n;if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e))return!1;t.add(e);try{return((n=Array.isArray(e)?e:hv(e)?Object.values(e):null)==null?void 0:n.every(o=>ha(o,t)))??!1}catch{return!1}finally{t.delete(e)}}function fv(e){if(!Ee(e))return!1;switch(e.type){case"text":return typeof e.text=="string";case"image":case"audio":return typeof e.data=="string"&&typeof e.mimeType=="string";case"resource_link":return typeof e.uri=="string"&&typeof e.name=="string";case"resource":{const t=e.resource;return Ee(t)&&typeof t.uri=="string"&&(typeof t.text=="string"||typeof t.blob=="string")}default:return!1}}function gv(e){return Ee(e)&&ha(e)&&Array.isArray(e.content)&&e.content.every(fv)&&(e.isError===void 0||typeof e.isError=="boolean")&&(e._meta===void 0||Ee(e._meta))}function Sv(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function yv(e){if(gv(e))return e;const t={content:[{type:"text",text:Sv(e)}],isError:!1};return ha(e)&&(t.structuredContent=e),t}function fa(e){if(!Ee(e))return null;const t=e["~standard"];return Ee(t)?t:null}function $c(e){const t=fa(e);return!!(t&&t.version===1&&typeof t.validate=="function")}function _v(e){const t=fa(e);return!t||t.version!==1||!Ee(t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function vv(e){const t=fa(e);return!!(t&&t.version===1&&typeof t.vendor=="string"&&typeof t.validate=="function"&&Ee(t.jsonSchema)&&typeof t.jsonSchema.input=="function"&&typeof t.jsonSchema.output=="function")}function bv(e){for(const t of mv)try{const n=e["~standard"].jsonSchema.input({target:t}),o=JSON.parse(Qr(n));if(Ee(o))return o}catch{}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function li(e){if(e===void 0)return{inputSchema:Tc};if(_v(e)){const o=bv(e),r=Qr(o);return $c(e)&&Object.defineProperty(o,"~standard",{value:e["~standard"]}),{inputSchema:o,registeredInputSchema:r}}if($c(e))throw new Error("Standard Schema inputSchema must provide ~standard.jsonSchema.input() for tool metadata");const t=Qr(e),n=JSON.parse(t);return!Ee(n)||Object.keys(n).length===0?{inputSchema:Tc,registeredInputSchema:t}:{inputSchema:n.type===void 0?{type:"object",...n}:n,registeredInputSchema:t}}var wv=Object.create,ga=Object.defineProperty,Rv=Object.getOwnPropertyDescriptor,Tv=Object.getOwnPropertyNames,$v=Object.getPrototypeOf,Ev=Object.prototype.hasOwnProperty,Pv=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),kv=(e,t)=>{let n={};for(var o in e)ga(n,o,{get:e[o],enumerable:!0});return n},Cv=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var r=Tv(t),s=0,i=r.length,a;s<i;s++)a=r[s],!Ev.call(e,a)&&a!==n&&ga(e,a,{get:(c=>t[c]).bind(null,a),enumerable:!(o=Rv(t,a))||o.enumerable});return e},Ov=(e,t,n)=>(n=e!=null?wv($v(e)):{},Cv(ga(n,"default",{value:e,enumerable:!0}),e));const Iv=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),Lp=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),qv=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),Nv=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function Mv(e){return typeof e=="string"&&Lp.has(e.replace(/#$/,""))}function Av(e,t){if(!("$schema"in e)||typeof e.$schema!="string")return"2020-12";const n=e.$schema.replace(/#$/,"");if(Iv.has(n))return"2020-12";if(Lp.has(n))return"2019-09";if(qv.has(n)||Nv.has(n))return"draft-7";throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}const ui=Symbol.for("mcp.sdk.errorBrands");function jp(e,t){const n=new Set;let o=t;for(;typeof o=="function";){const r=o.mcpBrand;Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof r=="string"&&n.add(r),o=Object.getPrototypeOf(o)}n.size!==0&&Object.defineProperty(e,ui,{value:n,enumerable:!1,configurable:!0})}function es(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,ui)){const n=t[ui];if(n&&typeof n.has=="function"&&n.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}let X=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({});var An,K=(An=class extends Error{static[Symbol.hasInstance](t){return es(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return es(this,t)}constructor(t,n,o,r){super(n,r),this.code=t,this.data=o,this.name="SdkError",jp(this,new.target)}},Object.defineProperty(An,"mcpBrand",{value:"mcp.SdkError"}),An);function Ec(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function xv(e,t,n){return e==="elicitation"&&t==="form"&&n.form===void 0&&n.url===void 0}function zv(e){var t;switch(e.method){case"elicitation/create":return((t=e.params)==null?void 0:t.mode)==="url"?{elicitation:{url:{}}}:{elicitation:{form:{}}};case"sampling/createMessage":{const n=e.params;return n!==void 0&&(n.tools!==void 0||n.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case"roots/list":return{roots:{}};default:return}}function Dp(e,t){const n={};for(const[o,r]of Object.entries(e)){if(r===void 0)continue;const s=t===void 0?void 0:t[o];if(s===void 0){n[o]=r;continue}if(Ec(r)&&Ec(s)){const i={};for(const[a,c]of Object.entries(r))c!==void 0&&s[a]===void 0&&!xv(o,a,s)&&(i[a]=c);Object.keys(i).length>0&&(n[o]=i)}}return Object.keys(n).length>0?n:void 0}const Up="2026-07-28",Lv=[Up];function vs(e){return e>=Up}function jv(e){return e.filter(t=>!vs(t))}function zs(e){return e.filter(t=>vs(t))}function Zp(e){var n;const t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(((n=e.content)==null?void 0:n.some(o=>o.type==="text"))??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}const Hp=["task","inputRequests","requestState"];function Fp(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Hp.some(t=>t in e)?e:{...e,content:[]}}function Dv(){const e=Ai(()=>N([l(),$(),q(),Jo(),C(l(),e),y(e)])),t=C(l(),e),n=N([l(),$().int()]),o=l(),r=g({ttl:$().optional()}),s=g({taskId:l()}),i=U({progressToken:n.optional(),"io.modelcontextprotocol/related-task":s.optional()}),a=g({_meta:i.optional()}),c=a.extend({task:r.optional()}),d=g({method:l(),params:a.loose().optional()}),u=g({_meta:i.optional()}),p=g({method:l(),params:u.loose().optional()}),m=U({_meta:i.optional()}),h=N([l(),$().int()]),f=m.strict(),_=u.extend({requestId:h.optional(),reason:l().optional()}),S=p.extend({method:v("notifications/cancelled"),params:_}),b=g({src:l(),mimeType:l().optional(),sizes:y(l()).optional(),theme:B(["light","dark"]).optional()}),R=g({icons:y(b).optional()}),M=g({name:l(),title:l().optional()}),L=M.extend({...M.shape,...R.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),te=gn(g({applyDefaults:q().optional()}),t),oe=Bo($e=>$e&&typeof $e=="object"&&!Array.isArray($e)&&Object.keys($e).length===0?{form:{}}:$e,gn(g({form:te.optional(),url:t.optional()}),t.optional())),Y=U({list:t.optional(),cancel:t.optional(),requests:U({sampling:U({createMessage:t.optional()}).optional(),elicitation:U({create:t.optional()}).optional()}).optional()}),H=U({list:t.optional(),cancel:t.optional(),requests:U({tools:U({call:t.optional()}).optional()}).optional()}),ne=g({experimental:C(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:oe.optional(),roots:g({listChanged:q().optional()}).optional(),tasks:Y.optional(),extensions:C(l(),t).optional()}),Q=a.extend({protocolVersion:l(),capabilities:ne,clientInfo:L}),re=d.extend({method:v("initialize"),params:Q}),we=g({experimental:C(l(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:q().optional()}).optional(),resources:g({subscribe:q().optional(),listChanged:q().optional()}).optional(),tools:g({listChanged:q().optional()}).optional(),tasks:H.optional(),extensions:C(l(),t).optional()}),Me=m.extend({protocolVersion:l(),capabilities:we,serverInfo:L,instructions:l().optional()}),pe=p.extend({method:v("notifications/initialized"),params:u.optional()}),_e=d.extend({method:v("ping"),params:a.optional()}),Ke=g({progress:$(),total:z($()),message:z(l())}),Ae=g({...u.shape,...Ke.shape,progressToken:n}),Ge=p.extend({method:v("notifications/progress"),params:Ae}),ct=a.extend({cursor:o.optional()}),Ue=d.extend({params:ct.optional()}),ke=m.extend({nextCursor:o.optional()}),_t=g({uri:l(),mimeType:z(l()),_meta:C(l(),j()).optional()}),vt=_t.extend({text:l()}),lt=l().refine($e=>{try{return atob($e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Re=_t.extend({blob:lt}),Ce=B(["user","assistant"]),Oe=g({audience:y(Ce).optional(),priority:$().min(0).max(1).optional(),lastModified:is({offset:!0}).optional()}),nt=g({...M.shape,...R.shape,uri:l(),description:z(l()),mimeType:z(l()),size:z($()),annotations:Oe.optional(),_meta:z(U({}))}),Bt=g({...M.shape,...R.shape,uriTemplate:l(),description:z(l()),mimeType:z(l()),annotations:Oe.optional(),_meta:z(U({}))}),Ze=Ue.extend({method:v("resources/list")}),He=ke.extend({resources:y(nt)}),xe=Ue.extend({method:v("resources/templates/list")}),Ye=ke.extend({resourceTemplates:y(Bt)}),Xe=a.extend({uri:l()}),ut=Xe,dt=d.extend({method:v("resources/read"),params:ut}),kt=m.extend({contents:y(N([vt,Re]))}),pt=p.extend({method:v("notifications/resources/list_changed"),params:u.optional()}),Wt=Xe,O=d.extend({method:v("resources/subscribe"),params:Wt}),mt=Xe,D=d.extend({method:v("resources/unsubscribe"),params:mt}),A=u.extend({uri:l()}),W=p.extend({method:v("notifications/resources/updated"),params:A}),I=g({name:l(),description:z(l()),required:z(q())}),k=g({...M.shape,...R.shape,description:z(l()),arguments:z(y(I)),_meta:z(U({}))}),J=Ue.extend({method:v("prompts/list")}),F=ke.extend({prompts:y(k)}),he=a.extend({name:l(),arguments:C(l(),l()).optional()}),Kt=d.extend({method:v("prompts/get"),params:he}),ht=g({type:v("text"),text:l(),annotations:Oe.optional(),_meta:C(l(),j()).optional()}),Gt=g({type:v("image"),data:lt,mimeType:l(),annotations:Oe.optional(),_meta:C(l(),j()).optional()}),Yt=g({type:v("audio"),data:lt,mimeType:l(),annotations:Oe.optional(),_meta:C(l(),j()).optional()}),to=g({type:v("tool_use"),name:l(),id:l(),input:C(l(),j()),_meta:C(l(),j()).optional()}),Ct=g({type:v("resource"),resource:N([vt,Re]),annotations:Oe.optional(),_meta:C(l(),j()).optional()}),no=nt.extend({type:v("resource_link")}),Qe=N([ht,Gt,Yt,no,Ct]),_n=g({role:Ce,content:Qe}),vn=m.extend({description:l().optional(),messages:y(_n)}),Xt=p.extend({method:v("notifications/prompts/list_changed"),params:u.optional()}),oo=g({title:l().optional(),readOnlyHint:q().optional(),destructiveHint:q().optional(),idempotentHint:q().optional(),openWorldHint:q().optional()}),bn=g({taskSupport:B(["required","optional","forbidden"]).optional()}),Qt=g({...M.shape,...R.shape,description:l().optional(),inputSchema:g({type:v("object"),properties:C(l(),e).optional(),required:y(l()).optional()}).catchall(j()),outputSchema:g({type:v("object"),properties:C(l(),e).optional(),required:y(l()).optional()}).catchall(j()).optional(),annotations:oo.optional(),execution:bn.optional(),_meta:C(l(),j()).optional()}),wn=Ue.extend({method:v("tools/list")}),Rn=ke.extend({tools:y(Qt)}),Tn=m.extend({content:y(Qe),structuredContent:C(l(),j()).optional(),isError:q().optional()}),Te=c.extend({name:l(),arguments:C(l(),j()).optional()}),ro=d.extend({method:v("tools/call"),params:Te}),sr=p.extend({method:v("notifications/tools/list_changed"),params:u.optional()}),$n=B(["debug","info","notice","warning","error","critical","alert","emergency"]),so=a.extend({level:$n}),io=d.extend({method:v("logging/setLevel"),params:so}),ao=u.extend({level:$n,logger:l().optional(),data:j()}),co=p.extend({method:v("notifications/message"),params:ao}),lo=g({name:l().optional()}),uo=g({hints:y(lo).optional(),costPriority:$().min(0).max(1).optional(),speedPriority:$().min(0).max(1).optional(),intelligencePriority:$().min(0).max(1).optional()}),po=g({mode:B(["auto","required","none"]).optional()}),ir=g({type:v("tool_result"),toolUseId:l().describe("The unique identifier for the corresponding tool call."),content:y(Qe),structuredContent:g({}).loose().optional(),isError:q().optional(),_meta:C(l(),j()).optional()}),mo=Kr("type",[ht,Gt,Yt]),Ot=Kr("type",[ht,Gt,Yt,to,ir]),ho=g({role:Ce,content:N([Ot,y(Ot)]),_meta:C(l(),j()).optional()}),fo=c.extend({messages:y(ho),modelPreferences:uo.optional(),systemPrompt:l().optional(),includeContext:B(["none","thisServer","allServers"]).optional(),temperature:$().optional(),maxTokens:$().int(),stopSequences:y(l()).optional(),metadata:t.optional(),tools:y(Qt).optional(),toolChoice:po.optional()}),go=d.extend({method:v("sampling/createMessage"),params:fo}),So=m.extend({model:l(),stopReason:z(B(["endTurn","stopSequence","maxTokens"]).or(l())),role:Ce,content:mo}),yo=m.extend({model:l(),stopReason:z(B(["endTurn","stopSequence","maxTokens","toolUse"]).or(l())),role:Ce,content:N([Ot,y(Ot)])}),_o=g({type:v("boolean"),title:l().optional(),description:l().optional(),default:q().optional()}),vo=g({type:v("string"),title:l().optional(),description:l().optional(),minLength:$().optional(),maxLength:$().optional(),format:B(["email","uri","date","date-time"]).optional(),default:l().optional()}),bo=g({type:B(["number","integer"]),title:l().optional(),description:l().optional(),minimum:$().optional(),maximum:$().optional(),default:$().optional()}),wo=g({type:v("string"),title:l().optional(),description:l().optional(),enum:y(l()),default:l().optional()}),Ro=g({type:v("string"),title:l().optional(),description:l().optional(),oneOf:y(g({const:l(),title:l()})),default:l().optional()}),To=g({type:v("string"),title:l().optional(),description:l().optional(),enum:y(l()),enumNames:y(l()).optional(),default:l().optional()}),$o=N([wo,Ro]),en=g({type:v("array"),title:l().optional(),description:l().optional(),minItems:$().optional(),maxItems:$().optional(),items:g({type:v("string"),enum:y(l())}),default:y(l()).optional()}),tn=g({type:v("array"),title:l().optional(),description:l().optional(),minItems:$().optional(),maxItems:$().optional(),items:g({anyOf:y(g({const:l(),title:l()}))}),default:y(l()).optional()}),ar=N([en,tn]),cr=N([To,$o,ar]),Fe=N([cr,_o,vo,bo]),Ve=c.extend({mode:v("form").optional(),message:l(),requestedSchema:g({type:v("object"),properties:C(l(),Fe),required:y(l()).optional()}).catchall(j())}),Eo=c.extend({mode:v("url"),message:l(),elicitationId:l(),url:l().url()}),ot=N([Ve,Eo]),lr=d.extend({method:v("elicitation/create"),params:ot}),ur=u.extend({elicitationId:l()}),dr=p.extend({method:v("notifications/elicitation/complete"),params:ur}),pr=m.extend({action:B(["accept","decline","cancel"]),content:Bo($e=>$e===null?void 0:$e,C(l(),N([l(),$(),q(),y(l())])).optional())}),mr=g({type:v("ref/resource"),uri:l()}),hr=g({type:v("ref/prompt"),name:l()}),fr=a.extend({ref:N([hr,mr]),argument:g({name:l(),value:l()}),context:g({arguments:C(l(),l()).optional()}).optional()}),Po=d.extend({method:v("completion/complete"),params:fr}),gr=m.extend({completion:U({values:y(l()).max(100),total:z($().int()),hasMore:z(q())})}),Sr=g({uri:l().startsWith("file://"),name:l().optional(),_meta:C(l(),j()).optional()}),En=d.extend({method:v("roots/list"),params:a.optional()}),ko=m.extend({roots:y(Sr)}),yr=p.extend({method:v("notifications/roots/list_changed"),params:u.optional()}),_r=U({ttl:$().optional(),pollInterval:$().optional()}),Co=B(["working","input_required","completed","failed","cancelled"]),It=g({taskId:l(),status:Co,ttl:N([$(),Jo()]),createdAt:l(),lastUpdatedAt:l(),pollInterval:z($()),statusMessage:z(l())}),ze=m.extend({task:It}),vr=u.merge(It),nn=p.extend({method:v("notifications/tasks/status"),params:vr}),Pn=d.extend({method:v("tasks/get"),params:a.extend({taskId:l()})}),kn=m.merge(It),Cn=d.extend({method:v("tasks/result"),params:a.extend({taskId:l()})}),ws=m.loose(),Ie=Ue.extend({method:v("tasks/list")}),me=ke.extend({tasks:y(It)}),on=d.extend({method:v("tasks/cancel"),params:a.extend({taskId:l()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:o,TaskMetadataSchema:r,RelatedTaskMetadataSchema:s,RequestMetaSchema:i,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:c,RequestSchema:d,NotificationsParamsSchema:u,NotificationSchema:p,ResultSchema:m,RequestIdSchema:h,EmptyResultSchema:f,CancelledNotificationParamsSchema:_,CancelledNotificationSchema:S,IconSchema:b,IconsSchema:R,BaseMetadataSchema:M,ImplementationSchema:L,ClientTasksCapabilitySchema:Y,ServerTasksCapabilitySchema:H,ClientCapabilitiesSchema:ne,InitializeRequestParamsSchema:Q,InitializeRequestSchema:re,ServerCapabilitiesSchema:we,InitializeResultSchema:Me,InitializedNotificationSchema:pe,PingRequestSchema:_e,ProgressSchema:Ke,ProgressNotificationParamsSchema:Ae,ProgressNotificationSchema:Ge,PaginatedRequestParamsSchema:ct,PaginatedRequestSchema:Ue,PaginatedResultSchema:ke,ResourceContentsSchema:_t,TextResourceContentsSchema:vt,BlobResourceContentsSchema:Re,RoleSchema:Ce,AnnotationsSchema:Oe,ResourceSchema:nt,ResourceTemplateSchema:Bt,ListResourcesRequestSchema:Ze,ListResourcesResultSchema:He,ListResourceTemplatesRequestSchema:xe,ListResourceTemplatesResultSchema:Ye,ResourceRequestParamsSchema:Xe,ReadResourceRequestParamsSchema:ut,ReadResourceRequestSchema:dt,ReadResourceResultSchema:kt,ResourceListChangedNotificationSchema:pt,SubscribeRequestParamsSchema:Wt,SubscribeRequestSchema:O,UnsubscribeRequestParamsSchema:mt,UnsubscribeRequestSchema:D,ResourceUpdatedNotificationParamsSchema:A,ResourceUpdatedNotificationSchema:W,PromptArgumentSchema:I,PromptSchema:k,ListPromptsRequestSchema:J,ListPromptsResultSchema:F,GetPromptRequestParamsSchema:he,GetPromptRequestSchema:Kt,TextContentSchema:ht,ImageContentSchema:Gt,AudioContentSchema:Yt,ToolUseContentSchema:to,EmbeddedResourceSchema:Ct,ResourceLinkSchema:no,ContentBlockSchema:Qe,PromptMessageSchema:_n,GetPromptResultSchema:vn,PromptListChangedNotificationSchema:Xt,ToolAnnotationsSchema:oo,ToolExecutionSchema:bn,ToolSchema:Qt,ListToolsRequestSchema:wn,ListToolsResultSchema:Rn,CallToolResultSchema:Tn,CallToolRequestParamsSchema:Te,CallToolRequestSchema:ro,ToolListChangedNotificationSchema:sr,LoggingLevelSchema:$n,SetLevelRequestParamsSchema:so,SetLevelRequestSchema:io,LoggingMessageNotificationParamsSchema:ao,LoggingMessageNotificationSchema:co,ModelHintSchema:lo,ModelPreferencesSchema:uo,ToolChoiceSchema:po,ToolResultContentSchema:ir,SamplingContentSchema:mo,SamplingMessageContentBlockSchema:Ot,SamplingMessageSchema:ho,CreateMessageRequestParamsSchema:fo,CreateMessageRequestSchema:go,CreateMessageResultSchema:So,CreateMessageResultWithToolsSchema:yo,BooleanSchemaSchema:_o,StringSchemaSchema:vo,NumberSchemaSchema:bo,UntitledSingleSelectEnumSchemaSchema:wo,TitledSingleSelectEnumSchemaSchema:Ro,LegacyTitledEnumSchemaSchema:To,SingleSelectEnumSchemaSchema:$o,UntitledMultiSelectEnumSchemaSchema:en,TitledMultiSelectEnumSchemaSchema:tn,MultiSelectEnumSchemaSchema:ar,EnumSchemaSchema:cr,PrimitiveSchemaDefinitionSchema:Fe,ElicitRequestFormParamsSchema:Ve,ElicitRequestURLParamsSchema:Eo,ElicitRequestParamsSchema:ot,ElicitRequestSchema:lr,ElicitationCompleteNotificationParamsSchema:ur,ElicitationCompleteNotificationSchema:dr,ElicitResultSchema:pr,ResourceTemplateReferenceSchema:mr,PromptReferenceSchema:hr,CompleteRequestParamsSchema:fr,CompleteRequestSchema:Po,CompleteResultSchema:gr,RootSchema:Sr,ListRootsRequestSchema:En,ListRootsResultSchema:ko,RootsListChangedNotificationSchema:yr,TaskCreationParamsSchema:_r,TaskStatusSchema:Co,TaskSchema:It,CreateTaskResultSchema:ze,TaskStatusNotificationParamsSchema:vr,TaskStatusNotificationSchema:nn,GetTaskRequestSchema:Pn,GetTaskResultSchema:kn,GetTaskPayloadRequestSchema:Cn,GetTaskPayloadResultSchema:ws,ListTasksRequestSchema:Ie,ListTasksResultSchema:me,CancelTaskRequestSchema:on,CancelTaskResultSchema:m.merge(It),ClientRequestSchema:N([_e,re,Po,io,Kt,J,Ze,xe,dt,O,D,ro,wn,Pn,Cn,Ie,on]),ClientNotificationSchema:N([S,Ge,pe,yr,nn]),ClientResultSchema:N([f,So,yo,pr,ko,kn,me,ze]),ServerRequestSchema:N([_e,go,lr,En,Pn,Cn,Ie,on]),ServerNotificationSchema:N([S,Ge,co,W,pt,sr,Xt,nn,dr]),ServerResultSchema:N([f,Me,gr,vn,F,He,Ye,kt,Tn,Rn,kn,me,ze]),CallToolResultWireSchema:j().superRefine(($e,ym)=>{if(!(typeof $e!="object"||$e===null||Array.isArray($e)||$e.content!==void 0)){for(const Ta of Hp)if(Ta in $e){ym.addIssue({code:"custom",message:`content is required when the body carries '${Ta}' — another result family cannot default into an empty tools/call success`});return}}}).transform(Fp).pipe(Tn)}}let Uv;function Vp(){return Uv??(Uv=Dv())}function Jp(e){return e.type!=="object"}const Zv=new Set(["const","enum","default","examples"]),Hv=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function Pc(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}function Fv(e){const t=typeof e.$schema=="string"?e.$schema:void 0;if(Pc(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};const n=Mv(e.$schema)&&e.$recursiveAnchor!==!0,o=(r,s)=>{if(Array.isArray(r))return r.map(c=>o(c,!1));if(r===null||typeof r!="object"||!s&&Pc(r.$id))return r;const i={};let a=!1;for(const[c,d]of Object.entries(r))s?i[c]=o(d,!1):(c==="$ref"||c==="$dynamicRef")&&typeof d=="string"?i[c]=d==="#"?"#/properties/result":d.startsWith("#/")?`#/properties/result${d.slice(1)}`:d:c==="$recursiveRef"&&d==="#"&&n?a=!0:Zv.has(c)?i[c]=d:Hv.has(c)?i[c]=o(d,!0):i[c]=o(d,!1);return a&&("$ref"in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:"#/properties/result"}]:i.$ref="#/properties/result"),i};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}const Vv={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Jv={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},Bv={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};let kr;function Sa(){if(kr)return kr;const e=Vp();return kr={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},kr}function Bp(e){return Object.prototype.hasOwnProperty.call(Vv,e)}function Wp(e){return Object.prototype.hasOwnProperty.call(Jv,e)}function Wv(e){return Object.prototype.hasOwnProperty.call(Bv,e)}function Kv(e){return Wv(e)?Sa().resultSchemas[e]:void 0}function Gv(e){return Bp(e)?Sa().requestSchemas[e]:void 0}function Yv(e){return Wp(e)?Sa().notificationSchemas[e]:void 0}function di(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Cr(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};const n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:"invalid",message:String(n.error)}}const kc={ok:!1,reason:"not-in-era"};function Cc(e){return di(e)&&di(e.outputSchema)&&Jp(e.outputSchema)}const ya={era:"2025-11-25",hasRequestMethod:Bp,hasNotificationMethod:Wp,validateRequest:(e,t)=>Cr(Gv(e),t),validateResult:(e,t)=>Cr(Kv(e),t),validateNotification:(e,t)=>Cr(Yv(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>kc,validateInputResponse:()=>kc,samplingResultVariant:((e,t)=>{const n=Vp();return Cr(e?n.CreateMessageResultWithToolsSchema:n.CreateMessageResultSchema,t)}),outboundEnvelope:e=>{},validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){const n=Zp(e),o=n.structuredContent;if(o===void 0)return n;const r=typeof o!="object"||o===null||Array.isArray(o),s=t!==void 0&&Jp(t);return!r&&!s?n:{...n,structuredContent:{result:o}}},decodeResult(e,t){if(di(t)&&"resultType"in t){const n={...t};return delete n.resultType,{kind:"complete",result:n}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;const n=t.tools;return!Array.isArray(n)||!n.some(o=>Cc(o))?t:{...t,tools:n.map(o=>Cc(o)?{...o,outputSchema:Fv(o.outputSchema)}:o)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>{}};function Xv(){const e=Ai(()=>N([l(),$(),q(),Jo(),C(l(),e),y(e)])),t=C(l(),e),n=N([l(),$().int()]),o=l(),r=N([l(),$().int()]),s=B(["user","assistant"]),i=B(["debug","info","notice","warning","error","critical","alert","emergency"]),a=l().refine(me=>{try{return atob(me),!0}catch{return!1}},{message:"Invalid Base64 string"}),c=g({ttl:$().optional()}),d=g({taskId:l()}),u=U({progressToken:n.optional(),"io.modelcontextprotocol/related-task":d.optional()}),p=g({_meta:u.optional()}),m=p.extend({task:c.optional()}),h=g({_meta:u.optional()}),f=g({method:l(),params:h.loose().optional()}),_=g({src:l(),mimeType:l().optional(),sizes:y(l()).optional(),theme:B(["light","dark"]).optional()}),S=g({icons:y(_).optional()}),b=g({name:l(),title:l().optional()}),R=b.extend({...b.shape,...S.shape,version:l(),websiteUrl:l().optional(),description:l().optional()}),M=gn(g({applyDefaults:q().optional()}),t),L=Bo(me=>me&&typeof me=="object"&&!Array.isArray(me)&&Object.keys(me).length===0?{form:{}}:me,gn(g({form:M.optional(),url:t.optional()}),t.optional())),te=U({list:t.optional(),cancel:t.optional(),requests:U({sampling:U({createMessage:t.optional()}).optional(),elicitation:U({create:t.optional()}).optional()}).optional()}),oe=U({list:t.optional(),cancel:t.optional(),requests:U({tools:U({call:t.optional()}).optional()}).optional()}),Y=g({experimental:C(l(),t).optional(),sampling:g({context:t.optional(),tools:t.optional()}).optional(),elicitation:L.optional(),roots:g({listChanged:q().optional()}).optional(),tasks:te.optional(),extensions:C(l(),t).optional()}),H=g({experimental:C(l(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:g({listChanged:q().optional()}).optional(),resources:g({subscribe:q().optional(),listChanged:q().optional()}).optional(),tools:g({listChanged:q().optional()}).optional(),tasks:oe.optional(),extensions:C(l(),t).optional()}),ne=g({progress:$(),total:z($()),message:z(l())}),Q=g({...h.shape,...ne.shape,progressToken:n}),re=f.extend({method:v("notifications/progress"),params:Q}),we=h.extend({level:i,logger:l().optional(),data:j()}),Me=f.extend({method:v("notifications/message"),params:we}),pe=g({uri:l(),mimeType:z(l()),_meta:C(l(),j()).optional()}),_e=pe.extend({text:l()}),Ke=pe.extend({blob:a}),Ae=g({audience:y(s).optional(),priority:$().min(0).max(1).optional(),lastModified:is({offset:!0}).optional()}),Ge=g({...b.shape,...S.shape,uri:l(),description:z(l()),mimeType:z(l()),size:z($()),annotations:Ae.optional(),_meta:z(U({}))}),ct=g({...b.shape,...S.shape,uriTemplate:l(),description:z(l()),mimeType:z(l()),annotations:Ae.optional(),_meta:z(U({}))}),Ue=f.extend({method:v("notifications/resources/list_changed"),params:h.optional()}),ke=h.extend({uri:l()}),_t=f.extend({method:v("notifications/resources/updated"),params:ke}),vt=g({name:l(),description:z(l()),required:z(q())}),lt=g({...b.shape,...S.shape,description:z(l()),arguments:z(y(vt)),_meta:z(U({}))}),Re=f.extend({method:v("notifications/prompts/list_changed"),params:h.optional()}),Ce=g({type:v("text"),text:l(),annotations:Ae.optional(),_meta:C(l(),j()).optional()}),Oe=g({type:v("image"),data:a,mimeType:l(),annotations:Ae.optional(),_meta:C(l(),j()).optional()}),nt=g({type:v("audio"),data:a,mimeType:l(),annotations:Ae.optional(),_meta:C(l(),j()).optional()}),Bt=g({type:v("tool_use"),name:l(),id:l(),input:C(l(),j()),_meta:C(l(),j()).optional()}),Ze=g({type:v("resource"),resource:N([_e,Ke]),annotations:Ae.optional(),_meta:C(l(),j()).optional()}),He=Ge.extend({type:v("resource_link")}),xe=N([Ce,Oe,nt,He,Ze]),Ye=g({role:s,content:xe}),Xe=g({title:l().optional(),readOnlyHint:q().optional(),destructiveHint:q().optional(),idempotentHint:q().optional(),openWorldHint:q().optional()}),ut=f.extend({method:v("notifications/tools/list_changed"),params:h.optional()}),dt=g({name:l().optional()}),kt=g({hints:y(dt).optional(),costPriority:$().min(0).max(1).optional(),speedPriority:$().min(0).max(1).optional(),intelligencePriority:$().min(0).max(1).optional()}),pt=g({mode:B(["auto","required","none"]).optional()}),Wt=g({type:v("boolean"),title:l().optional(),description:l().optional(),default:q().optional()}),O=g({type:v("string"),title:l().optional(),description:l().optional(),minLength:$().optional(),maxLength:$().optional(),format:B(["email","uri","date","date-time"]).optional(),default:l().optional()}),mt=g({type:B(["number","integer"]),title:l().optional(),description:l().optional(),minimum:$().optional(),maximum:$().optional(),default:$().optional()}),D=g({type:v("string"),title:l().optional(),description:l().optional(),enum:y(l()),default:l().optional()}),A=g({type:v("string"),title:l().optional(),description:l().optional(),oneOf:y(g({const:l(),title:l()})),default:l().optional()}),W=g({type:v("string"),title:l().optional(),description:l().optional(),enum:y(l()),enumNames:y(l()).optional(),default:l().optional()}),I=N([D,A]),k=g({type:v("array"),title:l().optional(),description:l().optional(),minItems:$().optional(),maxItems:$().optional(),items:g({type:v("string"),enum:y(l())}),default:y(l()).optional()}),J=g({type:v("array"),title:l().optional(),description:l().optional(),minItems:$().optional(),maxItems:$().optional(),items:g({anyOf:y(g({const:l(),title:l()}))}),default:y(l()).optional()}),F=N([k,J]),he=N([W,I,F]),Kt=N([he,Wt,O,mt]),ht=m.extend({mode:v("form").optional(),message:l(),requestedSchema:g({type:v("object"),properties:C(l(),Kt),required:y(l()).optional()}).catchall(j())}),Gt=g({type:v("ref/resource"),uri:l()}),Yt=g({type:v("ref/prompt"),name:l()}),to=g({uri:l().startsWith("file://"),name:l().optional(),_meta:C(l(),j()).optional()}),Ct=Y.shape,no=g({experimental:Ct.experimental,sampling:Ct.sampling,elicitation:Ct.elicitation,roots:Ct.roots,extensions:Ct.extensions}),Qe=H.shape,_n=g({experimental:Qe.experimental,logging:Qe.logging,completions:Qe.completions,prompts:Qe.prompts,resources:Qe.resources,tools:Qe.tools,extensions:Qe.extensions}),vn=U({progressToken:n.optional(),[as]:l(),[xi]:R.optional(),[nr]:no,[cs]:i.optional()}),Xt=g({...b.shape,...S.shape,description:l().optional(),inputSchema:U({$schema:l().optional(),type:v("object")}),outputSchema:U({$schema:l().optional()}).optional(),annotations:Xe.optional(),_meta:C(l(),j()).optional()}),oo=g({type:v("tool_result"),toolUseId:l(),content:y(xe),structuredContent:j().optional(),isError:q().optional(),_meta:C(l(),j()).optional()}),bn=N([Ce,Oe,nt,Bt,oo]),Qt=g({role:s,content:N([bn,y(bn)]),_meta:C(l(),j()).optional()}),wn=l(),Rn=U({[jo]:R.optional().catch(void 0)}),Tn=Rn.optional();function Te(me){return U({_meta:Tn,resultType:wn.default("complete"),...me})}const ro=Te({}),sr=Te({nextCursor:o.optional()}),$n=Te({content:y(xe),structuredContent:j().optional(),isError:q().optional()}),so=Te({ttlMs:$().int().min(0),cacheScope:B(["public","private"]),tools:y(Xt),nextCursor:o.optional()}),io=Te({ttlMs:$().int().min(0),cacheScope:B(["public","private"]),prompts:y(lt),nextCursor:o.optional()}),ao=Te({description:l().optional(),messages:y(Ye)}),co=Te({ttlMs:$().int().min(0),cacheScope:B(["public","private"]),resources:y(Ge),nextCursor:o.optional()}),lo=Te({ttlMs:$().int().min(0),cacheScope:B(["public","private"]),resourceTemplates:y(ct),nextCursor:o.optional()}),uo=Te({ttlMs:$().int().min(0),cacheScope:B(["public","private"]),contents:y(N([_e,Ke]))}),po=Te({completion:g({values:y(l()).max(100),total:$().int().optional(),hasMore:q().optional()}).loose()}),ir=Te({ttlMs:$().int().min(0),cacheScope:B(["public","private"])}),mo=Te({ttlMs:$().int().min(0).catch(0),cacheScope:B(["public","private"]).catch("private"),supportedVersions:y(l()),capabilities:_n,instructions:l().optional()}),Ot=g({messages:y(Qt),modelPreferences:kt.optional(),systemPrompt:l().optional(),includeContext:B(["none","thisServer","allServers"]).optional(),temperature:$().optional(),maxTokens:$().int(),stopSequences:y(l()).optional(),metadata:t.optional(),tools:y(Xt).optional(),toolChoice:pt.optional()}),ho=g({method:v("sampling/createMessage"),params:Ot}),fo=g({method:v("roots/list"),params:g({_meta:C(l(),j()).optional()}).optional()}),go=g({...Qt.shape,model:l(),stopReason:l().optional()}),So=g({roots:y(to)}),yo=g({action:B(["accept","decline","cancel"]),content:C(l(),N([l(),$(),q(),y(l())])).optional()}),_o=g({mode:v("url"),message:l(),url:l().url()}),vo=N([ht,_o]),bo=g({method:v("elicitation/create"),params:vo}),wo=N([ho,fo,bo]),Ro=N([go,So,yo]),To=C(l(),wo),$o=C(l(),Ro),en=Te({inputRequests:To.optional(),requestState:l().optional()}),tn={inputResponses:$o.optional(),requestState:l().optional()},ar=g({_meta:vn,...tn}),cr=U({progressToken:n.optional()});function Fe(me,on){return g({method:v(me),params:g({_meta:vn,...on})})}function Ve(me,on){return g({method:v(me),params:g({_meta:cr.optional(),...on}).optional()})}const Eo={name:l(),arguments:C(l(),j()).optional(),...tn},ot={cursor:o.optional()},lr=Fe("tools/call",Eo),ur=Fe("tools/list",ot),dr=Fe("prompts/list",ot),pr=Fe("prompts/get",{name:l(),arguments:C(l(),l()).optional(),...tn}),mr=Fe("resources/list",ot),hr=Fe("resources/templates/list",ot),fr=Fe("resources/read",{uri:l(),...tn}),Po={ref:N([Yt,Gt]),argument:g({name:l(),value:l()}),context:g({arguments:C(l(),l()).optional()}).optional()},gr=Fe("completion/complete",Po),Sr=Fe("server/discover",{}),En=g({toolsListChanged:q().optional(),promptsListChanged:q().optional(),resourcesListChanged:q().optional(),resourceSubscriptions:y(l()).optional()}),ko={notifications:En},yr=Fe("subscriptions/listen",ko),_r=Rn.extend({"io.modelcontextprotocol/subscriptionId":r}),Co=U({_meta:_r,resultType:wn.default("complete")}),It={"tools/call":Ve("tools/call",Eo),"tools/list":Ve("tools/list",ot),"prompts/get":Ve("prompts/get",{name:l(),arguments:C(l(),l()).optional()}),"prompts/list":Ve("prompts/list",ot),"resources/list":Ve("resources/list",ot),"resources/templates/list":Ve("resources/templates/list",ot),"resources/read":Ve("resources/read",{uri:l()}),"completion/complete":Ve("completion/complete",Po),"server/discover":Ve("server/discover",{}),"subscriptions/listen":Ve("subscriptions/listen",ko)};function ze(me){return U({_meta:Tn,...me})}const vr={"tools/call":ze({content:y(xe),structuredContent:j().optional(),isError:q().optional()}),"tools/list":ze({ttlMs:$().int().min(0),cacheScope:B(["public","private"]),tools:y(Xt),nextCursor:o.optional()}),"prompts/get":ze({description:l().optional(),messages:y(Ye)}),"prompts/list":ze({ttlMs:$().int().min(0),cacheScope:B(["public","private"]),prompts:y(lt),nextCursor:o.optional()}),"resources/list":ze({ttlMs:$().int().min(0),cacheScope:B(["public","private"]),resources:y(Ge),nextCursor:o.optional()}),"resources/templates/list":ze({ttlMs:$().int().min(0),cacheScope:B(["public","private"]),resourceTemplates:y(ct),nextCursor:o.optional()}),"resources/read":ze({ttlMs:$().int().min(0),cacheScope:B(["public","private"]),contents:y(N([_e,Ke]))}),"completion/complete":ze({completion:g({values:y(l()).max(100),total:$().int().optional(),hasMore:q().optional()}).loose()}),"server/discover":ze({ttlMs:$().int().min(0).catch(0),cacheScope:B(["public","private"]).catch("private"),supportedVersions:y(l()),capabilities:_n,instructions:l().optional()}),"subscriptions/listen":ze({})},nn=U({"io.modelcontextprotocol/subscriptionId":r.optional()}),Pn=g({method:v("notifications/subscriptions/acknowledged"),params:g({_meta:nn.optional(),notifications:En})}),kn=g({_meta:nn.optional(),requestId:r,reason:l().optional()}),Cn=g({method:v("notifications/cancelled"),params:kn}),ws={"notifications/cancelled":Cn,"notifications/progress":re,"notifications/message":Me,"notifications/resources/updated":_t,"notifications/resources/list_changed":Ue,"notifications/tools/list_changed":ut,"notifications/prompts/list_changed":Re,"notifications/subscriptions/acknowledged":Pn},Ie=me=>g({jsonrpc:v("2.0"),id:N([l(),$().int()]),result:me}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:o,RequestIdSchema:r,RoleSchema:s,LoggingLevelSchema:i,TaskMetadataSchema:c,RelatedTaskMetadataSchema:d,RequestMetaSchema:u,BaseRequestParamsSchema:p,TaskAugmentedRequestParamsSchema:m,NotificationsParamsSchema:h,NotificationSchema:f,IconSchema:_,IconsSchema:S,BaseMetadataSchema:b,ImplementationSchema:R,ClientTasksCapabilitySchema:te,ServerTasksCapabilitySchema:oe,ClientCapabilitiesSchema:Y,ServerCapabilitiesSchema:H,ProgressSchema:ne,ProgressNotificationParamsSchema:Q,ProgressNotificationSchema:re,LoggingMessageNotificationParamsSchema:we,LoggingMessageNotificationSchema:Me,ResourceContentsSchema:pe,TextResourceContentsSchema:_e,BlobResourceContentsSchema:Ke,AnnotationsSchema:Ae,ResourceSchema:Ge,ResourceTemplateSchema:ct,ResourceListChangedNotificationSchema:Ue,ResourceUpdatedNotificationParamsSchema:ke,ResourceUpdatedNotificationSchema:_t,PromptArgumentSchema:vt,PromptSchema:lt,PromptListChangedNotificationSchema:Re,TextContentSchema:Ce,ImageContentSchema:Oe,AudioContentSchema:nt,ToolUseContentSchema:Bt,EmbeddedResourceSchema:Ze,ResourceLinkSchema:He,ContentBlockSchema:xe,PromptMessageSchema:Ye,ToolAnnotationsSchema:Xe,ToolListChangedNotificationSchema:ut,ModelHintSchema:dt,ModelPreferencesSchema:kt,ToolChoiceSchema:pt,BooleanSchemaSchema:Wt,StringSchemaSchema:O,NumberSchemaSchema:mt,UntitledSingleSelectEnumSchemaSchema:D,TitledSingleSelectEnumSchemaSchema:A,LegacyTitledEnumSchemaSchema:W,SingleSelectEnumSchemaSchema:I,UntitledMultiSelectEnumSchemaSchema:k,TitledMultiSelectEnumSchemaSchema:J,MultiSelectEnumSchemaSchema:F,EnumSchemaSchema:he,PrimitiveSchemaDefinitionSchema:Kt,ElicitRequestFormParamsSchema:ht,ResourceTemplateReferenceSchema:Gt,PromptReferenceSchema:Yt,RootSchema:to,ClientCapabilities2026Schema:no,ServerCapabilities2026Schema:_n,RequestMetaEnvelopeSchema:vn,ToolSchema:Xt,ToolResultContentSchema:oo,SamplingMessageContentBlockSchema:bn,SamplingMessageSchema:Qt,ResultTypeSchema:wn,ResultMetaSchema:Rn,ResultSchema:ro,PaginatedResultSchema:sr,CallToolResultSchema:$n,ListToolsResultSchema:so,ListPromptsResultSchema:io,GetPromptResultSchema:ao,ListResourcesResultSchema:co,ListResourceTemplatesResultSchema:lo,ReadResourceResultSchema:uo,CompleteResultSchema:po,CacheableResultSchema:ir,DiscoverResultSchema:mo,CreateMessageRequestParamsSchema:Ot,CreateMessageRequestSchema:ho,ListRootsRequestSchema:fo,CreateMessageResultSchema:go,ListRootsResultSchema:So,ElicitResultSchema:yo,ElicitRequestURLParamsSchema:_o,ElicitRequestParamsSchema:vo,ElicitRequestSchema:bo,InputRequestSchema:wo,InputResponseSchema:Ro,InputRequestsSchema:To,InputResponsesSchema:$o,InputRequiredResultSchema:en,InputResponseRequestParamsSchema:ar,CallToolRequestSchema:lr,ListToolsRequestSchema:ur,ListPromptsRequestSchema:dr,GetPromptRequestSchema:pr,ListResourcesRequestSchema:mr,ListResourceTemplatesRequestSchema:hr,ReadResourceRequestSchema:fr,CompleteRequestSchema:gr,DiscoverRequestSchema:Sr,SubscriptionFilterSchema:En,SubscriptionsListenRequestSchema:yr,SubscriptionsListenResultMetaSchema:_r,SubscriptionsListenResultSchema:Co,dispatchRequestSchemas:It,dispatchResultSchemas:vr,NotificationMetaSchema:nn,SubscriptionsAcknowledgedNotificationSchema:Pn,CancelledNotificationParamsSchema:kn,CancelledNotificationSchema:Cn,notificationSchemas2026:ws,JSONRPCResultResponseSchema:Ie(ro),CallToolResultResponseSchema:Ie(N([$n,en])),ListToolsResultResponseSchema:Ie(so),ListPromptsResultResponseSchema:Ie(io),GetPromptResultResponseSchema:Ie(N([ao,en])),ListResourcesResultResponseSchema:Ie(co),ListResourceTemplatesResultResponseSchema:Ie(lo),ReadResourceResultResponseSchema:Ie(N([uo,en])),CompleteResultResponseSchema:Ie(po),DiscoverResultResponseSchema:Ie(mo),SubscriptionsListenResultResponseSchema:Ie(Co)}}let Qv;function Ht(){return Qv??(Qv=Xv())}const eb=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function tb(e){return eb.includes(e)}const Nn=Symbol("modelcontextprotocol.resultCacheHintFallback");function pi(e,t){if(t===void 0)return e;const n=e[Nn];if(n===void 0)return{...e,[Nn]:t};const o={},r=n.ttlMs??t.ttlMs;r!==void 0&&(o.ttlMs=r);const s=n.cacheScope??t.cacheScope;return s!==void 0&&(o.cacheScope=s),{...e,[Nn]:o}}function nb(e){return e[Nn]}function _a(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function va(e){return e==="public"||e==="private"}function Kp(e,t){if(e.ttlMs!==void 0&&!_a(e.ttlMs))throw new RangeError(`Invalid cache hint for ${t}: ttlMs must be a non-negative safe integer (got ${String(e.ttlMs)})`);if(e.cacheScope!==void 0&&!va(e.cacheScope))throw new RangeError(`Invalid cache hint for ${t}: cacheScope must be 'public' or 'private' (got ${String(e.cacheScope)})`)}let P=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({});var hn,Z=(hn=class extends Error{static[Symbol.hasInstance](t){return es(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return es(this,t)}constructor(t,n,o){super(n),this.code=t,this.data=o,this.name="ProtocolError",jp(this,new.target)}static fromError(t,n,o){if(t===P.UrlElicitationRequired&&o){const r=o;if(r.elicitations)return new ob(r.elicitations,n)}if(t===P.UnsupportedProtocolVersion&&o){const r=o;if(Array.isArray(r.supported)&&typeof r.requested=="string")return new rb({supported:r.supported,requested:r.requested},n)}if(t===P.InvalidParams||t===P.ResourceNotFound){const r=o;if(typeof(r==null?void 0:r.uri)=="string"&&(t===P.ResourceNotFound||Object.keys(r).length===1))return new Gp(r.uri,n)}if(t===P.MissingRequiredClientCapability&&o){const r=o;if(r.requiredCapabilities!==null&&typeof r.requiredCapabilities=="object"&&!Array.isArray(r.requiredCapabilities))return new Yp({requiredCapabilities:r.requiredCapabilities},n)}return new hn(t,n,o)}},Object.defineProperty(hn,"mcpBrand",{value:"mcp.ProtocolError"}),hn),xn,Gp=(xn=class extends Z{constructor(t,n=`Resource not found: ${t}`){super(P.InvalidParams,n,{uri:t})}get uri(){return this.data.uri}},Object.defineProperty(xn,"mcpBrand",{value:"mcp.ResourceNotFoundError"}),xn),zn,ob=(zn=class extends Z{constructor(t,n=`URL elicitation${t.length>1?"s":""} required`){super(P.UrlElicitationRequired,n,{elicitations:t})}get elicitations(){var t;return((t=this.data)==null?void 0:t.elicitations)??[]}},Object.defineProperty(zn,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"}),zn),Ln,rb=(Ln=class extends Z{constructor(t,n=`Unsupported protocol version: ${t.requested}`){super(P.UnsupportedProtocolVersion,n,t)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Object.defineProperty(Ln,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"}),Ln),jn,Yp=(jn=class extends Z{constructor(t,n=`Missing required client capabilities: ${Object.keys(t.requiredCapabilities).join(", ")}`){super(P.MissingRequiredClientCapability,n,t)}get requiredCapabilities(){return this.data.requiredCapabilities}},Object.defineProperty(jn,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"}),jn);const sb=0,ib="private",ab=["tools/call","prompts/get","resources/read"];function cb(e,t){const n=t.resultType;if(n===void 0)return{...t,resultType:"complete"};if(n==="complete"||ab.includes(e))return t;throw new Z(P.InternalError,`Handler for ${e} returned resultType '${String(n)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function lb(e,t){const n=nb(t);if(t.resultType!=="complete"||!tb(e))return n===void 0?t:hb(t);const o=t,r=_a(o.ttlMs)?o.ttlMs:pb(n),s=va(o.cacheScope)?o.cacheScope:mb(n),i={...o,ttlMs:r,cacheScope:s};return delete i[Nn],i}function ub(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function db(e,t){if(t===void 0)return e;const n=e._meta;return n===void 0?{...e,_meta:{[jo]:t}}:!ub(n)||n[jo]!==void 0?e:{...e,_meta:{...n,[jo]:t}}}function pb(e){return e!==void 0&&_a(e.ttlMs)?e.ttlMs:sb}function mb(e){return e!==void 0&&va(e.cacheScope)?e.cacheScope:ib}function hb(e){const t={...e};return delete t[Nn],t}const fb=["elicitation/create","sampling/createMessage","roots/list"];let Or;function Xp(){if(Or)return Or;const e=Ht();return Or={request:{"elicitation/create":g({method:v("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":g({method:v("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":g({method:v("roots/list"),params:U({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Or}function Qp(e){return fb.includes(e)}function Ls(e){return Qp(e)?Xp().request[e]:void 0}function gb(e){return Qp(e)?Xp().response[e]:void 0}const em={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},Sb={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function tm(e){return Object.prototype.hasOwnProperty.call(em,e)}function nm(e){return Object.prototype.hasOwnProperty.call(Sb,e)}function yb(e){return Object.prototype.hasOwnProperty.call(em,e)}function _b(e){return tm(e)?Ht().dispatchRequestSchemas[e]:void 0}function vb(e){return yb(e)?Ht().dispatchResultSchemas[e]:void 0}function bb(e){return nm(e)?Ht().notificationSchemas2026[e]:void 0}function Do(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Io(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};const n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:"invalid",message:String(n.error)}}const wb={ok:!1,reason:"not-in-era"},Rb=[as,nr];function Tb(e,t){let n=t,o=!1;const r=()=>(o||(n={...n},o=!0),n),s=t.tools;e==="tools/list"&&Array.isArray(s)&&s.some(a=>Do(a)&&"execution"in a)&&(r().tools=s.map(a=>{if(!Do(a)||!("execution"in a))return a;const c={...a};return delete c.execution,c}));const i=t.capabilities;if(Do(i)&&"tasks"in i){const a={...i};delete a.tasks,r().capabilities=a}return n}const ba={era:"2026-07-28",hasRequestMethod:tm,hasNotificationMethod:nm,hasInputRequestMethod:e=>Ls(e)!==void 0,validateRequest:(e,t)=>Io(_b(e),t),validateResult:(e,t)=>Io(vb(e),t),validateNotification:(e,t)=>Io(bb(e),t),validateInputRequest:(e,t)=>Io(Ls(e),t),validateInputResponse:(e,t)=>Io(gb(e),t),samplingResultVariant:()=>wb,outboundEnvelope(e){return{[as]:e.protocolVersion,[xi]:e.clientInfo,[nr]:e.clientCapabilities,...e.logLevel!==void 0&&{[cs]:e.logLevel}}},validateEnvelopeMeta(e){const t=[];for(const o of Rb)o in e||t.push({key:o,problem:"missing"});const n=Ht().RequestMetaEnvelopeSchema.safeParse(e);if(!n.success)for(const o of n.error.issues){const r=o.path.map(String),s=r.length>0?r.join("."):"_meta";r.length===1&&t.some(i=>i.key===s&&i.problem==="missing")||t.push({key:s,problem:o.message})}return t},projectCallToolResult:e=>Zp(e),inputRequestSchema:Ls,decodeResult(e,t){if(!Do(t))return{kind:"invalid",error:new K(X.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};const n=t.resultType;if(n===void 0)return{kind:"invalid",error:new K(X.InvalidResult,`Invalid result for ${e}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof n!="string")return{kind:"invalid",error:new K(X.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:n})};if(n==="input_required"){const i=t.inputRequests,a=Do(i)?i:{},c=t.requestState,d=t._meta===void 0?void 0:Ht().ResultMetaSchema.safeParse(t._meta),u=d!=null&&d.success?d.data:void 0;return Object.keys(a).length===0&&typeof c!="string"?{kind:"invalid",error:new K(X.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:a,...typeof c=="string"&&{requestState:c},...u!==void 0&&{_meta:u}}}if(n!=="complete")return{kind:"invalid",error:new K(X.UnsupportedResultType,`Unsupported result type '${n}' for ${e}`,{resultType:n,method:e})};const o=$b(),r=Object.hasOwn(o,e)?o[e]:void 0;if(r!==void 0){const i=r.safeParse(t);if(!i.success)return{kind:"invalid",error:new K(X.InvalidResult,`Invalid result for ${e}: ${i.error}`,{method:e})}}const s={...t};return delete s.resultType,{kind:"complete",result:s}},encodeResult(e,t,n){return db(lb(e,cb(e,Tb(e,t))),n)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";const t=Ht().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(n=>n.message).join("; ")}`}};let Ir;function $b(){if(Ir)return Ir;const e=Ht();return Ir={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},Ir}const om="2026-07-28";function Xo(e){return e!==void 0&&vs(e)?ba:ya}function Oc(e){return e.revision!==void 0?Xo(e.revision).era:e.era==="modern"?ba.era:ya.era}function js(e){return rm.some(t=>t.hasRequestMethod(e))}function Ds(e){return rm.some(t=>t.hasNotificationMethod(e))}function Ic(e){return e==="tasks/get"||e==="tasks/cancel"}const rm=[ya,ba];var Eb=kv({AnnotationsSchema:()=>yn,AudioContentSchema:()=>gs,BaseMetadataSchema:()=>Sn,BaseRequestParamsSchema:()=>Pe,BlobResourceContentsSchema:()=>Xi,BooleanSchemaSchema:()=>oa,CallToolRequestParamsSchema:()=>kd,CallToolRequestSchema:()=>Cd,CallToolResultSchema:()=>na,CancelTaskRequestSchema:()=>p_,CancelTaskResultSchema:()=>m_,CancelledNotificationParamsSchema:()=>Iu,CancelledNotificationSchema:()=>Vi,ClientCapabilitiesSchema:()=>Au,ClientNotificationSchema:()=>f_,ClientRequestSchema:()=>h_,ClientResultSchema:()=>g_,ClientTasksCapabilitySchema:()=>Nu,CompatibilityCallToolResultSchema:()=>t_,CompleteRequestParamsSchema:()=>np,CompleteRequestSchema:()=>op,CompleteResultSchema:()=>rp,ContentBlockSchema:()=>Ss,CreateMessageRequestParamsSchema:()=>Ud,CreateMessageRequestSchema:()=>Zd,CreateMessageResultSchema:()=>Hd,CreateMessageResultWithToolsSchema:()=>Fd,CreateTaskResultSchema:()=>r_,CursorSchema:()=>Li,DiscoverRequestSchema:()=>Du,DiscoverResultSchema:()=>Uu,ElicitRequestFormParamsSchema:()=>_s,ElicitRequestParamsSchema:()=>Kd,ElicitRequestSchema:()=>Gd,ElicitRequestURLParamsSchema:()=>Wd,ElicitResultSchema:()=>Qd,ElicitationCompleteNotificationParamsSchema:()=>Yd,ElicitationCompleteNotificationSchema:()=>Xd,EmbeddedResourceSchema:()=>_d,EmptyResultSchema:()=>Fi,EnumSchemaSchema:()=>Bd,GetPromptRequestParamsSchema:()=>gd,GetPromptRequestSchema:()=>Sd,GetPromptResultSchema:()=>wd,GetTaskPayloadRequestSchema:()=>c_,GetTaskPayloadResultSchema:()=>l_,GetTaskRequestSchema:()=>i_,GetTaskResultSchema:()=>a_,IconSchema:()=>qu,IconsSchema:()=>Gn,ImageContentSchema:()=>fs,ImplementationSchema:()=>ps,InitializeRequestParamsSchema:()=>xu,InitializeRequestSchema:()=>zu,InitializeResultSchema:()=>Lu,InitializedNotificationSchema:()=>ju,JSONArraySchema:()=>Yy,JSONObjectSchema:()=>fe,JSONRPCErrorResponseSchema:()=>ds,JSONRPCMessageSchema:()=>Hi,JSONRPCNotificationSchema:()=>Zi,JSONRPCRequestSchema:()=>Ui,JSONRPCResponseSchema:()=>Xy,JSONRPCResultResponseSchema:()=>us,JSONValueSchema:()=>Fn,LegacyTitledEnumSchemaSchema:()=>ia,ListChangedOptionsBaseSchema:()=>n_,ListPromptsRequestSchema:()=>hd,ListPromptsResultSchema:()=>fd,ListResourceTemplatesRequestSchema:()=>Wu,ListResourceTemplatesResultSchema:()=>Ku,ListResourcesRequestSchema:()=>Ju,ListResourcesResultSchema:()=>Bu,ListRootsRequestSchema:()=>ip,ListRootsResultSchema:()=>ap,ListTasksRequestSchema:()=>u_,ListTasksResultSchema:()=>d_,ListToolsRequestSchema:()=>Ed,ListToolsResultSchema:()=>Pd,LoggingLevelSchema:()=>Wo,LoggingMessageNotificationParamsSchema:()=>Nd,LoggingMessageNotificationSchema:()=>Md,ModelHintSchema:()=>Ad,ModelPreferencesSchema:()=>xd,MultiSelectEnumSchemaSchema:()=>Jd,NotificationSchema:()=>De,NotificationsParamsSchema:()=>je,NumberSchemaSchema:()=>Gr,PaginatedRequestParamsSchema:()=>Fu,PaginatedRequestSchema:()=>Yn,PaginatedResultSchema:()=>Xn,PingRequestSchema:()=>Bi,PrimitiveSchemaDefinitionSchema:()=>la,ProgressNotificationParamsSchema:()=>Hu,ProgressNotificationSchema:()=>Wi,ProgressSchema:()=>Zu,ProgressTokenSchema:()=>zi,PromptArgumentSchema:()=>pd,PromptListChangedNotificationSchema:()=>Rd,PromptMessageSchema:()=>bd,PromptReferenceSchema:()=>tp,PromptSchema:()=>md,ReadResourceRequestParamsSchema:()=>Gu,ReadResourceRequestSchema:()=>Yu,ReadResourceResultSchema:()=>Xu,RelatedTaskMetadataSchema:()=>Ou,RequestIdSchema:()=>Kn,RequestMetaSchema:()=>ji,RequestSchema:()=>ge,ResourceContentsSchema:()=>Ki,ResourceLinkSchema:()=>vd,ResourceListChangedNotificationSchema:()=>Qu,ResourceRequestParamsSchema:()=>ms,ResourceSchema:()=>Qi,ResourceTemplateReferenceSchema:()=>ep,ResourceTemplateSchema:()=>Vu,ResourceUpdatedNotificationParamsSchema:()=>ud,ResourceUpdatedNotificationSchema:()=>dd,ResultMetaObjectSchema:()=>Di,ResultSchema:()=>Se,RoleSchema:()=>Qn,RootSchema:()=>sp,RootsListChangedNotificationSchema:()=>cp,SamplingContentSchema:()=>jd,SamplingMessageContentBlockSchema:()=>Ko,SamplingMessageSchema:()=>Dd,ServerCapabilitiesSchema:()=>Ji,ServerNotificationSchema:()=>y_,ServerRequestSchema:()=>S_,ServerResultSchema:()=>__,ServerTasksCapabilitySchema:()=>Mu,SetLevelRequestParamsSchema:()=>Id,SetLevelRequestSchema:()=>qd,SingleSelectEnumSchemaSchema:()=>Vd,StringSchemaSchema:()=>ys,SubscribeRequestParamsSchema:()=>ed,SubscribeRequestSchema:()=>td,SubscriptionFilterSchema:()=>ea,SubscriptionsAcknowledgedNotificationParamsSchema:()=>id,SubscriptionsAcknowledgedNotificationSchema:()=>ad,SubscriptionsListenRequestParamsSchema:()=>rd,SubscriptionsListenRequestSchema:()=>sd,SubscriptionsListenResultMetaSchema:()=>cd,SubscriptionsListenResultSchema:()=>ld,TaskAugmentedRequestParamsSchema:()=>or,TaskCreationParamsSchema:()=>o_,TaskMetadataSchema:()=>Cu,TaskSchema:()=>eo,TaskStatusNotificationParamsSchema:()=>up,TaskStatusNotificationSchema:()=>s_,TaskStatusSchema:()=>lp,TextContentSchema:()=>hs,TextResourceContentsSchema:()=>Gi,TitledMultiSelectEnumSchemaSchema:()=>ca,TitledSingleSelectEnumSchemaSchema:()=>sa,ToolAnnotationsSchema:()=>Td,ToolChoiceSchema:()=>zd,ToolExecutionSchema:()=>$d,ToolListChangedNotificationSchema:()=>Od,ToolResultContentSchema:()=>Ld,ToolSchema:()=>ta,ToolUseContentSchema:()=>yd,UnsubscribeRequestParamsSchema:()=>nd,UnsubscribeRequestSchema:()=>od,UntitledMultiSelectEnumSchemaSchema:()=>aa,UntitledSingleSelectEnumSchemaSchema:()=>ra});const sm=e=>Ui.safeParse(e).success,Pb=e=>Zi.safeParse(e).success,mi=e=>us.safeParse(e).success,hi=e=>ds.safeParse(e).success,jt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";function kb(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Cb(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const qc="x-mcp-header",Ob=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Ib=new Set(["string","integer","boolean"]);function qb(e){const t=[],n=new Map;let o;const r=(i,a,c)=>{if(i===null||typeof i!="object")return;const d=i;if(qc in d){if(!c||a.length===0)return`${qr(a)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;const p=d[qc];if(typeof p!="string"||p.length===0)return`${qr(a)}: x-mcp-header MUST be a non-empty string`;if(!Ob.test(p))return`${qr(a)}: x-mcp-header '${p}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;const m=typeof d.type=="string"?d.type:void 0;if(m===void 0||!Ib.has(m)){const _=`${qr(a)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${m??"<none>"}`;if(m!=="number")return _;o??(o=_)}const h=p.toLowerCase(),f=n.get(h);if(f!==void 0)return`x-mcp-header '${p}' is not case-insensitively unique (also declared as '${f}')`;n.set(h,p),t.push({path:a,headerName:p,type:m})}const u=d.properties;if(u!==null&&typeof u=="object")for(const[p,m]of Object.entries(u)){const h=r(m,[...a,p],c);if(h!==void 0)return h}for(const p of Nb){const m=d[p];if(m===void 0)continue;const h=Array.isArray(m)?m:m!==null&&typeof m=="object"&&Mb.has(p)?Object.values(m):[m];for(const f of h){const _=r(f,[...a,`<${p}>`],!1);if(_!==void 0)return _}}},s=r(e,[],!0);return s!==void 0?{valid:!1,reason:o??s}:o===void 0?{valid:!0,declarations:t}:{valid:!1,reason:o,declarations:t}}const Nb=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],Mb=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function qr(e){return e.length===0?"<root>":e.join(".")}const Dr=-32020;P.InvalidRequest,P.UnsupportedProtocolVersion,P.InvalidParams,P.MethodNotFound,P.InvalidParams,P.MissingRequiredClientCapability;const Ab={[P.ParseError]:400,[P.InvalidRequest]:400,[P.MethodNotFound]:404,[P.UnsupportedProtocolVersion]:400,[P.MissingRequiredClientCapability]:400,[Dr]:400};function wa(e,t){return fu(e,t)}function qo(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function Jn(e){var n;if(e==null)return!1;const t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof((n=e["~standard"])==null?void 0:n.validate)=="function"}let Nc=!1;const fi="draft-2020-12";function Bn(e,t="input"){const n=e["~standard"];let o;if(n.jsonSchema)o=n.jsonSchema[t]({target:fi});else if(n.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");Nc||(Nc=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),o=hu(e,{target:fi,io:t})}else throw new Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return o.type!==void 0?o:im(o)?{type:"object",...o}:o;if(o.type!==void 0&&o.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}const xb=/^#\/(\$defs|definitions)\/([^/~%]+)$/;function im(e,t=e){var o,r;if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;const n=typeof e.$ref=="string"&&xb.exec(e.$ref);if(n&&((r=(o=t[n[1]])==null?void 0:o[n[2]])==null?void 0:r.type)==="object")return!0;for(const s of["oneOf","anyOf","allOf"]){const i=e[s];if(Array.isArray(i)&&i.length>0)return i.every(a=>a!==null&&typeof a=="object"&&(a.type==="object"||im(a,"$id"in a?{}:t)))}return!1}function zb(e){var t;return(t=e.path)!=null&&t.length?`${e.path.map(n=>String(typeof n=="object"?n.key:n)).join(".")}: ${e.message}`:e.message}async function Mn(e,t){const n=await e["~standard"].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(o=>zb(o)).join(", ")}:{success:!0,data:n.value}}function Lb(e){const t=hu(e,{target:fi,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}const jb=/\\\.\\d\{(\d+)\}/;function Db(e){const t=jb.exec(e),n=[void 0,-1,0];return t&&n.push(Number(t[1])),[!1,!0].flatMap(o=>[!1,!0].flatMap(r=>n.map(s=>is({local:o,offset:r,precision:s}))))}function Ub(e,t){let n;switch(e){case"email":n=[QS()];break;case"uri":n=[bu()];break;case"date":n=[Jy()];break;case"date-time":n=Db(t);break}return new Set(n.map(o=>Lb(o)).filter(o=>o!==void 0))}function Zb(e,t,n){return n!=="zod"?!0:Ub(e,t).has(t)}function Hb(e){const t=Bn(e,"input"),n=t.properties||{},o=t.required||[];return Object.entries(n).map(([r,s])=>({name:r,description:s==null?void 0:s.description,required:o.includes(r)}))}function Qo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Fb(e){try{return Bn(e,"input")}catch(t){const n=t instanceof Error?t.message:String(t);throw new Z(P.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${n}`)}}const Vb=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function Ra(e){return Vb.has(e)||e.startsWith("x-")}const Jb=new Set(["$schema",...Object.keys(_s.shape.requestedSchema.shape)]),Mc={string:qo([ys,ra,sa,ia]),number:qo([Gr]),integer:qo([Gr]),boolean:qo([oa]),array:qo([aa,ca])},Bb=new Set(ys.shape.format.unwrap().options);function Wb(e,t,n,o){if(!Qo(e))return e;const r=typeof e.type=="string"&&Object.hasOwn(Mc,e.type)?Mc[e.type]:void 0;if(r===void 0)return e;const s={};for(const[i,a]of Object.entries(e))r.has(i)||Ra(i)?s[i]=a:i==="pattern"&&e.type==="string"&&typeof e.format=="string"?Bb.has(e.format)?(typeof a!="string"||!Zb(e.format,a,n))&&o.push(`${t}.${i}`):s[i]=a:o.push(`${t}.${i}`);return s}function Kb(e,t){const n={},o=[];for(const[r,s]of Object.entries(e))r==="properties"&&Qo(s)?n[r]=Object.fromEntries(Object.entries(s).map(([i,a])=>[i,Wb(a,`properties.${i}`,t,o)])):Jb.has(r)?n[r]=s:Ra(r)||o.push(r);if(o.length>0)throw new Z(P.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return n}function Gb(e,t){if(!Qo(e.properties))return t;const n=Object.entries(e.properties).filter(([,o])=>!wa(la,o).success).map(([o])=>`properties.${o}`);return n.length>0?n.join(", "):t}function gi(e,t,n=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,r)=>gi(o,t[r],`${n}[${r}]`)):!Qo(e)||!Qo(t)?[]:Object.entries(e).flatMap(([o,r])=>{const s=n?`${n}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?gi(r,t[o],s):Ra(o)?[]:[s]})}function Yb(e){if(!Jn(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};const t=e.requestedSchema["~standard"].vendor,n=Kb(Fb(e.requestedSchema),t),o=wa(_s.shape.requestedSchema,n);if(!o.success)throw new Z(P.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Gb(n,o.error.message)}`);const r=gi(n,o.data);if(r.length>0)throw new Z(P.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${r.join(", ")}`);const s=(o.data.required??[]).filter(i=>!Object.prototype.hasOwnProperty.call(o.data.properties,i));if(s.length>0)throw new Z(P.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function Xb(e){const t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,n=typeof e.requestState=="string";if(!t&&!n)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}Object.assign(Xb,{elicit(e){try{return{method:"elicitation/create",params:Yb(e)}}catch(t){throw t instanceof Z?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});const Qb=250;function ew(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function tw(e,t){return new Promise((n,o)=>{if(t!=null&&t.aborted){o(t.reason instanceof K?t.reason:new K(X.RequestTimeout,String(t.reason)));return}const r=setTimeout(()=>{t==null||t.removeEventListener("abort",s),n()},e),s=()=>{clearTimeout(r),o((t==null?void 0:t.reason)instanceof K?t.reason:new K(X.RequestTimeout,String(t==null?void 0:t.reason)))};t==null||t.addEventListener("abort",s,{once:!0})})}function nw(e){const t=new AbortController,n=()=>t.abort(e==null?void 0:e.reason);return e==null||e.addEventListener("abort",n,{once:!0}),e!=null&&e.aborted&&t.abort(e.reason),{signal:t.signal,abort:o=>t.abort(o),dispose:()=>e==null?void 0:e.removeEventListener("abort",n)}}const ow=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],rw={IdJagTokenExchangeResponseSchema:R_,OAuthClientInformationFullSchema:$_,OAuthClientInformationSchema:hp,OAuthClientMetadataSchema:mp,OAuthClientRegistrationErrorSchema:E_,OAuthErrorResponseSchema:T_,OAuthMetadataSchema:dp,OAuthProtectedResourceMetadataSchema:v_,OAuthTokenRevocationRequestSchema:P_,OAuthTokensSchema:w_,OpenIdProviderDiscoveryMetadataSchema:b_,OpenIdProviderMetadataSchema:pp},am={},cm={};function lm(e,t){const n=e.slice(0,-6);am[n]=t,cm[n]=o=>t.safeParse(o).success}for(const e of ow)lm(e,Eb[e]);for(const[e,t]of Object.entries(rw))lm(e,t);Object.freeze(am);Object.freeze(cm);function sw(e){switch(e){case"initialize":case"notifications/initialized":return Xo(void 0);case"server/discover":return Xo(om);default:return}}const iw=6e4,aw=[as,xi,nr,cs],cw=["inputResponses","requestState"];function Ac(e,t){const n=e.params;if(!Uo(n))return{message:e,lifted:{}};const o=n._meta,r=Uo(o)?aw.filter(c=>c in o):[],s=t==="request"?cw.filter(c=>c in n):[];if(r.length===0&&s.length===0)return{message:e,lifted:{}};const i={},a={...n};if(r.length>0&&Uo(o)){const c={},d={...o};for(const u of r)c[u]=o[u],delete d[u];i.envelope=c,Object.keys(d).length>0?a._meta=d:delete a._meta}for(const c of s)c==="inputResponses"&&(i.inputResponses=a[c]),c==="requestState"&&(i.requestState=a[c]),delete a[c];return{message:{...e,params:a},lifted:i}}function xc(e,t){const n=e.validateResult(t,void 0);if(!(!n.ok&&n.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){const r=e.validateResult(t,o);return r.ok?{value:r.value}:{issues:[{message:r.reason==="invalid"?r.message:`not-in-era: ${t}`}]}}}}}function bs(e){return()=>e}const lw=bs(void 0);function um(e,t){return{...e,mcpReq:{...e.mcpReq,requestState:bs(t)}}}var uw=class{constructor(e){T(this,"_transport");T(this,"_requestMessageId",0);T(this,"_requestHandlers",new Map);T(this,"_customSchemaRequestMethods",new Set);T(this,"_requestHandlerAbortControllers",new Map);T(this,"_notificationHandlers",new Map);T(this,"_responseHandlers",new Map);T(this,"_progressHandlers",new Map);T(this,"_timeoutInfo",new Map);T(this,"_pendingDebouncedNotifications",new Set);T(this,"_negotiatedProtocolVersion");T(this,"_supportedProtocolVersions");T(this,"onclose");T(this,"onerror");T(this,"fallbackRequestHandler");T(this,"fallbackNotificationHandler");this._options=e,this._supportedProtocolVersions=(e==null?void 0:e.supportedProtocolVersions)??Wy,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){const t=this._outboundMetaEnvelope();if(t===void 0)return e;const n=e.params??{};return{...e,params:{...n,_meta:{...t,...n._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new K(X.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){var t;e.params.requestId!==void 0&&((t=this._requestHandlerAbortControllers.get(e.params.requestId))==null||t.abort(e.params.reason))}_setupTimeout(e,t,n,o,r=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:r,onTimeout:o})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new K(X.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,s,i,a;this._transport=e;const t=(r=this.transport)==null?void 0:r.onclose;this._transport.onclose=()=>{try{t==null||t()}finally{this._onclose()}};const n=(s=this.transport)==null?void 0:s.onerror;this._transport.onerror=c=>{n==null||n(c),this._onerror(c)};const o=(i=this._transport)==null?void 0:i.onmessage;this._transport.onmessage=(c,d)=>{o==null||o(c,d),mi(c)||hi(c)?this._onresponse(c):sm(c)?this._onrequest(c,d):Pb(c)?this._onnotification(c,d):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},(a=e.setSupportedProtocolVersions)==null||a.call(e,this._supportedProtocolVersions),await this._transport.start()}_onclose(){var o;const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();const t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;const n=new K(X.ConnectionClosed,"Connection closed");this._transport=void 0;try{(o=this.onclose)==null||o.call(this)}finally{for(const r of e.values())r(n);for(const r of t.values())r.abort(n)}}_onerror(e){var t;(t=this.onerror)==null||t.call(this,e)}_onnotification(e,t){const{message:n}=Ac(e,"notification"),o=this._negotiatedWireCodec();if((t==null?void 0:t.classification)===void 0&&this._shouldDropInbound(e)==="drop")return;if((t==null?void 0:t.classification)!==void 0){const i=Oc(t.classification);if(i!==o.era){this._onerror(new Error(`Era mismatch on inbound notification '${n.method}': classified as ${i} but this instance serves ${o.era}`));return}}if(Ds(n.method)&&!o.hasNotificationMethod(n.method))return;const r=this._notificationHandlers.get(n.method),s=this.fallbackNotificationHandler;r===void 0&&s===void 0||Promise.resolve().then(()=>r===void 0?s(n):r(n,o)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,t){var _;const{message:n,lifted:o}=Ac(e,"request"),r=this._negotiatedWireCodec();if((t==null?void 0:t.classification)===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}const s=this._transport,i=(S,b,R)=>{const M={jsonrpc:"2.0",id:n.id,error:{code:S,message:b,...R!==void 0&&{data:R}}};s==null||s.send(M).catch(L=>this._onerror(new Error(`Failed to send an error response: ${L}`)))};if((t==null?void 0:t.classification)!==void 0){const S=Oc(t.classification);if(S!==r.era){this._onerror(new Error(`Era mismatch on inbound request '${n.method}': classified as ${S} but this instance serves ${r.era}`));const b=t.classification.revision??S;i(P.UnsupportedProtocolVersion,`Unsupported protocol version: ${b}`,{supported:this._supportedProtocolVersions,requested:b});return}}if(js(n.method)&&!r.hasRequestMethod(n.method)&&!(Ic(n.method)&&this._customSchemaRequestMethods.has(n.method))){i(P.MethodNotFound,"Method not found");return}const a=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(a===void 0){i(P.MethodNotFound,"Method not found");return}const c=r.checkInboundEnvelope(o);if(c!==void 0){i(P.InvalidParams,c);return}const d=(S,b)=>this._notificationViaCodec(this._resolveOutboundCodec(S.method),S,{...b,relatedRequestId:n.id}),u=(S,b,R)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(S.method),S,b,{...R,relatedRequestId:n.id}),p=new AbortController;this._requestHandlerAbortControllers.set(n.id,p);const m=o.inputResponses===void 0?void 0:dw(o.inputResponses),h={sessionId:s==null?void 0:s.sessionId,mcpReq:{id:n.id,method:n.method,_meta:(_=n.params)==null?void 0:_._meta,...o.envelope!==void 0&&{envelope:o.envelope},...m!==void 0&&{inputResponses:m.accepted},...m!==void 0&&m.droppedKeys.length>0&&{droppedInputResponseKeys:m.droppedKeys},requestState:o.requestState===void 0?lw:bs(o.requestState),signal:p.signal,send:((S,b,R)=>{const M=this._resolveOutboundCodec(S.method);if(this._assertOutboundRequestInEra(M,S.method),Jn(b))return u(S,b,R);const L=xc(M,S.method);if(L===void 0)throw new TypeError(`'${S.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return u(S,L,b)}),notify:d},http:t!=null&&t.authInfo?{authInfo:t.authInfo}:void 0},f=this.buildContext(h,t);Promise.resolve().then(()=>a(n,f)).then(async S=>{if(p.signal.aborted)return;let b;try{b=r.encodeResult(n.method,S,this._outboundServerInfo())}catch(M){this._onerror(new Error(`Failed to encode result for ${n.method}: ${M}`)),i(P.InternalError,"Internal error");return}const R={result:b,jsonrpc:"2.0",id:n.id};await(s==null?void 0:s.send(R))},async S=>{if(p.signal.aborted)return;const b=Number.isSafeInteger(S.code)?S.code:P.InternalError,R={jsonrpc:"2.0",id:n.id,error:{code:r.encodeErrorCode(b),message:S.message??"Internal error",...S.data!==void 0&&{data:S.data}}};await(s==null?void 0:s.send(R))}).catch(S=>this._onerror(new Error(`Failed to send response: ${S}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===p&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(e){const{progressToken:t,...n}=e.params,o=Number(t),r=this._progressHandlers.get(o);if(!r){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const s=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(a);return}r(n)}_onresponse(e){const t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),mi(e)?n(e):n(Z.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){var e;await((e=this._transport)==null?void 0:e.close())}request(e,t,n){const o=this._resolveOutboundCodec(e.method);if(Jn(t))return Ic(e.method)||this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,n);this._assertOutboundRequestInEra(o,e.method);const r=xc(o,e.method);if(r===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(o,e,r,t)}_negotiatedWireCodec(){return Xo(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){const t=sw(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(js(t)&&!e.hasRequestMethod(t))throw new K(X.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,n){const o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,n)}_requestWithSchemaViaCodec(e,t,n,o){const{relatedRequestId:r,resumptionToken:s,onresumptiontoken:i,headers:a}=o??{},c=Date.now();let d,u;return new Promise((p,m)=>{var oe,Y,H,ne;const h=Q=>{m(Q)};if(!this._transport){h(new Error("Not connected"));return}if(((oe=this._options)==null?void 0:oe.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(t.method)}catch(Q){h(Q);return}if((Y=o==null?void 0:o.signal)!=null&&Y.aborted){const Q=o.signal.reason;throw Q instanceof K?Q:new K(X.RequestTimeout,String(Q))}const f=e.era===om&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,_=this._requestMessageId++;u=_;const S={...t,jsonrpc:"2.0",id:_};o!=null&&o.onprogress&&(this._progressHandlers.set(_,o.onprogress),S.params={...t.params,_meta:{...(H=t.params)==null?void 0:H._meta,progressToken:_}});const b=this._envelopeOutbound(S);let R=!1;const M=Q=>{var re;R||(this._progressHandlers.delete(_),f===void 0?t.method!=="initialize"&&((re=this._transport)==null||re.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:_,reason:String(Q)}}),{relatedRequestId:r,resumptionToken:s,onresumptiontoken:i}).catch(we=>this._onerror(new Error(`Failed to send cancellation: ${we}`)))):f.abort(),m(Q instanceof K?Q:new K(X.RequestTimeout,String(Q))))};this._responseHandlers.set(_,Q=>{var Me;if((Me=o==null?void 0:o.signal)!=null&&Me.aborted)return;if(R=!0,Q instanceof Error)return m(Q);let re;try{re=e.decodeResult(t.method,Q.result)}catch(pe){return m(pe instanceof Error?pe:new Error(String(pe)))}if(re.kind==="invalid")return m(re.error);if(re.kind==="input_required"){if((o==null?void 0:o.allowInputRequired)===!0)return p(pw(re));const pe={codec:e,request:t,resultSchema:n,options:o,flowStartedAt:c,retry:(_e,Ke)=>this._requestWithSchemaViaCodec(e,_e===void 0?{method:t.method}:{method:t.method,params:_e},n,Ke)};return p(this._resolveNonCompleteResult(re,pe))}const we=re.result;Mn(n,we).then(pe=>{pe.success?p(pe.data):m(new K(X.InvalidResult,`Invalid result for ${t.method}: ${pe.error}`))},m)}),d=()=>{var Q;return M((Q=o==null?void 0:o.signal)==null?void 0:Q.reason)},(ne=o==null?void 0:o.signal)==null||ne.addEventListener("abort",d,{once:!0});const L=(o==null?void 0:o.timeout)??iw,te=()=>M(new K(X.RequestTimeout,"Request timed out",{timeout:L}));this._setupTimeout(_,L,o==null?void 0:o.maxTotalTimeout,te,(o==null?void 0:o.resetTimeoutOnProgress)??!1),this._transport.send(b,{relatedRequestId:r,resumptionToken:s,onresumptiontoken:i,headers:a,requestSignal:f==null?void 0:f.signal}).catch(Q=>{this._progressHandlers.delete(_),m(Q)})}).finally(()=>{var p;d&&((p=o==null?void 0:o.signal)==null||p.removeEventListener("abort",d)),u!==void 0&&(this._responseHandlers.delete(u),this._cleanupTimeout(u))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,n){var r;if(!this._transport)throw new K(X.NotConnected,"Not connected");if(Ds(t.method)&&!e.hasNotificationMethod(t.method))throw new K(X.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);const o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((((r=this._options)==null?void 0:r.debouncedNotificationMethods)??[]).includes(t.method)&&!t.params&&(n==null?void 0:n.relatedRequestId)===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{var s;this._pendingDebouncedNotifications.delete(t.method),this._transport&&((s=this._transport)==null||s.send(o,n).catch(i=>this._onerror(i)))});return}await this._transport.send(o,n)}setRequestHandler(e,t,n){this.assertRequestHandlerCapability(e);let o;if(typeof t=="function"){if(!js(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=(r,s)=>{const i=this._negotiatedWireCodec();let a=i.validateRequest(e,r);if(!a.ok&&a.reason==="not-in-era"&&(a=i.validateInputRequest(e,r)),!a.ok)throw a.reason==="not-in-era"?new Z(P.InternalError,`No wire schema for ${e} in the resolved era`):new Error(a.message);return Promise.resolve(t(a.value,s))}}else if(n)o=async(r,s)=>{const i=await Mn(t.params,{...r.params});if(!i.success)throw new Z(P.InvalidParams,`Invalid params for ${e}: ${i.error}`);return n(i.data,s)};else throw new TypeError("setRequestHandler: handler is required");typeof t=="function"?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,n){if(typeof t=="function"){if(!Ds(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,r)=>{const s=r.validateNotification(e,o);if(!s.ok)throw s.reason==="not-in-era"?new Z(P.InternalError,`No wire schema for ${e} in the resolved era`):new Error(s.message);return Promise.resolve(t(s.value))});return}if(!n)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async o=>{const r=await Mn(t.params,{...o.params});if(!r.success)throw new Z(P.InvalidParams,`Invalid params for notification ${e}: ${r.error}`);await n(r.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Uo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dm(e,t){const n={...e};for(const o in t){const r=o,s=t[r];if(s===void 0)continue;const i=n[r];n[r]=Uo(i)&&Uo(s)?{...i,...s}:s}return n}function zc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dw(e){const t={},n=[];if(!zc(e))return{accepted:t,droppedKeys:n};for(const[o,r]of Object.entries(e)){if(!zc(r)||"method"in r||"result"in r){n.push(o);continue}t[o]=r}return{accepted:t,droppedKeys:n}}function pw(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}/*!
|
|
61
|
+
* content-type
|
|
62
|
+
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
63
|
+
* MIT Licensed
|
|
64
|
+
*/var mw=Pv((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,n=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=r;function r(a){if(!a)throw new TypeError("argument string is required");var c=typeof a=="object"?s(a):a;if(typeof c!="string")throw new TypeError("argument string is required to be a string");var d=c.indexOf(";"),u=d!==-1?c.slice(0,d).trim():c.trim();if(!o.test(u))throw new TypeError("invalid media type");var p=new i(u.toLowerCase());if(d!==-1){var m,h,f;for(t.lastIndex=d;h=t.exec(c);){if(h.index!==d)throw new TypeError("invalid parameter format");d+=h[0].length,m=h[1].toLowerCase(),f=h[2],f.charCodeAt(0)===34&&(f=f.slice(1,-1),f.indexOf("\\")!==-1&&(f=f.replace(n,"$1"))),p.parameters[m]=f}if(d!==c.length)throw new TypeError("invalid parameter format")}return p}function s(a){var c;if(typeof a.getHeader=="function"?c=a.getHeader("content-type"):typeof a.headers=="object"&&(c=a.headers&&a.headers["content-type"]),typeof c!="string")throw new TypeError("content-type header is missing from object");return c}function i(a){this.parameters=Object.create(null),this.type=a}}));mw();const hw=/^[A-Za-z0-9._-]{1,128}$/;function fw(e){const t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!hw.test(e)){const n=[...e].filter(o=>!/[A-Za-z0-9._-]/.test(o)).filter((o,r,s)=>s.indexOf(o)===r);return t.push(`Tool name contains invalid characters: ${n.map(o=>`"${o}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function gw(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const n of t)console.warn(` - ${n}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Lc(e){const t=fw(e);return gw(e,t.warnings),t.isValid}const jc=1e6,Us=1e6,Dc=1e4,Sw=1e6;var yw=class sn{constructor(t){T(this,"template");T(this,"parts");sn.validateLength(t,jc,"Template"),this.template=t,this.parts=this.parse(t)}static isTemplate(t){return/\{[^}\s]+\}/.test(t)}static validateLength(t,n,o){if(t.length>n)throw new Error(`${o} exceeds maximum length of ${n} characters (got ${t.length})`)}get variableNames(){return this.parts.flatMap(t=>typeof t=="string"?[]:t.names)}toString(){return this.template}parse(t){const n=[];let o="",r=0,s=0;for(;r<t.length;)if(t[r]==="{"){o&&(n.push(o),o="");const i=t.indexOf("}",r);if(i===-1)throw new Error("Unclosed template expression");if(s++,s>Dc)throw new Error(`Template contains too many expressions (max ${Dc})`);const a=t.slice(r+1,i),c=this.getOperator(a),d=a.includes("*"),u=this.getNames(a),p=u[0];for(const m of u)sn.validateLength(m,Us,"Variable name");n.push({name:p,operator:c,names:u,exploded:d}),r=i+1}else o+=t[r],r++;return o&&n.push(o),n}getOperator(t){return["+","#",".","/","?","&"].find(n=>t.startsWith(n))||""}getNames(t){const n=this.getOperator(t);return t.slice(n.length).split(",").map(o=>o.replace("*","").trim()).filter(o=>o.length>0)}encodeValue(t,n){return sn.validateLength(t,Us,"Variable value"),n==="+"||n==="#"?encodeURI(t):encodeURIComponent(t)}expandPart(t,n){if(t.operator==="?"||t.operator==="&"){const s=t.names.map(i=>{const a=n[i];return a===void 0?"":`${i}=${Array.isArray(a)?a.map(c=>this.encodeValue(c,t.operator)).join(","):this.encodeValue(a.toString(),t.operator)}`}).filter(i=>i.length>0);return s.length===0?"":(t.operator==="?"?"?":"&")+s.join("&")}if(t.names.length>1){const s=t.names.map(i=>n[i]).filter(i=>i!==void 0);return s.length===0?"":s.map(i=>Array.isArray(i)?i[0]:i).join(",")}const o=n[t.name];if(o===void 0)return"";const r=(Array.isArray(o)?o:[o]).map(s=>this.encodeValue(s,t.operator));switch(t.operator){case"":return r.join(",");case"+":return r.join(",");case"#":return"#"+r.join(",");case".":return"."+r.join(".");case"/":return"/"+r.join("/");default:return r.join(",")}}expand(t){let n="",o=!1;for(const r of this.parts){if(typeof r=="string"){n+=r;continue}const s=this.expandPart(r,t);s&&(n+=(r.operator==="?"||r.operator==="&")&&o?s.replace("?","&"):s,(r.operator==="?"||r.operator==="&")&&(o=!0))}return n}escapeRegExp(t){return t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(t){const n=[];for(const s of t.names)sn.validateLength(s,Us,"Variable name");if(t.operator==="?"||t.operator==="&"){for(let s=0;s<t.names.length;s++){const i=t.names[s],a=s===0?"\\"+t.operator:"&";n.push({pattern:a+this.escapeRegExp(i)+"=([^&]+)",name:i})}return n}let o;const r=t.name;switch(t.operator){case"":o=t.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":o="(.+)";break;case".":o=String.raw`\.([^/,]+)`;break;case"/":o="/"+(t.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:o="([^/]+)"}return n.push({pattern:o,name:r}),n}match(t){sn.validateLength(t,jc,"URI");let n="^";const o=[];for(const a of this.parts)if(typeof a=="string")n+=this.escapeRegExp(a);else{const c=this.partToRegExp(a);for(const{pattern:d,name:u}of c)n+=d,o.push({name:u,exploded:a.exploded})}n+="$",sn.validateLength(n,Sw,"Generated regex pattern");const r=new RegExp(n),s=t.match(r);if(!s)return null;const i={};for(const[a,c]of o.entries()){const{name:d,exploded:u}=c,p=s[a+1],m=d.replace("*","");i[m]=u&&p.includes(",")?p.split(","):p}return i}};function _w(e){return typeof e=="object"&&e!==null&&"_zod"in e}function vw(e){var t;return typeof e=="object"&&e!==null&&!("_zod"in e)&&"_def"in e&&typeof((t=e._def)==null?void 0:t.typeName)=="string"}function bw(e){if(typeof e!="object"||e===null||Jn(e))return!1;const t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.values(e).every(n=>_w(n))}function Zs(e){if(e!==void 0){if(bw(e))return g(e);if(typeof e=="object"&&e!==null&&!Jn(e)&&Object.values(e).some(t=>vw(t)))throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!Jn(e))throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return e}}function ww(e,t){const n=t.getValidator(e);return{"~standard":{version:1,vendor:"mcp",jsonSchema:{input:()=>e,output:()=>e},validate:o=>{const r=n(o);return r.valid?{value:r.data}:{issues:[{message:r.errorMessage}]}}}}}function Zo(e,t){const n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const o=e.length;if(o!==t.length)return!1;for(let r=0;r<o;r++)if(!Zo(e[r],t[r]))return!1;return!0}if(n==="object"){if(!e||!t)return e===t;const o=Object.keys(e),r=Object.keys(t);if(o.length!==r.length)return!1;for(const s of o)if(!Zo(e[s],t[s]))return!1;return!0}return e===t}function st(e){return encodeURI(Rw(e))}function Rw(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}const Tw={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},$w={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Ew={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};let Pw=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function ln(e,t=Object.create(null),n=Pw,o=""){if(e&&typeof e=="object"&&!Array.isArray(e)){const s=e.$id||e.id;if(s){const i=new URL(s,n.href);i.hash.length>1?t[i.href]=e:(i.hash="",o===""?n=i:ln(e,t,n))}}else if(e!==!0&&e!==!1)return t;const r=n.href+(o?"#"+o:"");if(t[r]!==void 0)throw new Error(`Duplicate schema URI "${r}".`);if(t[r]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:r}),e.$ref&&e.__absolute_ref__===void 0){const s=new URL(e.$ref,n.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){const s=new URL(e.$recursiveRef,n.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){const s=new URL("#"+e.$anchor,n.href);t[s.href]=e}for(let s in e){if(Ew[s])continue;const i=`${o}/${st(s)}`,a=e[s];if(Array.isArray(a)){if(Tw[s]){const c=a.length;for(let d=0;d<c;d++)ln(a[d],t,n,`${i}/${d}`)}}else if($w[s])for(let c in a)ln(a[c],t,n,`${i}/${st(c)}`);else ln(a,t,n,i)}return t}const kw=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Cw=[0,31,28,31,30,31,30,31,31,30,31,30,31],Ow=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Iw=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,qw=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Nw=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Mw=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Aw=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,xw=/^(?:\/(?:[^~/]|~0|~1)*)*$/,zw=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Lw=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,jw=e=>{if(e[0]==='"')return!1;const[t,n,...o]=e.split("@");return!t||!n||o.length!==0||t.length>64||n.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(".").every(r=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(r))},Dw=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Uw=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Zw=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function ft(e){return e.test.bind(e)}const Uc={date:pm,time:mm.bind(void 0,!1),"date-time":Vw,duration:Zw,uri:Ww,"uri-reference":ft(qw),"uri-template":ft(Nw),url:ft(Mw),email:jw,hostname:ft(Iw),ipv4:ft(Dw),ipv6:ft(Uw),regex:Gw,uuid:ft(Aw),"json-pointer":ft(xw),"json-pointer-uri-fragment":ft(zw),"relative-json-pointer":ft(Lw)};function Hw(e){return e%4===0&&(e%100!==0||e%400===0)}function pm(e){const t=e.match(kw);if(!t)return!1;const n=+t[1],o=+t[2],r=+t[3];return o>=1&&o<=12&&r>=1&&r<=(o==2&&Hw(n)?29:Cw[o])}function mm(e,t){const n=t.match(Ow);if(!n)return!1;const o=+n[1],r=+n[2],s=+n[3],i=!!n[5];return(o<=23&&r<=59&&s<=59||o==23&&r==59&&s==60)&&(!e||i)}const Fw=/t|\s/i;function Vw(e){const t=e.split(Fw);return t.length==2&&pm(t[0])&&mm(!0,t[1])}const Jw=/\/|:/,Bw=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Ww(e){return Jw.test(e)&&Bw.test(e)}const Kw=/[^\\]\\Z/;function Gw(e){if(Kw.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}function Yw(e){let t=0,n=e.length,o=0,r;for(;o<n;)t++,r=e.charCodeAt(o++),r>=55296&&r<=56319&&o<n&&(r=e.charCodeAt(o),(r&64512)==56320&&o++);return t}function ue(e,t,n="2019-09",o=ln(t),r=!0,s=null,i="#",a="#",c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};const d=typeof e;let u;switch(d){case"boolean":case"number":case"string":u=d;break;case"object":e===null?u="null":Array.isArray(e)?u="array":u="object";break;default:throw new Error(`Instances of "${d}" type are not supported.`)}const{$ref:p,$recursiveRef:m,$recursiveAnchor:h,type:f,const:_,enum:S,required:b,not:R,anyOf:M,allOf:L,oneOf:te,if:oe,then:Y,else:H,format:ne,properties:Q,patternProperties:re,additionalProperties:we,unevaluatedProperties:Me,minProperties:pe,maxProperties:_e,propertyNames:Ke,dependentRequired:Ae,dependentSchemas:Ge,dependencies:ct,prefixItems:Ue,items:ke,additionalItems:_t,unevaluatedItems:vt,contains:lt,minContains:Re,maxContains:Ce,minItems:Oe,maxItems:nt,uniqueItems:Bt,minimum:Ze,maximum:He,exclusiveMinimum:xe,exclusiveMaximum:Ye,multipleOf:Xe,minLength:ut,maxLength:dt,pattern:kt,__absolute_ref__:pt,__absolute_recursive_ref__:Wt}=t,O=[];if(h===!0&&s===null&&(s=t),m==="#"){const D=s===null?o[Wt]:s,A=`${a}/$recursiveRef`,W=ue(e,s===null?t:s,n,o,r,D,i,A,c);W.valid||O.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:A,error:"A subschema had errors."},...W.errors)}if(p!==void 0){const D=o[pt||p];if(D===void 0){let I=`Unresolved $ref "${p}".`;throw pt&&pt!==p&&(I+=` Absolute URI "${pt}".`),I+=`
|
|
65
|
+
Known schemas:
|
|
66
|
+
- ${Object.keys(o).join(`
|
|
67
|
+
- `)}`,new Error(I)}const A=`${a}/$ref`,W=ue(e,D,n,o,r,s,i,A,c);if(W.valid||O.push({instanceLocation:i,keyword:"$ref",keywordLocation:A,error:"A subschema had errors."},...W.errors),n==="4"||n==="7")return{valid:O.length===0,errors:O}}if(Array.isArray(f)){let D=f.length,A=!1;for(let W=0;W<D;W++)if(u===f[W]||f[W]==="integer"&&u==="number"&&e%1===0&&e===e){A=!0;break}A||O.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${f.join('", "')}".`})}else f==="integer"?(u!=="number"||e%1||e!==e)&&O.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${f}".`}):f!==void 0&&u!==f&&O.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${f}".`});if(_!==void 0&&(u==="object"||u==="array"?Zo(e,_)||O.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(_)}.`}):e!==_&&O.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(_)}.`})),S!==void 0&&(u==="object"||u==="array"?S.some(D=>Zo(e,D))||O.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`}):S.some(D=>e===D)||O.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(S)}.`})),R!==void 0){const D=`${a}/not`;ue(e,R,n,o,r,s,i,D).valid&&O.push({instanceLocation:i,keyword:"not",keywordLocation:D,error:'Instance matched "not" schema.'})}let mt=[];if(M!==void 0){const D=`${a}/anyOf`,A=O.length;let W=!1;for(let I=0;I<M.length;I++){const k=M[I],J=Object.create(c),F=ue(e,k,n,o,r,h===!0?s:null,i,`${D}/${I}`,J);O.push(...F.errors),W=W||F.valid,F.valid&&mt.push(J)}W?O.length=A:O.splice(A,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:D,error:"Instance does not match any subschemas."})}if(L!==void 0){const D=`${a}/allOf`,A=O.length;let W=!0;for(let I=0;I<L.length;I++){const k=L[I],J=Object.create(c),F=ue(e,k,n,o,r,h===!0?s:null,i,`${D}/${I}`,J);O.push(...F.errors),W=W&&F.valid,F.valid&&mt.push(J)}W?O.length=A:O.splice(A,0,{instanceLocation:i,keyword:"allOf",keywordLocation:D,error:"Instance does not match every subschema."})}if(te!==void 0){const D=`${a}/oneOf`,A=O.length,W=te.filter((I,k)=>{const J=Object.create(c),F=ue(e,I,n,o,r,h===!0?s:null,i,`${D}/${k}`,J);return O.push(...F.errors),F.valid&&mt.push(J),F.valid}).length;W===1?O.length=A:O.splice(A,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:D,error:`Instance does not match exactly one subschema (${W} matches).`})}if((u==="object"||u==="array")&&Object.assign(c,...mt),oe!==void 0){const D=`${a}/if`;if(ue(e,oe,n,o,r,s,i,D,c).valid){if(Y!==void 0){const A=ue(e,Y,n,o,r,s,i,`${a}/then`,c);A.valid||O.push({instanceLocation:i,keyword:"if",keywordLocation:D,error:'Instance does not match "then" schema.'},...A.errors)}}else if(H!==void 0){const A=ue(e,H,n,o,r,s,i,`${a}/else`,c);A.valid||O.push({instanceLocation:i,keyword:"if",keywordLocation:D,error:'Instance does not match "else" schema.'},...A.errors)}}if(u==="object"){if(b!==void 0)for(const I of b)I in e||O.push({instanceLocation:i,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${I}".`});const D=Object.keys(e);if(pe!==void 0&&D.length<pe&&O.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${pe} properties.`}),_e!==void 0&&D.length>_e&&O.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${_e} properties.`}),Ke!==void 0){const I=`${a}/propertyNames`;for(const k in e){const J=`${i}/${st(k)}`,F=ue(k,Ke,n,o,r,s,J,I);F.valid||O.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:I,error:`Property name "${k}" does not match schema.`},...F.errors)}}if(Ae!==void 0){const I=`${a}/dependantRequired`;for(const k in Ae)if(k in e){const J=Ae[k];for(const F of J)F in e||O.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:I,error:`Instance has "${k}" but does not have "${F}".`})}}if(Ge!==void 0)for(const I in Ge){const k=`${a}/dependentSchemas`;if(I in e){const J=ue(e,Ge[I],n,o,r,s,i,`${k}/${st(I)}`,c);J.valid||O.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:k,error:`Instance has "${I}" but does not match dependant schema.`},...J.errors)}}if(ct!==void 0){const I=`${a}/dependencies`;for(const k in ct)if(k in e){const J=ct[k];if(Array.isArray(J))for(const F of J)F in e||O.push({instanceLocation:i,keyword:"dependencies",keywordLocation:I,error:`Instance has "${k}" but does not have "${F}".`});else{const F=ue(e,J,n,o,r,s,i,`${I}/${st(k)}`);F.valid||O.push({instanceLocation:i,keyword:"dependencies",keywordLocation:I,error:`Instance has "${k}" but does not match dependant schema.`},...F.errors)}}}const A=Object.create(null);let W=!1;if(Q!==void 0){const I=`${a}/properties`;for(const k in Q){if(!(k in e))continue;const J=`${i}/${st(k)}`,F=ue(e[k],Q[k],n,o,r,s,J,`${I}/${st(k)}`);if(F.valid)c[k]=A[k]=!0;else if(W=r,O.push({instanceLocation:i,keyword:"properties",keywordLocation:I,error:`Property "${k}" does not match schema.`},...F.errors),W)break}}if(!W&&re!==void 0){const I=`${a}/patternProperties`;for(const k in re){const J=new RegExp(k,"u"),F=re[k];for(const he in e){if(!J.test(he))continue;const Kt=`${i}/${st(he)}`,ht=ue(e[he],F,n,o,r,s,Kt,`${I}/${st(k)}`);ht.valid?c[he]=A[he]=!0:(W=r,O.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:I,error:`Property "${he}" matches pattern "${k}" but does not match associated schema.`},...ht.errors))}}}if(!W&&we!==void 0){const I=`${a}/additionalProperties`;for(const k in e){if(A[k])continue;const J=`${i}/${st(k)}`,F=ue(e[k],we,n,o,r,s,J,I);F.valid?c[k]=!0:(W=r,O.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:I,error:`Property "${k}" does not match additional properties schema.`},...F.errors))}}else if(!W&&Me!==void 0){const I=`${a}/unevaluatedProperties`;for(const k in e)if(!c[k]){const J=`${i}/${st(k)}`,F=ue(e[k],Me,n,o,r,s,J,I);F.valid?c[k]=!0:O.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:I,error:`Property "${k}" does not match unevaluated properties schema.`},...F.errors)}}}else if(u==="array"){nt!==void 0&&e.length>nt&&O.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${nt}).`}),Oe!==void 0&&e.length<Oe&&O.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Oe}).`});const D=e.length;let A=0,W=!1;if(Ue!==void 0){const I=`${a}/prefixItems`,k=Math.min(Ue.length,D);for(;A<k;A++){const J=ue(e[A],Ue[A],n,o,r,s,`${i}/${A}`,`${I}/${A}`);if(c[A]=!0,!J.valid&&(W=r,O.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:I,error:"Items did not match schema."},...J.errors),W))break}}if(ke!==void 0){const I=`${a}/items`;if(Array.isArray(ke)){const k=Math.min(ke.length,D);for(;A<k;A++){const J=ue(e[A],ke[A],n,o,r,s,`${i}/${A}`,`${I}/${A}`);if(c[A]=!0,!J.valid&&(W=r,O.push({instanceLocation:i,keyword:"items",keywordLocation:I,error:"Items did not match schema."},...J.errors),W))break}}else for(;A<D;A++){const k=ue(e[A],ke,n,o,r,s,`${i}/${A}`,I);if(c[A]=!0,!k.valid&&(W=r,O.push({instanceLocation:i,keyword:"items",keywordLocation:I,error:"Items did not match schema."},...k.errors),W))break}if(!W&&_t!==void 0){const k=`${a}/additionalItems`;for(;A<D;A++){const J=ue(e[A],_t,n,o,r,s,`${i}/${A}`,k);c[A]=!0,J.valid||(W=r,O.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:k,error:"Items did not match additional items schema."},...J.errors))}}}if(lt!==void 0)if(D===0&&Re===void 0)O.push({instanceLocation:i,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Re!==void 0&&D<Re)O.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${D}) than minContains (${Re}).`});else{const I=`${a}/contains`,k=O.length;let J=0;for(let F=0;F<D;F++){const he=ue(e[F],lt,n,o,r,s,`${i}/${F}`,I);he.valid?(c[F]=!0,J++):O.push(...he.errors)}J>=(Re||0)&&(O.length=k),Re===void 0&&Ce===void 0&&J===0?O.splice(k,0,{instanceLocation:i,keyword:"contains",keywordLocation:I,error:"Array does not contain item matching schema."}):Re!==void 0&&J<Re?O.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Re} items matching schema. Only ${J} items were found.`}):Ce!==void 0&&J>Ce&&O.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Ce} items matching schema. ${J} items were found.`})}if(!W&&vt!==void 0){const I=`${a}/unevaluatedItems`;for(;A<D;A++){if(c[A])continue;const k=ue(e[A],vt,n,o,r,s,`${i}/${A}`,I);c[A]=!0,k.valid||O.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:I,error:"Items did not match unevaluated items schema."},...k.errors)}}if(Bt)for(let I=0;I<D;I++){const k=e[I],J=typeof k=="object"&&k!==null;for(let F=0;F<D;F++){if(I===F)continue;const he=e[F];(k===he||J&&typeof he=="object"&&he!==null&&Zo(k,he))&&(O.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${I} and ${F}.`}),I=Number.MAX_SAFE_INTEGER,F=Number.MAX_SAFE_INTEGER)}}}else if(u==="number"){if(n==="4"?(Ze!==void 0&&(xe===!0&&e<=Ze||e<Ze)&&O.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${xe?"or equal to ":""} ${Ze}.`}),He!==void 0&&(Ye===!0&&e>=He||e>He)&&O.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Ye?"or equal to ":""} ${He}.`})):(Ze!==void 0&&e<Ze&&O.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Ze}.`}),He!==void 0&&e>He&&O.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${He}.`}),xe!==void 0&&e<=xe&&O.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${xe}.`}),Ye!==void 0&&e>=Ye&&O.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ye}.`})),Xe!==void 0){const D=e%Xe;Math.abs(0-D)>=11920929e-14&&Math.abs(Xe-D)>=11920929e-14&&O.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Xe}.`})}}else if(u==="string"){const D=ut===void 0&&dt===void 0?0:Yw(e);ut!==void 0&&D<ut&&O.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${D} < ${ut}).`}),dt!==void 0&&D>dt&&O.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${D} > ${dt}).`}),kt!==void 0&&!new RegExp(kt,"u").test(e)&&O.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),ne!==void 0&&Uc[ne]&&!Uc[ne](e)&&O.push({instanceLocation:i,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${ne}".`})}return{valid:O.length===0,errors:O}}var Xw=class{constructor(e,t="2019-09",n=!0){T(this,"schema");T(this,"draft");T(this,"shortCircuit");T(this,"lookup");this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=ln(e)}validate(e){return ue(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),ln(e,this.lookup)}},hm=class{constructor(e){T(this,"shortcircuit");T(this,"draft");this.shortcircuit=(e==null?void 0:e.shortcircuit)??!0,this.draft=e==null?void 0:e.draft}_draftFor(e){const t=Av(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){const t=new Xw(e,this.draft??this._draftFor(e),this.shortcircuit);return n=>{const o=t.validate(n);return o.valid?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:o.errors.map(r=>`${r.instanceLocation}: ${r.error}`).join("; ")}}}};const fm=Symbol.for("mcp.completable");function Zc(e){return!!e&&typeof e=="object"&&fm in e}function Qw(e){var t;return(t=e[fm])==null?void 0:t.complete}const eR=15e3,tR=2**31-1;function nR(e,t){var o;if(!Number.isFinite(e)||e<1)return;const n=setInterval(t,Math.min(e,tR));return(o=n.unref)==null||o.call(n),n}let gm;var Yc,oR=(Yc=class{constructor(e){T(this,"onclose");T(this,"onerror");T(this,"onmessage");T(this,"_classification");T(this,"_responseMode");T(this,"_started",!1);T(this,"_used",!1);T(this,"_closed",!1);T(this,"_terminalDelivered",!1);T(this,"_dispatchWindowOpen",!1);T(this,"_requestId");T(this,"_deferredResponse");T(this,"_sse");T(this,"_abortCleanup");T(this,"_keepAliveMs");this._classification=e.classification,this._responseMode=e.responseMode??"auto",this._keepAliveMs=e.keepAliveMs??eR}async start(){if(this._started)throw new Error("PerRequestHTTPServerTransport is already started");this._started=!0}async handleMessage(e,t){var r;if(this._used)throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request");if(!this._started||this.onmessage===void 0)throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message");if(this._closed)throw new Error("PerRequestHTTPServerTransport is closed");this._used=!0;const n=(r=t==null?void 0:t.request)==null?void 0:r.signal;if(n!=null&&n.aborted)throw await this.close(),new K(X.ConnectionClosed,"The request was aborted before it could be handled");const o={classification:this._classification,...(t==null?void 0:t.request)!==void 0&&{request:t.request},...(t==null?void 0:t.authInfo)!==void 0&&{authInfo:t.authInfo}};if(sm(e)){this._requestId=e.id;let s,i;const a=new Promise((c,d)=>{s=c,i=d});if(this._deferredResponse={promise:a,resolve:s,reject:i,settled:!1},n!==void 0){const c=()=>void this.close();n.addEventListener("abort",c,{once:!0}),this._abortCleanup=()=>n.removeEventListener("abort",c)}this._dispatchWindowOpen=!0;try{this.onmessage(e,o)}finally{this._dispatchWindowOpen=!1}return this._responseMode==="sse"&&!this._closed&&!this._deferredResponse.settled&&this.upgradeToSse(),a}return this.onmessage(e,o),new Response(null,{status:202})}async send(e,t){var r;if(this._closed)return;const n=mi(e)||hi(e),o=n?e.id:t==null?void 0:t.relatedRequestId;if(this._requestId===void 0||o===void 0||o!==this._requestId){n&&((r=this.onerror)==null||r.call(this,new Error(`Received a response for an unknown request id: ${String(e.id)}`)));return}if(n){if(this._terminalDelivered)return;this._terminalDelivered=!0;const s=hi(e)?e.error.code:void 0,i=s!==void 0&&(this._dispatchWindowOpen||s===P.MissingRequiredClientCapability)?Ab[s]:void 0;if(i!==void 0&&this._sse===void 0){this.settleResponse(Response.json(e,{status:i,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>void this.close());return}if(this._sse!==void 0||this._responseMode==="sse"){this._sse===void 0&&this.upgradeToSse(),this.writeMessageFrame(e),this.finalizeStream();return}this.settleResponse(Response.json(e,{status:200,headers:{"Content-Type":"application/json"}})),queueMicrotask(()=>void this.close());return}this._responseMode!=="json"&&(this._sse===void 0&&this.upgradeToSse(),this.writeMessageFrame(e))}writeCommentFrame(e){if(this._closed||this._sse===void 0||this._sse.closed)return;const t=e.split(`
|
|
68
|
+
`).map(n=>`: ${n}`).join(`
|
|
69
|
+
`);this.writeFrame(`${t}
|
|
70
|
+
|
|
71
|
+
`)}async close(){var e,t,n;if(!this._closed){if(this._closed=!0,(e=this._abortCleanup)==null||e.call(this),this._abortCleanup=void 0,((t=this._sse)==null?void 0:t.keepAliveTimer)!==void 0&&clearInterval(this._sse.keepAliveTimer),this._sse!==void 0&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}this._deferredResponse!==void 0&&!this._deferredResponse.settled&&(this._deferredResponse.settled=!0,this._deferredResponse.reject(new K(X.ConnectionClosed,"Connection closed before a response was produced"))),(n=this.onclose)==null||n.call(this)}}settleResponse(e){this._deferredResponse===void 0||this._deferredResponse.settled||(this._deferredResponse.settled=!0,this._deferredResponse.resolve(e))}upgradeToSse(){let e;const t=new ReadableStream({start:n=>{e=n},cancel:()=>{this.close()}});this._sse={controller:e,encoder:new TextEncoder,closed:!1},this._sse.keepAliveTimer=nR(this._keepAliveMs,()=>this.writeCommentFrame("keepalive")),this.settleResponse(new Response(t,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}))}finalizeStream(){var e;if(((e=this._sse)==null?void 0:e.keepAliveTimer)!==void 0&&clearInterval(this._sse.keepAliveTimer),this._sse!==void 0&&!this._sse.closed){this._sse.closed=!0;try{this._sse.controller.close()}catch{}}queueMicrotask(()=>void this.close())}writeMessageFrame(e){this.writeFrame(`event: message
|
|
72
|
+
data: ${JSON.stringify(e)}
|
|
73
|
+
|
|
74
|
+
`)}writeFrame(e){var t;if(!(this._sse===void 0||this._sse.closed))try{this._sse.controller.enqueue(this._sse.encoder.encode(e))}catch(n){(t=this.onerror)==null||t.call(this,new Error(`Failed to write to the response stream: ${n}`))}}},gm=e=>e._classification,Yc);function rR(e){return e instanceof oR?gm(e):void 0}function sR(e){return typeof e=="object"&&e!==null&&"setScopeChallengeResolver"in e&&typeof e.setScopeChallengeResolver=="function"}const iR=8,aR=6e5;function cR(e){if((e==null?void 0:e.maxRounds)!==void 0&&(!Number.isInteger(e.maxRounds)||e.maxRounds<1))throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${e.maxRounds})`);if((e==null?void 0:e.roundTimeoutMs)!==void 0&&(!Number.isFinite(e.roundTimeoutMs)||e.roundTimeoutMs<=0))throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${e.roundTimeoutMs})`);return{maxRounds:(e==null?void 0:e.maxRounds)??iR,roundTimeoutMs:(e==null?void 0:e.roundTimeoutMs)??aR,legacyShim:(e==null?void 0:e.legacyShim)??!0}}function Sm(e,t,n){if(n===null||typeof n!="object"||typeof n.method!="string")throw new Z(P.InternalError,`Handler for ${e} returned an invalid input request '${t}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);const o=n,r=zv(o);if(r===void 0)throw new Z(P.InternalError,`Handler for ${e} returned an input request '${t}' of kind '${o.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:o,required:r}}function lR(){const e=globalThis.crypto;if((e==null?void 0:e.randomUUID)!==void 0)return e.randomUUID();const t=new Uint8Array(16);e.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;const n=[...t].map(o=>o.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function Hs(e,t){if(e==="tools/call")return{content:[{type:"text",text:t}],isError:!0};throw new Z(P.InternalError,t)}var uR=class{constructor(e){this._host=e}async fulfill(e,t,n,o,r){const{maxRounds:s,roundTimeoutMs:i}=this._host,a=o.mcpReq.signal;let c=r,d=0;for(;;){if(d+=1,d>s)return Hs(e,ew(e,s));const u=c.inputRequests,p=u!=null&&Object.keys(u).length>0,m=typeof c.requestState=="string"?c.requestState:void 0;if(!p&&m===void 0)throw new Z(P.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let h;if(p){const S=this._host.resolvedClientCapabilities(o),b=[];for(const[M,L]of Object.entries(u)){const{embedded:te,required:oe}=Sm(e,M,L);if(te.method!=="roots/list"&&te.params===void 0)throw new Z(P.InternalError,`Handler for ${e} returned an input request '${M}' of kind '${te.method}' without params`);if(Dp(oe,S)!==void 0)return Hs(e,`Cannot request input '${M}' (${te.method}): the client on this 2025-era connection did not declare the required capability${S===void 0?" (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)":""}`);b.push([M,te])}const R=nw(a);try{const M={relatedRequestId:o.mcpReq.id,timeout:i,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:R.signal},L=await Promise.all(b.map(async([te,oe])=>{try{return[te,await this._dispatchLeg(oe,M)]}catch(Y){throw R.abort(Y),Y}}));h=Object.fromEntries(L)}catch(M){if(a.aborted)throw M;return Hs(e,`Fulfilling input required by '${e}' failed: ${M instanceof Error?M.message:String(M)}`)}finally{R.dispose()}}else await tw(Qb,a);let f={...o,mcpReq:{...o.mcpReq,inputResponses:h,droppedInputResponseKeys:void 0,requestState:bs(m)}};if(m!==void 0){const S=await this._host.verifyRequestState(m,f,e);S!==void 0&&(f=um(f,S))}const _=await t(n,f);if(!jt(_))return _;c=_}}async _dispatchLeg(e,t){switch(e.method){case"elicitation/create":{let n=e.params;return n.mode==="url"&&n.elicitationId===void 0&&(n={...n,elicitationId:lR()}),await this._host.sendElicitation(n,t)}case"sampling/createMessage":return await this._host.sendSampling(e.params,t);case"roots/list":return await this._host.listRoots(e.params,t)}}};const dR=new Set(["tools/call","prompts/get","resources/read"]);var pR=class extends uw{constructor(t,n){var o;super(n);T(this,"_clientCapabilities");T(this,"_clientVersion");T(this,"_capabilities");T(this,"_instructions");T(this,"_jsonSchemaValidator");T(this,"_cacheHints");T(this,"_requestStateVerify");T(this,"_inputRequiredServing");T(this,"_legacyShim");T(this,"_boundFromTransport",!1);T(this,"oninitialized");T(this,"_loggingLevels",new Map);T(this,"LOG_LEVEL_SEVERITY",new Map(Wo.options.map((t,n)=>[t,n])));T(this,"isMessageIgnored",(t,n)=>{const o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(t)<this.LOG_LEVEL_SEVERITY.get(o):!1});if(this._serverInfo=t,this._capabilities=n!=null&&n.capabilities?{...n.capabilities}:{},this._instructions=n==null?void 0:n.instructions,this._jsonSchemaValidator=(n==null?void 0:n.jsonSchemaValidator)??new hm,this._requestStateVerify=(o=n==null?void 0:n.requestState)==null?void 0:o.verify,this._inputRequiredServing=cR(n==null?void 0:n.inputRequired),(n==null?void 0:n.cacheHints)!==void 0){for(const[r,s]of Object.entries(n.cacheHints))s!==void 0&&Kp(s,`cacheHints['${r}']`);this._cacheHints=n.cacheHints}this.setRequestHandler("initialize",r=>this._oninitialize(r)),this.setNotificationHandler("notifications/initialized",()=>{var r;return(r=this.oninitialized)==null?void 0:r.call(this)}),zs(this._supportedProtocolVersions).length>0&&this.setRequestHandler("server/discover",()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}_legacyInputRequiredShim(){return this._legacyShim??(this._legacyShim=new uR({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:t=>this._inputRequestCapabilityView(t),verifyRequestState:(t,n,o)=>this._verifyRequestState(t,n,o),sendElicitation:(t,n)=>this._sendElicitationLeg(t,n,{validateAcceptedContent:!1}),sendSampling:(t,n)=>this.createMessage(t,n),listRoots:(t,n)=>this.listRoots(t,n)}))}async connect(t){var o;if(this.transport!==void 0)throw new K(X.AlreadyConnected,"Use a separate Server instance per connection: this instance is already connected to a transport. To connect it to a new transport, call close() first.");this._boundFromTransport&&(this._boundFromTransport=!1,this._negotiatedProtocolVersion=void 0);const n=(o=rR(t))==null?void 0:o.revision;n!==void 0&&!this._servedModernEra()&&Lv.includes(n)&&zs(this._supportedProtocolVersions).includes(n)&&(this._negotiatedProtocolVersion=n,this._boundFromTransport=!0),await super.connect(t)}_registerLoggingHandler(){this.setRequestHandler("logging/setLevel",async(t,n)=>{var i,a;const o=n.sessionId||((a=(i=n.http)==null?void 0:i.req)==null?void 0:a.headers.get("mcp-session-id"))||void 0,{level:r}=t.params,s=wa(Wo,r);return s.success&&this._loggingLevels.set(o,s.data),{}})}buildContext(t,n){const o=t.http||(n==null?void 0:n.request)||(n==null?void 0:n.closeSSEStream)||(n==null?void 0:n.closeStandaloneSSEStream);return{...t,mcpReq:{...t.mcpReq,log:(r,s,i)=>{var c;if(!this._capabilities.logging)return Promise.resolve();let a;if(this._servedModernEra()){if(a=(c=t.mcpReq.envelope)==null?void 0:c[cs],a===void 0)return Promise.resolve()}else a=this._loggingLevels.get(t.sessionId)??this._loggingLevels.get(void 0);return a!==void 0&&this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(a)?Promise.resolve():t.mcpReq.notify({method:"notifications/message",params:{level:r,data:s,logger:i}})},elicitInput:(r,s)=>this.elicitInput(r,s),requestSampling:(r,s)=>this.createMessage(r,s)},http:o?{...t.http,req:n==null?void 0:n.request,closeSSE:n==null?void 0:n.closeSSEStream,closeStandaloneSSE:n==null?void 0:n.closeStandaloneSSEStream}:void 0}}registerCapabilities(t){if(this.transport)throw new K(X.AlreadyConnected,"Cannot register capabilities after connecting to transport");const n=!!this._capabilities.logging;this._capabilities=dm(this._capabilities,t),!n&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(t,n){var o;if(t!=="tools/call"){const r=(o=this._cacheHints)==null?void 0:o[t],s=dR.has(t);return r===void 0&&!s?async(i,a)=>{const c=await n(i,a);if(jt(c))throw new Z(P.InternalError,`Handler for ${t} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return c}:async(i,a)=>{const c=s?await this._invokeInputRequiredCapableHandler(t,n,i,a):await n(i,a);if(jt(c)){if(!s)throw new Z(P.InternalError,`Handler for ${t} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return c}return r===void 0?c:pi(c,r)}}return async(r,s)=>{const i=Xo(this._negotiatedProtocolVersion),a=i.validateRequest("tools/call",r);if(!a.ok)throw new Z(a.reason==="not-in-era"?P.InternalError:P.InvalidParams,a.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call request: ${a.message}`);const c=await this._invokeInputRequiredCapableHandler("tools/call",n,r,s);if(jt(c))return c;const d=Fp(c),u=i.validateResult("tools/call",d);if(!u.ok)throw new Z(u.reason==="not-in-era"?P.InternalError:P.InvalidParams,u.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call result: ${u.message}`);return u.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&vs(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(t,n,o,r){const s=this._servedModernEra(),i=r.mcpReq.requestState();if(i!==void 0&&typeof i!="string")throw new Z(P.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"});let a=r;if(typeof i=="string"){const m=await this._verifyRequestState(i,r,t);m!==void 0&&(a=um(r,m))}let c;try{c=await n(o,a)}catch(m){throw m instanceof Z&&m.code===P.UrlElicitationRequired&&s?new Z(P.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):m}if(!jt(c))return c;if(!s){if(!this._inputRequiredServing.legacyShim)throw new Z(P.InternalError,`Handler for ${t} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??ei}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(t,n,o,a,c)}const d=c.inputRequests,u=d!=null&&Object.keys(d).length>0,p=typeof c.requestState=="string";if(!u&&!p)throw new Z(P.InternalError,`Handler for ${t} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(u){const m=this._inputRequestCapabilityView(r);for(const[h,f]of Object.entries(d)){const{embedded:_,required:S}=Sm(t,h,f),b=Dp(S,m);if(b!==void 0)throw new Yp({requiredCapabilities:b},`Cannot request input '${h}' (${_.method}): the request's client capabilities do not declare the required capability`)}}return c}async _verifyRequestState(t,n,o){var r;if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(t,n)}catch(s){throw(r=this.onerror)==null||r.call(this,new Error(`requestState verification rejected ${o}: ${s instanceof Error?s.message:String(s)}`)),new Z(P.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"})}}_inputRequestCapabilityView(t){var n;return this._servedModernEra()?(n=t.mcpReq.envelope)==null?void 0:n[nr]:this._clientCapabilities}_assertPushApiInServedEra(t){if(this._servedModernEra())throw new K(X.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${t}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:t,era:"2026-07-28"})}assertCapabilityForMethod(t){var n,o,r;switch(t){case"sampling/createMessage":if(!((n=this._clientCapabilities)!=null&&n.sampling))throw new K(X.CapabilityNotSupported,`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!((o=this._clientCapabilities)!=null&&o.elicitation))throw new K(X.CapabilityNotSupported,`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!((r=this._clientCapabilities)!=null&&r.roots))throw new K(X.CapabilityNotSupported,`Client does not support listing roots (required for ${t})`);break}}assertNotificationCapability(t){var n,o;switch(t){case"notifications/message":if(!this._capabilities.logging)throw new K(X.CapabilityNotSupported,`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new K(X.CapabilityNotSupported,`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new K(X.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new K(X.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!((o=(n=this._clientCapabilities)==null?void 0:n.elicitation)!=null&&o.url))throw new K(X.CapabilityNotSupported,`Client does not support URL elicitation (required for ${t})`);break}}assertRequestHandlerCapability(t){switch(t){case"completion/complete":if(!this._capabilities.completions)throw new K(X.CapabilityNotSupported,`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new K(X.CapabilityNotSupported,`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new K(X.CapabilityNotSupported,`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new K(X.CapabilityNotSupported,`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new K(X.CapabilityNotSupported,`Server does not support tools (required for ${t})`);break}}async _oninitialize(t){var s,i;const n=t.params.protocolVersion;this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo;const o=jv(this._supportedProtocolVersions),r=o.includes(n)?n:o[0]??ei;return this._negotiatedProtocolVersion=r,(i=(s=this.transport)==null?void 0:s.setProtocolVersion)==null||i.call(s,r),{protocolVersion:r,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:zs(this._supportedProtocolVersions),capabilities:mR(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(t,n){return this._wireCodec().projectCallToolResult(t,n)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra("ping"),this.request({method:"ping"})}async createMessage(t,n){var i,a;if(this._assertPushApiInServedEra("sampling/createMessage"),(t.tools||t.toolChoice)&&!((a=(i=this._clientCapabilities)==null?void 0:i.sampling)!=null&&a.tools))throw new K(X.CapabilityNotSupported,"Client does not support sampling tools capability.");if(t.messages.length>0){const c=t.messages.at(-1),d=Array.isArray(c.content)?c.content:[c.content],u=d.some(f=>f.type==="tool_result"),p=t.messages.length>1?t.messages.at(-2):void 0,m=p?Array.isArray(p.content)?p.content:[p.content]:[],h=m.some(f=>f.type==="tool_use");if(u){if(d.some(f=>f.type!=="tool_result"))throw new Z(P.InvalidParams,"The last message must contain only tool_result content if any is present");if(!h)throw new Z(P.InvalidParams,"tool_result blocks are not matching any tool_use from the previous message")}if(h){const f=new Set(m.filter(S=>S.type==="tool_use").map(S=>S.id)),_=new Set(d.filter(S=>S.type==="tool_result").map(S=>S.toolUseId));if(f.size!==_.size||![...f].every(S=>_.has(S)))throw new Z(P.InvalidParams,"ids of tool_result blocks and tool_use blocks from previous message do not match")}}const o=!!(t.tools||t.toolChoice),r=await this.request({method:"sampling/createMessage",params:t},n),s=this._wireCodec().samplingResultVariant(o,r);if(!s.ok)throw new K(X.InvalidResult,`Invalid sampling/createMessage result: ${s.reason==="invalid"?s.message:s.reason}`);return s.value}async elicitInput(t,n){var o,r,s,i;switch(this._assertPushApiInServedEra("elicitation/create"),t.mode??"form"){case"url":if(!((r=(o=this._clientCapabilities)==null?void 0:o.elicitation)!=null&&r.url))throw new K(X.CapabilityNotSupported,"Client does not support url elicitation.");break;case"form":if(!((i=(s=this._clientCapabilities)==null?void 0:s.elicitation)!=null&&i.form))throw new K(X.CapabilityNotSupported,"Client does not support form elicitation.");break}return this._sendElicitationLeg(t,n)}async _sendElicitationLeg(t,n,o){const r=t.mode??"form",s=(o==null?void 0:o.validateAcceptedContent)??!0;switch(r){case"url":{const i=t;return this.request({method:"elicitation/create",params:i},n)}case"form":{const i=t.mode==="form"?t:{...t,mode:"form"},a=await this.request({method:"elicitation/create",params:i},n);if(s&&a.action==="accept"&&a.content&&i.requestedSchema)try{const c=this._jsonSchemaValidator.getValidator(i.requestedSchema)(a.content);if(!c.valid)throw new Z(P.InvalidParams,`Elicitation response content does not match requested schema: ${c.errorMessage}`)}catch(c){throw c instanceof Z?c:new Z(P.InternalError,`Error validating elicitation response: ${c instanceof Error?c.message:String(c)}`)}return a}}}createElicitationCompletionNotifier(t,n){var o,r;if(!((r=(o=this._clientCapabilities)==null?void 0:o.elicitation)!=null&&r.url))throw new K(X.CapabilityNotSupported,"Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},n)}async listRoots(t,n){return this._assertPushApiInServedEra("roots/list"),this.request({method:"roots/list",params:t},n)}async sendLoggingMessage(t,n){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,n))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};function mR(e){return{...e}}function hR(e,t){let n=0;const o=[e];for(;o.length>0;){const r=o.pop();if(!(r===null||typeof r!="object"))if(Array.isArray(r))for(const s of r){if(++n>t)return n;s!==null&&typeof s=="object"&&o.push(s)}else for(const s in r){if(!Object.prototype.hasOwnProperty.call(r,s))continue;if(++n>t)return n;const i=r[s];i!==null&&typeof i=="object"&&o.push(i)}}return n}function fR(e){if(!(e===void 0||e===1/0)){if(typeof e!="number"||Number.isNaN(e)||e<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}var gR=class{constructor(e,t){T(this,"server");T(this,"_maxToolInputElements");T(this,"_registeredResources",{});T(this,"_registeredResourceTemplates",{});T(this,"_registeredTools",{});T(this,"_registeredPrompts",{});T(this,"_toolInputSchemaJson",{});T(this,"resolveScopeChallenge",e=>{var t,n,o,r,s,i,a;switch(e.request.method){case"tools/call":{const c=(t=e.request.params)==null?void 0:t.name;if(typeof c!="string")return;const d=this._registeredTools[c];return d===void 0||!d.enabled||(n=d.scopeChallenge)==null?void 0:n.call(d,e)}case"resources/read":{const c=(o=e.request.params)==null?void 0:o.uri;if(typeof c!="string")return;let d;try{d=new URL(c)}catch{return}const u=this._registeredResources[d.toString()];if(u!==void 0)return u.enabled?(r=u.scopeChallenge)==null?void 0:r.call(u,e):void 0;for(const p of Object.values(this._registeredResourceTemplates))if(p.resourceTemplate.uriTemplate.match(d.toString()))return p.enabled?(s=p.scopeChallenge)==null?void 0:s.call(p,e):void 0;return}case"prompts/get":{const c=(i=e.request.params)==null?void 0:i.name;if(typeof c!="string")return;const d=this._registeredPrompts[c];return d===void 0||!d.enabled||(a=d.scopeChallenge)==null?void 0:a.call(d,e)}default:return}});T(this,"_toolHandlersInitialized",!1);T(this,"_completionHandlerInitialized",!1);T(this,"_resourceHandlersInitialized",!1);T(this,"_promptHandlersInitialized",!1);var n,o,r;this.server=new pR(e,t),this._maxToolInputElements=fR(t==null?void 0:t.maxToolInputElements),(n=t==null?void 0:t.capabilities)!=null&&n.tools&&this.setToolRequestHandlers(),(o=t==null?void 0:t.capabilities)!=null&&o.resources&&this.setResourceRequestHandlers(),(r=t==null?void 0:t.capabilities)!=null&&r.prompts&&this.setPromptRequestHandlers()}toolInputSchemaJson(e){const t=this._registeredTools[e];if(!(t===void 0||!t.enabled)){if(Object.hasOwn(this._toolInputSchemaJson,e))return this._toolInputSchemaJson[e];if(t.inputSchema===void 0)return Fc;try{const n=Bn(t.inputSchema,"input");return this._toolInputSchemaJson[e]=n,n}catch{return}}}async connect(e){return sR(e)&&e.setScopeChallengeResolver(t=>this.resolveScopeChallenge(t)),await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){var e;this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler("tools/list"),this.server.assertCanSetRequestHandler("tools/call"),this.server.registerCapabilities({tools:{listChanged:((e=this.server.getCapabilities().tools)==null?void 0:e.listChanged)??!0}}),this.server.setRequestHandler("tools/list",()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,n])=>{const o={name:t,title:n.title,description:n.description,inputSchema:n.inputSchema?yR(t,n.inputSchema):Fc,annotations:n.annotations,icons:n.icons,execution:n.execution,_meta:n._meta};return n.outputSchema&&(o.outputSchema=Bn(n.outputSchema,"output")),o})})),this.server.setRequestHandler("tools/call",async(t,n)=>{const o=this._registeredTools[t.params.name];if(!o)throw new Z(P.InvalidParams,`Tool ${t.params.name} not found`);if(!o.enabled)throw new Z(P.InvalidParams,`Tool ${t.params.name} disabled`);try{const r=await this.validateToolInput(o,t.params.arguments,t.params.name),s=await this.executeToolHandler(o,r,n);return await this.validateToolOutput(o,s,t.params.name),jt(s)?s:this.server.projectCallToolResult(s,o.outputSchemaJson)}catch(r){if(r instanceof Z&&r.code===P.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,n){if(this._maxToolInputElements!==void 0&&hR(t,this._maxToolInputElements)>this._maxToolInputElements)throw new Z(P.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;const o=await Mn(e.inputSchema,t??{});if(!o.success)throw new Z(P.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${o.error}`);return o.data}async validateToolOutput(e,t,n){if(!e.outputSchema||jt(t)||t.isError)return;if(t.structuredContent===void 0)throw new Z(P.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const o=await Mn(e.outputSchema,t.structuredContent);if(!o.success)throw new Z(P.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${o.error}`)}async executeToolHandler(e,t,n){return e.executor(t,n)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler("completion/complete"),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler("completion/complete",async e=>{switch(e.params.ref.type){case"ref/prompt":return kb(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Cb(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Z(P.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){var s;const n=this._registeredPrompts[t.name];if(!n)throw new Z(P.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Z(P.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return No;const o=Kc((s=Wc(n.argsSchema))==null?void 0:s[e.params.argument.name]);if(!Zc(o))return No;const r=Qw(o);return r?Bc(await r(e.params.argument.value,e.params.context)):No}async handleResourceCompletion(e,t){const n=Object.values(this._registeredResourceTemplates).find(r=>r.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return No;throw new Z(P.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const o=n.resourceTemplate.completeCallback(e.params.argument.name);return o?Bc(await o(e.params.argument.value,e.params.context)):No}setResourceRequestHandlers(){var e;this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler("resources/list"),this.server.assertCanSetRequestHandler("resources/templates/list"),this.server.assertCanSetRequestHandler("resources/read"),this.server.registerCapabilities({resources:{listChanged:((e=this.server.getCapabilities().resources)==null?void 0:e.listChanged)??!0}}),this.server.setRequestHandler("resources/list",async(t,n)=>{const o=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),r=[];for(const s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;const i=await s.resourceTemplate.listCallback(n);for(const a of i.resources)r.push({...s.metadata,...a})}return{resources:[...o,...r]}}),this.server.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,n])=>({name:t,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler("resources/read",async(t,n)=>{let o;try{o=new URL(t.params.uri)}catch{throw new Z(P.InvalidParams,`Resource URI ${t.params.uri} is invalid`,{uri:t.params.uri,reason:"invalid_uri"})}const r=this._registeredResources[o.toString()];if(r){if(!r.enabled)throw new Z(P.InvalidParams,`Resource ${o} disabled`);return pi(await r.readCallback(o,n),r.cacheHint)}for(const s of Object.values(this._registeredResourceTemplates)){const i=s.resourceTemplate.uriTemplate.match(o.toString());if(i){if(!s.enabled)throw new Z(P.InvalidParams,`Resource template ${s.resourceTemplate.uriTemplate} disabled`);return pi(await s.readCallback(o,i,n),s.cacheHint)}}throw new Gp(t.params.uri)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){var e;this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler("prompts/list"),this.server.assertCanSetRequestHandler("prompts/get"),this.server.registerCapabilities({prompts:{listChanged:((e=this.server.getCapabilities().prompts)==null?void 0:e.listChanged)??!0}}),this.server.setRequestHandler("prompts/list",()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,n])=>({name:t,title:n.title,description:n.description,arguments:n.argsSchema?Hb(n.argsSchema):void 0,icons:n.icons,_meta:n._meta}))})),this.server.setRequestHandler("prompts/get",async(t,n)=>{const o=this._registeredPrompts[t.params.name];if(!o)throw new Z(P.InvalidParams,`Prompt ${t.params.name} not found`);if(!o.enabled)throw new Z(P.InvalidParams,`Prompt ${t.params.name} disabled`);return o.handler(t.params.arguments,n)}),this._promptHandlersInitialized=!0)}registerResource(e,t,n,o){const{cacheHint:r,scopeChallenge:s,...i}=n,a=i;if(r!==void 0&&Kp(r,`resource ${e}`),typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const c=this._createRegisteredResource(e,n.title,t,a,s,o);return r!==void 0&&(c.cacheHint=r),this.setResourceRequestHandlers(),this.sendResourceListChanged(),c}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const c=this._createRegisteredResourceTemplate(e,n.title,t,a,s,o);return r!==void 0&&(c.cacheHint=r),this.setResourceRequestHandlers(),this.sendResourceListChanged(),c}}_createRegisteredResource(e,t,n,o,r,s){const i={name:e,title:t,metadata:o,readCallback:s,scopeChallenge:r,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{a.uri!==void 0&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),a.name!==void 0&&(i.name=a.name),a.metadata!==void 0&&(i.metadata=a.metadata),a.title!==void 0&&(i.title=a.title,i.metadata={...i.metadata,title:a.title}),a.callback!==void 0&&(i.readCallback=a.callback),a.scopeChallenge!==void 0&&(i.scopeChallenge=a.scopeChallenge===null?void 0:a.scopeChallenge),a.enabled!==void 0&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,t,n,o,r,s){const i={resourceTemplate:n,title:t,metadata:o,readCallback:s,scopeChallenge:r,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:c=>{c.name!==void 0&&c.name!==e&&(delete this._registeredResourceTemplates[e],c.name&&(this._registeredResourceTemplates[c.name]=i)),c.template!==void 0&&(i.resourceTemplate=c.template),c.metadata!==void 0&&(i.metadata=c.metadata),c.title!==void 0&&(i.title=c.title,i.metadata={...i.metadata,title:c.title}),c.callback!==void 0&&(i.readCallback=c.callback),c.scopeChallenge!==void 0&&(i.scopeChallenge=c.scopeChallenge===null?void 0:c.scopeChallenge),c.enabled!==void 0&&(i.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;const a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(c=>!!n.completeCallback(c))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,t,n,o,r,s,i,a){let c=o,d=r;const u={title:t,description:n,argsSchema:o,icons:s,scopeChallenge:i,_meta:a,handler:Jc(e,o,r),enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:p=>{p.name!==void 0&&p.name!==e&&(delete this._registeredPrompts[e],p.name&&(this._registeredPrompts[p.name]=u)),p.title!==void 0&&(u.title=p.title),p.description!==void 0&&(u.description=p.description),p.icons!==void 0&&(u.icons=p.icons),p.scopeChallenge!==void 0&&(u.scopeChallenge=p.scopeChallenge===null?void 0:p.scopeChallenge),p._meta!==void 0&&(u._meta=p._meta);let m=!1;p.argsSchema!==void 0&&(u.argsSchema=p.argsSchema,c=p.argsSchema,m=!0),p.callback!==void 0&&(d=p.callback,m=!0),m&&(u.handler=Jc(e,c,d)),p.enabled!==void 0&&(u.enabled=p.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=u,o){const p=Wc(o);p&&Object.values(p).some(m=>Zc(Kc(m)))&&this.setCompletionRequestHandler()}return u}_createRegisteredTool(e,t,n,o,r,s,i,a,c,d,u){Lc(e);let p=u,m;const h={title:t,description:n,inputSchema:o,outputSchema:r,get outputSchemaJson(){return m??(m=Vc(h.outputSchema))},set outputSchemaJson(f){m=f},annotations:s,icons:i,execution:a,scopeChallenge:c,_meta:d,handler:u,executor:Hc(o,u),enabled:!0,disable:()=>h.update({enabled:!1}),enable:()=>h.update({enabled:!0}),remove:()=>h.update({name:null}),update:f=>{f.name!==void 0&&f.name!==e&&(typeof f.name=="string"&&Lc(f.name),delete this._registeredTools[e],delete this._toolInputSchemaJson[e],f.name&&(delete this._toolInputSchemaJson[f.name],this._registeredTools[f.name]=h,e=f.name)),f.title!==void 0&&(h.title=f.title),f.description!==void 0&&(h.description=f.description);let _=!1;f.paramsSchema!==void 0&&(h.inputSchema=f.paramsSchema,delete this._toolInputSchemaJson[e],_=!0),f.callback!==void 0&&(h.handler=f.callback,p=f.callback,_=!0),_&&(h.executor=Hc(h.inputSchema,p)),f.outputSchema!==void 0&&(h.outputSchema=f.outputSchema,h.outputSchemaJson=Vc(f.outputSchema)),f.annotations!==void 0&&(h.annotations=f.annotations),f.icons!==void 0&&(h.icons=f.icons),f.scopeChallenge!==void 0&&(h.scopeChallenge=f.scopeChallenge===null?void 0:f.scopeChallenge),f._meta!==void 0&&(h._meta=f._meta),f.enabled!==void 0&&(h.enabled=f.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=h,this.setToolRequestHandlers(),this.sendToolListChanged(),h}registerTool(e,t,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:o,description:r,inputSchema:s,outputSchema:i,annotations:a,icons:c,scopeChallenge:d,_meta:u}=t;return this._createRegisteredTool(e,o,r,Zs(s),Zs(i),a,c,void 0,d,u,n)}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:o,description:r,argsSchema:s,icons:i,scopeChallenge:a,_meta:c}=t,d=this._createRegisteredPrompt(e,o,r,Zs(s),n,i,a,c);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),d}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},SR=class{constructor(e,t){T(this,"_uriTemplate");this._callbacks=t,this._uriTemplate=typeof e=="string"?new yw(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){var t;return(t=this._callbacks.complete)==null?void 0:t[e]}};function Hc(e,t){if(e){const o=t;return async(r,s)=>o(r,s)}const n=t;return async(o,r)=>n(r)}const Fc={type:"object",properties:{}};function yR(e,t){const n=Bn(t,"input"),o=qb(n);return o.valid||console.warn(`[mcp-sdk] tool '${e}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${o.reason}`),n}function Vc(e){if(e!==void 0)try{return Bn(e,"output")}catch{return}}function Jc(e,t,n){if(t){const o=n;return async(r,s)=>{const i=await Mn(t,r??{});if(!i.success)throw new Z(P.InvalidParams,`Invalid arguments for prompt ${e}: ${i.error}`);return o(i.data,s)}}else{const o=n;return async(r,s)=>o(s)}}function Bc(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}const No={completion:{values:[],hasMore:!1}};function Wc(e){const t=e;if(t.shape&&typeof t.shape=="object")return t.shape}function _R(e){return(e==null?void 0:e.type)==="optional"}function Kc(e){var t;return _R(e)?((t=e.def)==null?void 0:t.innerType)??e:e}let vR;function Si(e,t){return ww(e,vR??(vR=new hm))}const bR=li(void 0).inputSchema,yi="__isBrowserMcpServer";function wR(e){return typeof e=="object"&&e!==null&&yi in e&&e[yi]===!0}function RR(e){return"clientOrigin"in e&&(e.clientOrigin===void 0||typeof e.clientOrigin=="string")&&(!("onclientorigin"in e)||e.onclientorigin===void 0||typeof e.onclientorigin=="function")}function TR(e){let t;try{t=JSON.parse(e)}catch{t=e}return Ee(t)?t:{content:[{type:"text",text:typeof t=="string"?t:e}]}}function $R(e,t){return new Promise((n,o)=>{t.throwIfAborted();const r=()=>o(t.reason);t.addEventListener("abort",r,{once:!0}),Promise.resolve().then(e).then(n,o).finally(()=>t.removeEventListener("abort",r))})}function ER(e){return vv(e.inputSchema)?e.inputSchema:Si(e.inputSchema)}var Xc,Qc,PR=class extends(Qc=EventTarget,Xc=yi,Qc){constructor(t,n={}){var s,i,a,c,d;super();T(this,Xc,!0);T(this,"mcpServer");T(this,"native");T(this,"ownerDocument");T(this,"tools",new Map);T(this,"peerOrigin");T(this,"stopObservingPeerOrigin");T(this,"registrations",new Set);T(this,"nativeToolAbortControllers",new Map);T(this,"nativeBackfilledTools",new Map);T(this,"pendingTools",new Map);T(this,"removingNativeTools",new Set);T(this,"nativeSyncQueue",Promise.resolve());T(this,"nativeToolChangeQueue",Promise.resolve());T(this,"nativeToolChangeListener");T(this,"closed",!1);T(this,"closePromise");T(this,"eventHandlers",new Map);T(this,"eventHandlerListener",t=>{var n;(n=this.eventHandlers.get(t.type))==null||n.call(this,t)});T(this,"nativeLifecycleListener",t=>{if(this.closed)return;const n=new Event(t.type);"toolName"in t&&Object.defineProperty(n,"toolName",{enumerable:!0,value:t.toolName}),this.dispatchEvent(n)});T(this,"registerTool",async(t,n={})=>{var f,_,S,b,R,M,L,te,oe,Y;const{signal:o,exposedTo:r}=n??{},s={};if(o&&(s.signal=o),r&&(s.exposedTo=[...r]),this.closed)throw Ne("BrowserMcpServer is closed");if(!Ee(t))throw new TypeError("registerTool(tool) requires a tool object");const i=dv(t);if(this.tools.has(i.name)&&!this.nativeBackfilledTools.has(i.name)||this.pendingTools.has(i.name))throw Ne(`Tool already registered: ${i.name}`);const a=li(i.inputSchema);(f=s.signal)==null||f.throwIfAborted();const c=i.execute,d=(H,ne)=>$R(()=>c(H,ne),ne.signal),u=new AbortController,p=(_=s.exposedTo)==null?void 0:_.map(H=>{var ne;return((ne=URL.parse(H))==null?void 0:ne.origin)??H});let m;const h=()=>{var H;this.pendingTools.get(i.name)===u&&this.pendingTools.delete(i.name),m&&this.tools.get(i.name)===m?this.removeTool(i.name):((H=m==null?void 0:m.mcpHandle)==null||H.remove(),this.abortNativeToolMirror(i.name,u)),m=void 0};(S=s.signal)==null||S.addEventListener("abort",h,{once:!0}),this.pendingTools.set(i.name,u);try{if(this.nativeBackfilledTools.has(i.name)||(m=this.registerToolInMcp(i,a,d,p)),(b=s.signal)==null||b.throwIfAborted(),await this.registerNativeToolMirror(i,a,s,d,u),this.closed)throw Ne("BrowserMcpServer is closed");(R=s.signal)==null||R.throwIfAborted(),this.removeTool(i.name,{skipNative:!0}),m??(m=this.registerToolInMcp(i,a,d,p)),this.tools.set(i.name,m),this.applyToolExposure(),(M=s.signal)!=null&&M.aborted&&(h(),s.signal.throwIfAborted())}catch(H){throw(L=m==null?void 0:m.mcpHandle)==null||L.remove(),this.abortNativeToolMirror(i.name,u),(te=s.signal)==null||te.removeEventListener("abort",h),(oe=s.signal)==null||oe.throwIfAborted(),H}finally{this.pendingTools.get(i.name)===u&&this.pendingTools.delete(i.name)}if(s.signal&&(m.abortSignal=s.signal,m.abortListener=h),this.tools.get(i.name)===m&&await this.nativeToolChangeQueue,this.closed)throw Ne("BrowserMcpServer is closed");(Y=s.signal)==null||Y.throwIfAborted()});const{native:o,...r}=n;!o&&!((s=globalThis.document)!=null&&s.modelContext)&&zp(),this.mcpServer=new gR(t,{...r,capabilities:dm(r.capabilities??{},{tools:{listChanged:!0},resources:{listChanged:!0},prompts:{listChanged:!0}})}),this.native=o??((i=globalThis.document)==null?void 0:i.modelContext),this.ownerDocument=globalThis.document??null,this.nativeToolChangeListener=()=>{this.closed||(this.nativeToolChangeQueue=this.nativeToolChangeQueue.then(async()=>{try{await this.syncNativeTools()}catch(u){console.warn("[BrowserMcpServer] Native WebMCP tool reconciliation failed:",u)}await this.notifyProducerToolsChanged()}))},(a=this.native)==null||a.addEventListener("toolchange",this.nativeToolChangeListener),(c=this.native)==null||c.addEventListener("toolactivated",this.nativeLifecycleListener),(d=this.native)==null||d.addEventListener("toolcancel",this.nativeLifecycleListener)}getEventHandler(t){return this.eventHandlers.get(t)??null}setEventHandler(t,n){typeof n=="function"?(this.eventHandlers.has(t)||super.addEventListener(t,this.eventHandlerListener),this.eventHandlers.set(t,n)):this.eventHandlers.delete(t)&&super.removeEventListener(t,this.eventHandlerListener)}get ontoolchange(){return this.getEventHandler("toolchange")}set ontoolchange(t){this.setEventHandler("toolchange",t)}get ontoolactivated(){return this.getEventHandler("toolactivated")}set ontoolactivated(t){this.setEventHandler("toolactivated",t)}get ontoolcancel(){return this.getEventHandler("toolcancel")}set ontoolcancel(t){this.setEventHandler("toolcancel",t)}async notifyProducerToolsChanged(){this.closed||(await new Promise(t=>setTimeout(t,0)),this.closed||this.dispatchEvent(new Event("toolchange")))}async registerNativeToolMirror(t,n,o,r,s){const i=this.native;if(!i)return;const a=o.signal?AbortSignal.any([o.signal,s.signal]):s.signal,c={name:t.name,description:t.description,execute:r};if(t.title!==void 0&&(c.title=t.title),n.registeredInputSchema!==void 0){const d=JSON.parse(n.registeredInputSchema);if(!Ee(d))throw new TypeError("inputSchema must be an object");c.inputSchema=d}t.annotations&&(c.annotations=t.annotations),this.nativeToolAbortControllers.set(t.name,s);try{await i.registerTool(c,{...o,signal:a})}catch(d){if(s.abort(),this.nativeToolAbortControllers.get(t.name)===s&&this.nativeToolAbortControllers.delete(t.name),d instanceof DOMException&&d.name==="NotAllowedError"){console.warn(`[BrowserMcpServer] Tool "${t.name}" is available over MCP only: ${d.message}. Grant allow="tools" on the iframe to expose it to WebMCP.`);return}throw d}this.nativeToolAbortControllers.get(t.name)===s&&this.removingNativeTools.delete(t.name)}abortNativeToolMirror(t,n=this.nativeToolAbortControllers.get(t)){!n||this.nativeToolAbortControllers.get(t)!==n||(this.removingNativeTools.add(t),n.abort(),this.nativeToolAbortControllers.delete(t))}registerToolInMcp(t,n,o,r){const s={name:t.name,description:t.description,inputSchema:n.inputSchema};t.title!==void 0&&(s.title=t.title),t.outputSchema!==void 0&&(s.outputSchema=structuredClone(t.outputSchema)),t.annotations&&(s.annotations=t.annotations);const i={description:t.description};if(s.outputSchema!==void 0&&(i.outputSchema=Si(s.outputSchema)),t.title!==void 0&&(i.title=t.title),t.annotations){const{untrustedContentHint:d,...u}=t.annotations;i.annotations=u}let a;n.inputSchema.type===void 0||n.inputSchema.type==="object"?(i.inputSchema=ER(n),a=this.mcpServer.registerTool(t.name,i,async(d,u)=>{const p=await o(d,{signal:u.mcpReq.signal});if(jt(p))throw new Error(`WebMCP tool "${t.name}" returned input_required. Multi-round tool flows require BrowserMcpServer.mcpServer.registerTool().`);return yv(p)}),a.disable()):console.warn(`[BrowserMcpServer] Tool "${t.name}" remains available through WebMCP but cannot be exposed over MCP because MCP input schemas require an object root.`);const c={item:s,mcpHandle:a};return r!=null&&r.length&&(c.exposedTo=r),c}removeTool(t,n){var r;const o=this.tools.get(t);o&&(o.abortSignal&&o.abortListener&&o.abortSignal.removeEventListener("abort",o.abortListener),this.tools.delete(t),this.nativeBackfilledTools.delete(t),(r=o.mcpHandle)==null||r.remove()),n!=null&&n.skipNative||this.abortNativeToolMirror(t)}syncNativeTools(){const t=this.native,n=this.nativeSyncQueue.then(async()=>{this.closed||!t||await this.backfillNativeStandardTools(t)});return this.nativeSyncQueue=n.then(()=>{},()=>{}),n}async backfillNativeStandardTools(t){var s;const n=(s=this.ownerDocument)==null?void 0:s.defaultView,o=(await t.getTools()).filter(i=>{if(i.window===n)return!0;if((n==null?void 0:n.parent)!==n)return!1;let a=i.window;for(;a;){if(a===n)return!0;const c=a.parent;if(c===a)break;a=c}return!1});if(this.closed)return;for(const i of this.removingNativeTools)o.some(a=>a.name===i&&a.window===n)||this.removingNativeTools.delete(i);const r=new Map;for(const i of o){if(r.has(i.name)||this.pendingTools.has(i.name)||this.removingNativeTools.has(i.name))continue;let a;try{a=JSON.parse(Qr(i.inputSchema??bR))}catch{}if(!Ee(a)){console.warn(`[BrowserMcpServer] Native tool "${i.name}" was not exposed over MCP because its input schema is malformed.`);continue}const c={name:i.name,description:i.description,inputSchema:a};i.title!==void 0&&(c.title=i.title),i.annotations&&(c.annotations=i.annotations),r.set(i.name,{source:i,item:c,fingerprint:JSON.stringify(c)})}for(const[i,a]of this.nativeBackfilledTools){const c=r.get(i);(c==null?void 0:c.fingerprint)===a.fingerprint?this.nativeBackfilledTools.set(i,c):this.removeTool(i,{skipNative:!0})}for(const[i,a]of r){if(this.tools.has(i))continue;const c=async(u,p)=>{var h;const m=(h=this.nativeBackfilledTools.get(i))==null?void 0:h.source;if(!m)throw new Error(`Native tool not found: ${i}`);try{return TR(await t.executeTool(m,u,p))}catch(f){throw m.window.closed&&this.nativeToolChangeListener(),f}},d={...a.item,execute:c};try{const u=li(d.inputSchema);this.tools.set(i,this.registerToolInMcp(d,u,c)),this.nativeBackfilledTools.set(i,a)}catch(u){console.warn(`[BrowserMcpServer] Native tool "${i}" was not exposed over MCP because its schema could not be compiled:`,u)}}this.applyToolExposure()}registerResource(t){if(this.closed)throw Ne("BrowserMcpServer is closed");const n={...t},o={};n.description!==void 0&&(o.description=n.description),n.mimeType!==void 0&&(o.mimeType=n.mimeType);const r=n.uri.includes("{")?new SR(n.uri,{list:void 0}):void 0,s=r?this.mcpServer.registerResource(n.name,r,o,async(i,a)=>n.read(i,a)):this.mcpServer.registerResource(n.name,n.uri,o,async i=>n.read(i));return this.registrations.add(s),{unregister:()=>{this.registrations.delete(s)&&s.remove()}}}registerPrompt(t){if(this.closed)throw Ne("BrowserMcpServer is closed");const n={...t};t.argsSchema!==void 0&&(n.argsSchema=structuredClone(t.argsSchema));const o=n.argsSchema===void 0?void 0:Si(n.argsSchema),r={};n.description!==void 0&&(r.description=n.description),o&&(r.argsSchema=o);const s=this.mcpServer.registerPrompt(n.name,r,async i=>n.get(i??{}));return this.registrations.add(s),{unregister:()=>{this.registrations.delete(s)&&s.remove()}}}listTools(){return structuredClone([...this.tools.values()].map(({item:t})=>t))}async getTools(t){if(this.closed)throw Ne("BrowserMcpServer is closed");if(!this.native)throw Ne("BrowserMcpServer has no WebMCP context");return this.native.getTools(t)}async executeTool(...t){if(this.closed)throw Ne("BrowserMcpServer is closed");if(!this.native)throw Ne("BrowserMcpServer has no WebMCP context");return this.native.executeTool(...t)}applyToolExposure(){for(const{exposedTo:t,mcpHandle:n}of this.tools.values()){if(!n)continue;const o=!(t!=null&&t.length)||this.peerOrigin!==void 0&&this.peerOrigin!=="null"&&t.includes(this.peerOrigin);o!==n.enabled&&(o?n.enable():n.disable())}}observePeerOrigin(t){var i;if((i=this.stopObservingPeerOrigin)==null||i.call(this),this.stopObservingPeerOrigin=void 0,this.peerOrigin=void 0,this.applyToolExposure(),!RR(t))return;const n=t;this.peerOrigin=n.clientOrigin,this.applyToolExposure();const o=n.onclientorigin;let r=!0;const s=a=>{o==null||o(a),r&&(this.peerOrigin=a,this.applyToolExposure())};n.onclientorigin=s,this.stopObservingPeerOrigin=()=>{r=!1,n.onclientorigin===s&&(n.onclientorigin=o)}}async connect(t){if(this.closed)throw Ne("BrowserMcpServer is closed");if(this.mcpServer.server.transport)throw Ne("BrowserMcpServer is already connected");this.observePeerOrigin(t);const n=this.stopObservingPeerOrigin;try{await this.mcpServer.connect(t)}catch(o){throw this.stopObservingPeerOrigin===n&&(n==null||n(),this.stopObservingPeerOrigin=void 0,this.peerOrigin=void 0,this.applyToolExposure()),this.mcpServer.server.transport===t&&await this.mcpServer.close(),o}}close(){var t;return this.closePromise?this.closePromise:(this.closed=!0,(t=this.stopObservingPeerOrigin)==null||t.call(this),this.stopObservingPeerOrigin=void 0,this.closePromise=(async()=>{var n,o,r;(n=this.native)==null||n.removeEventListener("toolchange",this.nativeToolChangeListener),(o=this.native)==null||o.removeEventListener("toolactivated",this.nativeLifecycleListener),(r=this.native)==null||r.removeEventListener("toolcancel",this.nativeLifecycleListener);for(const s of this.nativeToolAbortControllers.keys())this.abortNativeToolMirror(s);for(const s of this.tools.keys())this.removeTool(s);for(const s of this.registrations)s.remove();this.registrations.clear(),this.nativeBackfilledTools.clear(),this.removingNativeTools.clear(),await this.mcpServer.close()})(),this.closePromise)}};let it=null;function kR(e){if(window.parent!==window&&(e==null?void 0:e.iframeServer)!==!1)return new k_((e==null?void 0:e.iframeServer)||{allowedOrigins:["*"]});if((e==null?void 0:e.tabServer)===!1)throw new Error("tabServer transport is disabled and iframe transport was not selected");return new C_((e==null?void 0:e.tabServer)||{allowedOrigins:["*"]})}function CR(e){if(!globalThis.window||!globalThis.document||globalThis.isSecureContext===!1||it||wR(document.modelContext))return;zp();const t=document.modelContext;if(!t)throw new Error("modelContext is not available");const n=Object.getOwnPropertyDescriptor(document,"modelContext");if(n?!n.configurable:!Object.isExtensible(document))return;const o=kR(e==null?void 0:e.transport),r=new PR({name:`${window.location.hostname||"localhost"}-webmcp`,version:"1.0.0"},{native:t});try{Object.defineProperty(document,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:r}),it={server:r,transport:o,previousDescriptor:n}}catch(s){throw r.close(),o.close(),s}(async()=>{try{await r.syncNativeTools()}catch(s){console.warn("[WebModelContext] Native WebMCP tool synchronization failed:",s)}if((it==null?void 0:it.server)===r)try{await r.connect(o)}catch(s){console.error("[WebModelContext] Failed to connect MCP transport:",s),(it==null?void 0:it.server)===r&&OR()}})()}function OR(){if(!it)return;const{server:e,transport:t,previousDescriptor:n}=it;it=null,e.close(),t.close(),n?Object.defineProperty(document,"modelContext",n):Reflect.deleteProperty(document,"modelContext")}var el;const Nr=(el=globalThis.window)==null?void 0:el.__webModelContextOptions;if((Nr==null?void 0:Nr.autoInitialize)!==!1)try{CR(Nr)}catch(e){console.error("[WebModelContext] Auto-initialization failed:",e)}export{OR as cleanupWebModelContext,CR as initializeWebModelContext};
|