videobook 0.2.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +6 -2
  3. package/dist/archive-b2.js +1 -1
  4. package/dist/cli/args.js +42 -3
  5. package/dist/cli/config-command.js +17 -1
  6. package/dist/cli/doctor-command.js +15 -0
  7. package/dist/cli/har-command.js +86 -0
  8. package/dist/cli/main.js +13 -1
  9. package/dist/command-reference.js +5 -1
  10. package/dist/content-store.js +2 -1
  11. package/dist/diagnostics.js +1 -1
  12. package/dist/env-secrets.js +1 -0
  13. package/dist/generation-har.js +106 -0
  14. package/dist/har-capture.js +142 -0
  15. package/dist/har-export.js +238 -0
  16. package/dist/har-index.js +98 -0
  17. package/dist/har-retention.js +73 -0
  18. package/dist/har-settings.js +27 -0
  19. package/dist/jobs/_alibaba-upload.js +2 -4
  20. package/dist/jobs/_fal-upload.js +2 -4
  21. package/dist/jobs/_image-edit-adapter.js +1 -1
  22. package/dist/jobs/_kie-upload.js +2 -4
  23. package/dist/jobs/complete-provider-task.js +5 -2
  24. package/dist/jobs/generate-media.js +9 -1
  25. package/dist/jobs/image-subjects.js +1 -1
  26. package/dist/jobs/kie-paygate.js +10 -3
  27. package/dist/jobs/run-notebook.js +4 -1
  28. package/dist/jobs/xai-paygate.js +5 -2
  29. package/dist/media/adapters/kie.js +2 -1
  30. package/dist/media/catalog.js +20 -0
  31. package/dist/media/cost.js +1 -1
  32. package/dist/package-version.js +18 -0
  33. package/dist/posts/dropbox-auth.js +1 -1
  34. package/dist/posts/post-metrics.js +2 -1
  35. package/dist/provider-usage.js +1 -18
  36. package/dist/queue.js +12 -1
  37. package/dist/serve.js +2 -0
  38. package/dist/tools/api-status.js +1 -1
  39. package/dist/tools/generate-media.js +3 -0
  40. package/dist/tools/generation-payload.js +17 -2
  41. package/dist/tools/get-generation-har.js +43 -0
  42. package/dist/tools/index.js +4 -0
  43. package/dist/tools/list-cell-generations.js +19 -0
  44. package/dist/tools/reconcile-project-work.js +18 -12
  45. package/dist/tools/set-har-capture.js +30 -0
  46. package/dist/upload.js +2 -1
  47. package/dist/usage-providers.js +48 -10
  48. package/dist/workspace-action-groups.js +2 -2
  49. package/dist/x/account.js +1 -1
  50. package/dist/x/authenticated-handle.js +1 -1
  51. package/dist/x/oauth-flow.js +1 -1
  52. package/dist/x/post-to-x.js +2 -1
  53. package/dist/x/x-tokens.js +2 -1
  54. package/package.json +15 -14
  55. package/ui/assets/{alive-captions-Bp6dxosy.js → alive-captions-Cj8C1tCN.js} +1 -1
  56. package/ui/assets/{confirm-bodies-Ds1HtaGc.js → confirm-bodies-BxWXwDf0.js} +1 -1
  57. package/ui/assets/{fullscreen-BCeVHjvY.js → fullscreen-DyEncSdm.js} +1 -1
  58. package/ui/assets/{goal-ui-DbAGwgMN.js → goal-ui-BdFeoSWh.js} +2 -2
  59. package/ui/assets/{index-D1d-F1y9.js → index-QZ8lbemN.js} +9 -9
  60. package/ui/assets/inspector-BC6xWkJU.js +1 -0
  61. package/ui/assets/{jobs-ui-C1cbw-xG.js → jobs-ui-BudI4w0r.js} +1 -1
  62. package/ui/assets/{music-video-CWtxPlxq.js → music-video-CT4C55ok.js} +1 -1
  63. package/ui/assets/ui-mq0uIS5P.css +1 -0
  64. package/ui/assets/ui-z5r-p0K9.js +2 -0
  65. package/ui/assets/{vendor-BFupLz37.js → vendor-D8XcMav4.js} +2 -2
  66. package/ui/assets/{vendor-flow-CKiuzaeM.js → vendor-flow-nqTFQmTh.js} +1 -1
  67. package/ui/assets/vendor-mcp-D_C3EZPv.js +60 -0
  68. package/ui/assets/videobook-CsW453sb.js +21 -0
  69. package/ui/index.html +12 -12
  70. package/ui/assets/inspector-BJTC0luH.js +0 -1
  71. package/ui/assets/ui-CXDi5Omq.js +0 -2
  72. package/ui/assets/ui-Oirr9VOf.css +0 -1
  73. package/ui/assets/vendor-mcp-DQEeVZH0.js +0 -67
  74. package/ui/assets/videobook-J-j9bSjM.js +0 -20
@@ -0,0 +1,60 @@
1
+ import{W as ap,X as cp}from"./vendor-D8XcMav4.js";const up="modulepreload",lp=function(e){return"/"+e},Ui={},SR=function(t,n,o){let r=Promise.resolve();if(n&&n.length>0){let u=function(d){return Promise.all(d.map(l=>Promise.resolve(l).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),a=i?.nonce||i?.getAttribute("nonce");r=u(n.map(d=>{if(d=lp(d),d in Ui)return;Ui[d]=!0;const l=d.endsWith(".css"),p=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const h=document.createElement("link");if(h.rel=l?"stylesheet":up,l||(h.as="script"),h.crossOrigin="",h.href=d,a&&h.setAttribute("nonce",a),document.head.appendChild(h),l)return new Promise((f,S)=>{h.addEventListener("load",f),h.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${d}`)))})}))}function s(i){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=i,window.dispatchEvent(a),!a.defaultPrevented)throw i}return r.then(i=>{for(const a of i||[])a.status==="rejected"&&s(a.reason);return t().catch(s)})};function is(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 ji(e,t="|"){return e.map(n=>sc(n)).join(t)}function as(e,t){return typeof t=="bigint"?t.toString():t}class dp{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 Pr(e){return new dp(e)}function pp(e){return e==null}function ks(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function hp(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 Di=Symbol("evaluating");function mp(e,t,n){let o;Object.defineProperty(e,t,{get(){if(o!==Di)return o===void 0&&(o=Di,o=n()),o},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function ut(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ts(e){const t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function mt(e){return Ts(e._zod.def)??e._zod.def.shape}function tc(e,t,n){Object.defineProperty(e,t,{get(){const o=n();return ut(this,t,o),o},enumerable:!0,configurable:!0})}function nc(e,t,n){t in e?ut(e,t,n):e[t]=n}function Zt(e,t,n,o){const r=mt(t);for(const s of n){const i=Object.getOwnPropertyDescriptor(r,s);i.enumerable&&(i.get?tc(e,s,()=>{const a=t._zod.def.shape[s];return o?o(a,s):a}):nc(e,s,o?o(i.value,s):i.value))}}function fp(e,t){for(const n of Reflect.ownKeys(t)){const o=Object.getOwnPropertyDescriptor(t,n);o.enumerable&&(o.get?tc(e,n,()=>t[n]):nc(e,n,o.value))}}function ze(...e){const t={};for(const n of e){const o=Object.getOwnPropertyDescriptors(n);Object.assign(t,o)}return Object.defineProperties({},t)}function Sp(e){return JSON.stringify(e)}function gp(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const oc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function yo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const _p=Pr(()=>{if(Ve.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function vn(e){if(yo(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(yo(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function rc(e){return vn(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const vp=new Set(["string","number","symbol"]);function yn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kt(e,t,n){const o=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(o._zod.parent=e),o}function N(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(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 sc(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function yp(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}const ic={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]},bp={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Rp(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 Zt(s,e,$r(e,t)),kt(e,ze(n,{shape:s,checks:[]}))}function $r(e,t){const n=mt(e),o=[];for(const r of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,r)?.enumerable)throw new Error(`Unrecognized key: "${String(r)}"`);t[r]&&o.push(r)}return o}function wp(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($r(e,t)),i={};return Zt(i,e,Reflect.ownKeys(mt(e)).filter(a=>!s.has(a))),kt(e,ze(n,{shape:i,checks:[]}))}function Pp(e,t){if(!vn(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=mt(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 kt(e,ze(e._zod.def,{shape:ac(e,t)}))}function ac(e,t){const n={};return Zt(n,e,Reflect.ownKeys(mt(e))),fp(n,t),n}function $p(e,t){if(!vn(t))throw new Error("Invalid input to safeExtend: expected a plain object");return kt(e,ze(e._zod.def,{shape:ac(e,t)}))}function kp(e,t){if(!t?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n={};Zt(n,e,Reflect.ownKeys(mt(e))),Zt(n,t,Reflect.ownKeys(mt(t)));const o=ze(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return kt(e,o)}function Zi(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($r(t,n)):void 0,u={};return Zt(u,t,Reflect.ownKeys(mt(t)),e&&((d,l)=>a&&!a.has(l)?d:new e({type:"optional",innerType:d}))),kt(t,ze(t._zod.def,{shape:u,checks:[]}))}function Tp(e,t,n){const o=n?new Set($r(t,n)):void 0,r={};return Zt(r,t,Reflect.ownKeys(mt(t)),(s,i)=>o&&!o.has(i)?s:new e({type:"nonoptional",innerType:s})),kt(t,ze(t._zod.def,{shape:r}))}function Ge(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Ep(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function ht(e,t){return t.map(n=>{var o;return(o=n).path??(o.path=[]),n.path.unshift(e),n})}function ao(e){return typeof e=="string"?e:e?.message}function Fi(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 cs(e,t,n){var o;for(let r=t;r<e.length;r++)(o=e[r]).schema??(o.schema=n)}function wt(e,t,n){var o;const r=e.inst?._zod?.traits;r?.has("$ZodType")&&(r.has("$ZodCheck")?(o=e).schema??(o.schema=e.inst):e.schema=e.inst);const s=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,i=e.message?e.message:ao(e.inst?._zod.def?.error?.(e))??ao(s?.(e))??ao(t?.error?.(e))??ao(n.customError?.(e))??ao(n.localeError?.(e))??"Invalid input",a={};for(const u of Object.keys(e))u==="inst"||u==="schema"||u==="continue"||u==="input"||u==="__proto__"||(a[u]=e[u]);return a.path??(a.path=[]),a.message=i,t?.reportInput&&(a.input=e.input),a}const Cp=/[\uD800-\uDBFF]/;function Es(e){const t=e.length;if(!Cp.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 Cs(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ip(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 bo(...e){const[t,n,o]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:o}:{...t}}function Op(e,t){for(const n in t){const o=Object.getOwnPropertyDescriptor(t,n);o.get?Object.defineProperty(e,n,{...o,enumerable:!1}):qp(e,n,o.value)}}function Pt(e,t,n,o=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:o,value:n}),n}function Is(e,t,n){return Pt(e,t,n,!1)}function cc(e,t){for(const n in e){const o=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return Pt(this,n,o(this))},set(r){Pt(this,n,r)}})}return t}function qp(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:Pt(this,t,n.bind(this))},set(o){Pt(this,t,o)}})}function Np(e,t){const n=Object.getPrototypeOf(e);return t in n?void 0:n}let Vr,vt=!1;const Mp={configurable:!0,get(){vt=!0}};function W(e,t,n){const o=Object.getPrototypeOf(e._zod);if(t in o&&Vr!==e._zod){Vr=void 0;return}Vr=e._zod,Object.defineProperty(o,t,{configurable:!0,get(){Object.defineProperty(this,t,Mp);const r=vt;vt=!1;try{const s=n(this);return vt?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s}),vt=vt||r,s}catch(s){throw delete this[t],vt=vt||r,s}},set(r){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r})}})}function xp(e,t,n,o){const r=Np(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 zp="~constantCatch";function Ap(e){const t=()=>e;return t[zp]=!0,t}var Vi;const Lp=Object.freeze({status:"aborted"}),Hr={value:void 0,enumerable:!1};let Hi="captureStackTrace"in Error?Error:null;function Up(e){const t=Hi;if(t){const n=t.stackTraceLimit;if(typeof n=="number"){try{t.stackTraceLimit=0}catch{return Hi=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function b(e,t,n,o){const r={};function s(h){this.def=h,this.constr=p,this.traits=new Set}s.prototype=r;const i=n,a=i&&new WeakSet;function u(h,f){if(h._zod){if(h._zod.traits.has(e))return}else{Hr.value=new s(f);try{Object.defineProperty(h,"_zod",Hr)}finally{Hr.value=void 0}}if(h._zod.traits.add(e),t(h,f),a){const v=Object.getPrototypeOf(h),y=h._zod.constr.prototype;let w=v;for(;w&&w!==y;)w=Object.getPrototypeOf(w);const x=w??v;a.has(x)||(a.add(x),Op(x,i))}const S=p.prototype;for(const v in S)Object.prototype.hasOwnProperty.call(S,v)&&(v in h||(h[v]=S[v].bind(h)))}const d=o?.Parent??Object;class l extends d{}Object.defineProperty(l,"name",{value:e});function p(h){const f=o?.Parent?Up(l):this;u(f,h);const S=f._zod.deferred;if(S){for(const y of S)y();f._zod.deferred=void 0}const v=globalThis.__zod_globalConfig?.postProcessor;return v&&v(f),f}return Object.defineProperty(p,"init",{value:u}),Object.defineProperty(p,Symbol.hasInstance,{value:h=>o?.Parent&&h instanceof o.Parent?!0:h?._zod?.traits?.has(e)}),Object.defineProperty(p,"name",{value:e}),p}class Ut extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class uc extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Vi=globalThis).__zod_globalConfig??(Vi.__zod_globalConfig={});const Ve=globalThis.__zod_globalConfig;function at(e){return e&&Object.assign(Ve,e),Ve}function jp(){const e=this._zod;return e.message??(e.message=JSON.stringify(e.def,as,2)),e.message}function Dp(e){this._zod.message=e}const Zp={get:jp,set:Dp,enumerable:!0,configurable:!0},Jr={value:void 0,enumerable:!1},Ji=new WeakSet([Object.prototype,Error.prototype]),Fp=(e,t)=>{e.name="$ZodError",Jr.value=t,Object.defineProperty(e,"issues",Jr),Jr.value=void 0,Object.defineProperty(e,"message",Zp);const n=Object.getPrototypeOf(e);Ji.has(n)||(Ji.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})}}))},Vp=b("$ZodError",Fp);function Hp(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 Jp(e,t=n=>n.message){const n={},o=[];for(const r of e.issues)r.path.length>0?Hp(n,r.path[0],()=>[]).push(t(r)):o.push(t(r));return{formErrors:o,fieldErrors:n}}function Bp(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 u=n,d=0;for(;d<a.length;){const l=a[d],p=d===a.length-1;if(l==="_errors"){p&&u._errors.push(t(i)),d++;continue}Object.prototype.hasOwnProperty.call(u,l)||Object.defineProperty(u,l,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});const h=u[l];p&&h._errors.push(t(i)),u=h,d++}}}};return o(e),n}function kr(e,t){return{callee:t?.callee??e,Err:t?.Err}}const Os=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 Ut;if(a.issues.length){const u=new(s?.Err??e)(a.issues.map(d=>wt(d,i,at())));throw oc(u,s?.callee??t),u}return a.value};return t},qs=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 u=new(s?.Err??e)(a.issues.map(d=>wt(d,i,at())));throw oc(u,s?.callee??t),u}return a.value};return t},Ns=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 Ut;return s.issues.length?lc(e,s.issues,r):{success:!0,data:s.value}};function lc(e,t,n){let o;return{success:!1,get error(){return o||(o=new e(t.map(r=>wt(r,n,at()))),t=void 0,n=void 0),o},set error(r){o=r,t=void 0,n=void 0}}}const Ms=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?lc(e,s.issues,r):{success:!0,data:s.value}},Wp=Symbol.for("zod.compile.invalid"),Gp=Symbol.for("zod.compile.fallback"),Kp=((e,t,n)=>{const o=e._zod.bag.validator;if(o!==void 0){if(o(t)!==Wp)return!0;if(o.definite===!0&&n===void 0)return!1}return Yp(e,t,n)});function Yp(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[Gp]=!0,s=r({value:t,issues:[]},o)):s=e._zod.run({value:t,issues:[]},o),s instanceof Promise)throw new Ut;return s.issues.length===0}const Xp=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},Qp=e=>{const t=Os(e),n=(o,r,s,i)=>{const a=s?{...s,direction:"backward"}:{direction:"backward"};return t(o,r,a,kr(n,i))};return n},eh=e=>{const t=Os(e),n=(o,r,s,i)=>t(o,r,s,kr(n,i));return n},th=e=>{const t=qs(e),n=async(o,r,s,i)=>{const a=s?{...s,direction:"backward"}:{direction:"backward"};return await t(o,r,a,kr(n,i))};return n},nh=e=>{const t=qs(e),n=async(o,r,s,i)=>await t(o,r,s,kr(n,i));return n},oh=e=>(t,n,o)=>{const r=o?{...o,direction:"backward"}:{direction:"backward"};return Ns(e)(t,n,r)},rh=e=>(t,n,o)=>Ns(e)(t,n,o),sh=e=>async(t,n,o)=>{const r=o?{...o,direction:"backward"}:{direction:"backward"};return Ms(e)(t,n,r)},ih=e=>async(t,n,o)=>Ms(e)(t,n,o),ah=/^[cC][0-9a-z]{6,}$/,ch=/^[0-9a-z]+$/,uh=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,lh=/^[0-9a-vA-V]{20}$/,dh=/^[A-Za-z0-9]{27}$/,ph=/^[a-zA-Z0-9_-]{21}$/;function hh(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const mh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,fh=/^([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})$/,Bi=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)$/,Sh=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,gh="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function _h(){return new RegExp(gh,"u")}const vh=/^(?:(?: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])$/,yh=/^(([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}|:))$/,bh=/^((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])$/,Rh=/^(([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])$/,wh=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ph=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,$h=/^https?$/,kh=/^\+[1-9]\d{6,14}$/,dc="(?:(?:\\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 Th(e){return new RegExp(`^${e}$`)}const Eh=Th(dc);function us(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 Ch(e){return new RegExp(`^${us(e)}$`)}function Ih(e){const t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${us({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,o=e.local?`${n}|${us({precision:e.precision})}`:n;return new RegExp(`^${dc}T(?:${o})$`)}const Oh=/^[\s\S]{0,}$/,qh=/^-?\d+$/,xs=/^-?\d+(?:\.\d+)?$/,Nh=/^(?:true|false)$/i,Mh=/^null$/i,xh=/^[^A-Z]*$/,zh=/^[^a-z]*$/,$e=b("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),zs=e=>{const t=e.value;return!pp(t)&&t.length!==void 0},pr={number:"number",bigint:"bigint",object:"date"},pc=b("$ZodCheckLessThan",(e,t)=>{$e.init(e,t);const n=pr[typeof t.value];e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:pr[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})}}),hc=b("$ZodCheckGreaterThan",(e,t)=>{$e.init(e,t);const n=pr[typeof t.value];e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:pr[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})}}),Ah=b("$ZodCheckMultipleOf",(e,t)=>{$e.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):hp(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})}}),Lh=b("$ZodCheckNumberFormat",(e,t)=>{$e.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),o=n?"int":"number",[r,s]=ic[t.format];e._zod.check=i=>{const a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,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}):i.issues.push({input:a,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}}a<r&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),Uh=b("$ZodCheckMaxLength",(e,t)=>{var n;$e.init(e,t),(n=e._zod.def).when??(n.when=zs),e._zod.check=o=>{const r=o.value,s=r.length;if((typeof r=="string"&&s>t.maximum?Es(r):s)<=t.maximum)return;const a=Cs(r);o.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),jh=b("$ZodCheckMinLength",(e,t)=>{var n;$e.init(e,t),(n=e._zod.def).when??(n.when=zs),e._zod.check=o=>{const r=o.value,s=r.length;if((typeof r=="string"&&s>=t.minimum&&s<t.minimum*2?Es(r):s)>=t.minimum)return;const a=Cs(r);o.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Dh=b("$ZodCheckLengthEquals",(e,t)=>{var n;$e.init(e,t),(n=e._zod.def).when??(n.when=zs),e._zod.check=o=>{const r=o.value,s=r.length,i=typeof r=="string"&&s>=t.length&&s<=t.length*2?Es(r):s;if(i===t.length)return;const a=Cs(r),u=i>t.length;o.issues.push({origin:a,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Tr=b("$ZodCheckStringFormat",(e,t)=>{var n,o;$e.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=()=>{})}),Zh=b("$ZodCheckRegex",(e,t)=>{Tr.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})}}),Fh=b("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=xh),Tr.init(e,t)}),Vh=b("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=zh),Tr.init(e,t)}),Hh=b("$ZodCheckIncludes",(e,t)=>{$e.init(e,t);const n=yn(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})}}),Jh=b("$ZodCheckStartsWith",(e,t)=>{$e.init(e,t);const n=new RegExp(`^${yn(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})}}),Bh=b("$ZodCheckEndsWith",(e,t)=>{$e.init(e,t);const n=new RegExp(`.*${yn(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})}});function Wi(e,t,n){e.issues.length&&t.issues.push(...ht(n,e.issues))}const Wh=b("$ZodCheckProperties",(e,t)=>{$e.init(e,t),Is(e,Symbol.iterator,function*(){yield e});let n;e._zod.check=o=>{if(o.value==null){o.issues.push({expected:"object",code:"invalid_type",input:o.value,inst:e});return}n??(n=Reflect.ownKeys(t.shape).map(i=>[i,t.shape[i]]));const r=o.value;let s;for(const[i,a]of n){const u=a._zod.run({value:r[i],issues:[]},{});u instanceof Promise?(s??(s=[]),s.push(u.then(d=>Wi(d,o,i)))):Wi(u,o,i)}if(s)return Promise.all(s).then(()=>{})}}),Gh=b("$ZodCheckOverwrite",(e,t)=>{$e.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class Kh{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?.content??[""];return new t(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
3
+ ${n.join(`
4
+ `)}
5
+ };`)(...Object.values(this.closed))}}const Yh={major:4,minor:6,patch:7},X=b("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Yh;const o=e._zod.def.checks,r=e._zod.traits.has("$ZodCheck")?[e,...o??[]]:o?.length?[...o]:[];for(const s of r)for(const i of s._zod.onattach)i(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const s=(a,u,d)=>{if(a.memo)return a;let l=Ge(a),p;for(const h of u){if(h._zod.def.when){if(Ep(a)||!h._zod.def.when(a))continue}else if(l)continue;const f=a.issues.length,S=h._zod.check(a);if(S instanceof Promise&&d?.async===!1)throw new Ut;if(p||S instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await S,a.issues.length!==f&&(cs(a.issues,f,e),l||(l=Ge(a,f)))});else{if(a.issues.length===f)continue;cs(a.issues,f,e),l||(l=Ge(a,f))}}return p?p.then(()=>a):a},i=(a,u,d)=>{if(Ge(a))return a.aborted=!0,a;const l=s(u,r,d);if(l instanceof Promise){if(d.async===!1)throw new Ut;return l.then(p=>e._zod.parse(p,d))}return e._zod.parse(l,d)};e._zod.run=(a,u)=>{if(u.skipChecks)return e._zod.parse(a,u);if(u.direction==="backward"){const l=e._zod.parse({value:a.value,issues:[]},{...u,skipChecks:!0});return l instanceof Promise?l.then(p=>i(p,a,u)):i(l,a,u)}const d=e._zod.parse(a,u);if(d instanceof Promise){if(u.async===!1)throw new Ut;return d.then(l=>s(l,r,u))}return s(d,r,u)}}},{get"~standard"(){return Is(this,"~standard",fc(this))},set"~standard"(e){Pt(this,"~standard",e)}}),mc=(e,t)=>e.issues.length?{issues:e.issues.map(n=>wt(n,t,at()))}:{value:e.value};async function Xh(e,t){const n={async:!0};return mc(await e._zod.run({value:t,issues:[]},n),n)}function fc(e){return{validate:t=>{const n={async:!1};try{const o=e._zod.run({value:t,issues:[]},n);if(!(o instanceof Promise))return mc(o,n)}catch{}return Xh(e,t)},vendor:"zod",version:1}}const As=b("$ZodString",(e,t)=>{X.init(e,t),e._zod.pattern=t.pattern??Oh,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}}),oe=b("$ZodStringFormat",(e,t)=>{Tr.init(e,t),As.init(e,t)}),Qh=b("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=fh),oe.init(e,t)}),em=b("$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=Bi(o))}else t.pattern??(t.pattern=Bi());oe.init(e,t)}),tm=b("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Sh),oe.init(e,t)}),Sc=1,hr=2;function gc(e){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function nm(e,t){return!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t)?gc(e)||hr:om(e,t)}function om(e,t){if(!t.normalize&&t.protocol?.source===$h.source&&!/^https?:\/\//i.test(e))return Sc;try{if(typeof URL<"u"){const n=URL;if(typeof n.parse=="function")return n.parse(e)??hr}return new URL(e)}catch{return hr}}const rm=/[\t\n\r]/g;function Gi(e){return e.replace(rm,"")}function sm(e,t){return t.lastIndex=0,t.test(e.hostname)}function im(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}const am=b("$ZodURL",(e,t)=>{oe.init(e,t),e._zod.check=n=>{try{const o=n.value.trim(),r=nm(o,t);if(r===Sc){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(r===hr){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(r===!0){n.value=Gi(o);return}t.hostname&&!sm(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&&!im(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:Gi(o);return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),cm=b("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=_h()),oe.init(e,t)}),um=b("$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?ph:hh(t.length)),oe.init(e,t)}),lm=b("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ah),oe.init(e,t)}),dm=b("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ch),oe.init(e,t)}),pm=b("$ZodULID",(e,t)=>{t.pattern??(t.pattern=uh),oe.init(e,t)}),hm=b("$ZodXID",(e,t)=>{t.pattern??(t.pattern=lh),oe.init(e,t)}),mm=b("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=dh),oe.init(e,t)}),fm=b("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Ih(t)),oe.init(e,t)}),Sm=b("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Eh),oe.init(e,t)}),gm=b("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Ch(t)),oe.init(e,t)}),_m=b("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=mh),oe.init(e,t)}),vm=b("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=vh),oe.init(e,t)}),ym=/^[0-9a-fA-F:.]+$/;function _c(e){return ym.test(e)?gc(`http://[${e}]`):!1}const bm=b("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=yh),oe.init(e,t),e._zod.check=n=>{_c(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),Rm=b("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=bh),oe.init(e,t)});function wm(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:_c(n)}const Pm=b("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Rh),oe.init(e,t),e._zod.check=n=>{wm(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});function vc(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const yc=/^[0-9a-zA-Z+/]*={0,2}$/,$m=b("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=yc),oe.init(e,t),e._zod.check=n=>{vc(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Ls=/^[A-Za-z0-9_-]*$/;function km(e){if(!Ls.test(e))return!1;const t=e.replace(/[-_]/g,o=>o==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return vc(n)}const Tm=b("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ls),oe.init(e,t),e._zod.check=n=>{km(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Em=b("$ZodE164",(e,t)=>{t.pattern??(t.pattern=kh),oe.init(e,t)});function Cm(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?.typ!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const Im=b("$ZodJWT",(e,t)=>{oe.init(e,t),e._zod.check=n=>{Cm(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),bc=b("$ZodNumber",(e,t)=>{X.init(e,t),e._zod.pattern=xs,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}}),Om=b("$ZodNumberFormat",(e,t)=>{Lh.init(e,t),bc.init(e,t)}),qm=b("$ZodBoolean",(e,t)=>{X.init(e,t),e._zod.pattern=Nh,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}}),Nm=b("$ZodNull",(e,t)=>{X.init(e,t),e._zod.pattern=Mh,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}}),Mm=b("$ZodAny",(e,t)=>{X.init(e,t),e._zod.parse=n=>n}),xm=b("$ZodUnknown",(e,t)=>{X.init(e,t),e._zod.parse=n=>n}),zm=b("$ZodNever",(e,t)=>{X.init(e,t),e._zod.parse=(n,o)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Am(e,t){const n=Fi(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?.skipChecks&&i?.direction!=="backward"){for(const[u,d]of Fi(e._zod.def.checks))if(a>u&&d._zod.def.when(s)){const l=s.issues.length;return d._zod.check(s),s.issues[l].continue=!1,cs(s.issues,l,e),s}}return r(s,i)}}const Lm=e=>Array.isArray(e)?e.length:-1;function Ki(e,t,n){e.issues.length&&t.issues.push(...ht(n,e.issues)),t.value[n]=e.value}const Um=b("$ZodArray",(e,t)=>{X.init(e,t);const n=Ve.memoizer;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?.abortEarly;for(let u=0;u<s.length;u++){const d=s[u],l=t.element._zod.run({value:d,issues:[]},r);if(l instanceof Promise)i.push(l.then(p=>Ki(p,o,u)));else if(Ki(l,o,u),a&&l.issues.length!==0&&Ge(l))break}return i.length?Promise.all(i).then(()=>o):o},Am(e,Lm)});function mr(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(...ht(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 jm=[];function Rc(e){const t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),o=n.length?n:jm,r=o.length?[...t,...o]:t;for(const i of r)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(i)}": expected a Zod schema`);const s=yp(e.shape);return{...e,allKeys:r,symbolKeys:o,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function wc(e,t,n,o,r,s,i){const a=[],u=r.keySet,d=r.catchall._zod,l=d.def.type,p=d.optin,h=d.optout;let f=0;for(const S in t){if(i&&n.issues.length!==f){if(Ge(n,f))break;f=n.issues.length}if(u.has(S))continue;if(S==="__proto__"){l==="never"&&a.push(S);continue}if(l==="never"){a.push(S);continue}const v=d.run({value:t[S],issues:[]},o);v instanceof Promise?e.push(v.then(y=>mr(y,n,S,t,p,h))):mr(v,n,S,t,p,h)}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 Dm=b("$ZodObject",(e,t)=>{X.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape"),o=n?.get?n.get.raw:t.shape??{};if(o){const d=()=>{const l={...o};return Object.defineProperty(t,"shape",{value:l}),d.raw=l,l};d.raw=o,Object.defineProperty(t,"shape",{get:d})}const r=Pr(()=>Rc(t));W(e,"propValues",d=>{const l=d.def.shape,p={};for(const h in l){const f=l[h]._zod;if(f.values){Object.prototype.hasOwnProperty.call(p,h)||ut(p,h,new Set);for(const S of f.values)p[h].add(S);f.optin!==void 0&&p[h].add(void 0)}}return p});const s=yo,i=t.catchall;let a;const u=Ve.memoizer;u?.attach(e),e._zod.parse=(d,l)=>{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=u?u.alloc(e,d,{},l):{};const h=[],f=a.shape,S=l?.abortEarly;let v=d.issues.length;for(const y of a.allKeys){if(S&&d.issues.length!==v){if(Ge(d,v))break;v=d.issues.length}if(y==="__proto__")continue;const w=f[y],x=w._zod.optin,z=w._zod.optout,J=w._zod.run({value:p[y],issues:[]},l);J instanceof Promise?h.push(J.then(B=>mr(B,d,y,p,x,z))):mr(J,d,y,p,x,z)}return i?wc(h,p,d,l,r.value,e,S===!0):h.length?Promise.all(h).then(()=>d):d}}),Zm=b("$ZodObjectJIT",(e,t)=>{Dm.init(e,t);const n=e._zod.parse,o=Pr(()=>Rc(t)),r=Ve.memoizer,s=f=>{const S=o.value,v=S.symbolKeys,y=new Kh(["payload","ctx"],{shape:f,inst:e,memo:r,syms:v}),w=B=>`shape[${B}]._zod.run({ value: input[${B}], issues: [] }, ctx)`,x=(B,O)=>`
6
+ let ${B}_ab = false;
7
+ for (let i = 0; i < ${B}.issues.length; i++) {
8
+ const iss = ${B}.issues[i];
9
+ iss.path = iss.path ? [${O}, ...iss.path] : [${O}];
10
+ payload.issues.push(iss);
11
+ if (iss.continue !== true) ${B}_ab = true;
12
+ }
13
+ if (${B}_ab && ctx && ctx.abortEarly) {
14
+ payload.value = newResult;
15
+ return payload;
16
+ }`;y.write("const input = payload.value;");const z=Object.create(null);let J=0;for(const B of S.allKeys)z[B]=`key_${J++}`;y.write(r?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(const B of S.allKeys){if(B==="__proto__")continue;const O=z[B],G=typeof B=="symbol"?`syms[${v.indexOf(B)}]`:Sp(B),ie=`${G} in input`,te=f[B],pe=te?._zod?.optin,fe=pe!==void 0,K=te?._zod?.optout==="optional";if(y.write(`const ${O} = ${w(G)};`),fe&&K){const ne=pe==="optional"?`${O}_present`:`${O}.value !== undefined || ${O}_present`;y.write(`
17
+ const ${O}_present = ${ie};
18
+ if (!${O}.issues.length || ${O}_present) {
19
+ if (${O}.issues.length) {${x(O,G)}
20
+ }
21
+
22
+ if (${ne}) {
23
+ newResult[${G}] = ${O}.value;
24
+ }
25
+ }
26
+
27
+ `)}else fe?(y.write(`
28
+ if (${O}.issues.length) {${x(O,G)}
29
+ }
30
+ `),pe==="defaulted"?y.write(`newResult[${G}] = ${O}.value;`):y.write(`
31
+ if (${O}.value !== undefined || ${ie}) {
32
+ newResult[${G}] = ${O}.value;
33
+ }
34
+ `)):y.write(`
35
+ const ${O}_present = ${ie};
36
+ if (${O}.issues.length) {${x(O,G)}
37
+ }
38
+ if (!${O}_present && !${O}.issues.length) {
39
+ payload.issues.push({
40
+ code: "invalid_type",
41
+ expected: "nonoptional",
42
+ input: undefined,
43
+ path: [${G}]
44
+ });
45
+ if (ctx && ctx.abortEarly) {
46
+ payload.value = newResult;
47
+ return payload;
48
+ }
49
+ }
50
+
51
+ if (${O}_present) {
52
+ newResult[${G}] = ${O}.value;
53
+ }
54
+
55
+ `)}return y.write("payload.value = newResult;"),y.write("return payload;"),y.compile()};let i;const a=yo,u=!Ve.jitless,l=u&&_p.value,p=t.catchall;let h;e._zod.parse=(f,S)=>{h??(h=o.value);const v=f.value;return a(v)?u&&l&&S?.async===!1&&S.jitless!==!0?(i||(i=s(t.shape)),f=i(f,S),p?wc([],v,f,S,h,e,S?.abortEarly===!0):f):n(f,S):(f.issues.push({expected:"object",code:"invalid_type",input:v,inst:e}),f)}});function Yi(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=>!Ge(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=>wt(i,o,at())))}),t)}const Pc=b("$ZodUnion",(e,t)=>{X.init(e,t),W(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),W(e,"optout",o=>o.def.options.some(r=>r._zod.optout==="optional")?"optional":void 0),W(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)))}),W(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=>ks(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 u=a._zod.run({value:o.value,issues:[]},r);if(u instanceof Promise)i.push(u),s=!0;else{if(u.issues.length===0)return u;i.push(u)}}return s?Promise.all(i).then(a=>Yi(a,o,e,r)):Yi(i,o,e,r)}});function Fm(e){const t=new Map;for(const n of e.options){const o=n._zod.propValues?.[e.discriminator];if(!o||o.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(const r of o)if(t.has(r)){if(r!==void 0)throw new Error(`Duplicate discriminator value "${String(r)}"`);t.set(r,null)}else t.set(r,n)}return t}const Vm=b("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Pc.init(e,t);const n=e._zod.parse;W(e,"propValues",r=>{const s={};let i=0;for(const a of r.def.options){const u=a._zod.propValues;if(!u||Object.keys(u).length===0)throw new Error(`Invalid discriminated union option at index "${r.def.options.indexOf(a)}"`);u[r.def.discriminator]?.has(void 0)&&i++;for(const[d,l]of Object.entries(u)){Object.prototype.hasOwnProperty.call(s,d)||ut(s,d,new Set);for(const p of l)s[d].add(p)}}return!r.def.unionFallback&&i>1&&s[r.def.discriminator]?.delete(void 0),s}),t.options.forEach((r,s)=>{const i=Ts(r._zod.def);if(i&&!Object.prototype.hasOwnProperty.call(i,t.discriminator))throw new Error(`Invalid discriminated union option at index "${s}"`)});const o=Pr(()=>Fm(t));e._zod.parse=(r,s)=>{const i=r.value;if(!yo(i))return r.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),r;const a=i?.[t.discriminator],u=o.value.get(a);return u&&(a!==void 0||s.direction!=="backward")?u._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)}}),Hm=b("$ZodIntersection",(e,t)=>{X.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(([u,d])=>Xi(n,u,d)):Xi(n,s,i)}});function ls(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(vn(e)&&vn(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=ls(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=ls(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 Xi(e,t,n){const o=new Map;let r;const s=new Map,i=(d,l)=>{let p;if(d.code==="unrecognized_keys"&&!d.path?.length)r??(r=d),p=d.keys;else if(d.code==="invalid_key"&&d.origin==="record"&&d.path?.length===1){const h=String(d.path[0]);s.has(h)||s.set(h,d),p=[h]}else return!1;for(const h of p)o.has(h)||o.set(h,{}),o.get(h)[l]=!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(l=>r.keys.includes(l)):[];d.length&&e.issues.push({...r,keys:d});for(const l of a)!d.includes(l)&&s.has(l)&&e.issues.push(s.get(l))}const u=ls(t.value,n.value);if(!u.valid){if(Ge(e))return e;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`)}return e.value=u.data,e}const Jm=b("$ZodTuple",(e,t)=>{X.init(e,t);const n=t.items,o=Ve.memoizer;o?.attach(e),e._zod.parse=(r,s)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),r;r.value=o?o.alloc(e,r,[],s):[];const a=[],u=Qi(n,"optin"),d=Qi(n,"optout");if(!t.rest){if(i.length<u)return r.issues.push({code:"too_small",minimum:u,inclusive:!0,input:i,inst:e,origin:"array"}),r;i.length>n.length&&r.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:i,inst:e,origin:"array"})}const l=new Array(n.length),p=t.rest?s?.abortEarly:void 0;let h=!1;for(let f=0;f<n.length;f++){const S=n[f]._zod.run({value:i[f],issues:[]},s);S instanceof Promise?a.push(S.then(v=>{l[f]=v})):(l[f]=S,p&&!h&&S.issues.length&&(h=Ge(S)))}if(t.rest&&!h){let f=n.length-1;const S=i.slice(n.length);let v=r.issues.length;for(const y of S){if(p&&r.issues.length!==v){if(Ge(r,v))break;v=r.issues.length}f++;const w=t.rest._zod.run({value:y,issues:[]},s);w instanceof Promise?a.push(w.then(x=>ea(x,r,f))):ea(w,r,f)}}return a.length?Promise.all(a).then(()=>ta(l,r,n,i,d)):ta(l,r,n,i,d)}});function Qi(e,t){for(let n=e.length-1;n>=0;n--)if(!(t==="optin"?e[n]._zod.optin!==void 0:e[n]._zod.optout==="optional"))return n+1;return 0}function ea(e,t,n){e.issues.length&&t.issues.push(...ht(n,e.issues)),t.value[n]=e.value}function ta(e,t,n,o,r){for(let s=0;s<n.length;s++){const i=e[s],a=s<o.length;if(!a&&s>=r&&n[s]._zod.optin==="optional"){t.value.length=s;break}if(i.issues.length){if(!a&&s>=r){t.value.length=s;break}t.issues.push(...ht(s,i.issues))}t.value[s]=i.value}for(let s=t.value.length-1;s>=o.length&&(n[s]._zod.optout==="optional"&&t.value[s]===void 0);s--)t.value.length=s;return t}const Bm=b("$ZodRecord",(e,t)=>{X.init(e,t);const n=Ve.memoizer;n?.attach(e),e._zod.parse=(o,r)=>{const s=o.value;if(!vn(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 u=new Set;for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){if(u.add(typeof l=="number"?l.toString():l),l==="__proto__")continue;const p=t.keyType._zod.run({value:l,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(S=>wt(S,r,at())),input:l,path:[l],inst:e});continue}const h=p.value;if(h==="__proto__")continue;const f=t.valueType._zod.run({value:s[l],issues:[]},r);f instanceof Promise?i.push(f.then(S=>{S.issues.length&&o.issues.push(...ht(l,S.issues)),o.value[h]=S.value})):(f.issues.length&&o.issues.push(...ht(l,f.issues)),o.value[h]=f.value)}let d;for(const l in s)if(!u.has(l))if(t.mode==="loose"){if(l==="__proto__")continue;o.value[l]=s[l]}else d=d??[],d.push(l);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 u;for(const d of Reflect.ownKeys(s)){if(d==="__proto__"||!Object.prototype.propertyIsEnumerable.call(s,d))continue;let l=t.keyType._zod.run({value:d,issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof d=="string"&&xs.test(d)&&l.issues.length){const S=t.keyType._zod.run({value:Number(d),issues:[]},r);if(S instanceof Promise)throw new Error("Async schemas not supported in object keys currently");S.issues.length===0&&(l=S)}if(l.issues.length){t.mode==="loose"?o.value[d]=s[d]:a?(u=u??[],u.push(d)):o.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(S=>wt(S,r,at())),input:d,path:[d],inst:e});continue}const h=l.value;if(h==="__proto__")continue;const f=t.valueType._zod.run({value:s[d],issues:[]},r);f instanceof Promise?i.push(f.then(S=>{S.issues.length&&o.issues.push(...ht(d,S.issues)),o.value[h]=S.value})):(f.issues.length&&o.issues.push(...ht(d,f.issues)),o.value[h]=f.value)}u&&u.length>0&&o.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:u,continue:!0})}return i.length?Promise.all(i).then(()=>o):o}}),Wm=b("$ZodEnum",(e,t)=>{X.init(e,t);const n=is(t.entries),o=new Set(n);e._zod.values=o,W(e,"pattern",r=>{const s=is(r.def.entries).filter(i=>vp.has(typeof i));return new RegExp(s.length?`^(${s.map(i=>yn(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}}),Gm=b("$ZodLiteral",(e,t)=>{X.init(e,t);const n=new Set(t.values);e._zod.values=n,W(e,"pattern",o=>{const r=o.def.values;return new RegExp(r.length?`^(${r.map(s=>typeof s=="string"?yn(s):s?yn(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}}),Km=b("$ZodTransform",(e,t)=>{X.init(e,t),e._zod.optin="optional",Ve.memoizer?.guard(e),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new uc(e.constructor.name);const r=t.transform(n.value,n);if(o.async)return(r instanceof Promise?r:Promise.resolve(r)).then(i=>(n.value=i,n));if(r instanceof Promise)throw new Ut;return n.value=r,n}});function na(e,t){return e.value=t.issues.length?void 0:t.value,e}const $c=b("$ZodOptional",(e,t)=>{X.init(e,t),W(e,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",W(e,"values",n=>{const o=n.def.innerType._zod.values;return o?new Set([...o,void 0]):void 0}),W(e,"pattern",n=>{const o=n.def.innerType._zod.pattern;return o?new RegExp(`^(${ks(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=>na(n,s)):na(n,r)}return t.innerType._zod.run(n,o)}}),Ym=b("$ZodExactOptional",(e,t)=>{$c.init(e,t),W(e,"values",n=>n.def.innerType._zod.values),W(e,"pattern",n=>n.def.innerType._zod.pattern),e._zod.parse=(n,o)=>t.innerType._zod.run(n,o)}),Xm=b("$ZodNullable",(e,t)=>{X.init(e,t),W(e,"optin",n=>n.def.innerType._zod.optin),W(e,"optout",n=>n.def.innerType._zod.optout),W(e,"pattern",n=>{const o=n.def.innerType._zod.pattern;return o?new RegExp(`^(${ks(o.source)}|null)$`):void 0}),W(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)}),Qm=b("$ZodDefault",(e,t)=>{X.init(e,t),e._zod.optin="defaulted",W(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=>oa(s,t)):oa(r,t)}});function oa(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const ef=b("$ZodPrefault",(e,t)=>{X.init(e,t),e._zod.optin="defaulted",W(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))}),tf=b("$ZodNonOptional",(e,t)=>{X.init(e,t),W(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=>ra(s,e)):ra(r,e)}});function ra(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 sa(e,t,n,o){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(r=>wt(r,o,at()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const nf=b("$ZodCatch",(e,t)=>{X.init(e,t),W(e,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),W(e,"optout",n=>n.def.innerType._zod.optout),W(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=>sa(n,s,t,o)):sa(n,r,t,o)}}),kc=b("$ZodPipe",(e,t)=>{X.init(e,t),W(e,"values",n=>n.def.in._zod.values),W(e,"optin",n=>n.def.in._zod.optin),W(e,"optout",n=>n.def.out._zod.optout),W(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=>Go(i,t.in,o)):Go(s,t.in,o)}const r=t.in._zod.run(n,o);return r instanceof Promise?r.then(s=>Go(s,t.out,o)):Go(r,t.out,o)}});function Go(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 of=b("$ZodPreprocess",(e,t)=>{kc.init(e,t)}),rf=b("$ZodReadonly",(e,t)=>{X.init(e,t),W(e,"propValues",n=>n.def.innerType._zod.propValues),W(e,"values",n=>n.def.innerType._zod.values),W(e,"optin",n=>n.def.innerType?._zod?.optin),W(e,"optout",n=>n.def.innerType?._zod?.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(ia):ia(r)}});function ia(e){return e.memo||(e.value=Object.freeze(e.value)),e}const sf=b("$ZodLazy",(e,t)=>{X.init(e,t),mp(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),W(e,"pattern",n=>n.innerType?._zod?.pattern),W(e,"propValues",n=>n.innerType?._zod?.propValues),W(e,"optin",n=>n.innerType?._zod?.optin??void 0),W(e,"optout",n=>n.innerType?._zod?.optout??void 0),e._zod.parse=(n,o)=>e._zod.innerType._zod.run(n,o)}),af=b("$ZodCustom",(e,t)=>{$e.init(e,t),X.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=>aa(s,n,o,e));aa(r,n,o,e)}});function aa(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(bo(r))}}class cf extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}const ds="~memo",ca=[];function Tc(e){return e!==null&&typeof e=="object"}function Br(e){return e.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}const Ec=new WeakMap,lo=0,ar=1,fo=2;function cr(e,t,n){const o=Ec.get(e);if(o!==void 0)return o?fo:lo;if(t.has(e))return fo;t.add(e);let r=lo;const s=l=>{if(r!==fo&&l?._zod){const p=cr(l,t);p>r&&(r=p)}},i=(l,p)=>{let h=lo;for(const f of Reflect.ownKeys(l)){const S=Object.getOwnPropertyDescriptor(l,f);if(!S.enumerable)continue;const v=S.get?ar:S.value?._zod?cr(S.value,t):lo;v>h&&(h=v)}return h},a=l=>{l>r&&(r=l)},u=e._zod.def;switch(u.type){case"object":{const l=Ts(u);a(l?i(l):ar),s(u.catchall);break}case"array":s(u.element);break;case"tuple":for(const l of u.items)s(l);s(u.rest);break;case"record":case"map":s(u.keyType),s(u.valueType);break;case"set":s(u.valueType);break;case"union":for(const l of u.options)s(l);break;case"intersection":s(u.left),s(u.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(u.innerType);break;case"pipe":s(u.in),s(u.out);break;case"function":s(u.input),s(u.output);break;case"lazy":{const l=u._cachedInner??void 0;a(l?cr(l,t):ar);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 l in u){const p=Object.getOwnPropertyDescriptor(u,l);if(!p||p.get)continue;const h=p.value;if(!(!h||typeof h!="object")){if(h._zod)s(h);else if(Array.isArray(h))for(const f of h)s(f)}}}return t.delete(e),uf(e,r)}function uf(e,t){return t!==ar&&Ec.set(e,t===fo),t}function lf(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}let Ko;const Yo=[],df={alloc(e,t,n){const o=Ko;if(!o)return n;Ko=void 0;const r={value:n,issues:null};return o.set(t.value,r),Yo.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"&&hf(s,r.value))throw new cf;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=(u,d)=>{if(n===void 0){const w=cr(e,new Set);if(w===lo)return e._zod.parse=i,e._zod.run===a&&(e._zod.run=i),i(u,d);w===fo||o?n=!0:o=!0}const l=u.value;if(!Tc(l))return i(u,d);let p=d[ds];p||(p={buckets:new WeakMap,backEdges:void 0},d[ds]=p);let h;r===d?h=s:(h=lf(p,e),r=d,s=h);const f=h.get(l);if(f)return u.value=f.value,f.issues?f.issues.length&&u.issues.push(...Br(f.issues)):(u.memo=!0,p.backEdges??(p.backEdges=new WeakSet),p.backEdges.add(f.value)),u;Ko=h;const S=Yo.length,v=i(u,d);Ko=void 0;const y=Yo.length>S?Yo.pop():void 0;return v instanceof Promise?v.then(w=>(y&&(y.issues=w.issues.length?Br(w.issues):ca),w)):(y&&(y.issues=v.issues.length?Br(v.issues):ca),v)};e._zod.parse=a,e._zod.run===i&&(e._zod.run=a)})}};function pf(){return df}function hf(e,t){const n=e[ds]?.backEdges;return n!==void 0&&Tc(t)&&n.has(t)}const mf=()=>{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=Ip(s.input),u=r(a,s.input);return`Invalid input: expected ${i}, received ${u}`}case"invalid_value":return s.values.length===1?`Invalid input: expected ${sc(s.values[0])}`:`Invalid option: expected one of ${ji(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":""}: ${ji(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 ff(){return{localeError:mf()}}var ua;class Sf{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 gf(){return new Sf}(ua=globalThis).__zod_globalRegistry??(ua.__zod_globalRegistry=gf());const po=globalThis.__zod_globalRegistry;function Us(e){return e.checks&&(e.checks=[...e.checks]),e}function _f(e,t){return new e(Us({type:"string",...N(t)}))}function Cc(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...N(t)})}function vf(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...N(t)})}function yf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...N(t)})}function bf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...N(t)})}function Rf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...N(t)})}function wf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...N(t)})}function Ic(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...N(t)})}function Pf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...N(t)})}function $f(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...N(t)})}function kf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...N(t)})}function Tf(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...N(t)})}function Ef(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...N(t)})}function Cf(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...N(t)})}function If(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...N(t)})}function Of(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...N(t)})}function qf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...N(t)})}function Nf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...N(t)})}function Mf(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...N(t)})}function xf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...N(t)})}function zf(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...N(t)})}function Af(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...N(t)})}function Lf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...N(t)})}function Oc(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...N(t)})}function qc(e,t){return new e({type:"string",format:"date",check:"string_format",...N(t)})}function Uf(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...N(t)})}function jf(e,t){return new e({type:"string",format:"duration",check:"string_format",...N(t)})}function Df(e,t){return new e(Us({type:"number",checks:[],...N(t)}))}function Zf(e,t){return new e(Us({type:"number",coerce:!0,checks:[],...N(t)}))}function Ff(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...N(t)})}function Vf(e,t){return new e({type:"boolean",...N(t)})}function Hf(e,t){return new e({type:"null",...N(t)})}function Jf(e){return new e({type:"any"})}function Bf(e){return new e({type:"unknown"})}function Wf(e,t){return new e({type:"never",...N(t)})}function la(e,t){return new pc({check:"less_than",...N(t),value:e,inclusive:!1})}function Wr(e,t){return new pc({check:"less_than",...N(t),value:e,inclusive:!0})}function da(e,t){return new hc({check:"greater_than",...N(t),value:e,inclusive:!1})}function Gr(e,t){return new hc({check:"greater_than",...N(t),value:e,inclusive:!0})}function pa(e,t){return new Ah({check:"multiple_of",...N(t),value:e})}function Nc(e,t){return new Uh({check:"max_length",...N(t),maximum:e})}function fr(e,t){return new jh({check:"min_length",...N(t),minimum:e})}function Mc(e,t){return new Dh({check:"length_equals",...N(t),length:e})}function Gf(e,t){return new Zh({check:"string_format",format:"regex",...N(t),pattern:e})}function Kf(e){return new Fh({check:"string_format",format:"lowercase",...N(e)})}function Yf(e){return new Vh({check:"string_format",format:"uppercase",...N(e)})}function Xf(e,t){return new Hh({check:"string_format",format:"includes",...N(t),includes:e})}function Qf(e,t){return new Jh({check:"string_format",format:"starts_with",...N(t),prefix:e})}function eS(e,t){return new Bh({check:"string_format",format:"ends_with",...N(t),suffix:e})}function tS(e,t){return new Wh({check:"properties",shape:e,...N(t)})}function kn(e){return new Gh({check:"overwrite",tx:e})}function nS(e){return kn(t=>t.normalize(e))}function oS(){return kn(e=>e.trim())}function rS(){return kn(e=>e.toLowerCase())}function sS(){return kn(e=>e.toUpperCase())}function iS(){return kn(e=>gp(e))}function aS(e,t,n){return new e({type:"array",element:t,...N(n)})}function cS(e,t,n){const o=N(n);return o.abort??(o.abort=!0),new e({type:"custom",check:"custom",fn:t,...o})}function uS(e,t,n){return new e({type:"custom",check:"custom",fn:t,...N(n)})}function lS(e,t){const n=dS(o=>(o.addIssue=r=>{if(typeof r=="string")o.issues.push(bo(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(bo(s))}},e(o.value,o)),t);return n}function dS(e,t){const n=new $e({check:"custom",...N(t)});return n._zod.check=e,n}function So(e,...t){for(const n of t)for(const o of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,o)&&ut(e,o,n[o]);return e}function Sr(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??po,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function me(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 ee(e,t,n={path:[],schemaPath:[]}){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=e._zod.toJSONSchema?.();if(a)i.schema=a;else{const l={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,l);else{const h=i.schema,f=t.processors[r.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);f(e,t,h,l)}const p=e._zod.parent;p&&(i.ref||(i.ref=p),ee(p,t,l),t.seen.get(p).isParent=!0)}const u=t.metadataRegistry.get(e);return u&&So(i.schema,u),t.io==="input"&&Pe(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 ha(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function gr(e,t){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 i of e.seen.entries()){const a=e.metadataRegistry.get(i[0])?.id;if(a){const u=o.get(a);if(u&&u!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,i[0])}}const r=i=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const p=e.external.registry.get(i[0])?.id,h=e.external.uri??(S=>S);if(p)return{ref:h(p)};const f=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=f,{defId:f,ref:`${h("__shared")}#/${a}/${ha(f)}`}}const u="#",d=`${u}/${a}/`;if(i[1]===n&&!i[1].schema.id)return{ref:u};const l=i[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:d+ha(l)}},s=i=>{if(i[1].schema.$ref)return;const a=i[1],{ref:u,defId:d}=r(i);a.def={...a.schema},d&&(a.defId=d);const l=a.schema;for(const p in l)delete l[p];l.$ref=u};if(e.cycles==="throw")for(const i of e.seen.entries()){const a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
56
+
57
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const a=i[1];if(t===i[0]){s(i);continue}if(e.external){const d=e.external.registry.get(i[0])?.id;if(t!==i[0]&&d){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}a.count>1&&e.reused==="ref"&&s(i)}e.external&&(e.sharedDefsExtractedFor=e.external)}function xc(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;xc(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 zc=new Set(["type","properties","required","additionalProperties"]),ma=["oneOf","anyOf"];function fa(e){const t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function ps(e){const t=[];for(const s of e){if(typeof s!="object"||s.type!=="object")return null;for(const i in s)if(!zc.has(i))return null;t.push(s)}const n={},o=new Set;for(const s of t){for(const i in s.properties){if(Object.prototype.hasOwnProperty.call(n,i))continue;const a=[];for(const d of t){const l=d.properties?.[i]??fa(d);l!=null&&(a.some(p=>JSON.stringify(p)===JSON.stringify(l))||a.push(l))}const u=a.length===1?a[0]:ps(a)??{allOf:a};ut(n,i,u)}for(const i of s.required??[])o.add(i)}const r={type:"object",properties:n};if(o.size&&(r.required=[...o]),t.every(s=>s.additionalProperties===!1))r.additionalProperties=!1;else{const s=[];for(const i of t){const a=fa(i);a&&!s.some(u=>JSON.stringify(u)===JSON.stringify(a))&&s.push(a)}s.length===1?r.additionalProperties=s[0]:s.length>1&&(r.additionalProperties={allOf:s})}return r}function pS(e){const t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(const r of zc)if(r in e)return;const n=t.filter(r=>ma.some(s=>Array.isArray(r[s])));let o=null;if(!n.length)o=ps(t);else{const r=n[0],s=ma.find(u=>Array.isArray(r[u]));if(Object.keys(r).length!==1)return;const i=t.filter(u=>u!==r),a=r[s].map(u=>ps([...i,u]));if(a.some(u=>!u))return;o={[s]:a}}o&&(delete e.allOf,So(e,o))}function _r(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const o=a=>{const u=e.seen.get(a);if(u.ref===null)return;const d=u.def??u.schema,l={...d},p=u.ref;if(u.ref=null,p){o(p);const f=e.seen.get(p),S=f.schema;if(S.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(d.allOf=d.allOf??[],d.allOf.push(S)):So(d,S),So(d,l),a._zod.parent===p)for(const y in d)y==="$ref"||y==="allOf"||y in l||delete d[y];if(S.$ref&&f.def)for(const y in d)y==="$ref"||y==="allOf"||y in f.def&&JSON.stringify(d[y])===JSON.stringify(f.def[y])&&delete d[y]}const h=a._zod.parent;if(h&&h!==p){o(h);const f=e.seen.get(h);if(f?.schema.$ref&&(d.$ref=f.schema.$ref,f.def))for(const S in d)S==="$ref"||S==="allOf"||S in f.def&&JSON.stringify(d[S])===JSON.stringify(f.def[S])&&delete d[S]}e.override({zodSchema:a,jsonSchema:d,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(const a of[...e.seen.entries()].reverse())o(a[0]);if(e.target!=="openapi-3.0")for(const a of e.seen.entries())xc(a[1].def??a[1].schema);for(const a of e.deferred)a();if(e.intersections.length){const a=new Map;for(const u of e.seen.values())for(const d of[u.schema,u.def]){const l=d?.allOf;if(!Array.isArray(l))continue;const p=a.get(l);p?p.push(d):a.set(l,[d])}for(const u of e.intersections)for(const d of a.get(u)??[])pS(d)}}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,e.external?.uri){const a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(a)}So(r,n.defId?n.schema:n.def??n.schema);const s=e.metadataRegistry.get(t)?.id;s!==void 0&&r.id===s&&delete r.id;const i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(const a of e.seen.entries()){const u=a[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,ut(i,u.defId,u.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 a=JSON.parse(JSON.stringify(r));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:vr(t,"input",e.processors),output:vr(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Pe(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 Pe(o.element,n);if(o.type==="set")return Pe(o.valueType,n);if(o.type==="lazy")return Pe(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 Pe(o.innerType,n);if(o.type==="intersection")return Pe(o.left,n)||Pe(o.right,n);if(o.type==="record"||o.type==="map")return Pe(o.keyType,n)||Pe(o.valueType,n);if(o.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Pe(o.in,n)||Pe(o.out,n);if(o.type==="object"){for(const r in o.shape)if(Pe(o.shape[r],n))return!0;return!1}if(o.type==="union"){for(const r of o.options)if(Pe(r,n))return!0;return!1}if(o.type==="tuple"){for(const r of o.items)if(Pe(r,n))return!0;return!!(o.rest&&Pe(o.rest,n))}return!1}const hS=(e,t={})=>n=>{const o=Sr({...n,processors:t});return ee(e,o),gr(o,e),_r(o,e)},vr=(e,t,n={})=>o=>{const{libraryOptions:r,target:s}=o??{},i=Sr({...r??{},target:s,io:t,processors:n});return ee(e,i),gr(i,e),_r(i,e)},bn=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},Rn=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Sa=(e,t)=>{bn(e,"minimum",t),Rn(e,"maximum",t)},Ac=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},Lc=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Uc=(e,t)=>{e.mime=e.mime?e.mime.filter(n=>t.includes(n)):[...t]},jc=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},ga=(e,t)=>bn(e,"minimum",t.minimum),_a=(e,t)=>Rn(e,"maximum",t.maximum),va=e=>(t,n)=>{jc(t,n.format);const[o,r]=e[n.format];bn(t,"minimum",o),Rn(t,"maximum",r)},mS={greater_than:(e,t)=>bn(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Rn(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Ac(e,t.value),number_format:va(ic),bigint_format:va(bp),min_length:ga,max_length:_a,length_equals:(e,t)=>Sa(e,t.length),min_size:ga,max_size:_a,size_equals:(e,t)=>Sa(e,t.size),string_format:(e,t)=>{jc(e,t.format),t.pattern&&Lc(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)=>Uc(e,t.mime)};function Ae(e){const t={},n=e._zod.def,o=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(const s of o)mS[s._zod.def.check]?.(t,s._zod.def);const r=e._zod.bag;r.minimum!==void 0&&bn(t,"minimum",r.minimum),r.exclusiveMinimum!==void 0&&bn(t,"exclusiveMinimum",r.exclusiveMinimum),r.maximum!==void 0&&Rn(t,"maximum",r.maximum),r.exclusiveMaximum!==void 0&&Rn(t,"exclusiveMaximum",r.exclusiveMaximum),r.multipleOf!==void 0&&Ac(t,r.multipleOf),r.format!==void 0&&(t.format??(t.format=r.format),r.format.includes("int")&&(t.isInt=!0)),r.mime&&Uc(t,r.mime);for(const s of r.patterns??[])Lc(t,s);return t}const fS={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},SS=new Map([[yc,wh],[Ls,Ph]]),Dc=e=>SS.get(e)??e,Zc=(e,t,n,o)=>{const r=n;r.type="string";const{minimum:s,maximum:i,format:a,patterns:u,contentEncoding:d,laxFormat:l}=Ae(e);if(typeof s=="number"&&(r.minLength=s),typeof i=="number"&&(r.maxLength=i),a&&(r.format=fS[a]??a,r.format===""&&delete r.format,(a==="time"||l)&&delete r.format),d&&(r.contentEncoding=d),u&&u.size>0){const p=[...u].map(Dc);p.length===1?r.pattern=p[0].source:p.length>1&&(r.allOf=[...p.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},Fc=(e,t,n,o)=>{const r=n,{minimum:s,maximum:i,multipleOf:a,exclusiveMaximum:u,exclusiveMinimum:d,isInt:l}=Ae(e);r.type=l?"integer":"number";const p=typeof d=="number"&&d>=(s??Number.NEGATIVE_INFINITY),h=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(p?f?(r.minimum=d,r.exclusiveMinimum=!0):r.exclusiveMinimum=d:typeof s=="number"&&(r.minimum=s),h?f?(r.maximum=u,r.exclusiveMaximum=!0):r.exclusiveMaximum=u:typeof i=="number"&&(r.maximum=i),a){const S=new Set;for(const w of a)Number.isFinite(w)&&w!==0?S.add(Math.abs(w)):me(e,t,r,o,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);const[v,...y]=S;v!==void 0&&(r.multipleOf=v),y.length&&(r.allOf=[...r.allOf??[],...y.map(w=>({multipleOf:w}))])}},Vc=(e,t,n,o)=>{n.type="boolean"},gS=(e,t,n,o)=>{me(e,t,n,o,"BigInt cannot be represented in JSON Schema")},_S=(e,t,n,o)=>{me(e,t,n,o,"Symbols cannot be represented in JSON Schema")},Hc=(e,t,n,o)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},vS=(e,t,n,o)=>{me(e,t,n,o,"Undefined cannot be represented in JSON Schema")},yS=(e,t,n,o)=>{me(e,t,n,o,"Void cannot be represented in JSON Schema")},Jc=(e,t,n,o)=>{n.not={}},Bc=(e,t,n,o)=>{},Wc=(e,t,n,o)=>{},bS=(e,t,n,o)=>{me(e,t,n,o,"Date cannot be represented in JSON Schema")},Gc=(e,t,n,o)=>{const r=e._zod.def,s=is(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},Kc=(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(me(e,t,n,o,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i=="bigint"){if(me(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},RS=(e,t,n,o)=>{me(e,t,n,o,"NaN cannot be represented in JSON Schema")},wS=(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},PS=(e,t,n,o)=>{const r=n;r.type="string",r.format="binary",r.contentEncoding="binary";const{minimum:s,maximum:i,mime:a}=Ae(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(u=>({contentMediaType:u})))},$S=(e,t,n,o)=>{n.type="boolean"},Yc=(e,t,n,o)=>{me(e,t,n,o,"Custom types cannot be represented in JSON Schema")},kS=(e,t,n,o)=>{me(e,t,n,o,"Function types cannot be represented in JSON Schema")},Xc=(e,t,n,o)=>{me(e,t,n,o,"Transforms cannot be represented in JSON Schema")},TS=(e,t,n,o)=>{me(e,t,n,o,"Map cannot be represented in JSON Schema")},ES=(e,t,n,o)=>{me(e,t,n,o,"Set cannot be represented in JSON Schema")},Qc=(e,t,n,o)=>{const r=n,s=e._zod.def,{minimum:i,maximum:a}=Ae(e);typeof i=="number"&&(r.minItems=i),typeof a=="number"&&(r.maxItems=a),r.type="array",r.items=ee(s.element,t,{...o,path:[...o.path,"items"]})};function Ro(e){const t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Ro(t.out):t.type==="catch"?Ro(t.innerType):e._zod.optin}const eu=(e,t,n,o)=>{const r=n,s=e._zod.def,i=s.shape;if(Object.getOwnPropertySymbols(i).length&&me(e,t,r,o,"Symbol keys cannot be represented in JSON Schema"))return;r.type="object",r.properties={};for(const d in i)ut(r.properties,d,ee(i[d],t,{...o,path:[...o.path,"properties",d]}));const u=[];for(const d of Object.keys(i)){const l=s.shape[d];(t.io==="input"?Ro(l)===void 0:l._zod.optout===void 0)&&u.push(d)}u.length>0&&(r.required=u),s.catchall?._zod.def.type==="never"?r.additionalProperties=!1:s.catchall?s.catchall&&(r.additionalProperties=ee(s.catchall,t,{...o,path:[...o.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},tu=(e,t,n,o)=>{const r=e._zod.def,s=r.inclusive===!1,i=r.options.map((a,u)=>ee(a,t,{...o,path:[...o.path,s?"oneOf":"anyOf",u]}));s?n.oneOf=i:n.anyOf=i},nu=(e,t,n,o)=>{const r=e._zod.def,s=ee(r.left,t,{...o,path:[...o.path,"allOf",0]}),i=ee(r.right,t,{...o,path:[...o.path,"allOf",1]}),a=d=>"allOf"in d&&Object.keys(d).length===1,u=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];n.allOf=u,t.intersections.push(u)},ou=(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",u=s.items.map((v,y)=>ee(v,t,{...o,path:[...o.path,i,y]})),d=s.rest?ee(s.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;let l=s.items.length;for(;l>0;){const v=s.items[l-1];if(!(t.io==="input"?Ro(v)!==void 0:v._zod.optout==="optional"))break;l--}const p=s.items.length,h=!s.rest;t.target==="draft-2020-12"?(r.prefixItems=u,h?r.items=!1:d&&(r.items=d),l>0&&(r.minItems=l),h&&(r.maxItems=p)):t.target==="openapi-3.0"?(r.items={anyOf:u},d&&r.items.anyOf.push(d),l>0&&(r.minItems=l),h&&(r.maxItems=p)):(r.items=u,h?r.additionalItems=!1:d&&(r.additionalItems=d),l>0&&(r.minItems=l),h&&(r.maxItems=p));const{minimum:f,maximum:S}=Ae(e);typeof f=="number"&&(r.minItems=f),typeof S=="number"&&(r.maxItems=S)};function hs(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);const S=e.get(t)?.def;if(!S)return t;const v=hs(e,S,n);return v===S?t:v}for(const S of["anyOf","oneOf"]){const v=t[S];if(!Array.isArray(v))continue;const y=v.map(w=>hs(e,w,n));y.some((w,x)=>w!==v[x])&&(t={...t,[S]:y})}const o=Array.isArray(t.type)?t.type:[t.type],r=!o.includes("string")&&o.some(S=>S==="number"||S==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!r&&!s?.some(S=>typeof S=="number"))return t;const{minimum:i,maximum:a,exclusiveMinimum:u,exclusiveMaximum:d,multipleOf:l,format:p,id:h,...f}=t;return f.enum?f.enum=f.enum.map(S=>typeof S=="number"?String(S):S):typeof f.const=="number"&&(f.const=String(f.const)),r&&(f.type="string",s||(f.pattern=(o.includes("number")?xs:qh).source)),f}const ms=new WeakMap;function CS(e){const t=new Map;for(const o of e.seen.values())o.def&&!t.has(o.schema)&&t.set(o.schema,o);const n=new Map;for(const o of ms.get(e)??[]){const r=e.seen.get(o),s=(r?.def??r?.schema)?.propertyNames;if(!s||s===!0||n.has(s))continue;const i=hs(t,s,new Set);i!==s&&n.set(s,i)}if(n.size)for(const o of e.seen.values())for(const r of[o.schema,o.def]){const s=r&&n.get(r.propertyNames);s&&(r.propertyNames=s)}}const ru=(e,t,n,o)=>{const r=n,s=e._zod.def;r.type="object";const i=s.keyType,a=Ae(i).patterns;if(s.mode==="loose"&&a&&a.size>0){const l=ee(s.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});r.patternProperties={};for(const p of a)ut(r.patternProperties,Dc(p).source,l)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){r.propertyNames=ee(s.keyType,t,{...o,path:[...o.path,"propertyNames"]});let l=ms.get(t);l||(l=[],ms.set(t,l),t.deferred.push(()=>CS(t))),l.push(e)}r.additionalProperties=ee(s.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}const u=i._zod.values,d=t.io==="input"&&Ro(s.valueType)!==void 0;if(u&&!s.partial&&!d){const l=[...u].filter(p=>typeof p=="string"||typeof p=="number");l.length>0&&(r.required=l.map(String))}},su=(e,t,n,o)=>{const r=e._zod.def,s=ee(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;ee(r.innerType,t,o);const s=t.seen.get(e);s.ref=r.innerType},js=Symbol();function au(e,t,n,o,r){let s=!1;const i=JSON.stringify(e,(a,u)=>typeof u!="bigint"?u:(s=!0,null));return s?(me(t,n,o,r,"BigInt defaults cannot be represented in JSON Schema"),js):JSON.parse(i)}const cu=(e,t,n,o)=>{const r=e._zod.def;ee(r.innerType,t,o);const s=t.seen.get(e);s.ref=r.innerType;const i=au(r.defaultValue,e,t,n,o);i!==js&&(n.default=i)},uu=(e,t,n,o)=>{const r=e._zod.def;ee(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!==js&&(n._prefault=i)},lu=(e,t,n,o)=>{const r=e._zod.def;ee(r.innerType,t,o);const s=t.seen.get(e);s.ref=r.innerType;let i;try{i=r.catchValue(void 0)}catch{me(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;ee(i,t,o);const a=t.seen.get(e);a.ref=i},pu=(e,t,n,o)=>{const r=e._zod.def;ee(r.innerType,t,o);const s=t.seen.get(e);s.ref=r.innerType,n.readOnly=!0},IS=(e,t,n,o)=>{const r=e._zod.def;ee(r.innerType,t,o);const s=t.seen.get(e);s.ref=r.innerType},Ds=(e,t,n,o)=>{const r=e._zod.def;ee(r.innerType,t,o);const s=t.seen.get(e);s.ref=r.innerType},hu=(e,t,n,o)=>{const r=e._zod.innerType;ee(r,t,o);const s=t.seen.get(e);s.ref=r},ya={string:Zc,number:Fc,boolean:Vc,bigint:gS,symbol:_S,null:Hc,undefined:vS,void:yS,never:Jc,any:Bc,unknown:Wc,date:bS,enum:Gc,literal:Kc,nan:RS,template_literal:wS,file:PS,success:$S,custom:Yc,function:kS,transform:Xc,map:TS,set:ES,array:Qc,object:eu,union:tu,intersection:nu,tuple:ou,record:ru,nullable:su,nonoptional:iu,default:cu,prefault:uu,catch:lu,pipe:du,readonly:pu,promise:IS,optional:Ds,lazy:hu};function mu(e,t){if("_idmap"in e){const o=e,r=Sr({...t,processors:ya}),s={};for(const u of o._idmap.entries()){const[d,l]=u;ee(l,r)}const i={},a={registry:o,uri:t?.uri,defs:s};r.external=a;for(const u of o._idmap.entries()){const[d,l]=u;gr(r,l),ut(i,d,_r(r,l))}if(Object.keys(s).length>0){const u=r.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[u]:s}}return{schemas:i}}const n=Sr({...t,processors:ya});return ee(e,n),gr(n,e),_r(n,e)}const ba=new WeakSet([Object.prototype,Error.prototype]);function Xo(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 OS=(e,t)=>{Vp.init(e,t),e.name="ZodError";const n=Object.getPrototypeOf(e);ba.has(n)||(ba.add(n),Xo(n,"format",o=>r=>Bp(o,r)),Xo(n,"flatten",o=>r=>Jp(o,r)),Xo(n,"addIssue",o=>r=>{o.issues.push(r),o.message=JSON.stringify(o.issues,as,2)}),Xo(n,"addIssues",o=>r=>{o.issues.push(...r),o.message=JSON.stringify(o.issues,as,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},He=b("ZodError",OS,void 0,{Parent:Error}),qS=Os(He),NS=qs(He),fu=Ns(He),MS=Ms(He),xS=Qp(He),zS=eh(He),AS=th(He),LS=nh(He),US=oh(He),jS=rh(He),DS=sh(He),ZS=ih(He);function FS(){Ve.localeError||at(ff())}function Co(){Ve.memoizer||at({memoizer:pf()})}const Q=b("ZodType",(e,t)=>(FS(),X.init(e,t),e.def=t,e.type=t.type,e),{check(...e){const t=this.def;return this.clone(ze(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 kt(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Ag(e,t))},superRefine(e,t){return this.check(Lg(e,t))},overwrite(e){return this.check(kn(e))},optional(){return A(this)},exactOptional(){return Pg(this)},nullable(){return Pa(this)},nullish(){return A(Pa(this))},nonoptional(e){return Ig(this,e)},array(){return g(this)},or(e){return C([this,e])},and(e){return Ft(this,e)},transform(e){return $a(this,Pu(e))},default(e){return Tg(this,e)},prefault(e){return Cg(this,e)},catch(e){return qg(this,e)},pipe(e){return $a(this,e)},readonly(){return xg(this)},describe(e){const t=this.clone();return po.add(t,{description:e}),t},meta(...e){if(e.length===0)return po.get(this);const t=this.clone();return po.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 Is(this,"~standard",{...fc(this),jsonSchema:{input:vr(this,"input"),output:vr(this,"output")}})},set"~standard"(e){Pt(this,"~standard",e)},parse:function e(t,n){return qS(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await NS(this,t,n,{callee:e})},safeParse(e,t){return fu(this,e,t)},async safeParseAsync(e,t){return MS(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Pt(this,"spa",e)},validate(e,t){return Kp(this,e,t)},validateAsync(e,t){return Xp(this,e,t)},encode:function e(t,n){return xS(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 AS(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await LS(this,t,n,{callee:e})},safeEncode(e,t){return US(this,e,t)},safeDecode(e,t){return jS(this,e,t)},async safeEncodeAsync(e,t){return DS(this,e,t)},async safeDecodeAsync(e,t){return ZS(this,e,t)},toJSONSchema(e){return hS(this,{})(e)},get description(){return po.get(this)?.description},get _def(){return this._zod.def}}),Su=b("_ZodString",(e,t)=>{As.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Zc(e,n,o)},cc({format:e=>Ae(e).format??null,minLength:e=>Ae(e).minimum??null,maxLength:e=>Ae(e).maximum??null},{regex(...e){return this.check(Gf(...e))},includes(...e){return this.check(Xf(...e))},startsWith(...e){return this.check(Qf(...e))},endsWith(...e){return this.check(eS(...e))},min(...e){return this.check(fr(...e))},max(...e){return this.check(Nc(...e))},length(...e){return this.check(Mc(...e))},nonempty(...e){return this.check(fr(1,...e))},lowercase(e){return this.check(Kf(e))},uppercase(e){return this.check(Yf(e))},trim(){return this.check(oS())},normalize(...e){return this.check(nS(...e))},toLowerCase(){return this.check(rS())},toUpperCase(){return this.check(sS())},slugify(){return this.check(iS())}})),VS=b("ZodString",(e,t)=>{As.init(e,t),Su.init(e,t)},{email(e){return this.check(Cc(vu,e))},url(e){return this.check(Ic(yu,e))},jwt(e){return this.check(Lf(ug,e))},emoji(e){return this.check(Pf(GS,e))},guid(e){return this.check(vf(WS,e))},uuid(e){return this.check(yf(Qo,e))},uuidv4(e){return this.check(bf(Qo,e))},uuidv6(e){return this.check(Rf(Qo,e))},uuidv7(e){return this.check(wf(Qo,e))},nanoid(e){return this.check($f(KS,e))},cuid(e){return this.check(kf(YS,e))},cuid2(e){return this.check(Tf(XS,e))},ulid(e){return this.check(Ef(QS,e))},base64(e){return this.check(xf(ig,e))},base64url(e){return this.check(zf(ag,e))},xid(e){return this.check(Cf(eg,e))},ksuid(e){return this.check(If(tg,e))},ipv4(e){return this.check(Of(ng,e))},ipv6(e){return this.check(qf(og,e))},cidrv4(e){return this.check(Nf(rg,e))},cidrv6(e){return this.check(Mf(sg,e))},e164(e){return this.check(Af(cg,e))},datetime(e){return this.check(Oc(gu,e))},date(e){return this.check(qc(_u,e))},time(e){return this.check(Uf(HS,e))},duration(e){return this.check(jf(JS,e))}});function c(e){return _f(VS,e)}const se=b("ZodStringFormat",(e,t)=>{oe.init(e,t),Su.init(e,t)}),gu=b("ZodISODateTime",(e,t)=>{fm.init(e,t),se.init(e,t)}),_u=b("ZodISODate",(e,t)=>{Sm.init(e,t),se.init(e,t)}),HS=b("ZodISOTime",(e,t)=>{gm.init(e,t),se.init(e,t)}),JS=b("ZodISODuration",(e,t)=>{_m.init(e,t),se.init(e,t)}),vu=b("ZodEmail",(e,t)=>{tm.init(e,t),se.init(e,t)});function BS(e){return Cc(vu,e)}const WS=b("ZodGUID",(e,t)=>{Qh.init(e,t),se.init(e,t)}),Qo=b("ZodUUID",(e,t)=>{em.init(e,t),se.init(e,t)}),yu=b("ZodURL",(e,t)=>{am.init(e,t),se.init(e,t)});function bu(e){return Ic(yu,e)}const GS=b("ZodEmoji",(e,t)=>{cm.init(e,t),se.init(e,t)}),KS=b("ZodNanoID",(e,t)=>{um.init(e,t),se.init(e,t)}),YS=b("ZodCUID",(e,t)=>{lm.init(e,t),se.init(e,t)}),XS=b("ZodCUID2",(e,t)=>{dm.init(e,t),se.init(e,t)}),QS=b("ZodULID",(e,t)=>{pm.init(e,t),se.init(e,t)}),eg=b("ZodXID",(e,t)=>{hm.init(e,t),se.init(e,t)}),tg=b("ZodKSUID",(e,t)=>{mm.init(e,t),se.init(e,t)}),ng=b("ZodIPv4",(e,t)=>{vm.init(e,t),se.init(e,t)}),og=b("ZodIPv6",(e,t)=>{bm.init(e,t),se.init(e,t)}),rg=b("ZodCIDRv4",(e,t)=>{Rm.init(e,t),se.init(e,t)}),sg=b("ZodCIDRv6",(e,t)=>{Pm.init(e,t),se.init(e,t)}),ig=b("ZodBase64",(e,t)=>{$m.init(e,t),se.init(e,t)}),ag=b("ZodBase64URL",(e,t)=>{Tm.init(e,t),se.init(e,t)}),cg=b("ZodE164",(e,t)=>{Em.init(e,t),se.init(e,t)}),ug=b("ZodJWT",(e,t)=>{Im.init(e,t),se.init(e,t)}),Zs=b("ZodNumber",(e,t)=>{bc.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Fc(e,n,o,r),e.isFinite=!0},cc({minValue:e=>{const{minimum:t,exclusiveMinimum:n}=Ae(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:e=>{const{maximum:t,exclusiveMaximum:n}=Ae(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:e=>{const{isInt:t,multipleOf:n}=Ae(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Ae(e).format??null},{gt(e,t){return this.check(da(e,t))},gte(e,t){return this.check(Gr(e,t))},min(e,t){return this.check(Gr(e,t))},lt(e,t){return this.check(la(e,t))},lte(e,t){return this.check(Wr(e,t))},max(e,t){return this.check(Wr(e,t))},int(e){return this.check(Ra(e))},safe(e){return this.check(Ra(e))},positive(e){return this.check(da(0,e))},nonnegative(e){return this.check(Gr(0,e))},negative(e){return this.check(la(0,e))},nonpositive(e){return this.check(Wr(0,e))},multipleOf(e,t){return this.check(pa(e,t))},step(e,t){return this.check(pa(e,t))},finite(){return this}}));function R(e){return Df(Zs,e)}const lg=b("ZodNumberFormat",(e,t)=>{Om.init(e,t),Zs.init(e,t)});function Ra(e){return Ff(lg,e)}const dg=b("ZodBoolean",(e,t)=>{qm.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Vc(e,n,o)});function E(e){return Vf(dg,e)}const pg=b("ZodNull",(e,t)=>{Nm.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Hc(e,n,o)});function wo(e){return Hf(pg,e)}const hg=b("ZodAny",(e,t)=>{Mm.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Bc()});function mg(){return Jf(hg)}const fg=b("ZodUnknown",(e,t)=>{xm.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Wc()});function L(){return Bf(fg)}const Sg=b("ZodNever",(e,t)=>{zm.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Jc(e,n,o)});function gg(e){return Wf(Sg,e)}const _g=b("ZodArray",(e,t)=>{Co(),Um.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Qc(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(Nc(e,t))},length(e,t){return this.check(Mc(e,t))},unwrap(){return this.element}});function g(e,t){return aS(_g,e,t)}const Ru=b("ZodObject",(e,t)=>{Co(),Zm.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>eu(e,n,o,r),xp(e,"shape",n=>n._zod.def.shape,!1)},{keyof(){return V(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(ze(this._zod.def,{catchall:e}))},passthrough(){return this.clone(ze(this._zod.def,{catchall:L()}))},loose(){return this.clone(ze(this._zod.def,{catchall:L()}))},strict(){return this.clone(ze(this._zod.def,{catchall:gg()}))},strip(){return this.clone(ze(this._zod.def,{catchall:void 0}))},extend(e){return Pp(this,e)},safeExtend(e){return $p(this,e)},merge(e){return kp(this,e)},pick(e){return Rp(this,e)},omit(e){return wp(this,e)},partial(...e){return Zi(Fs,this,e[0])},exactPartial(...e){return Zi($u,this,e[0],"exactPartial")},required(...e){return Tp(ku,this,e[0])}});function m(e,t){const n={type:"object",shape:e??{},...N(t)};return new Ru(n)}function j(e,t){return new Ru({type:"object",shape:e,catchall:L(),...N(t)})}const wu=b("ZodUnion",(e,t)=>{Pc.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>tu(e,n,o,r),e.options=t.options});function C(e,t){return new wu({type:"union",options:e,...N(t)})}const vg=b("ZodDiscriminatedUnion",(e,t)=>{wu.init(e,t),Vm.init(e,t)});function yr(e,t,n){return new vg({type:"union",options:t,discriminator:e,...N(n)})}const yg=b("ZodIntersection",(e,t)=>{Hm.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>nu(e,n,o,r)});function Ft(e,t){return new yg({type:"intersection",left:e,right:t})}const bg=b("ZodTuple",(e,t)=>{Co(),Jm.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ou(e,n,o,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){const e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new Fs({type:"optional",innerType:t}))})}});function gR(e,t,n){const o=t instanceof X,r=o?n:t,s=o?t:null;return new bg({type:"tuple",items:e,rest:s,...N(r)})}const wa=b("ZodRecord",(e,t)=>{Co(),Bm.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>ru(e,n,o,r),e.keyType=t.keyType,e.valueType=t.valueType});function $(e,t,n){return!t||!t._zod?new wa({type:"record",keyType:c(),valueType:e,...N(t)}):new wa({type:"record",keyType:e,valueType:t,...N(n)})}const fs=b("ZodEnum",(e,t)=>{Wm.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(o,r,s)=>Gc(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 fs({...t,checks:[],...N(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 fs({...t,checks:[],...N(r),entries:s})}});function V(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new fs({type:"enum",entries:n,...N(t)})}const Rg=b("ZodLiteral",(e,t)=>{Gm.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Kc(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 _(e,t){return new Rg({type:"literal",values:Array.isArray(e)?e:[e],...N(t)})}const wg=b("ZodTransform",(e,t)=>{Co(),Km.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Xc(e,n,o,r),e._zod.parse=(n,o)=>{if(o.direction==="backward")throw new uc(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(bo(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(bo(i))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(s=>(n.value=s,n)):(n.value=r,n)}});function Pu(e){return new wg({type:"transform",transform:e})}const Fs=b("ZodOptional",(e,t)=>{$c.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Ds(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function A(e){return new Fs({type:"optional",innerType:e})}const $u=b("ZodExactOptional",(e,t)=>{Ym.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Ds(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function Pg(e){return new $u({type:"optional",innerType:e})}const $g=b("ZodNullable",(e,t)=>{Xm.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>su(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function Pa(e){return new $g({type:"nullable",innerType:e})}const kg=b("ZodDefault",(e,t)=>{Qm.init(e,t),Q.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 Tg(e,t){return new kg({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():rc(t)}})}const Eg=b("ZodPrefault",(e,t)=>{ef.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>uu(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function Cg(e,t){return new Eg({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():rc(t)}})}const ku=b("ZodNonOptional",(e,t)=>{tf.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>iu(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function Ig(e,t){return new ku({type:"nonoptional",innerType:e,...N(t)})}const Og=b("ZodCatch",(e,t)=>{nf.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>lu(e,n,o,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function qg(e,t){return new Og({type:"catch",innerType:e,catchValue:typeof t=="function"?t:Ap(t)})}const Tu=b("ZodPipe",(e,t)=>{kc.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>du(e,n,o,r),e.in=t.in,e.out=t.out});function $a(e,t){return new Tu({type:"pipe",in:e,out:t})}const Ng=b("ZodPreprocess",(e,t)=>{Tu.init(e,t),of.init(e,t)}),Mg=b("ZodReadonly",(e,t)=>{rf.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>pu(e,n,o,r),e.unwrap=()=>e._zod.def.innerType});function xg(e){return new Mg({type:"readonly",innerType:e})}const zg=b("ZodLazy",(e,t)=>{sf.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>hu(e,n,o,r),e.unwrap=()=>e._zod.def.getter()});function Vs(e){return new zg({type:"lazy",getter:e})}const Hs=b("ZodCustom",(e,t)=>{af.init(e,t),Q.init(e,t),e._zod.processJSONSchema=(n,o,r)=>Yc(e,n,o,r)});function _R(e,t){return cS(Hs,(()=>!0),t)}function Ag(e,t={}){return uS(Hs,e,t)}function Lg(e,t){return lS(e,t)}const Ug=b("ZodInstanceOf",(e,t)=>{Hs.init(e,t)},{properties(e,t){return this.check(tS(e,t))}});function vR(e,t={}){const n=new Ug({type:"custom",check:"custom",fn:o=>o instanceof e,abort:!0,...N(t)});return n._zod.bag.Class=e,n._zod.check=o=>{o.value instanceof e||o.issues.push({code:"invalid_type",expected:e.name,input:o.value,inst:n,path:[...n._zod.def.path??[]]})},n}function Po(e,t){return new Ng({type:"pipe",in:Pu(e),out:t})}const jg={custom:"custom"};function Er(e){return Oc(gu,e)}function Dg(e){return qc(_u,e)}function Zg(e){return Zf(Zs,e)}var Fg=Object.create,Js=Object.defineProperty,Vg=Object.getOwnPropertyDescriptor,Hg=Object.getOwnPropertyNames,Jg=Object.getPrototypeOf,Bg=Object.prototype.hasOwnProperty,Wg=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Gg=(e,t)=>{let n={};for(var o in e)Js(n,o,{get:e[o],enumerable:!0});return n},Kg=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var r=Hg(t),s=0,i=r.length,a;s<i;s++)a=r[s],!Bg.call(e,a)&&a!==n&&Js(e,a,{get:(u=>t[u]).bind(null,a),enumerable:!(o=Vg(t,a))||o.enumerable});return e},Yg=(e,t,n)=>(n=e!=null?Fg(Jg(e)):{},Kg(Js(n,"default",{value:e,enumerable:!0}),e));const Xg=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),Eu=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),Qg=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),e_=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function t_(e){return typeof e=="string"&&Eu.has(e.replace(/#$/,""))}function n_(e,t){if(!("$schema"in e)||typeof e.$schema!="string")return"2020-12";const n=e.$schema.replace(/#$/,"");if(Xg.has(n))return"2020-12";if(Eu.has(n))return"2019-09";if(Qg.has(n)||e_.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 Bs="2025-11-25",o_=[Bs,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],r_="io.modelcontextprotocol/related-task",wn="io.modelcontextprotocol/protocolVersion",Ws="io.modelcontextprotocol/clientInfo",rn="io.modelcontextprotocol/serverInfo",Cr="io.modelcontextprotocol/clientCapabilities",Cu="io.modelcontextprotocol/subscriptionId",Gs="io.modelcontextprotocol/logLevel",Ir="2.0",Pn=Vs(()=>C([c(),R(),E(),wo(),$(c(),Pn),g(Pn)])),ue=$(c(),Pn),s_=g(Pn),Ks=C([c(),R().int()]),Ys=c(),Iu=m({ttl:R().optional()}),Ou=m({taskId:c()}),Xs=j({progressToken:Ks.optional(),[r_]:Ou.optional()}),ve=m({_meta:Xs.optional()}),Io=ve.extend({task:Iu.optional()}),le=m({method:c(),params:ve.loose().optional()}),Ce=m({_meta:Xs.optional()}),Ie=m({method:c(),params:Ce.loose().optional()}),Qs=j({get[rn](){return Nr.optional().catch(void 0)}}),de=j({_meta:Qs.optional()}),Tn=C([c(),R().int()]),ei=m({jsonrpc:_(Ir),id:Tn,...le.shape}).strict(),ti=m({jsonrpc:_(Ir),...Ie.shape}).strict(),Or=m({jsonrpc:_(Ir),id:Tn,result:de}).strict(),qr=m({jsonrpc:_(Ir),id:Tn.optional(),error:m({code:R().int(),message:c(),data:L().optional()})}).strict(),ho=C([ei,ti,Or,qr]),i_=C([Or,qr]),ni=de.strict(),qu=Ce.extend({requestId:Tn.optional(),reason:c().optional()}),oi=Ie.extend({method:_("notifications/cancelled"),params:qu}),Nu=m({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:V(["light","dark"]).optional()}),En=m({icons:g(Nu).optional()}),Vt=m({name:c(),title:c().optional()}),Nr=Vt.extend({...Vt.shape,...En.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),a_=Ft(m({applyDefaults:E().optional()}),ue),c_=Po(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Ft(m({form:a_.optional(),url:ue.optional()}),ue.optional())),Mu=j({list:ue.optional(),cancel:ue.optional(),requests:j({sampling:j({createMessage:ue.optional()}).optional(),elicitation:j({create:ue.optional()}).optional()}).optional()}),xu=j({list:ue.optional(),cancel:ue.optional(),requests:j({tools:j({call:ue.optional()}).optional()}).optional()}),zu=m({experimental:$(c(),ue).optional(),sampling:m({context:ue.optional(),tools:ue.optional()}).optional(),elicitation:c_.optional(),roots:m({listChanged:E().optional()}).optional(),tasks:Mu.optional(),extensions:$(c(),ue).optional()}),Au=ve.extend({protocolVersion:c(),capabilities:zu,clientInfo:Nr}),ri=le.extend({method:_("initialize"),params:Au}),si=m({experimental:$(c(),ue).optional(),logging:ue.optional(),completions:ue.optional(),prompts:m({listChanged:E().optional()}).optional(),resources:m({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:m({listChanged:E().optional()}).optional(),tasks:xu.optional(),extensions:$(c(),ue).optional()}),Lu=de.extend({protocolVersion:c(),capabilities:si,serverInfo:Nr,instructions:c().optional()}),ii=Ie.extend({method:_("notifications/initialized"),params:Ce.optional()}),Uu=le.extend({method:_("server/discover"),params:ve.optional()}),Mr=de.extend({supportedVersions:g(c()),capabilities:si,instructions:c().optional()}),ai=le.extend({method:_("ping"),params:ve.optional()}),ju=m({progress:R(),total:A(R()),message:A(c())}),Du=m({...Ce.shape,...ju.shape,progressToken:Ks}),ci=Ie.extend({method:_("notifications/progress"),params:Du}),Zu=ve.extend({cursor:Ys.optional()}),Cn=le.extend({params:Zu.optional()}),In=de.extend({nextCursor:Ys.optional()}),ui=m({uri:c(),mimeType:A(c()),_meta:$(c(),L()).optional()}),li=ui.extend({text:c()}),di=c().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),pi=ui.extend({blob:di}),On=V(["user","assistant"]),Ht=m({audience:g(On).optional(),priority:R().min(0).max(1).optional(),lastModified:Er({offset:!0}).optional()}),hi=m({...Vt.shape,...En.shape,uri:c(),description:A(c()),mimeType:A(c()),size:A(R()),annotations:Ht.optional(),_meta:A(j({}))}),Fu=m({...Vt.shape,...En.shape,uriTemplate:c(),description:A(c()),mimeType:A(c()),annotations:Ht.optional(),_meta:A(j({}))}),Vu=Cn.extend({method:_("resources/list")}),Hu=In.extend({resources:g(hi)}),Ju=Cn.extend({method:_("resources/templates/list")}),Bu=In.extend({resourceTemplates:g(Fu)}),xr=ve.extend({uri:c()}),Wu=xr,Gu=le.extend({method:_("resources/read"),params:Wu}),Ku=de.extend({contents:g(C([li,pi]))}),Yu=Ie.extend({method:_("notifications/resources/list_changed"),params:Ce.optional()}),Xu=xr,Qu=le.extend({method:_("resources/subscribe"),params:Xu}),el=xr,tl=le.extend({method:_("resources/unsubscribe"),params:el}),mi=m({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:g(c()).optional()}),nl=ve.extend({notifications:mi}),ol=le.extend({method:_("subscriptions/listen"),params:nl}),rl=Ce.extend({notifications:mi}),sl=Ie.extend({method:_("notifications/subscriptions/acknowledged"),params:rl}),il=Qs.extend({[Cu]:Tn}),al=de.extend({_meta:il}),cl=Ce.extend({uri:c()}),ul=Ie.extend({method:_("notifications/resources/updated"),params:cl}),ll=m({name:c(),description:A(c()),required:A(E())}),dl=m({...Vt.shape,...En.shape,description:A(c()),arguments:A(g(ll)),_meta:A(j({}))}),pl=Cn.extend({method:_("prompts/list")}),hl=In.extend({prompts:g(dl)}),ml=ve.extend({name:c(),arguments:$(c(),c()).optional()}),fl=le.extend({method:_("prompts/get"),params:ml}),zr=m({type:_("text"),text:c(),annotations:Ht.optional(),_meta:$(c(),L()).optional()}),Ar=m({type:_("image"),data:di,mimeType:c(),annotations:Ht.optional(),_meta:$(c(),L()).optional()}),Lr=m({type:_("audio"),data:di,mimeType:c(),annotations:Ht.optional(),_meta:$(c(),L()).optional()}),Sl=m({type:_("tool_use"),name:c(),id:c(),input:$(c(),L()),_meta:$(c(),L()).optional()}),gl=m({type:_("resource"),resource:C([li,pi]),annotations:Ht.optional(),_meta:$(c(),L()).optional()}),_l=hi.extend({type:_("resource_link")}),Ur=C([zr,Ar,Lr,_l,gl]),vl=m({role:On,content:Ur}),yl=de.extend({description:c().optional(),messages:g(vl)}),bl=Ie.extend({method:_("notifications/prompts/list_changed"),params:Ce.optional()}),Rl=m({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),wl=m({taskSupport:V(["required","optional","forbidden"]).optional()}),fi=m({...Vt.shape,...En.shape,description:c().optional(),inputSchema:m({type:_("object"),properties:$(c(),Pn).optional(),required:g(c()).optional()}).catchall(L()),outputSchema:j({$schema:c().optional()}).optional(),annotations:Rl.optional(),execution:wl.optional(),_meta:$(c(),L()).optional()}),Pl=Cn.extend({method:_("tools/list")}),$l=In.extend({tools:g(fi)}),Si=de.extend({content:g(Ur).default([]),structuredContent:L().optional(),isError:E().optional()}),u_=Si.or(de.extend({toolResult:L()})),kl=Io.extend({name:c(),arguments:$(c(),L()).optional()}),Tl=le.extend({method:_("tools/call"),params:kl}),El=Ie.extend({method:_("notifications/tools/list_changed"),params:Ce.optional()}),Cl=m({autoRefresh:E().default(!0),debounceMs:R().int().nonnegative().default(300)}),gi=V(["debug","info","notice","warning","error","critical","alert","emergency"]),Il=ve.extend({level:gi}),Ol=le.extend({method:_("logging/setLevel"),params:Il}),ql=Ce.extend({level:gi,logger:c().optional(),data:L()}),Nl=Ie.extend({method:_("notifications/message"),params:ql}),Ml=m({name:c().optional()}),xl=m({hints:g(Ml).optional(),costPriority:R().min(0).max(1).optional(),speedPriority:R().min(0).max(1).optional(),intelligencePriority:R().min(0).max(1).optional()}),zl=m({mode:V(["auto","required","none"]).optional()}),Al=m({type:_("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:g(Ur),structuredContent:L().optional(),isError:E().optional(),_meta:$(c(),L()).optional()}),Ll=yr("type",[zr,Ar,Lr]),$o=yr("type",[zr,Ar,Lr,Sl,Al]),Ul=m({role:On,content:C([$o,g($o)]),_meta:$(c(),L()).optional()}),jl=Io.extend({messages:g(Ul),modelPreferences:xl.optional(),systemPrompt:c().optional(),includeContext:V(["none","thisServer","allServers"]).optional(),temperature:R().optional(),maxTokens:R().int(),stopSequences:g(c()).optional(),metadata:ue.optional(),tools:g(fi).optional(),toolChoice:zl.optional()}),Dl=le.extend({method:_("sampling/createMessage"),params:jl}),Zl=de.extend({model:c(),stopReason:A(V(["endTurn","stopSequence","maxTokens"]).or(c())),role:On,content:Ll}),Fl=de.extend({model:c(),stopReason:A(V(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:On,content:C([$o,g($o)])}),_i=m({type:_("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),jr=m({type:_("string"),title:c().optional(),description:c().optional(),minLength:R().optional(),maxLength:R().optional(),format:V(["email","uri","date","date-time"]).optional(),default:c().optional()}),br=m({type:V(["number","integer"]),title:c().optional(),description:c().optional(),minimum:R().optional(),maximum:R().optional(),default:R().optional()}),vi=m({type:_("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),yi=m({type:_("string"),title:c().optional(),description:c().optional(),oneOf:g(m({const:c(),title:c()})),default:c().optional()}),bi=m({type:_("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),Vl=C([vi,yi]),Ri=m({type:_("array"),title:c().optional(),description:c().optional(),minItems:R().optional(),maxItems:R().optional(),items:m({type:_("string"),enum:g(c())}),default:g(c()).optional()}),wi=m({type:_("array"),title:c().optional(),description:c().optional(),minItems:R().optional(),maxItems:R().optional(),items:m({anyOf:g(m({const:c(),title:c()}))}),default:g(c()).optional()}),Hl=C([Ri,wi]),Jl=C([bi,Vl,Hl]),Pi=C([Jl,_i,jr,br]),Dr=Io.extend({mode:_("form").optional(),message:c(),requestedSchema:m({type:_("object"),properties:$(c(),Pi),required:g(c()).optional()}).catchall(L())}),Bl=Io.extend({mode:_("url"),message:c(),elicitationId:c(),url:c().url()}),Wl=C([Dr,Bl]),Gl=le.extend({method:_("elicitation/create"),params:Wl}),Kl=Ce.extend({elicitationId:c()}),Yl=Ie.extend({method:_("notifications/elicitation/complete"),params:Kl}),Xl=de.extend({action:V(["accept","decline","cancel"]),content:Po(e=>e===null?void 0:e,$(c(),C([c(),R(),E(),g(c())])).optional())}),Ql=m({type:_("ref/resource"),uri:c()}),ed=m({type:_("ref/prompt"),name:c()}),td=ve.extend({ref:C([ed,Ql]),argument:m({name:c(),value:c()}),context:m({arguments:$(c(),c()).optional()}).optional()}),nd=le.extend({method:_("completion/complete"),params:td}),od=de.extend({completion:j({values:g(c()).max(100),total:A(R().int()),hasMore:A(E())})}),rd=m({uri:c().startsWith("file://"),name:c().optional(),_meta:$(c(),L()).optional()}),sd=le.extend({method:_("roots/list"),params:ve.optional()}),id=de.extend({roots:g(rd)}),ad=Ie.extend({method:_("notifications/roots/list_changed"),params:Ce.optional()}),l_=j({ttl:R().optional(),pollInterval:R().optional()}),cd=V(["working","input_required","completed","failed","cancelled"]),qn=m({taskId:c(),status:cd,ttl:C([R(),wo()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:A(R()),statusMessage:A(c())}),d_=de.extend({task:qn}),ud=Ce.merge(qn),p_=Ie.extend({method:_("notifications/tasks/status"),params:ud}),h_=le.extend({method:_("tasks/get"),params:ve.extend({taskId:c()})}),m_=de.merge(qn),f_=le.extend({method:_("tasks/result"),params:ve.extend({taskId:c()})}),S_=de.loose(),g_=Cn.extend({method:_("tasks/list")}),__=In.extend({tasks:g(qn)}),v_=le.extend({method:_("tasks/cancel"),params:ve.extend({taskId:c()})}),y_=de.merge(qn),b_=C([ai,ri,Uu,nd,Ol,fl,pl,Vu,Ju,Gu,Qu,tl,ol,Tl,Pl]),R_=C([oi,ci,ii,ad]),w_=C([ni,Zl,Fl,Xl,id]),P_=C([ai,Dl,Gl,sd]),$_=C([oi,ci,Nl,ul,Yu,El,bl,sl,Yl]),k_=C([ni,Lu,Mr,od,yl,hl,Hu,Bu,Ku,Si,$l,al]),he=bu().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:jg.custom,message:"URL must be parseable",fatal:!0}),Lp}).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"}),ld=j({resource:c().url(),authorization_servers:g(he).optional(),jwks_uri:c().url().optional(),scopes_supported:g(c()).optional(),bearer_methods_supported:g(c()).optional(),resource_signing_alg_values_supported:g(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:E().optional(),authorization_details_types_supported:g(c()).optional(),dpop_signing_alg_values_supported:g(c()).optional(),dpop_bound_access_tokens_required:E().optional()}),$i=j({issuer:c(),authorization_endpoint:he,token_endpoint:he,registration_endpoint:he.optional(),scopes_supported:g(c()).optional(),response_types_supported:g(c()),response_modes_supported:g(c()).optional(),grant_types_supported:g(c()).optional(),token_endpoint_auth_methods_supported:g(c()).optional(),token_endpoint_auth_signing_alg_values_supported:g(c()).optional(),service_documentation:he.optional(),revocation_endpoint:he.optional(),revocation_endpoint_auth_methods_supported:g(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:g(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:g(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:g(c()).optional(),code_challenge_methods_supported:g(c()).optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0),dpop_signing_alg_values_supported:g(c()).optional()}),dd=j({issuer:c(),authorization_endpoint:he,token_endpoint:he,userinfo_endpoint:he.optional(),jwks_uri:he,registration_endpoint:he.optional(),scopes_supported:g(c()).optional(),response_types_supported:g(c()),response_modes_supported:g(c()).optional(),grant_types_supported:g(c()).optional(),acr_values_supported:g(c()).optional(),subject_types_supported:g(c()),id_token_signing_alg_values_supported:g(c()),id_token_encryption_alg_values_supported:g(c()).optional(),id_token_encryption_enc_values_supported:g(c()).optional(),userinfo_signing_alg_values_supported:g(c()).optional(),userinfo_encryption_alg_values_supported:g(c()).optional(),userinfo_encryption_enc_values_supported:g(c()).optional(),request_object_signing_alg_values_supported:g(c()).optional(),request_object_encryption_alg_values_supported:g(c()).optional(),request_object_encryption_enc_values_supported:g(c()).optional(),token_endpoint_auth_methods_supported:g(c()).optional(),token_endpoint_auth_signing_alg_values_supported:g(c()).optional(),display_values_supported:g(c()).optional(),claim_types_supported:g(c()).optional(),claims_supported:g(c()).optional(),service_documentation:c().optional(),claims_locales_supported:g(c()).optional(),ui_locales_supported:g(c()).optional(),claims_parameter_supported:E().optional(),request_parameter_supported:E().optional(),request_uri_parameter_supported:E().optional(),require_request_uri_registration:E().optional(),op_policy_uri:he.optional(),op_tos_uri:he.optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0)}),pd=m({...dd.shape,...$i.pick({code_challenge_methods_supported:!0}).shape}),hd=m({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:Zg().optional(),scope:c().optional(),refresh_token:c().optional(),issuer:c().optional().catch(void 0)}).strip(),T_=m({issued_token_type:_("urn:ietf:params:oauth:token-type:id-jag"),access_token:c(),token_type:c().optional(),expires_in:R().optional(),scope:c().optional()}).strip(),md=m({error:c(),error_description:c().optional(),error_uri:c().optional()}),ka=he.optional().or(_("").transform(()=>{})),fd=m({redirect_uris:g(he),token_endpoint_auth_method:c().optional(),grant_types:g(c()).optional(),response_types:g(c()).optional(),application_type:c().optional(),client_name:c().optional(),client_uri:he.optional(),logo_uri:ka,scope:c().optional(),contacts:g(c()).optional(),tos_uri:ka,policy_uri:c().optional(),jwks_uri:he.optional(),jwks:mg().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Sd=m({client_id:c(),client_secret:c().optional(),client_id_issued_at:R().optional(),client_secret_expires_at:R().optional(),issuer:c().optional().catch(void 0)}).strip(),gd=fd.merge(Sd),E_=m({error:c(),error_description:c().optional()}).strip(),C_=m({token:c(),token_type_hint:c().optional()}).strip(),Ss=Symbol.for("mcp.sdk.errorBrands");function Oo(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,Ss,{value:n,enumerable:!1,configurable:!0})}function ct(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,Ss)){const n=t[Ss];if(n&&typeof n.has=="function"&&n.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}let yt=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e})({});var jt,$n=(jt=class extends Error{static[Symbol.hasInstance](t){return ct(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 ct(this,t)}constructor(t,n,o){super(n),this.code=t,this.errorUri=o,this.name="OAuthError",Oo(this,new.target)}toResponseObject(){const t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new jt(t.error,t.error_description??t.error,t.error_uri)}},Object.defineProperty(jt,"mcpBrand",{value:"mcp.OAuthError"}),jt);let I=(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 sn,q=(sn=class extends Error{static[Symbol.hasInstance](t){return ct(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 ct(this,t)}constructor(t,n,o,r){super(n,r),this.code=t,this.data=o,this.name="SdkError",Oo(this,new.target)}},Object.defineProperty(sn,"mcpBrand",{value:"mcp.SdkError"}),sn),an,pt=(an=class extends q{constructor(t,n,o,r){super(t,n,o,r),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}},Object.defineProperty(an,"mcpBrand",{value:"mcp.SdkHttpError"}),an);function I_(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function _d(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;const t={...e};return delete t.issuer,t}function O_({requestedResource:e,configuredResource:t}){const n=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==o.origin||n.pathname.length<o.pathname.length)return!1;const r=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return r.startsWith(s)}const vd="2026-07-28",yd=[vd];function bt(e){return e>=vd}function bd(e){return e.filter(t=>!bt(t))}function Rr(e){return e.filter(t=>bt(t))}function Rd(e){const t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(n=>n.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}const wd=["task","inputRequests","requestState"];function q_(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||wd.some(t=>t in e)?e:{...e,content:[]}}function N_(){const e=Vs(()=>C([c(),R(),E(),wo(),$(c(),e),g(e)])),t=$(c(),e),n=C([c(),R().int()]),o=c(),r=m({ttl:R().optional()}),s=m({taskId:c()}),i=j({progressToken:n.optional(),"io.modelcontextprotocol/related-task":s.optional()}),a=m({_meta:i.optional()}),u=a.extend({task:r.optional()}),d=m({method:c(),params:a.loose().optional()}),l=m({_meta:i.optional()}),p=m({method:c(),params:l.loose().optional()}),h=j({_meta:i.optional()}),f=C([c(),R().int()]),S=h.strict(),v=l.extend({requestId:f.optional(),reason:c().optional()}),y=p.extend({method:_("notifications/cancelled"),params:v}),w=m({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:V(["light","dark"]).optional()}),x=m({icons:g(w).optional()}),z=m({name:c(),title:c().optional()}),J=z.extend({...z.shape,...x.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),B=Ft(m({applyDefaults:E().optional()}),t),O=Po(_e=>_e&&typeof _e=="object"&&!Array.isArray(_e)&&Object.keys(_e).length===0?{form:{}}:_e,Ft(m({form:B.optional(),url:t.optional()}),t.optional())),G=j({list:t.optional(),cancel:t.optional(),requests:j({sampling:j({createMessage:t.optional()}).optional(),elicitation:j({create:t.optional()}).optional()}).optional()}),ie=j({list:t.optional(),cancel:t.optional(),requests:j({tools:j({call:t.optional()}).optional()}).optional()}),te=m({experimental:$(c(),t).optional(),sampling:m({context:t.optional(),tools:t.optional()}).optional(),elicitation:O.optional(),roots:m({listChanged:E().optional()}).optional(),tasks:G.optional(),extensions:$(c(),t).optional()}),pe=a.extend({protocolVersion:c(),capabilities:te,clientInfo:J}),fe=d.extend({method:_("initialize"),params:pe}),K=m({experimental:$(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:m({listChanged:E().optional()}).optional(),resources:m({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:m({listChanged:E().optional()}).optional(),tasks:ie.optional(),extensions:$(c(),t).optional()}),ne=h.extend({protocolVersion:c(),capabilities:K,serverInfo:J,instructions:c().optional()}),Ke=p.extend({method:_("notifications/initialized"),params:l.optional()}),Le=d.extend({method:_("ping"),params:a.optional()}),Ye=m({progress:R(),total:A(R()),message:A(c())}),ke=m({...l.shape,...Ye.shape,progressToken:n}),Ue=p.extend({method:_("notifications/progress"),params:ke}),Xe=a.extend({cursor:o.optional()}),Oe=d.extend({params:Xe.optional()}),ye=h.extend({nextCursor:o.optional()}),lt=m({uri:c(),mimeType:A(c()),_meta:$(c(),L()).optional()}),dt=lt.extend({text:c()}),Qe=c().refine(_e=>{try{return atob(_e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Se=lt.extend({blob:Qe}),be=V(["user","assistant"]),Re=m({audience:g(be).optional(),priority:R().min(0).max(1).optional(),lastModified:Er({offset:!0}).optional()}),Je=m({...z.shape,...x.shape,uri:c(),description:A(c()),mimeType:A(c()),size:A(R()),annotations:Re.optional(),_meta:A(j({}))}),Tt=m({...z.shape,...x.shape,uriTemplate:c(),description:A(c()),mimeType:A(c()),annotations:Re.optional(),_meta:A(j({}))}),qe=Oe.extend({method:_("resources/list")}),Ne=ye.extend({resources:g(Je)}),Te=Oe.extend({method:_("resources/templates/list")}),je=ye.extend({resourceTemplates:g(Tt)}),De=a.extend({uri:c()}),et=De,tt=d.extend({method:_("resources/read"),params:et}),ft=h.extend({contents:g(C([dt,Se]))}),nt=p.extend({method:_("notifications/resources/list_changed"),params:l.optional()}),Et=De,k=d.extend({method:_("resources/subscribe"),params:Et}),ot=De,U=d.extend({method:_("resources/unsubscribe"),params:ot}),M=l.extend({uri:c()}),H=p.extend({method:_("notifications/resources/updated"),params:M}),T=m({name:c(),description:A(c()),required:A(E())}),P=m({...z.shape,...x.shape,description:A(c()),arguments:A(g(T)),_meta:A(j({}))}),Z=Oe.extend({method:_("prompts/list")}),D=ye.extend({prompts:g(P)}),ce=a.extend({name:c(),arguments:$(c(),c()).optional()}),Ct=d.extend({method:_("prompts/get"),params:ce}),rt=m({type:_("text"),text:c(),annotations:Re.optional(),_meta:$(c(),L()).optional()}),It=m({type:_("image"),data:Qe,mimeType:c(),annotations:Re.optional(),_meta:$(c(),L()).optional()}),Ot=m({type:_("audio"),data:Qe,mimeType:c(),annotations:Re.optional(),_meta:$(c(),L()).optional()}),Nn=m({type:_("tool_use"),name:c(),id:c(),input:$(c(),L()),_meta:$(c(),L()).optional()}),St=m({type:_("resource"),resource:C([dt,Se]),annotations:Re.optional(),_meta:$(c(),L()).optional()}),Mn=Je.extend({type:_("resource_link")}),Ze=C([rt,It,Ot,Mn,St]),Jt=m({role:be,content:Ze}),Bt=h.extend({description:c().optional(),messages:g(Jt)}),qt=p.extend({method:_("notifications/prompts/list_changed"),params:l.optional()}),xn=m({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Wt=m({taskSupport:V(["required","optional","forbidden"]).optional()}),Nt=m({...z.shape,...x.shape,description:c().optional(),inputSchema:m({type:_("object"),properties:$(c(),e).optional(),required:g(c()).optional()}).catchall(L()),outputSchema:m({type:_("object"),properties:$(c(),e).optional(),required:g(c()).optional()}).catchall(L()).optional(),annotations:xn.optional(),execution:Wt.optional(),_meta:$(c(),L()).optional()}),Gt=Oe.extend({method:_("tools/list")}),Kt=ye.extend({tools:g(Nt)}),Yt=h.extend({content:g(Ze),structuredContent:$(c(),L()).optional(),isError:E().optional()}),ge=u.extend({name:c(),arguments:$(c(),L()).optional()}),zn=d.extend({method:_("tools/call"),params:ge}),No=p.extend({method:_("notifications/tools/list_changed"),params:l.optional()}),Xt=V(["debug","info","notice","warning","error","critical","alert","emergency"]),An=a.extend({level:Xt}),Ln=d.extend({method:_("logging/setLevel"),params:An}),Un=l.extend({level:Xt,logger:c().optional(),data:L()}),jn=p.extend({method:_("notifications/message"),params:Un}),Dn=m({name:c().optional()}),Zn=m({hints:g(Dn).optional(),costPriority:R().min(0).max(1).optional(),speedPriority:R().min(0).max(1).optional(),intelligencePriority:R().min(0).max(1).optional()}),Fn=m({mode:V(["auto","required","none"]).optional()}),Mo=m({type:_("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:g(Ze),structuredContent:m({}).loose().optional(),isError:E().optional(),_meta:$(c(),L()).optional()}),Vn=yr("type",[rt,It,Ot]),gt=yr("type",[rt,It,Ot,Nn,Mo]),Hn=m({role:be,content:C([gt,g(gt)]),_meta:$(c(),L()).optional()}),Jn=u.extend({messages:g(Hn),modelPreferences:Zn.optional(),systemPrompt:c().optional(),includeContext:V(["none","thisServer","allServers"]).optional(),temperature:R().optional(),maxTokens:R().int(),stopSequences:g(c()).optional(),metadata:t.optional(),tools:g(Nt).optional(),toolChoice:Fn.optional()}),Bn=d.extend({method:_("sampling/createMessage"),params:Jn}),Wn=h.extend({model:c(),stopReason:A(V(["endTurn","stopSequence","maxTokens"]).or(c())),role:be,content:Vn}),Gn=h.extend({model:c(),stopReason:A(V(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:be,content:C([gt,g(gt)])}),Kn=m({type:_("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),Yn=m({type:_("string"),title:c().optional(),description:c().optional(),minLength:R().optional(),maxLength:R().optional(),format:V(["email","uri","date","date-time"]).optional(),default:c().optional()}),Xn=m({type:V(["number","integer"]),title:c().optional(),description:c().optional(),minimum:R().optional(),maximum:R().optional(),default:R().optional()}),Qn=m({type:_("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),eo=m({type:_("string"),title:c().optional(),description:c().optional(),oneOf:g(m({const:c(),title:c()})),default:c().optional()}),to=m({type:_("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),no=C([Qn,eo]),Mt=m({type:_("array"),title:c().optional(),description:c().optional(),minItems:R().optional(),maxItems:R().optional(),items:m({type:_("string"),enum:g(c())}),default:g(c()).optional()}),xt=m({type:_("array"),title:c().optional(),description:c().optional(),minItems:R().optional(),maxItems:R().optional(),items:m({anyOf:g(m({const:c(),title:c()}))}),default:g(c()).optional()}),xo=C([Mt,xt]),zo=C([to,no,xo]),Me=C([zo,Kn,Yn,Xn]),xe=u.extend({mode:_("form").optional(),message:c(),requestedSchema:m({type:_("object"),properties:$(c(),Me),required:g(c()).optional()}).catchall(L())}),oo=u.extend({mode:_("url"),message:c(),elicitationId:c(),url:c().url()}),Be=C([xe,oo]),Ao=d.extend({method:_("elicitation/create"),params:Be}),Lo=l.extend({elicitationId:c()}),Uo=p.extend({method:_("notifications/elicitation/complete"),params:Lo}),jo=h.extend({action:V(["accept","decline","cancel"]),content:Po(_e=>_e===null?void 0:_e,$(c(),C([c(),R(),E(),g(c())])).optional())}),Do=m({type:_("ref/resource"),uri:c()}),Zo=m({type:_("ref/prompt"),name:c()}),Fo=a.extend({ref:C([Zo,Do]),argument:m({name:c(),value:c()}),context:m({arguments:$(c(),c()).optional()}).optional()}),ro=d.extend({method:_("completion/complete"),params:Fo}),Vo=h.extend({completion:j({values:g(c()).max(100),total:A(R().int()),hasMore:A(E())})}),Ho=m({uri:c().startsWith("file://"),name:c().optional(),_meta:$(c(),L()).optional()}),Qt=d.extend({method:_("roots/list"),params:a.optional()}),so=h.extend({roots:g(Ho)}),Jo=p.extend({method:_("notifications/roots/list_changed"),params:l.optional()}),Bo=j({ttl:R().optional(),pollInterval:R().optional()}),io=V(["working","input_required","completed","failed","cancelled"]),_t=m({taskId:c(),status:io,ttl:C([R(),wo()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:A(R()),statusMessage:A(c())}),Ee=h.extend({task:_t}),Wo=l.merge(_t),zt=p.extend({method:_("notifications/tasks/status"),params:Wo}),en=d.extend({method:_("tasks/get"),params:a.extend({taskId:c()})}),tn=h.merge(_t),nn=d.extend({method:_("tasks/result"),params:a.extend({taskId:c()})}),Fr=h.loose(),we=Oe.extend({method:_("tasks/list")}),ae=ye.extend({tasks:g(_t)}),At=d.extend({method:_("tasks/cancel"),params:a.extend({taskId:c()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:o,TaskMetadataSchema:r,RelatedTaskMetadataSchema:s,RequestMetaSchema:i,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:u,RequestSchema:d,NotificationsParamsSchema:l,NotificationSchema:p,ResultSchema:h,RequestIdSchema:f,EmptyResultSchema:S,CancelledNotificationParamsSchema:v,CancelledNotificationSchema:y,IconSchema:w,IconsSchema:x,BaseMetadataSchema:z,ImplementationSchema:J,ClientTasksCapabilitySchema:G,ServerTasksCapabilitySchema:ie,ClientCapabilitiesSchema:te,InitializeRequestParamsSchema:pe,InitializeRequestSchema:fe,ServerCapabilitiesSchema:K,InitializeResultSchema:ne,InitializedNotificationSchema:Ke,PingRequestSchema:Le,ProgressSchema:Ye,ProgressNotificationParamsSchema:ke,ProgressNotificationSchema:Ue,PaginatedRequestParamsSchema:Xe,PaginatedRequestSchema:Oe,PaginatedResultSchema:ye,ResourceContentsSchema:lt,TextResourceContentsSchema:dt,BlobResourceContentsSchema:Se,RoleSchema:be,AnnotationsSchema:Re,ResourceSchema:Je,ResourceTemplateSchema:Tt,ListResourcesRequestSchema:qe,ListResourcesResultSchema:Ne,ListResourceTemplatesRequestSchema:Te,ListResourceTemplatesResultSchema:je,ResourceRequestParamsSchema:De,ReadResourceRequestParamsSchema:et,ReadResourceRequestSchema:tt,ReadResourceResultSchema:ft,ResourceListChangedNotificationSchema:nt,SubscribeRequestParamsSchema:Et,SubscribeRequestSchema:k,UnsubscribeRequestParamsSchema:ot,UnsubscribeRequestSchema:U,ResourceUpdatedNotificationParamsSchema:M,ResourceUpdatedNotificationSchema:H,PromptArgumentSchema:T,PromptSchema:P,ListPromptsRequestSchema:Z,ListPromptsResultSchema:D,GetPromptRequestParamsSchema:ce,GetPromptRequestSchema:Ct,TextContentSchema:rt,ImageContentSchema:It,AudioContentSchema:Ot,ToolUseContentSchema:Nn,EmbeddedResourceSchema:St,ResourceLinkSchema:Mn,ContentBlockSchema:Ze,PromptMessageSchema:Jt,GetPromptResultSchema:Bt,PromptListChangedNotificationSchema:qt,ToolAnnotationsSchema:xn,ToolExecutionSchema:Wt,ToolSchema:Nt,ListToolsRequestSchema:Gt,ListToolsResultSchema:Kt,CallToolResultSchema:Yt,CallToolRequestParamsSchema:ge,CallToolRequestSchema:zn,ToolListChangedNotificationSchema:No,LoggingLevelSchema:Xt,SetLevelRequestParamsSchema:An,SetLevelRequestSchema:Ln,LoggingMessageNotificationParamsSchema:Un,LoggingMessageNotificationSchema:jn,ModelHintSchema:Dn,ModelPreferencesSchema:Zn,ToolChoiceSchema:Fn,ToolResultContentSchema:Mo,SamplingContentSchema:Vn,SamplingMessageContentBlockSchema:gt,SamplingMessageSchema:Hn,CreateMessageRequestParamsSchema:Jn,CreateMessageRequestSchema:Bn,CreateMessageResultSchema:Wn,CreateMessageResultWithToolsSchema:Gn,BooleanSchemaSchema:Kn,StringSchemaSchema:Yn,NumberSchemaSchema:Xn,UntitledSingleSelectEnumSchemaSchema:Qn,TitledSingleSelectEnumSchemaSchema:eo,LegacyTitledEnumSchemaSchema:to,SingleSelectEnumSchemaSchema:no,UntitledMultiSelectEnumSchemaSchema:Mt,TitledMultiSelectEnumSchemaSchema:xt,MultiSelectEnumSchemaSchema:xo,EnumSchemaSchema:zo,PrimitiveSchemaDefinitionSchema:Me,ElicitRequestFormParamsSchema:xe,ElicitRequestURLParamsSchema:oo,ElicitRequestParamsSchema:Be,ElicitRequestSchema:Ao,ElicitationCompleteNotificationParamsSchema:Lo,ElicitationCompleteNotificationSchema:Uo,ElicitResultSchema:jo,ResourceTemplateReferenceSchema:Do,PromptReferenceSchema:Zo,CompleteRequestParamsSchema:Fo,CompleteRequestSchema:ro,CompleteResultSchema:Vo,RootSchema:Ho,ListRootsRequestSchema:Qt,ListRootsResultSchema:so,RootsListChangedNotificationSchema:Jo,TaskCreationParamsSchema:Bo,TaskStatusSchema:io,TaskSchema:_t,CreateTaskResultSchema:Ee,TaskStatusNotificationParamsSchema:Wo,TaskStatusNotificationSchema:zt,GetTaskRequestSchema:en,GetTaskResultSchema:tn,GetTaskPayloadRequestSchema:nn,GetTaskPayloadResultSchema:Fr,ListTasksRequestSchema:we,ListTasksResultSchema:ae,CancelTaskRequestSchema:At,CancelTaskResultSchema:h.merge(_t),ClientRequestSchema:C([Le,fe,ro,Ln,Ct,Z,qe,Te,tt,k,U,zn,Gt,en,nn,we,At]),ClientNotificationSchema:C([y,Ue,Ke,Jo,zt]),ClientResultSchema:C([S,Wn,Gn,jo,so,tn,ae,Ee]),ServerRequestSchema:C([Le,Bn,Ao,Qt,en,nn,we,At]),ServerNotificationSchema:C([y,Ue,jn,H,nt,No,qt,zt,Uo]),ServerResultSchema:C([S,ne,Vo,Bt,D,Ne,je,ft,Yt,Kt,tn,ae,Ee]),CallToolResultWireSchema:L().superRefine((_e,ip)=>{if(!(typeof _e!="object"||_e===null||Array.isArray(_e)||_e.content!==void 0)){for(const Li of wd)if(Li in _e){ip.addIssue({code:"custom",message:`content is required when the body carries '${Li}' — another result family cannot default into an empty tools/call success`});return}}}).transform(q_).pipe(Yt)}}let M_;function Pd(){return M_??=N_()}function $d(e){return e.type!=="object"}const x_=new Set(["const","enum","default","examples"]),z_=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function Ta(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}function A_(e){const t=typeof e.$schema=="string"?e.$schema:void 0;if(Ta(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};const n=t_(e.$schema)&&e.$recursiveAnchor!==!0,o=(r,s)=>{if(Array.isArray(r))return r.map(u=>o(u,!1));if(r===null||typeof r!="object"||!s&&Ta(r.$id))return r;const i={};let a=!1;for(const[u,d]of Object.entries(r))s?i[u]=o(d,!1):(u==="$ref"||u==="$dynamicRef")&&typeof d=="string"?i[u]=d==="#"?"#/properties/result":d.startsWith("#/")?`#/properties/result${d.slice(1)}`:d:u==="$recursiveRef"&&d==="#"&&n?a=!0:x_.has(u)?i[u]=d:z_.has(u)?i[u]=o(d,!0):i[u]=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 L_={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},U_={"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},j_={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 er;function ki(){if(er)return er;const e=Pd();return er={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}},er}function kd(e){return Object.prototype.hasOwnProperty.call(L_,e)}function Td(e){return Object.prototype.hasOwnProperty.call(U_,e)}function D_(e){return Object.prototype.hasOwnProperty.call(j_,e)}function Z_(e){return D_(e)?ki().resultSchemas[e]:void 0}function F_(e){return kd(e)?ki().requestSchemas[e]:void 0}function V_(e){return Td(e)?ki().notificationSchemas[e]:void 0}function gs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tr(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 Ea={ok:!1,reason:"not-in-era"};function Ca(e){return gs(e)&&gs(e.outputSchema)&&$d(e.outputSchema)}const Ti={era:"2025-11-25",hasRequestMethod:kd,hasNotificationMethod:Td,validateRequest:(e,t)=>tr(F_(e),t),validateResult:(e,t)=>tr(Z_(e),t),validateNotification:(e,t)=>tr(V_(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>Ea,validateInputResponse:()=>Ea,samplingResultVariant:((e,t)=>{const n=Pd();return tr(e?n.CreateMessageResultWithToolsSchema:n.CreateMessageResultSchema,t)}),outboundEnvelope:e=>{},validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){const n=Rd(e),o=n.structuredContent;if(o===void 0)return n;const r=typeof o!="object"||o===null||Array.isArray(o),s=t!==void 0&&$d(t);return!r&&!s?n:{...n,structuredContent:{result:o}}},decodeResult(e,t){if(gs(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=>Ca(o))?t:{...t,tools:n.map(o=>Ca(o)?{...o,outputSchema:A_(o.outputSchema)}:o)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>{}};function H_(){const e=Vs(()=>C([c(),R(),E(),wo(),$(c(),e),g(e)])),t=$(c(),e),n=C([c(),R().int()]),o=c(),r=C([c(),R().int()]),s=V(["user","assistant"]),i=V(["debug","info","notice","warning","error","critical","alert","emergency"]),a=c().refine(ae=>{try{return atob(ae),!0}catch{return!1}},{message:"Invalid Base64 string"}),u=m({ttl:R().optional()}),d=m({taskId:c()}),l=j({progressToken:n.optional(),"io.modelcontextprotocol/related-task":d.optional()}),p=m({_meta:l.optional()}),h=p.extend({task:u.optional()}),f=m({_meta:l.optional()}),S=m({method:c(),params:f.loose().optional()}),v=m({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:V(["light","dark"]).optional()}),y=m({icons:g(v).optional()}),w=m({name:c(),title:c().optional()}),x=w.extend({...w.shape,...y.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),z=Ft(m({applyDefaults:E().optional()}),t),J=Po(ae=>ae&&typeof ae=="object"&&!Array.isArray(ae)&&Object.keys(ae).length===0?{form:{}}:ae,Ft(m({form:z.optional(),url:t.optional()}),t.optional())),B=j({list:t.optional(),cancel:t.optional(),requests:j({sampling:j({createMessage:t.optional()}).optional(),elicitation:j({create:t.optional()}).optional()}).optional()}),O=j({list:t.optional(),cancel:t.optional(),requests:j({tools:j({call:t.optional()}).optional()}).optional()}),G=m({experimental:$(c(),t).optional(),sampling:m({context:t.optional(),tools:t.optional()}).optional(),elicitation:J.optional(),roots:m({listChanged:E().optional()}).optional(),tasks:B.optional(),extensions:$(c(),t).optional()}),ie=m({experimental:$(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:m({listChanged:E().optional()}).optional(),resources:m({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:m({listChanged:E().optional()}).optional(),tasks:O.optional(),extensions:$(c(),t).optional()}),te=m({progress:R(),total:A(R()),message:A(c())}),pe=m({...f.shape,...te.shape,progressToken:n}),fe=S.extend({method:_("notifications/progress"),params:pe}),K=f.extend({level:i,logger:c().optional(),data:L()}),ne=S.extend({method:_("notifications/message"),params:K}),Ke=m({uri:c(),mimeType:A(c()),_meta:$(c(),L()).optional()}),Le=Ke.extend({text:c()}),Ye=Ke.extend({blob:a}),ke=m({audience:g(s).optional(),priority:R().min(0).max(1).optional(),lastModified:Er({offset:!0}).optional()}),Ue=m({...w.shape,...y.shape,uri:c(),description:A(c()),mimeType:A(c()),size:A(R()),annotations:ke.optional(),_meta:A(j({}))}),Xe=m({...w.shape,...y.shape,uriTemplate:c(),description:A(c()),mimeType:A(c()),annotations:ke.optional(),_meta:A(j({}))}),Oe=S.extend({method:_("notifications/resources/list_changed"),params:f.optional()}),ye=f.extend({uri:c()}),lt=S.extend({method:_("notifications/resources/updated"),params:ye}),dt=m({name:c(),description:A(c()),required:A(E())}),Qe=m({...w.shape,...y.shape,description:A(c()),arguments:A(g(dt)),_meta:A(j({}))}),Se=S.extend({method:_("notifications/prompts/list_changed"),params:f.optional()}),be=m({type:_("text"),text:c(),annotations:ke.optional(),_meta:$(c(),L()).optional()}),Re=m({type:_("image"),data:a,mimeType:c(),annotations:ke.optional(),_meta:$(c(),L()).optional()}),Je=m({type:_("audio"),data:a,mimeType:c(),annotations:ke.optional(),_meta:$(c(),L()).optional()}),Tt=m({type:_("tool_use"),name:c(),id:c(),input:$(c(),L()),_meta:$(c(),L()).optional()}),qe=m({type:_("resource"),resource:C([Le,Ye]),annotations:ke.optional(),_meta:$(c(),L()).optional()}),Ne=Ue.extend({type:_("resource_link")}),Te=C([be,Re,Je,Ne,qe]),je=m({role:s,content:Te}),De=m({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),et=S.extend({method:_("notifications/tools/list_changed"),params:f.optional()}),tt=m({name:c().optional()}),ft=m({hints:g(tt).optional(),costPriority:R().min(0).max(1).optional(),speedPriority:R().min(0).max(1).optional(),intelligencePriority:R().min(0).max(1).optional()}),nt=m({mode:V(["auto","required","none"]).optional()}),Et=m({type:_("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),k=m({type:_("string"),title:c().optional(),description:c().optional(),minLength:R().optional(),maxLength:R().optional(),format:V(["email","uri","date","date-time"]).optional(),default:c().optional()}),ot=m({type:V(["number","integer"]),title:c().optional(),description:c().optional(),minimum:R().optional(),maximum:R().optional(),default:R().optional()}),U=m({type:_("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),M=m({type:_("string"),title:c().optional(),description:c().optional(),oneOf:g(m({const:c(),title:c()})),default:c().optional()}),H=m({type:_("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),T=C([U,M]),P=m({type:_("array"),title:c().optional(),description:c().optional(),minItems:R().optional(),maxItems:R().optional(),items:m({type:_("string"),enum:g(c())}),default:g(c()).optional()}),Z=m({type:_("array"),title:c().optional(),description:c().optional(),minItems:R().optional(),maxItems:R().optional(),items:m({anyOf:g(m({const:c(),title:c()}))}),default:g(c()).optional()}),D=C([P,Z]),ce=C([H,T,D]),Ct=C([ce,Et,k,ot]),rt=h.extend({mode:_("form").optional(),message:c(),requestedSchema:m({type:_("object"),properties:$(c(),Ct),required:g(c()).optional()}).catchall(L())}),It=m({type:_("ref/resource"),uri:c()}),Ot=m({type:_("ref/prompt"),name:c()}),Nn=m({uri:c().startsWith("file://"),name:c().optional(),_meta:$(c(),L()).optional()}),St=G.shape,Mn=m({experimental:St.experimental,sampling:St.sampling,elicitation:St.elicitation,roots:St.roots,extensions:St.extensions}),Ze=ie.shape,Jt=m({experimental:Ze.experimental,logging:Ze.logging,completions:Ze.completions,prompts:Ze.prompts,resources:Ze.resources,tools:Ze.tools,extensions:Ze.extensions}),Bt=j({progressToken:n.optional(),[wn]:c(),[Ws]:x.optional(),[Cr]:Mn,[Gs]:i.optional()}),qt=m({...w.shape,...y.shape,description:c().optional(),inputSchema:j({$schema:c().optional(),type:_("object")}),outputSchema:j({$schema:c().optional()}).optional(),annotations:De.optional(),_meta:$(c(),L()).optional()}),xn=m({type:_("tool_result"),toolUseId:c(),content:g(Te),structuredContent:L().optional(),isError:E().optional(),_meta:$(c(),L()).optional()}),Wt=C([be,Re,Je,Tt,xn]),Nt=m({role:s,content:C([Wt,g(Wt)]),_meta:$(c(),L()).optional()}),Gt=c(),Kt=j({[rn]:x.optional().catch(void 0)}),Yt=Kt.optional();function ge(ae){return j({_meta:Yt,resultType:Gt.default("complete"),...ae})}const zn=ge({}),No=ge({nextCursor:o.optional()}),Xt=ge({content:g(Te),structuredContent:L().optional(),isError:E().optional()}),An=ge({ttlMs:R().int().min(0),cacheScope:V(["public","private"]),tools:g(qt),nextCursor:o.optional()}),Ln=ge({ttlMs:R().int().min(0),cacheScope:V(["public","private"]),prompts:g(Qe),nextCursor:o.optional()}),Un=ge({description:c().optional(),messages:g(je)}),jn=ge({ttlMs:R().int().min(0),cacheScope:V(["public","private"]),resources:g(Ue),nextCursor:o.optional()}),Dn=ge({ttlMs:R().int().min(0),cacheScope:V(["public","private"]),resourceTemplates:g(Xe),nextCursor:o.optional()}),Zn=ge({ttlMs:R().int().min(0),cacheScope:V(["public","private"]),contents:g(C([Le,Ye]))}),Fn=ge({completion:m({values:g(c()).max(100),total:R().int().optional(),hasMore:E().optional()}).loose()}),Mo=ge({ttlMs:R().int().min(0),cacheScope:V(["public","private"])}),Vn=ge({ttlMs:R().int().min(0).catch(0),cacheScope:V(["public","private"]).catch("private"),supportedVersions:g(c()),capabilities:Jt,instructions:c().optional()}),gt=m({messages:g(Nt),modelPreferences:ft.optional(),systemPrompt:c().optional(),includeContext:V(["none","thisServer","allServers"]).optional(),temperature:R().optional(),maxTokens:R().int(),stopSequences:g(c()).optional(),metadata:t.optional(),tools:g(qt).optional(),toolChoice:nt.optional()}),Hn=m({method:_("sampling/createMessage"),params:gt}),Jn=m({method:_("roots/list"),params:m({_meta:$(c(),L()).optional()}).optional()}),Bn=m({...Nt.shape,model:c(),stopReason:c().optional()}),Wn=m({roots:g(Nn)}),Gn=m({action:V(["accept","decline","cancel"]),content:$(c(),C([c(),R(),E(),g(c())])).optional()}),Kn=m({mode:_("url"),message:c(),url:c().url()}),Yn=C([rt,Kn]),Xn=m({method:_("elicitation/create"),params:Yn}),Qn=C([Hn,Jn,Xn]),eo=C([Bn,Wn,Gn]),to=$(c(),Qn),no=$(c(),eo),Mt=ge({inputRequests:to.optional(),requestState:c().optional()}),xt={inputResponses:no.optional(),requestState:c().optional()},xo=m({_meta:Bt,...xt}),zo=j({progressToken:n.optional()});function Me(ae,At){return m({method:_(ae),params:m({_meta:Bt,...At})})}function xe(ae,At){return m({method:_(ae),params:m({_meta:zo.optional(),...At}).optional()})}const oo={name:c(),arguments:$(c(),L()).optional(),...xt},Be={cursor:o.optional()},Ao=Me("tools/call",oo),Lo=Me("tools/list",Be),Uo=Me("prompts/list",Be),jo=Me("prompts/get",{name:c(),arguments:$(c(),c()).optional(),...xt}),Do=Me("resources/list",Be),Zo=Me("resources/templates/list",Be),Fo=Me("resources/read",{uri:c(),...xt}),ro={ref:C([Ot,It]),argument:m({name:c(),value:c()}),context:m({arguments:$(c(),c()).optional()}).optional()},Vo=Me("completion/complete",ro),Ho=Me("server/discover",{}),Qt=m({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:g(c()).optional()}),so={notifications:Qt},Jo=Me("subscriptions/listen",so),Bo=Kt.extend({"io.modelcontextprotocol/subscriptionId":r}),io=j({_meta:Bo,resultType:Gt.default("complete")}),_t={"tools/call":xe("tools/call",oo),"tools/list":xe("tools/list",Be),"prompts/get":xe("prompts/get",{name:c(),arguments:$(c(),c()).optional()}),"prompts/list":xe("prompts/list",Be),"resources/list":xe("resources/list",Be),"resources/templates/list":xe("resources/templates/list",Be),"resources/read":xe("resources/read",{uri:c()}),"completion/complete":xe("completion/complete",ro),"server/discover":xe("server/discover",{}),"subscriptions/listen":xe("subscriptions/listen",so)};function Ee(ae){return j({_meta:Yt,...ae})}const Wo={"tools/call":Ee({content:g(Te),structuredContent:L().optional(),isError:E().optional()}),"tools/list":Ee({ttlMs:R().int().min(0),cacheScope:V(["public","private"]),tools:g(qt),nextCursor:o.optional()}),"prompts/get":Ee({description:c().optional(),messages:g(je)}),"prompts/list":Ee({ttlMs:R().int().min(0),cacheScope:V(["public","private"]),prompts:g(Qe),nextCursor:o.optional()}),"resources/list":Ee({ttlMs:R().int().min(0),cacheScope:V(["public","private"]),resources:g(Ue),nextCursor:o.optional()}),"resources/templates/list":Ee({ttlMs:R().int().min(0),cacheScope:V(["public","private"]),resourceTemplates:g(Xe),nextCursor:o.optional()}),"resources/read":Ee({ttlMs:R().int().min(0),cacheScope:V(["public","private"]),contents:g(C([Le,Ye]))}),"completion/complete":Ee({completion:m({values:g(c()).max(100),total:R().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":Ee({ttlMs:R().int().min(0).catch(0),cacheScope:V(["public","private"]).catch("private"),supportedVersions:g(c()),capabilities:Jt,instructions:c().optional()}),"subscriptions/listen":Ee({})},zt=j({"io.modelcontextprotocol/subscriptionId":r.optional()}),en=m({method:_("notifications/subscriptions/acknowledged"),params:m({_meta:zt.optional(),notifications:Qt})}),tn=m({_meta:zt.optional(),requestId:r,reason:c().optional()}),nn=m({method:_("notifications/cancelled"),params:tn}),Fr={"notifications/cancelled":nn,"notifications/progress":fe,"notifications/message":ne,"notifications/resources/updated":lt,"notifications/resources/list_changed":Oe,"notifications/tools/list_changed":et,"notifications/prompts/list_changed":Se,"notifications/subscriptions/acknowledged":en},we=ae=>m({jsonrpc:_("2.0"),id:C([c(),R().int()]),result:ae}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:o,RequestIdSchema:r,RoleSchema:s,LoggingLevelSchema:i,TaskMetadataSchema:u,RelatedTaskMetadataSchema:d,RequestMetaSchema:l,BaseRequestParamsSchema:p,TaskAugmentedRequestParamsSchema:h,NotificationsParamsSchema:f,NotificationSchema:S,IconSchema:v,IconsSchema:y,BaseMetadataSchema:w,ImplementationSchema:x,ClientTasksCapabilitySchema:B,ServerTasksCapabilitySchema:O,ClientCapabilitiesSchema:G,ServerCapabilitiesSchema:ie,ProgressSchema:te,ProgressNotificationParamsSchema:pe,ProgressNotificationSchema:fe,LoggingMessageNotificationParamsSchema:K,LoggingMessageNotificationSchema:ne,ResourceContentsSchema:Ke,TextResourceContentsSchema:Le,BlobResourceContentsSchema:Ye,AnnotationsSchema:ke,ResourceSchema:Ue,ResourceTemplateSchema:Xe,ResourceListChangedNotificationSchema:Oe,ResourceUpdatedNotificationParamsSchema:ye,ResourceUpdatedNotificationSchema:lt,PromptArgumentSchema:dt,PromptSchema:Qe,PromptListChangedNotificationSchema:Se,TextContentSchema:be,ImageContentSchema:Re,AudioContentSchema:Je,ToolUseContentSchema:Tt,EmbeddedResourceSchema:qe,ResourceLinkSchema:Ne,ContentBlockSchema:Te,PromptMessageSchema:je,ToolAnnotationsSchema:De,ToolListChangedNotificationSchema:et,ModelHintSchema:tt,ModelPreferencesSchema:ft,ToolChoiceSchema:nt,BooleanSchemaSchema:Et,StringSchemaSchema:k,NumberSchemaSchema:ot,UntitledSingleSelectEnumSchemaSchema:U,TitledSingleSelectEnumSchemaSchema:M,LegacyTitledEnumSchemaSchema:H,SingleSelectEnumSchemaSchema:T,UntitledMultiSelectEnumSchemaSchema:P,TitledMultiSelectEnumSchemaSchema:Z,MultiSelectEnumSchemaSchema:D,EnumSchemaSchema:ce,PrimitiveSchemaDefinitionSchema:Ct,ElicitRequestFormParamsSchema:rt,ResourceTemplateReferenceSchema:It,PromptReferenceSchema:Ot,RootSchema:Nn,ClientCapabilities2026Schema:Mn,ServerCapabilities2026Schema:Jt,RequestMetaEnvelopeSchema:Bt,ToolSchema:qt,ToolResultContentSchema:xn,SamplingMessageContentBlockSchema:Wt,SamplingMessageSchema:Nt,ResultTypeSchema:Gt,ResultMetaSchema:Kt,ResultSchema:zn,PaginatedResultSchema:No,CallToolResultSchema:Xt,ListToolsResultSchema:An,ListPromptsResultSchema:Ln,GetPromptResultSchema:Un,ListResourcesResultSchema:jn,ListResourceTemplatesResultSchema:Dn,ReadResourceResultSchema:Zn,CompleteResultSchema:Fn,CacheableResultSchema:Mo,DiscoverResultSchema:Vn,CreateMessageRequestParamsSchema:gt,CreateMessageRequestSchema:Hn,ListRootsRequestSchema:Jn,CreateMessageResultSchema:Bn,ListRootsResultSchema:Wn,ElicitResultSchema:Gn,ElicitRequestURLParamsSchema:Kn,ElicitRequestParamsSchema:Yn,ElicitRequestSchema:Xn,InputRequestSchema:Qn,InputResponseSchema:eo,InputRequestsSchema:to,InputResponsesSchema:no,InputRequiredResultSchema:Mt,InputResponseRequestParamsSchema:xo,CallToolRequestSchema:Ao,ListToolsRequestSchema:Lo,ListPromptsRequestSchema:Uo,GetPromptRequestSchema:jo,ListResourcesRequestSchema:Do,ListResourceTemplatesRequestSchema:Zo,ReadResourceRequestSchema:Fo,CompleteRequestSchema:Vo,DiscoverRequestSchema:Ho,SubscriptionFilterSchema:Qt,SubscriptionsListenRequestSchema:Jo,SubscriptionsListenResultMetaSchema:Bo,SubscriptionsListenResultSchema:io,dispatchRequestSchemas:_t,dispatchResultSchemas:Wo,NotificationMetaSchema:zt,SubscriptionsAcknowledgedNotificationSchema:en,CancelledNotificationParamsSchema:tn,CancelledNotificationSchema:nn,notificationSchemas2026:Fr,JSONRPCResultResponseSchema:we(zn),CallToolResultResponseSchema:we(C([Xt,Mt])),ListToolsResultResponseSchema:we(An),ListPromptsResultResponseSchema:we(Ln),GetPromptResultResponseSchema:we(C([Un,Mt])),ListResourcesResultResponseSchema:we(jn),ListResourceTemplatesResultResponseSchema:we(Dn),ReadResourceResultResponseSchema:we(C([Zn,Mt])),CompleteResultResponseSchema:we(Fn),DiscoverResultResponseSchema:we(Vn),SubscriptionsListenResultResponseSchema:we(io)}}let J_;function Rt(){return J_??=H_()}const B_=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function W_(e){return B_.includes(e)}const Ei=Symbol("modelcontextprotocol.resultCacheHintFallback");function G_(e){return e[Ei]}function Ed(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function Cd(e){return e==="public"||e==="private"}let F=(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 Dt,Y=(Dt=class extends Error{static[Symbol.hasInstance](t){return ct(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 ct(this,t)}constructor(t,n,o){super(n),this.code=t,this.data=o,this.name="ProtocolError",Oo(this,new.target)}static fromError(t,n,o){if(t===F.UrlElicitationRequired&&o){const r=o;if(r.elicitations)return new Y_(r.elicitations,n)}if(t===F.UnsupportedProtocolVersion&&o){const r=o;if(Array.isArray(r.supported)&&typeof r.requested=="string")return new Ci({supported:r.supported,requested:r.requested},n)}if(t===F.InvalidParams||t===F.ResourceNotFound){const r=o;if(typeof r?.uri=="string"&&(t===F.ResourceNotFound||Object.keys(r).length===1))return new K_(r.uri,n)}if(t===F.MissingRequiredClientCapability&&o){const r=o;if(r.requiredCapabilities!==null&&typeof r.requiredCapabilities=="object"&&!Array.isArray(r.requiredCapabilities))return new X_({requiredCapabilities:r.requiredCapabilities},n)}return new Dt(t,n,o)}},Object.defineProperty(Dt,"mcpBrand",{value:"mcp.ProtocolError"}),Dt),cn,K_=(cn=class extends Y{constructor(t,n=`Resource not found: ${t}`){super(F.InvalidParams,n,{uri:t})}get uri(){return this.data.uri}},Object.defineProperty(cn,"mcpBrand",{value:"mcp.ResourceNotFoundError"}),cn),un,Y_=(un=class extends Y{constructor(t,n=`URL elicitation${t.length>1?"s":""} required`){super(F.UrlElicitationRequired,n,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}},Object.defineProperty(un,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"}),un),ln,Ci=(ln=class extends Y{constructor(t,n=`Unsupported protocol version: ${t.requested}`){super(F.UnsupportedProtocolVersion,n,t)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Object.defineProperty(ln,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"}),ln),dn,X_=(dn=class extends Y{constructor(t,n=`Missing required client capabilities: ${Object.keys(t.requiredCapabilities).join(", ")}`){super(F.MissingRequiredClientCapability,n,t)}get requiredCapabilities(){return this.data.requiredCapabilities}},Object.defineProperty(dn,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"}),dn);const Q_=0,ev="private",tv=["tools/call","prompts/get","resources/read"];function nv(e,t){const n=t.resultType;if(n===void 0)return{...t,resultType:"complete"};if(n==="complete"||tv.includes(e))return t;throw new Y(F.InternalError,`Handler for ${e} returned resultType '${String(n)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function ov(e,t){const n=G_(t);if(t.resultType!=="complete"||!W_(e))return n===void 0?t:cv(t);const o=t,r=Ed(o.ttlMs)?o.ttlMs:iv(n),s=Cd(o.cacheScope)?o.cacheScope:av(n),i={...o,ttlMs:r,cacheScope:s};return delete i[Ei],i}function rv(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function sv(e,t){if(t===void 0)return e;const n=e._meta;return n===void 0?{...e,_meta:{[rn]:t}}:!rv(n)||n[rn]!==void 0?e:{...e,_meta:{...n,[rn]:t}}}function iv(e){return e!==void 0&&Ed(e.ttlMs)?e.ttlMs:Q_}function av(e){return e!==void 0&&Cd(e.cacheScope)?e.cacheScope:ev}function cv(e){const t={...e};return delete t[Ei],t}const uv=["elicitation/create","sampling/createMessage","roots/list"];let nr;function Id(){if(nr)return nr;const e=Rt();return nr={request:{"elicitation/create":m({method:_("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":m({method:_("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":m({method:_("roots/list"),params:j({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},nr}function Od(e){return uv.includes(e)}function Kr(e){return Od(e)?Id().request[e]:void 0}function lv(e){return Od(e)?Id().response[e]:void 0}const qd={"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},dv={"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 Nd(e){return Object.prototype.hasOwnProperty.call(qd,e)}function Md(e){return Object.prototype.hasOwnProperty.call(dv,e)}function pv(e){return Object.prototype.hasOwnProperty.call(qd,e)}function hv(e){return Nd(e)?Rt().dispatchRequestSchemas[e]:void 0}function mv(e){return pv(e)?Rt().dispatchResultSchemas[e]:void 0}function fv(e){return Md(e)?Rt().notificationSchemas2026[e]:void 0}function go(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function co(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 Sv={ok:!1,reason:"not-in-era"},gv=[wn,Cr];function _v(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=>go(a)&&"execution"in a)&&(r().tools=s.map(a=>{if(!go(a)||!("execution"in a))return a;const u={...a};return delete u.execution,u}));const i=t.capabilities;if(go(i)&&"tasks"in i){const a={...i};delete a.tasks,r().capabilities=a}return n}const Ii={era:"2026-07-28",hasRequestMethod:Nd,hasNotificationMethod:Md,hasInputRequestMethod:e=>Kr(e)!==void 0,validateRequest:(e,t)=>co(hv(e),t),validateResult:(e,t)=>co(mv(e),t),validateNotification:(e,t)=>co(fv(e),t),validateInputRequest:(e,t)=>co(Kr(e),t),validateInputResponse:(e,t)=>co(lv(e),t),samplingResultVariant:()=>Sv,outboundEnvelope(e){return{[wn]:e.protocolVersion,[Ws]:e.clientInfo,[Cr]:e.clientCapabilities,...e.logLevel!==void 0&&{[Gs]:e.logLevel}}},validateEnvelopeMeta(e){const t=[];for(const o of gv)o in e||t.push({key:o,problem:"missing"});const n=Rt().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=>Rd(e),inputRequestSchema:Kr,decodeResult(e,t){if(!go(t))return{kind:"invalid",error:new q(I.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};const n=t.resultType;if(n===void 0)return{kind:"invalid",error:new q(I.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 q(I.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:n})};if(n==="input_required"){const i=t.inputRequests,a=go(i)?i:{},u=t.requestState,d=t._meta===void 0?void 0:Rt().ResultMetaSchema.safeParse(t._meta),l=d?.success?d.data:void 0;return Object.keys(a).length===0&&typeof u!="string"?{kind:"invalid",error:new q(I.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 u=="string"&&{requestState:u},...l!==void 0&&{_meta:l}}}if(n!=="complete")return{kind:"invalid",error:new q(I.UnsupportedResultType,`Unsupported result type '${n}' for ${e}`,{resultType:n,method:e})};const o=vv(),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 q(I.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 sv(ov(e,nv(e,_v(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=Rt().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 or;function vv(){if(or)return or;const e=Rt();return or={"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},or}const Oi="2026-07-28";function $t(e){return e!==void 0&&bt(e)?Ii:Ti}function Ia(e){return e.revision!==void 0?$t(e.revision).era:e.era==="modern"?Ii.era:Ti.era}function Yr(e){return xd.some(t=>t.hasRequestMethod(e))}function Xr(e){return xd.some(t=>t.hasNotificationMethod(e))}function Oa(e){return e==="tasks/get"||e==="tasks/cancel"}const xd=[Ti,Ii];var yv=Gg({AnnotationsSchema:()=>Ht,AudioContentSchema:()=>Lr,BaseMetadataSchema:()=>Vt,BaseRequestParamsSchema:()=>ve,BlobResourceContentsSchema:()=>pi,BooleanSchemaSchema:()=>_i,CallToolRequestParamsSchema:()=>kl,CallToolRequestSchema:()=>Tl,CallToolResultSchema:()=>Si,CancelTaskRequestSchema:()=>v_,CancelTaskResultSchema:()=>y_,CancelledNotificationParamsSchema:()=>qu,CancelledNotificationSchema:()=>oi,ClientCapabilitiesSchema:()=>zu,ClientNotificationSchema:()=>R_,ClientRequestSchema:()=>b_,ClientResultSchema:()=>w_,ClientTasksCapabilitySchema:()=>Mu,CompatibilityCallToolResultSchema:()=>u_,CompleteRequestParamsSchema:()=>td,CompleteRequestSchema:()=>nd,CompleteResultSchema:()=>od,ContentBlockSchema:()=>Ur,CreateMessageRequestParamsSchema:()=>jl,CreateMessageRequestSchema:()=>Dl,CreateMessageResultSchema:()=>Zl,CreateMessageResultWithToolsSchema:()=>Fl,CreateTaskResultSchema:()=>d_,CursorSchema:()=>Ys,DiscoverRequestSchema:()=>Uu,DiscoverResultSchema:()=>Mr,ElicitRequestFormParamsSchema:()=>Dr,ElicitRequestParamsSchema:()=>Wl,ElicitRequestSchema:()=>Gl,ElicitRequestURLParamsSchema:()=>Bl,ElicitResultSchema:()=>Xl,ElicitationCompleteNotificationParamsSchema:()=>Kl,ElicitationCompleteNotificationSchema:()=>Yl,EmbeddedResourceSchema:()=>gl,EmptyResultSchema:()=>ni,EnumSchemaSchema:()=>Jl,GetPromptRequestParamsSchema:()=>ml,GetPromptRequestSchema:()=>fl,GetPromptResultSchema:()=>yl,GetTaskPayloadRequestSchema:()=>f_,GetTaskPayloadResultSchema:()=>S_,GetTaskRequestSchema:()=>h_,GetTaskResultSchema:()=>m_,IconSchema:()=>Nu,IconsSchema:()=>En,ImageContentSchema:()=>Ar,ImplementationSchema:()=>Nr,InitializeRequestParamsSchema:()=>Au,InitializeRequestSchema:()=>ri,InitializeResultSchema:()=>Lu,InitializedNotificationSchema:()=>ii,JSONArraySchema:()=>s_,JSONObjectSchema:()=>ue,JSONRPCErrorResponseSchema:()=>qr,JSONRPCMessageSchema:()=>ho,JSONRPCNotificationSchema:()=>ti,JSONRPCRequestSchema:()=>ei,JSONRPCResponseSchema:()=>i_,JSONRPCResultResponseSchema:()=>Or,JSONValueSchema:()=>Pn,LegacyTitledEnumSchemaSchema:()=>bi,ListChangedOptionsBaseSchema:()=>Cl,ListPromptsRequestSchema:()=>pl,ListPromptsResultSchema:()=>hl,ListResourceTemplatesRequestSchema:()=>Ju,ListResourceTemplatesResultSchema:()=>Bu,ListResourcesRequestSchema:()=>Vu,ListResourcesResultSchema:()=>Hu,ListRootsRequestSchema:()=>sd,ListRootsResultSchema:()=>id,ListTasksRequestSchema:()=>g_,ListTasksResultSchema:()=>__,ListToolsRequestSchema:()=>Pl,ListToolsResultSchema:()=>$l,LoggingLevelSchema:()=>gi,LoggingMessageNotificationParamsSchema:()=>ql,LoggingMessageNotificationSchema:()=>Nl,ModelHintSchema:()=>Ml,ModelPreferencesSchema:()=>xl,MultiSelectEnumSchemaSchema:()=>Hl,NotificationSchema:()=>Ie,NotificationsParamsSchema:()=>Ce,NumberSchemaSchema:()=>br,PaginatedRequestParamsSchema:()=>Zu,PaginatedRequestSchema:()=>Cn,PaginatedResultSchema:()=>In,PingRequestSchema:()=>ai,PrimitiveSchemaDefinitionSchema:()=>Pi,ProgressNotificationParamsSchema:()=>Du,ProgressNotificationSchema:()=>ci,ProgressSchema:()=>ju,ProgressTokenSchema:()=>Ks,PromptArgumentSchema:()=>ll,PromptListChangedNotificationSchema:()=>bl,PromptMessageSchema:()=>vl,PromptReferenceSchema:()=>ed,PromptSchema:()=>dl,ReadResourceRequestParamsSchema:()=>Wu,ReadResourceRequestSchema:()=>Gu,ReadResourceResultSchema:()=>Ku,RelatedTaskMetadataSchema:()=>Ou,RequestIdSchema:()=>Tn,RequestMetaSchema:()=>Xs,RequestSchema:()=>le,ResourceContentsSchema:()=>ui,ResourceLinkSchema:()=>_l,ResourceListChangedNotificationSchema:()=>Yu,ResourceRequestParamsSchema:()=>xr,ResourceSchema:()=>hi,ResourceTemplateReferenceSchema:()=>Ql,ResourceTemplateSchema:()=>Fu,ResourceUpdatedNotificationParamsSchema:()=>cl,ResourceUpdatedNotificationSchema:()=>ul,ResultMetaObjectSchema:()=>Qs,ResultSchema:()=>de,RoleSchema:()=>On,RootSchema:()=>rd,RootsListChangedNotificationSchema:()=>ad,SamplingContentSchema:()=>Ll,SamplingMessageContentBlockSchema:()=>$o,SamplingMessageSchema:()=>Ul,ServerCapabilitiesSchema:()=>si,ServerNotificationSchema:()=>$_,ServerRequestSchema:()=>P_,ServerResultSchema:()=>k_,ServerTasksCapabilitySchema:()=>xu,SetLevelRequestParamsSchema:()=>Il,SetLevelRequestSchema:()=>Ol,SingleSelectEnumSchemaSchema:()=>Vl,StringSchemaSchema:()=>jr,SubscribeRequestParamsSchema:()=>Xu,SubscribeRequestSchema:()=>Qu,SubscriptionFilterSchema:()=>mi,SubscriptionsAcknowledgedNotificationParamsSchema:()=>rl,SubscriptionsAcknowledgedNotificationSchema:()=>sl,SubscriptionsListenRequestParamsSchema:()=>nl,SubscriptionsListenRequestSchema:()=>ol,SubscriptionsListenResultMetaSchema:()=>il,SubscriptionsListenResultSchema:()=>al,TaskAugmentedRequestParamsSchema:()=>Io,TaskCreationParamsSchema:()=>l_,TaskMetadataSchema:()=>Iu,TaskSchema:()=>qn,TaskStatusNotificationParamsSchema:()=>ud,TaskStatusNotificationSchema:()=>p_,TaskStatusSchema:()=>cd,TextContentSchema:()=>zr,TextResourceContentsSchema:()=>li,TitledMultiSelectEnumSchemaSchema:()=>wi,TitledSingleSelectEnumSchemaSchema:()=>yi,ToolAnnotationsSchema:()=>Rl,ToolChoiceSchema:()=>zl,ToolExecutionSchema:()=>wl,ToolListChangedNotificationSchema:()=>El,ToolResultContentSchema:()=>Al,ToolSchema:()=>fi,ToolUseContentSchema:()=>Sl,UnsubscribeRequestParamsSchema:()=>el,UnsubscribeRequestSchema:()=>tl,UntitledMultiSelectEnumSchemaSchema:()=>Ri,UntitledSingleSelectEnumSchemaSchema:()=>vi});const on=e=>ei.safeParse(e).success,bv=e=>ti.safeParse(e).success,ko=e=>Or.safeParse(e).success,To=e=>qr.safeParse(e).success,Rv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required",qa=e=>ri.safeParse(e).success,wv=e=>ii.safeParse(e).success,Pv="Mcp-Param-",Na="x-mcp-header",$v=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,kv=new Set(["string","integer","boolean","number"]);function Ma(e){const t=[],n=new Map,o=(s,i,a)=>{if(s===null||typeof s!="object")return;const u=s;if(Na in u){if(!a||i.length===0)return`${rr(i)}: 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 l=u[Na];if(typeof l!="string"||l.length===0)return`${rr(i)}: x-mcp-header MUST be a non-empty string`;if(!$v.test(l))return`${rr(i)}: x-mcp-header '${l}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;const p=typeof u.type=="string"?u.type:void 0;if(p===void 0||!kv.has(p))return`${rr(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${p??"<none>"}`;const h=l.toLowerCase(),f=n.get(h);if(f!==void 0)return`x-mcp-header '${l}' is not case-insensitively unique (also declared as '${f}')`;n.set(h,l),t.push({path:i,headerName:l,type:p})}const d=u.properties;if(d!==null&&typeof d=="object")for(const[l,p]of Object.entries(d)){const h=o(p,[...i,l],a);if(h!==void 0)return h}for(const l of Tv){const p=u[l];if(p===void 0)continue;const h=Array.isArray(p)?p:p!==null&&typeof p=="object"&&Ev.has(l)?Object.values(p):[p];for(const f of h){const S=o(f,[...i,`<${l}>`],!1);if(S!==void 0)return S}}},r=o(e,[],!0);return r===void 0?{valid:!0,declarations:t}:{valid:!1,reason:r}}const Tv=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],Ev=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function rr(e){return e.length===0?"<root>":e.join(".")}const zd="=?base64?",Ad="?=";function Cv(e){if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function Iv(e){if(e.length===0||e.startsWith(zd)&&e.endsWith(Ad)||e!==e.trim())return!0;for(let t=0;t<e.length;t++){const n=e.codePointAt(t);if(!(n===9||n>=32&&n<=126))return!0}return!1}function Ov(e){const t=new TextEncoder().encode(e);let n="";for(const o of t)n+=String.fromCodePoint(o);return btoa(n)}function Ld(e){return Iv(e)?`${zd}${Ov(e)}${Ad}`:e}function qv(e,t){let n=e;for(const o of t){if(n===null||typeof n!="object")return;n=n[o]}return n}function Nv(e,t){const n={};for(const o of e){const r=qv(t,o.path);if(r==null)continue;const s=Cv(r);s!==void 0&&(n[`${Pv}${o.headerName}`]=Ld(s))}return n}const ur=-32020;F.InvalidRequest,F.UnsupportedProtocolVersion,F.InvalidParams,F.MethodNotFound,F.InvalidParams,F.MissingRequiredClientCapability;F.ParseError+"",F.InvalidRequest+"",F.MethodNotFound+"",F.UnsupportedProtocolVersion+"",F.MissingRequiredClientCapability+"";const xa={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function Mv(e,t){const n=Object.hasOwn(xa,e)?xa[e]:void 0;if(n===void 0)return;const o=xv(t)?t[n]:void 0;return{field:n,value:typeof o=="string"?o:void 0}}function xv(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function qi(e,t){return fu(e,t)}function uo(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function _s(e){if(e==null)return!1;const t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}let za=!1;const vs="draft-2020-12";function zv(e,t="input"){const n=e["~standard"];let o;if(n.jsonSchema)o=n.jsonSchema[t]({target:vs});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().");za||(za=!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=mu(e,{target:vs,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:Ud(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}}function Ud(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(const t of["oneOf","anyOf","allOf"]){const n=e[t];if(Array.isArray(n)&&n.length>0)return n.every(o=>o!==null&&typeof o=="object"&&(o.type==="object"||Ud(o)))}return!1}function Av(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}async function Qr(e,t){const n=await e["~standard"].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(o=>Av(o)).join(", ")}:{success:!0,data:n.value}}function Lv(e){const t=mu(e,{target:vs,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}const Uv=/\\\.\\d\{(\d+)\}/;function jv(e){const t=Uv.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=>Er({local:o,offset:r,precision:s}))))}function Dv(e,t){let n;switch(e){case"email":n=[BS()];break;case"uri":n=[bu()];break;case"date":n=[Dg()];break;case"date-time":n=jv(t);break}return new Set(n.map(o=>Lv(o)).filter(o=>o!==void 0))}function Zv(e,t,n){return n!=="zod"?!0:Dv(e,t).has(t)}function Eo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Fv(e){try{return zv(e,"input")}catch(t){const n=t instanceof Error?t.message:String(t);throw new Y(F.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${n}`)}}const Vv=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function Ni(e){return Vv.has(e)||e.startsWith("x-")}const Hv=new Set(["$schema",...Object.keys(Dr.shape.requestedSchema.shape)]),Aa={string:uo([jr,vi,yi,bi]),number:uo([br]),integer:uo([br]),boolean:uo([_i]),array:uo([Ri,wi])},Jv=new Set(jr.shape.format.unwrap().options);function Bv(e,t,n,o){if(!Eo(e))return e;const r=typeof e.type=="string"&&Object.hasOwn(Aa,e.type)?Aa[e.type]:void 0;if(r===void 0)return e;const s={};for(const[i,a]of Object.entries(e))r.has(i)||Ni(i)?s[i]=a:i==="pattern"&&e.type==="string"&&typeof e.format=="string"?Jv.has(e.format)?(typeof a!="string"||!Zv(e.format,a,n))&&o.push(`${t}.${i}`):s[i]=a:o.push(`${t}.${i}`);return s}function Wv(e,t){const n={},o=[];for(const[r,s]of Object.entries(e))r==="properties"&&Eo(s)?n[r]=Object.fromEntries(Object.entries(s).map(([i,a])=>[i,Bv(a,`properties.${i}`,t,o)])):Hv.has(r)?n[r]=s:Ni(r)||o.push(r);if(o.length>0)throw new Y(F.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return n}function Gv(e,t){if(!Eo(e.properties))return t;const n=Object.entries(e.properties).filter(([,o])=>!qi(Pi,o).success).map(([o])=>`properties.${o}`);return n.length>0?n.join(", "):t}function ys(e,t,n=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,r)=>ys(o,t[r],`${n}[${r}]`)):!Eo(e)||!Eo(t)?[]:Object.entries(e).flatMap(([o,r])=>{const s=n?`${n}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?ys(r,t[o],s):Ni(o)?[]:[s]})}function Kv(e){if(!_s(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};const t=e.requestedSchema["~standard"].vendor,n=Wv(Fv(e.requestedSchema),t),o=qi(Dr.shape.requestedSchema,n);if(!o.success)throw new Y(F.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Gv(n,o.error.message)}`);const r=ys(n,o.data);if(r.length>0)throw new Y(F.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 Y(F.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function Yv(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(Yv,{elicit(e){try{return{method:"elicitation/create",params:Kv(e)}}catch(t){throw t instanceof Y?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 Xv=!0,Qv=10,ey=250;function ty(e){return{autoFulfill:e?.autoFulfill??Xv,maxRounds:e?.maxRounds??Qv}}function ny(e,t,n){const o=t!==void 0&&Object.keys(t).length>0;return!o&&n===void 0?e:{...e,...o&&{inputResponses:t},...n!==void 0&&{requestState:n}}}function oy(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function ry(e,t){return new Promise((n,o)=>{if(t?.aborted){o(t.reason instanceof q?t.reason:new q(I.RequestTimeout,String(t.reason)));return}const r=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e),s=()=>{clearTimeout(r),o(t?.reason instanceof q?t.reason:new q(I.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",s,{once:!0})})}function sy(e){const t=new AbortController,n=()=>t.abort(e?.reason);return e?.addEventListener("abort",n,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:o=>t.abort(o),dispose:()=>e?.removeEventListener("abort",n)}}async function iy(e){const{config:t,method:n,originalParams:o,requestOptions:r,hooks:s,signal:i}=e,a=e.flowStartedAt??Date.now();let u=e.firstPayload,d=0;for(;;){if(d+=1,d>t.maxRounds)throw new q(I.InputRequiredRoundsExceeded,oy(n,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:u.inputRequests,...u.requestState!==void 0&&{requestState:u.requestState}}});r.onprogress?.({progress:d,message:`Fulfilling input required by '${n}' (round ${d})`});const l=Object.entries(u.inputRequests??{});let p;if(l.length>0){const S=sy(i);try{const v=await Promise.all(l.map(async([y,w])=>{try{return[y,await s.dispatchInputRequest(y,w,S.signal)]}catch(x){throw S.abort(x),x}}));p=Object.fromEntries(v)}finally{S.dispose()}}else await ry(ey,i);const h={...r.timeout!==void 0&&{timeout:r.timeout}};if(r.maxTotalTimeout!==void 0){const S=Date.now()-a,v=r.maxTotalTimeout-S;if(v<=0)throw new q(I.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:S});h.maxTotalTimeout=v}const f=await s.retry(ny(o,p,u.requestState),h);if(Rv(f)){u={inputRequests:f.inputRequests??{},...f.requestState!==void 0&&{requestState:f.requestState}};continue}return f}}const ay=["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"],cy={IdJagTokenExchangeResponseSchema:T_,OAuthClientInformationFullSchema:gd,OAuthClientInformationSchema:Sd,OAuthClientMetadataSchema:fd,OAuthClientRegistrationErrorSchema:E_,OAuthErrorResponseSchema:md,OAuthMetadataSchema:$i,OAuthProtectedResourceMetadataSchema:ld,OAuthTokenRevocationRequestSchema:C_,OAuthTokensSchema:hd,OpenIdProviderDiscoveryMetadataSchema:pd,OpenIdProviderMetadataSchema:dd},jd={},Dd={};function Zd(e,t){const n=e.slice(0,-6);jd[n]=t,Dd[n]=o=>t.safeParse(o).success}for(const e of ay)Zd(e,yv[e]);for(const[e,t]of Object.entries(cy))Zd(e,t);Object.freeze(jd);const uy=Object.freeze(Dd);function ly(e){switch(e){case"initialize":case"notifications/initialized":return $t(void 0);case"server/discover":return $t(Oi);default:return}}const bs=6e4,dy=[wn,Ws,Cr,Gs],py=["inputResponses","requestState"];function La(e,t){const n=e.params;if(!_o(n))return{message:e,lifted:{}};const o=n._meta,r=_o(o)?dy.filter(u=>u in o):[],s=t==="request"?py.filter(u=>u in n):[];if(r.length===0&&s.length===0)return{message:e,lifted:{}};const i={},a={...n};if(r.length>0&&_o(o)){const u={},d={...o};for(const l of r)u[l]=o[l],delete d[l];i.envelope=u,Object.keys(d).length>0?a._meta=d:delete a._meta}for(const u of s)u==="inputResponses"&&(i.inputResponses=a[u]),u==="requestState"&&(i.requestState=a[u]),delete a[u];return{message:{...e,params:a},lifted:i}}function Ua(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 Mi(e){return()=>e}const hy=Mi(void 0);var my=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??o_,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 q(I.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){e.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(e.params.requestId)?.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 q(I.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){this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};const n=this.transport?.onerror;this._transport.onerror=r=>{n?.(r),this._onerror(r)};const o=this._transport?.onmessage;this._transport.onmessage=(r,s)=>{o?.(r,s),ko(r)||To(r)?this._onresponse(r):on(r)?this._onrequest(r,s):bv(r)?this._onnotification(r,s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(r)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(const o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();const t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;const n=new q(I.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(const o of e.values())o(n);for(const o of t.values())o.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){const{message:n}=La(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){const i=Ia(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(Xr(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){const{message:n,lifted:o}=La(e,"request"),r=this._negotiatedWireCodec();if(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=(v,y,w)=>{const x={jsonrpc:"2.0",id:n.id,error:{code:v,message:y,...w!==void 0&&{data:w}}};s?.send(x).catch(z=>this._onerror(new Error(`Failed to send an error response: ${z}`)))};if(t?.classification!==void 0){const v=Ia(t.classification);if(v!==r.era){this._onerror(new Error(`Era mismatch on inbound request '${n.method}': classified as ${v} but this instance serves ${r.era}`));const y=t.classification.revision??v;i(F.UnsupportedProtocolVersion,`Unsupported protocol version: ${y}`,{supported:this._supportedProtocolVersions,requested:y});return}}if(Yr(n.method)&&!r.hasRequestMethod(n.method)&&!(Oa(n.method)&&this._customSchemaRequestMethods.has(n.method))){i(F.MethodNotFound,"Method not found");return}const a=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(a===void 0){i(F.MethodNotFound,"Method not found");return}const u=r.checkInboundEnvelope(o);if(u!==void 0){i(F.InvalidParams,u);return}const d=(v,y)=>this._notificationViaCodec(this._resolveOutboundCodec(v.method),v,{...y,relatedRequestId:n.id}),l=(v,y,w)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(v.method),v,y,{...w,relatedRequestId:n.id}),p=new AbortController;this._requestHandlerAbortControllers.set(n.id,p);const h=o.inputResponses===void 0?void 0:Sy(o.inputResponses),f={sessionId:s?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...h!==void 0&&{inputResponses:h.accepted},...h!==void 0&&h.droppedKeys.length>0&&{droppedInputResponseKeys:h.droppedKeys},requestState:o.requestState===void 0?hy:Mi(o.requestState),signal:p.signal,send:((v,y,w)=>{const x=this._resolveOutboundCodec(v.method);if(this._assertOutboundRequestInEra(x,v.method),_s(y))return l(v,y,w);const z=Ua(x,v.method);if(z===void 0)throw new TypeError(`'${v.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return l(v,z,y)}),notify:d},http:t?.authInfo?{authInfo:t.authInfo}:void 0},S=this.buildContext(f,t);Promise.resolve().then(()=>a(n,S)).then(async v=>{if(p.signal.aborted)return;let y;try{y=r.encodeResult(n.method,v,this._outboundServerInfo())}catch(x){this._onerror(new Error(`Failed to encode result for ${n.method}: ${x}`)),i(F.InternalError,"Internal error");return}const w={result:y,jsonrpc:"2.0",id:n.id};await s?.send(w)},async v=>{if(p.signal.aborted)return;const y=Number.isSafeInteger(v.code)?v.code:F.InternalError,w={jsonrpc:"2.0",id:n.id,error:{code:r.encodeErrorCode(y),message:v.message??"Internal error",...v.data!==void 0&&{data:v.data}}};await s?.send(w)}).catch(v=>this._onerror(new Error(`Failed to send response: ${v}`))).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),ko(e)?n(e):n(Y.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,n){const o=this._resolveOutboundCodec(e.method);if(_s(t))return Oa(e.method)||this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,n);this._assertOutboundRequestInEra(o,e.method);const r=Ua(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 $t(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){const t=ly(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Yr(t)&&!e.hasRequestMethod(t))throw new q(I.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??{},u=Date.now();let d,l;return new Promise((p,h)=>{const f=O=>{h(O)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(O){f(O);return}if(o?.signal?.aborted){const O=o.signal.reason;throw O instanceof q?O:new q(I.RequestTimeout,String(O))}const S=e.era===Oi&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,v=this._requestMessageId++;l=v;const y={...t,jsonrpc:"2.0",id:v};o?.onprogress&&(this._progressHandlers.set(v,o.onprogress),y.params={...t.params,_meta:{...t.params?._meta,progressToken:v}});const w=this._envelopeOutbound(y);let x=!1;const z=O=>{x||(this._progressHandlers.delete(v),S===void 0?t.method!=="initialize"&&this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:v,reason:String(O)}}),{relatedRequestId:r,resumptionToken:s,onresumptiontoken:i}).catch(G=>this._onerror(new Error(`Failed to send cancellation: ${G}`))):S.abort(),h(O instanceof q?O:new q(I.RequestTimeout,String(O))))};this._responseHandlers.set(v,O=>{if(o?.signal?.aborted)return;if(x=!0,O instanceof Error)return h(O);let G;try{G=e.decodeResult(t.method,O.result)}catch(te){return h(te instanceof Error?te:new Error(String(te)))}if(G.kind==="invalid")return h(G.error);if(G.kind==="input_required"){if(o?.allowInputRequired===!0)return p(by(G));const te={codec:e,request:t,resultSchema:n,options:o,flowStartedAt:u,retry:(pe,fe)=>this._requestWithSchemaViaCodec(e,pe===void 0?{method:t.method}:{method:t.method,params:pe},n,fe)};return p(this._resolveNonCompleteResult(G,te))}const ie=G.result;Qr(n,ie).then(te=>{te.success?p(te.data):h(new q(I.InvalidResult,`Invalid result for ${t.method}: ${te.error}`))},h)}),d=()=>z(o?.signal?.reason),o?.signal?.addEventListener("abort",d,{once:!0});const J=o?.timeout??bs,B=()=>z(new q(I.RequestTimeout,"Request timed out",{timeout:J}));this._setupTimeout(v,J,o?.maxTotalTimeout,B,o?.resetTimeoutOnProgress??!1),this._transport.send(w,{relatedRequestId:r,resumptionToken:s,onresumptiontoken:i,headers:a,requestSignal:S?.signal}).catch(O=>{this._progressHandlers.delete(v),h(O)})}).finally(()=>{d&&o?.signal?.removeEventListener("abort",d),l!==void 0&&(this._responseHandlers.delete(l),this._cleanupTimeout(l))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,n){if(!this._transport)throw new q(I.NotConnected,"Not connected");if(Xr(t.method)&&!e.hasNotificationMethod(t.method))throw new q(I.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((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&n?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(o,n).catch(r=>this._onerror(r))});return}await this._transport.send(o,n)}setRequestHandler(e,t,n){this.assertRequestHandlerCapability(e);let o;if(typeof t=="function"){if(!Yr(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 Y(F.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 Qr(t.params,{...r.params});if(!i.success)throw new Y(F.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(!Xr(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 Y(F.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 Qr(t.params,{...o.params});if(!r.success)throw new Y(F.InvalidParams,`Invalid params for notification ${e}: ${r.error}`);await n(r.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function _o(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fy(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]=_o(i)&&_o(s)?{...i,...s}:s}return n}function wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sy(e){const t={},n=[];if(!wr(e))return{accepted:t,droppedKeys:n};for(const[o,r]of Object.entries(e)){if(!wr(r)||"method"in r||"result"in r){n.push(o);continue}t[o]=r}return{accepted:t,droppedKeys:n}}function ja(e){throw new q(I.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function gy(e,t,n,o,r){return{sessionId:r,mcpReq:{id:e,method:t,_meta:n?._meta,requestState:Mi(void 0),signal:o,send:(()=>ja("send")),notify:()=>ja("notify")}}}async function _y(e,t,n,o,r){if(!wr(o)||typeof o.method!="string")throw new q(I.InvalidResult,`Invalid input request '${n}': each inputRequests entry must be an embedded request object with a method`,{key:n});const s=o.method;if(!t.hasInputRequestMethod(s))throw new q(I.InvalidResult,`Invalid input request '${n}': '${s}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:n,method:s});const i=e.getRequestHandler(s);if(i===void 0)throw new q(I.CapabilityNotSupported,`Cannot fulfil input request '${n}': no handler is registered for '${s}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:n,method:s});const a=wr(o.params)?o.params:void 0;return await i({jsonrpc:"2.0",id:n,method:s,...a!==void 0&&{params:a}},e.buildContext(gy(n,s,a,r,e.sessionId)))}function vy(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function yy(e,t,n,o){const{codec:r,request:s,options:i,flowStartedAt:a}=o,u={inputRequests:n.inputRequests,...n.requestState!==void 0&&{requestState:n.requestState}},d={dispatchInputRequest:(l,p,h)=>_y(e,r,l,p,h),retry:(l,p)=>o.retry(l,vy(i,p))};return iy({config:t,method:s.method,originalParams:s.params,firstPayload:u,flowStartedAt:a,signal:i?.signal,requestOptions:{...i?.timeout!==void 0&&{timeout:i.timeout},...i?.maxTotalTimeout!==void 0&&{maxTotalTimeout:i.maxTotalTimeout},...i?.onprogress!==void 0&&{onprogress:i.onprogress}},hooks:d})}function by(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}var Ry=Wg((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 u=typeof a=="object"?s(a):a;if(typeof u!="string")throw new TypeError("argument string is required to be a string");var d=u.indexOf(";"),l=d!==-1?u.slice(0,d).trim():u.trim();if(!o.test(l))throw new TypeError("invalid media type");var p=new i(l.toLowerCase());if(d!==-1){var h,f,S;for(t.lastIndex=d;f=t.exec(u);){if(f.index!==d)throw new TypeError("invalid parameter format");d+=f[0].length,h=f[1].toLowerCase(),S=f[2],S.charCodeAt(0)===34&&(S=S.slice(1,-1),S.indexOf("\\")!==-1&&(S=S.replace(n,"$1"))),p.parameters[h]=S}if(d!==u.length)throw new TypeError("invalid parameter format")}return p}function s(a){var u;if(typeof a.getHeader=="function"?u=a.getHeader("content-type"):typeof a.headers=="object"&&(u=a.headers&&a.headers["content-type"]),typeof u!="string")throw new TypeError("content-type header is missing from object");return u}function i(a){this.parameters=Object.create(null),this.type=a}})),wy=Yg(Ry());function Py(e){if(e)try{return wy.parse(e).type}catch{const t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}function Da(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function $y(e=fetch,t){return t?async(n,o)=>e(n,{...t,...o,headers:o?.headers?{...Da(t.headers),...Da(o.headers)}:t.headers}):e}const ky=new Set([301,302,303,307,308]),Ty=5;function Ey(e,t){return e.protocol===t.protocol&&e.host===t.host?!0:e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}function Fd(e,t){const n=ky.has(t.status)?t.headers?.get("location"):void 0;if(n)try{return new URL(n,e)}catch{return}}const Vd=new WeakSet;function Cy(e){const t=(n,o)=>e(n,o);return Vd.add(t),t}function Zr(e){return Vd.has(e)?e:async(t,n)=>{if(n?.redirect==="error"||n?.redirect==="manual")return e(t,n);const o=(n?.method??"GET").toUpperCase();let r=t;for(let s=0;;s++){const i=await e(r,{...n,redirect:"manual"}),a=Fd(r,i);if(!a||s===Ty)return i;const u=new URL(r),d=o==="GET"||i.status===307||i.status===308,l=!(a.username||a.password)||a.username===u.username&&a.password===u.password;if(!d||!l||!Ey(u,a))return i;await i.text?.().catch(()=>{}),r=a}}}function Iy(e,t){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";const n=Fd(t.url||e,t);if(n)return n.username=n.password=n.search=n.hash="",n.protocol==="http:"&&new URL(t.url||e).protocol==="https:"?(n.protocol="https:",`Redirect from https to plain http not followed; try ${n.href} as the endpoint`):`Redirect to ${n.href} not followed; use that URL as the endpoint if it is the intended server`}function vo(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(!vo(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(!vo(e[s],t[s]))return!1;return!0}return e===t}function We(e){return encodeURI(Oy(e))}function Oy(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}const qy={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Ny={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},My={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 xy=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 Lt(e,t=Object.create(null),n=xy,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:Lt(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(My[s])continue;const i=`${o}/${We(s)}`,a=e[s];if(Array.isArray(a)){if(qy[s]){const u=a.length;for(let d=0;d<u;d++)Lt(a[d],t,n,`${i}/${d}`)}}else if(Ny[s])for(let u in a)Lt(a[u],t,n,`${i}/${We(u)}`);else Lt(a,t,n,i)}return t}const zy=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Ay=[0,31,28,31,30,31,30,31,31,30,31,30,31],Ly=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Uy=/^(?=.{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,jy=/^(?:[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,Dy=/^(?:(?:[^\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,Zy=/^(?:(?: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,Fy=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Vy=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Hy=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Jy=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,By=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))},Wy=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Gy=/^((([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,Ky=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 st(e){return e.test.bind(e)}const Za={date:Hd,time:Jd.bind(void 0,!1),"date-time":Qy,duration:Ky,uri:nb,"uri-reference":st(jy),"uri-template":st(Dy),url:st(Zy),email:By,hostname:st(Uy),ipv4:st(Wy),ipv6:st(Gy),regex:rb,uuid:st(Fy),"json-pointer":st(Vy),"json-pointer-uri-fragment":st(Hy),"relative-json-pointer":st(Jy)};function Yy(e){return e%4===0&&(e%100!==0||e%400===0)}function Hd(e){const t=e.match(zy);if(!t)return!1;const n=+t[1],o=+t[2],r=+t[3];return o>=1&&o<=12&&r>=1&&r<=(o==2&&Yy(n)?29:Ay[o])}function Jd(e,t){const n=t.match(Ly);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 Xy=/t|\s/i;function Qy(e){const t=e.split(Xy);return t.length==2&&Hd(t[0])&&Jd(!0,t[1])}const eb=/\/|:/,tb=/^(?:[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 nb(e){return eb.test(e)&&tb.test(e)}const ob=/[^\\]\\Z/;function rb(e){if(ob.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}function sb(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 re(e,t,n="2019-09",o=Lt(t),r=!0,s=null,i="#",a="#",u=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 l;switch(d){case"boolean":case"number":case"string":l=d;break;case"object":e===null?l="null":Array.isArray(e)?l="array":l="object";break;default:throw new Error(`Instances of "${d}" type are not supported.`)}const{$ref:p,$recursiveRef:h,$recursiveAnchor:f,type:S,const:v,enum:y,required:w,not:x,anyOf:z,allOf:J,oneOf:B,if:O,then:G,else:ie,format:te,properties:pe,patternProperties:fe,additionalProperties:K,unevaluatedProperties:ne,minProperties:Ke,maxProperties:Le,propertyNames:Ye,dependentRequired:ke,dependentSchemas:Ue,dependencies:Xe,prefixItems:Oe,items:ye,additionalItems:lt,unevaluatedItems:dt,contains:Qe,minContains:Se,maxContains:be,minItems:Re,maxItems:Je,uniqueItems:Tt,minimum:qe,maximum:Ne,exclusiveMinimum:Te,exclusiveMaximum:je,multipleOf:De,minLength:et,maxLength:tt,pattern:ft,__absolute_ref__:nt,__absolute_recursive_ref__:Et}=t,k=[];if(f===!0&&s===null&&(s=t),h==="#"){const U=s===null?o[Et]:s,M=`${a}/$recursiveRef`,H=re(e,s===null?t:s,n,o,r,U,i,M,u);H.valid||k.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:M,error:"A subschema had errors."},...H.errors)}if(p!==void 0){const U=o[nt||p];if(U===void 0){let T=`Unresolved $ref "${p}".`;throw nt&&nt!==p&&(T+=` Absolute URI "${nt}".`),T+=`
58
+ Known schemas:
59
+ - ${Object.keys(o).join(`
60
+ - `)}`,new Error(T)}const M=`${a}/$ref`,H=re(e,U,n,o,r,s,i,M,u);if(H.valid||k.push({instanceLocation:i,keyword:"$ref",keywordLocation:M,error:"A subschema had errors."},...H.errors),n==="4"||n==="7")return{valid:k.length===0,errors:k}}if(Array.isArray(S)){let U=S.length,M=!1;for(let H=0;H<U;H++)if(l===S[H]||S[H]==="integer"&&l==="number"&&e%1===0&&e===e){M=!0;break}M||k.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${l}" is invalid. Expected "${S.join('", "')}".`})}else S==="integer"?(l!=="number"||e%1||e!==e)&&k.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${l}" is invalid. Expected "${S}".`}):S!==void 0&&l!==S&&k.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${l}" is invalid. Expected "${S}".`});if(v!==void 0&&(l==="object"||l==="array"?vo(e,v)||k.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(v)}.`}):e!==v&&k.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(v)}.`})),y!==void 0&&(l==="object"||l==="array"?y.some(U=>vo(e,U))||k.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(U=>e===U)||k.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),x!==void 0){const U=`${a}/not`;re(e,x,n,o,r,s,i,U).valid&&k.push({instanceLocation:i,keyword:"not",keywordLocation:U,error:'Instance matched "not" schema.'})}let ot=[];if(z!==void 0){const U=`${a}/anyOf`,M=k.length;let H=!1;for(let T=0;T<z.length;T++){const P=z[T],Z=Object.create(u),D=re(e,P,n,o,r,f===!0?s:null,i,`${U}/${T}`,Z);k.push(...D.errors),H=H||D.valid,D.valid&&ot.push(Z)}H?k.length=M:k.splice(M,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:U,error:"Instance does not match any subschemas."})}if(J!==void 0){const U=`${a}/allOf`,M=k.length;let H=!0;for(let T=0;T<J.length;T++){const P=J[T],Z=Object.create(u),D=re(e,P,n,o,r,f===!0?s:null,i,`${U}/${T}`,Z);k.push(...D.errors),H=H&&D.valid,D.valid&&ot.push(Z)}H?k.length=M:k.splice(M,0,{instanceLocation:i,keyword:"allOf",keywordLocation:U,error:"Instance does not match every subschema."})}if(B!==void 0){const U=`${a}/oneOf`,M=k.length,H=B.filter((T,P)=>{const Z=Object.create(u),D=re(e,T,n,o,r,f===!0?s:null,i,`${U}/${P}`,Z);return k.push(...D.errors),D.valid&&ot.push(Z),D.valid}).length;H===1?k.length=M:k.splice(M,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:U,error:`Instance does not match exactly one subschema (${H} matches).`})}if((l==="object"||l==="array")&&Object.assign(u,...ot),O!==void 0){const U=`${a}/if`;if(re(e,O,n,o,r,s,i,U,u).valid){if(G!==void 0){const M=re(e,G,n,o,r,s,i,`${a}/then`,u);M.valid||k.push({instanceLocation:i,keyword:"if",keywordLocation:U,error:'Instance does not match "then" schema.'},...M.errors)}}else if(ie!==void 0){const M=re(e,ie,n,o,r,s,i,`${a}/else`,u);M.valid||k.push({instanceLocation:i,keyword:"if",keywordLocation:U,error:'Instance does not match "else" schema.'},...M.errors)}}if(l==="object"){if(w!==void 0)for(const T of w)T in e||k.push({instanceLocation:i,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${T}".`});const U=Object.keys(e);if(Ke!==void 0&&U.length<Ke&&k.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${Ke} properties.`}),Le!==void 0&&U.length>Le&&k.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${Le} properties.`}),Ye!==void 0){const T=`${a}/propertyNames`;for(const P in e){const Z=`${i}/${We(P)}`,D=re(P,Ye,n,o,r,s,Z,T);D.valid||k.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:T,error:`Property name "${P}" does not match schema.`},...D.errors)}}if(ke!==void 0){const T=`${a}/dependantRequired`;for(const P in ke)if(P in e){const Z=ke[P];for(const D of Z)D in e||k.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:T,error:`Instance has "${P}" but does not have "${D}".`})}}if(Ue!==void 0)for(const T in Ue){const P=`${a}/dependentSchemas`;if(T in e){const Z=re(e,Ue[T],n,o,r,s,i,`${P}/${We(T)}`,u);Z.valid||k.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:P,error:`Instance has "${T}" but does not match dependant schema.`},...Z.errors)}}if(Xe!==void 0){const T=`${a}/dependencies`;for(const P in Xe)if(P in e){const Z=Xe[P];if(Array.isArray(Z))for(const D of Z)D in e||k.push({instanceLocation:i,keyword:"dependencies",keywordLocation:T,error:`Instance has "${P}" but does not have "${D}".`});else{const D=re(e,Z,n,o,r,s,i,`${T}/${We(P)}`);D.valid||k.push({instanceLocation:i,keyword:"dependencies",keywordLocation:T,error:`Instance has "${P}" but does not match dependant schema.`},...D.errors)}}}const M=Object.create(null);let H=!1;if(pe!==void 0){const T=`${a}/properties`;for(const P in pe){if(!(P in e))continue;const Z=`${i}/${We(P)}`,D=re(e[P],pe[P],n,o,r,s,Z,`${T}/${We(P)}`);if(D.valid)u[P]=M[P]=!0;else if(H=r,k.push({instanceLocation:i,keyword:"properties",keywordLocation:T,error:`Property "${P}" does not match schema.`},...D.errors),H)break}}if(!H&&fe!==void 0){const T=`${a}/patternProperties`;for(const P in fe){const Z=new RegExp(P,"u"),D=fe[P];for(const ce in e){if(!Z.test(ce))continue;const Ct=`${i}/${We(ce)}`,rt=re(e[ce],D,n,o,r,s,Ct,`${T}/${We(P)}`);rt.valid?u[ce]=M[ce]=!0:(H=r,k.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:T,error:`Property "${ce}" matches pattern "${P}" but does not match associated schema.`},...rt.errors))}}}if(!H&&K!==void 0){const T=`${a}/additionalProperties`;for(const P in e){if(M[P])continue;const Z=`${i}/${We(P)}`,D=re(e[P],K,n,o,r,s,Z,T);D.valid?u[P]=!0:(H=r,k.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:T,error:`Property "${P}" does not match additional properties schema.`},...D.errors))}}else if(!H&&ne!==void 0){const T=`${a}/unevaluatedProperties`;for(const P in e)if(!u[P]){const Z=`${i}/${We(P)}`,D=re(e[P],ne,n,o,r,s,Z,T);D.valid?u[P]=!0:k.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:T,error:`Property "${P}" does not match unevaluated properties schema.`},...D.errors)}}}else if(l==="array"){Je!==void 0&&e.length>Je&&k.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${Je}).`}),Re!==void 0&&e.length<Re&&k.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Re}).`});const U=e.length;let M=0,H=!1;if(Oe!==void 0){const T=`${a}/prefixItems`,P=Math.min(Oe.length,U);for(;M<P;M++){const Z=re(e[M],Oe[M],n,o,r,s,`${i}/${M}`,`${T}/${M}`);if(u[M]=!0,!Z.valid&&(H=r,k.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:T,error:"Items did not match schema."},...Z.errors),H))break}}if(ye!==void 0){const T=`${a}/items`;if(Array.isArray(ye)){const P=Math.min(ye.length,U);for(;M<P;M++){const Z=re(e[M],ye[M],n,o,r,s,`${i}/${M}`,`${T}/${M}`);if(u[M]=!0,!Z.valid&&(H=r,k.push({instanceLocation:i,keyword:"items",keywordLocation:T,error:"Items did not match schema."},...Z.errors),H))break}}else for(;M<U;M++){const P=re(e[M],ye,n,o,r,s,`${i}/${M}`,T);if(u[M]=!0,!P.valid&&(H=r,k.push({instanceLocation:i,keyword:"items",keywordLocation:T,error:"Items did not match schema."},...P.errors),H))break}if(!H&&lt!==void 0){const P=`${a}/additionalItems`;for(;M<U;M++){const Z=re(e[M],lt,n,o,r,s,`${i}/${M}`,P);u[M]=!0,Z.valid||(H=r,k.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:P,error:"Items did not match additional items schema."},...Z.errors))}}}if(Qe!==void 0)if(U===0&&Se===void 0)k.push({instanceLocation:i,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Se!==void 0&&U<Se)k.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${U}) than minContains (${Se}).`});else{const T=`${a}/contains`,P=k.length;let Z=0;for(let D=0;D<U;D++){const ce=re(e[D],Qe,n,o,r,s,`${i}/${D}`,T);ce.valid?(u[D]=!0,Z++):k.push(...ce.errors)}Z>=(Se||0)&&(k.length=P),Se===void 0&&be===void 0&&Z===0?k.splice(P,0,{instanceLocation:i,keyword:"contains",keywordLocation:T,error:"Array does not contain item matching schema."}):Se!==void 0&&Z<Se?k.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Se} items matching schema. Only ${Z} items were found.`}):be!==void 0&&Z>be&&k.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${be} items matching schema. ${Z} items were found.`})}if(!H&&dt!==void 0){const T=`${a}/unevaluatedItems`;for(;M<U;M++){if(u[M])continue;const P=re(e[M],dt,n,o,r,s,`${i}/${M}`,T);u[M]=!0,P.valid||k.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:T,error:"Items did not match unevaluated items schema."},...P.errors)}}if(Tt)for(let T=0;T<U;T++){const P=e[T],Z=typeof P=="object"&&P!==null;for(let D=0;D<U;D++){if(T===D)continue;const ce=e[D];(P===ce||Z&&typeof ce=="object"&&ce!==null&&vo(P,ce))&&(k.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${T} and ${D}.`}),T=Number.MAX_SAFE_INTEGER,D=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(n==="4"?(qe!==void 0&&(Te===!0&&e<=qe||e<qe)&&k.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Te?"or equal to ":""} ${qe}.`}),Ne!==void 0&&(je===!0&&e>=Ne||e>Ne)&&k.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${je?"or equal to ":""} ${Ne}.`})):(qe!==void 0&&e<qe&&k.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${qe}.`}),Ne!==void 0&&e>Ne&&k.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Ne}.`}),Te!==void 0&&e<=Te&&k.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${Te}.`}),je!==void 0&&e>=je&&k.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${je}.`})),De!==void 0){const U=e%De;Math.abs(0-U)>=11920929e-14&&Math.abs(De-U)>=11920929e-14&&k.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${De}.`})}}else if(l==="string"){const U=et===void 0&&tt===void 0?0:sb(e);et!==void 0&&U<et&&k.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${U} < ${et}).`}),tt!==void 0&&U>tt&&k.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${U} > ${tt}).`}),ft!==void 0&&!new RegExp(ft,"u").test(e)&&k.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),te!==void 0&&Za[te]&&!Za[te](e)&&k.push({instanceLocation:i,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${te}".`})}return{valid:k.length===0,errors:k}}var ib=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Lt(e)}validate(e){return re(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Lt(e,this.lookup)}},ab=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){const t=n_(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){const t=new ib(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("; ")}}}},pn,qo=(pn=class extends Error{static[Symbol.hasInstance](t){return ct(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 ct(this,t)}constructor(t){super(t),this.name=new.target.name,Oo(this,new.target)}},Object.defineProperty(pn,"mcpBrand",{value:"mcp.OAuthClientFlowError"}),pn),hn,Rs=(hn=class extends qo{kind;expected;received;constructor(t,n,o){super(`Issuer mismatch in ${t==="metadata"?"authorization server metadata (RFC 8414 §3.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(n)}, received ${JSON.stringify(o)}`),this.kind=t,this.expected=n,this.received=o}},Object.defineProperty(hn,"mcpBrand",{value:"mcp.IssuerMismatchError"}),hn),mn,cb=(mn=class extends qo{status;body;submittedMetadata;constructor(t){super(`Dynamic Client Registration rejected (HTTP ${t.status}): ${t.body}`),this.status=t.status,this.body=t.body,this.submittedMetadata=t.submittedMetadata}},Object.defineProperty(mn,"mcpBrand",{value:"mcp.RegistrationRejectedError"}),mn),fn,Bd=(fn=class extends qo{tokenEndpoint;constructor(t){super(`Refusing to send credentials to non-https token endpoint '${t}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=t}},Object.defineProperty(fn,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"}),fn),Sn,lr=(Sn=class extends qo{constructor(t,n){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(t)} but this call resolved ${JSON.stringify(n)}; refusing to present them to a different authorization server`),this.recordedIssuer=t,this.currentIssuer=n}},Object.defineProperty(Sn,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"}),Sn),gn,Fa=(gn=class extends qo{requiredScope;resourceMetadataUrl;errorDescription;constructor(t){super(`Insufficient scope${t.requiredScope?`: required "${t.requiredScope}"`:""}`),this.requiredScope=t.requiredScope,this.resourceMetadataUrl=t.resourceMetadataUrl,this.errorDescription=t.errorDescription}},Object.defineProperty(gn,"mcpBrand",{value:"mcp.InsufficientScopeError"}),gn);function ws(e,t,n){if(e)return typeof e.issuer!="string"?(n?.canPersistStamp!==!1&&console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."),e.issuer===void 0?e:{...e,issuer:void 0}):Wd(e.issuer,t)?e:void 0}function Wd(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function ub(e){if(e==null)return!1;const t=e;return typeof t.tokens=="function"&&typeof t.clientInformation=="function"}async function lb(e,t,n){const{resourceMetadataUrl:o,scope:r}=mo(t.response);if(await Ps(e,{serverUrl:t.serverUrl,resourceMetadataUrl:o,scope:r,fetchFn:t.fetchFn,...n})!=="AUTHORIZED")throw new it}function db(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async n=>lb(e,n,t)}}var _n,it=(_n=class extends Error{static[Symbol.hasInstance](t){return ct(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 ct(this,t)}constructor(t){super(t??"Unauthorized"),this.name="UnauthorizedError",Oo(this,new.target)}},Object.defineProperty(_n,"mcpBrand",{value:"mcp.UnauthorizedError"}),_n);function xi(e){return e?.authorization_response_iss_parameter_supported===!0}function zi({iss:e,expectedIssuer:t,issParameterSupported:n}){if(t!==void 0){if(e===void 0){if(n)throw new Rs("authorization_response",t,void 0);return}if(e!==t)throw new Rs("authorization_response",t,e)}}function es(...e){const t=new Set;for(const n of e)if(n)for(const o of n.split(/\s+/))o&&t.add(o);return t.size>0?[...t].join(" "):void 0}function pb(e,t){if(!e)return!1;const n=new Set((t??"").split(/\s+/).filter(Boolean));for(const o of e.split(/\s+/))if(o&&!n.has(o))return!0;return!1}async function hb(e,t,n,o,r){if(typeof e=="string")return{authorizationCode:e,iss:t};const s=e.get("iss")??void 0,i=e.get("code");if(i)return{authorizationCode:i,iss:s};let a=(await n.discoveryState?.())?.authorizationServerMetadata;if(!a)try{a=(await Qd(o,r)).authorizationServerMetadata}catch{a=void 0}if(!a)throw new it("Authorization callback failed and the issuer could not be verified");zi({iss:s,expectedIssuer:a.issuer,issParameterSupported:xi(a)});const u=e.get("error");throw u?new $n(u,e.get("error_description")??u,e.get("error_uri")??void 0):new it("Authorization callback contained neither `code` nor `error`")}function mb(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const ts="code",ns="S256";function fb(e,t){const n=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&mb(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?"client_secret_basic":"none":n&&t.includes("client_secret_basic")?"client_secret_basic":n&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":n?"client_secret_post":"none"}function Sb(e,t,n,o){const{client_id:r,client_secret:s}=t;switch(e){case"client_secret_basic":gb(r,s,n);return;case"client_secret_post":_b(r,s,o);return;case"none":vb(r,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function gb(e,t,n){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${t}`);n.set("Authorization",`Basic ${o}`)}function _b(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function vb(e,t){t.set("client_id",e)}function Gd(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function yb(e){const t=new URL(String(e));if(t.protocol!=="https:"&&!Gd(t.hostname))throw new Bd(t.href);return t}function bb(e){for(const t of e??[]){let n;try{n=new URL(t)}catch{continue}if(n.protocol!=="http:"&&n.protocol!=="https:"||Gd(n.hostname))return"native"}return"web"}function Rb(e){const t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??bb(t.redirect_uris)}}async function Va(e){const t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{const o=md.parse(JSON.parse(n));return $n.fromResponse(o)}catch(o){const r=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${n}`;return new $n(yt.ServerError,r)}}function Ha(e,t,n){const o=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${n} (provider implements no invalidateCredentials())`:`invalidating the stored ${n} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} — ${o}. Cause: ${JSON.stringify(t.message)}`)}async function Ps(e,t){try{return await os(e,t)}catch(n){if(n instanceof $n){if(n.code===yt.InvalidClient||n.code===yt.UnauthorizedClient)return Ha(e,n,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await os(e,t);if(n.code===yt.InvalidGrant||n.code===yt.InvalidDpopProof)return Ha(e,n,"tokens"),await e.invalidateCredentials?.("tokens"),await os(e,t)}throw n}}function wb(e){const{requestedScope:t,resourceMetadata:n,authServerMetadata:o,clientMetadata:r}=e;let s=t||n?.scopes_supported?.join(" ")||r.scope;return s&&o?.scopes_supported?.includes("offline_access")&&!s.split(" ").includes("offline_access")&&r.grant_types?.includes("refresh_token")&&(s=`${s} offline_access`),s}async function os(e,{serverUrl:t,authorizationCode:n,iss:o,scope:r,resourceMetadataUrl:s,fetchFn:i,skipIssuerMetadataValidation:a,forceReauthorization:u}){const d=Rb(e),l=await e.discoveryState?.();let p,h,f,S,v=s;if(!v&&l?.resourceMetadataUrl&&(v=new URL(l.resourceMetadataUrl)),l?.authorizationServerUrl){if(h=l.authorizationServerUrl,p=l.resourceMetadata,f=l.authorizationServerMetadata??await Xd(h,{fetchFn:i,skipIssuerValidation:a}),!p)try{p=await Kd(t,{resourceMetadataUrl:v},i)}catch(K){if(K instanceof TypeError)throw K}(f!==l.authorizationServerMetadata||p!==l.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(h),resourceMetadataUrl:v?.toString(),resourceMetadata:p,authorizationServerMetadata:f})}else{const K=await Qd(t,{resourceMetadataUrl:v,fetchFn:i,skipIssuerMetadataValidation:a});h=K.authorizationServerUrl,f=K.authorizationServerMetadata,p=K.resourceMetadata,S={authorizationServerUrl:String(h),resourceMetadataUrl:v?.toString(),resourceMetadata:p,authorizationServerMetadata:f}}const y=f?.issuer??String(h),w={issuer:y};if(await e.saveAuthorizationServerUrl?.(y),n!==void 0){const K=l?.authorizationServerMetadata?.issuer??l?.authorizationServerUrl;if(K===void 0){if(e.saveDiscoveryState!==void 0)throw new lr("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",y);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.")}else if(!Wd(K,y))throw new lr(K,y)}S&&await e.saveDiscoveryState?.(S);const x=await $b(t,e,p),z=x&&p&&!e.validateResourceURL?p.resource:x;z&&await e.saveResourceUrl?.(Ai(z));const J=wb({requestedScope:r,resourceMetadata:p,authServerMetadata:f,clientMetadata:e.clientMetadata}),B=await Promise.resolve(e.clientInformation(w));let O=ws(B,y,{canPersistStamp:e.saveClientInformation!==void 0});if(O===void 0&&B?.issuer&&e.saveClientInformation===void 0)throw new lr(B.issuer,y);if(O&&O.issuer===void 0&&(O={...O,issuer:y},await e.saveClientInformation?.(O,w)),!O){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const K=f?.client_id_metadata_document_supported===!0,ne=e.clientMetadataUrl;if(ne&&!Pb(ne))throw new $n(yt.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ne}`);if(K&&ne)O={client_id:ne,issuer:y},await e.saveClientInformation?.(O,w);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");O={...await xb(h,{metadata:f,clientMetadata:d,scope:J,fetchFn:i}),issuer:y},await e.saveClientInformation(O,w)}}const G=!e.redirectUrl;if(n!==void 0||G){n!==void 0&&zi({iss:o,expectedIssuer:f?.issuer,issParameterSupported:xi(f)});const K=await Mb(e,h,{metadata:f,resource:z,authorizationCode:n,iss:o,scope:J,fetchFn:i});return await e.saveTokens({...K,issuer:y},w),"AUTHORIZED"}let ie=ws(await e.tokens(w),y);if(ie&&ie.issuer===void 0&&(ie={...ie,issuer:y},await e.saveTokens(ie,w)),ie?.refresh_token&&!u){let K;try{K=await Nb(h,{metadata:f,clientInformation:O,refreshToken:ie.refresh_token,resource:z,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:i})}catch(ne){if(ne instanceof Bd)throw ne;if(!(ne instanceof $n)||ne.code===yt.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(ne instanceof Error?ne.message:String(ne))}`);else throw ne}if(K)return await e.saveTokens({...K,issuer:y},w),"AUTHORIZED"}const te=e.state?await e.state():void 0,{authorizationUrl:pe,codeVerifier:fe}=await Ob(h,{metadata:f,clientInformation:O,state:te,redirectUrl:e.redirectUrl,scope:J,resource:z});return await e.saveCodeVerifier(fe),await e.redirectToAuthorization(pe),"REDIRECT"}function Pb(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function $b(e,t,n){const o=I_(e);if(t.validateResourceURL)return await t.validateResourceURL(o,n?.resource);if(n){if(!O_({requestedResource:o,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${o} (or origin)`);return new URL(n.resource)}}const kb=new Set(["bearer","dpop"]);function mo(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[n,o]=t.split(" ");if(!n||!kb.has(n.toLowerCase())||!o)return{};const r=sr(e,"resource_metadata")||void 0;let s;if(r)try{s=new URL(r)}catch{}const i=sr(e,"scope")||void 0,a=sr(e,"error")||void 0,u=sr(e,"error_description")||void 0;return{resourceMetadataUrl:s,scope:i,error:a,errorDescription:u}}function sr(e,t){const n=e.headers.get("WWW-Authenticate");if(!n)return null;const o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),r=n.match(o);if(r){const s=r[1]||r[2];if(s)return s}return null}async function Kd(e,t,n=fetch){const o=await Cb(e,"oauth-protected-resource",n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.text?.().catch(()=>{}),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return ld.parse(await o.json())}async function Yd(e,t,n=fetch){const o=Zr(n);try{return await o(e,{headers:t})}catch(r){if(!(r instanceof TypeError))throw r;if(t)try{return await o(e,{})}catch(s){if(!(s instanceof TypeError))throw s;return}return}}function Tb(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Ja(e,t,n=fetch){return await Yd(e,{"MCP-Protocol-Version":t},n)}function Eb(e,t){return e?t==="/"?!1:!e.ok&&e.status<500||e.status===502:!0}async function Cb(e,t,n,o){const r=new URL(e),s=o?.protocolVersion??Bs;let i;if(o?.metadataUrl)i=new URL(o.metadataUrl);else{const u=Tb(t,r.pathname);i=new URL(u,o?.metadataServerUrl??r),i.search=r.search}let a=await Ja(i,s,n);return!o?.metadataUrl&&Eb(a,r.pathname)&&(a=await Ja(new URL(`/.well-known/${t}`,r),s,n)),a}function Ib(e){const t=typeof e=="string"?new URL(e):e,n=t.pathname!=="/",o=[];if(!n)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let r=t.pathname;return r.endsWith("/")&&(r=r.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"},{url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function Xd(e,{fetchFn:t=fetch,protocolVersion:n=Bs,skipIssuerValidation:o=!1}={}){const r={"MCP-Protocol-Version":n,Accept:"application/json"},s=Ib(e);for(const{url:i,type:a}of s){const u=await Yd(i,r,t);if(!u)continue;if(!u.ok){if(await u.text?.().catch(()=>{}),u.status<500||u.status===502)continue;throw new Error(`HTTP ${u.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}const d=a==="oauth"?$i.parse(await u.json()):pd.parse(await u.json());if(!o){const l=typeof e=="string"?e:e.href;if(!(d.issuer===l||l.endsWith("/")&&d.issuer===l.slice(0,-1)))throw new Rs("metadata",l,d.issuer)}return d}}async function Qd(e,t){let n,o;try{n=await Kd(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(o=n.authorization_servers[0])}catch(s){if(s instanceof TypeError)throw s}o||(o=String(new URL("/",e)));const r=await Xd(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:r,resourceMetadata:n}}function Ai(e){return typeof e=="string"?e:e.href}async function Ob(e,{metadata:t,clientInformation:n,redirectUrl:o,scope:r,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(ts))throw new Error(`Incompatible auth server: does not support response type ${ts}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(ns))throw new Error(`Incompatible auth server: does not support code challenge method ${ns}`)}else a=new URL("/authorize",e);const u=await cp(),d=u.code_verifier,l=u.code_challenge;return a.searchParams.set("response_type",ts),a.searchParams.set("client_id",n.client_id),a.searchParams.set("code_challenge",l),a.searchParams.set("code_challenge_method",ns),a.searchParams.set("redirect_uri",String(o)),s&&a.searchParams.set("state",s),r&&a.searchParams.set("scope",r),r?.split(" ").includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",Ai(i)),{authorizationUrl:a,codeVerifier:d}}function qb(e,t,n){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(n)})}async function ep(e,{metadata:t,tokenRequestParams:n,clientInformation:o,addClientAuthentication:r,resource:s,dpop:i,fetchFn:a}){const u=yb(t?.token_endpoint??new URL("/token",e)),d=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});s&&n.set("resource",Ai(s)),!r&&o&&Sb(fb(o,t?.token_endpoint_auth_methods_supported??[]),o,d,n);const l=async()=>{const f=new Headers(d);return r&&await r(f,n,u,t),i&&f.set("DPoP",await i.buildProof({htm:"POST",htu:u})),Zr(a??fetch)(u,{method:"POST",headers:f,body:n})};let p=await l();if(i&&p.status===400&&(await p.clone().json().catch(()=>{}))?.error===yt.UseDpopNonce&&(i.observeNonce(p,u),p=await l()),i?.observeNonce(p,u),!p.ok)throw await Va(p);const h=await p.json();try{return hd.parse(_d(h))}catch(f){throw typeof h=="object"&&h!==null&&"error"in h?await Va(JSON.stringify(h)):f}}async function Nb(e,{metadata:t,clientInformation:n,refreshToken:o,resource:r,addClientAuthentication:s,dpop:i,fetchFn:a}){return{refresh_token:o,...await ep(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:n,addClientAuthentication:s,resource:r,dpop:i,fetchFn:a})}}async function Mb(e,t,{metadata:n,resource:o,authorizationCode:r,iss:s,scope:i,fetchFn:a}={}){r!==void 0&&zi({iss:s,expectedIssuer:n?.issuer,issParameterSupported:xi(n)});const u=n?.issuer??String(t),d=async()=>{const f=await e.clientInformation({issuer:u}),S=ws(f,u,{canPersistStamp:!1});if(f&&S===void 0)throw new lr(String(f.issuer),u);return S};let l=await d();const p=i??e.clientMetadata.scope;let h;if(e.prepareTokenRequest&&(h=await e.prepareTokenRequest(p)),!h){if(!r)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");h=qb(r,await e.codeVerifier(),e.redirectUrl)}return l??=await d(),ep(t,{metadata:n,tokenRequestParams:h,clientInformation:l,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:a})}async function xb(e,{metadata:t,clientMetadata:n,scope:o,fetchFn:r}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);const i={...n,...o===void 0?{}:{scope:o}},a=await Zr(r??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!a.ok)throw new cb({status:a.status,body:await a.text(),submittedMetadata:i});return gd.parse(_d(await a.json()))}const ir=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]);var zb=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(rs(e))}set(e,t){const n=rs(e),o=ir.has(e.method),r=!this._entries.has(n);if(!o&&r&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(const i of this._entries.keys())if(!ir.has(i.slice(0,i.indexOf("\0")))){this._entries.delete(i),this._cappedSize--;break}}const s=++this._stamp;return this._entries.set(n,{...t,stamp:s}),r&&!o&&this._cappedSize++,s}delete(e){this._entries.delete(rs(e))&&!ir.has(e.method)&&this._cappedSize--}evict(e){const t=`${e}\0`,n=ir.has(e);for(const o of this._entries.keys())o.startsWith(t)&&(this._entries.delete(o),n||this._cappedSize--)}clear(){this._entries.clear(),this._cappedSize=0}};function rs(e){return`${e.method}\0${JSON.stringify([e.partition??"",e.params??""])}`}function ss(e,t){return t===void 0?e:`${e}\0${t}`}const Ab=864e5;var Lb=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,n=()=>{},o="",r=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=n,this._cachePartition=o,this._now=r}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){const n={method:e,params:t??""},o=this._partitionFor("private"),r=await this._store.get({...n,partition:o});if(r!==void 0)return r;const s=this._partitionFor("public");if(s===o)return;const i=await this._store.get({...n,partition:s});return i?.scope==="public"?i:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){const n=this._partitionFor("private"),o=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:n})}catch(r){this._reportError(r)}if(o!==n)try{await this._store.delete({method:e,params:t,partition:o})}catch(r){this._reportError(r)}}async evictKey(e,t){const n=ss(e,t),o=this._evictionGeneration.get(n);o!==void 0&&this._evictionGeneration.set(n,o+1),await this._deleteBoth(e,t)}captureGeneration(e,t){const n=ss(e,t),o=this._evictionGeneration.get(n)??0;return this._evictionGeneration.set(n,o),o}async write(e,t,n,o){if((this._evictionGeneration.get(ss(e,o?.params))??0)!==n)return;const r=o?.params??"",s=this._partitionFor("private"),i=this._partitionFor("public"),a=(o?.scope??"private")==="public"?i:s;try{await this._store.set({method:e,params:r,partition:a},{value:Ub(t),expiresAt:o?.expiresAt,scope:o?.scope})}catch(u){this._reportError(u)}if(i!==s)try{await this._store.delete({method:e,params:r,partition:a===s?i:s})}catch(u){this._reportError(u)}}async read(e,t){const n=await this._probe(e,t);if(!(n?.expiresAt===void 0||!(n.expiresAt>this.now())))try{const o=JSON.parse(n.value);if(typeof o!="object"||o===null||Array.isArray(o))throw new TypeError("cached document is not an object");return{value:o}}catch(o){this._reportError(o),await this._deleteBoth(e,t??"");return}}resetForReconnect(){this._isUserSupplied||this._store.clear(),this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){const t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){const n=this._decodeListTools(t),o=new Map;if(n!==void 0)for(const r of n.tools)o.set(r.name,r);this._toolIndex={stamp:t.stamp,byName:o}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){const n=await this._probe("tools/list");if(n===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==n.stamp){const o=this._decodeListTools(n)??{tools:[]},r=new Map;for(const s of o.tools){const i=t(s);i!==void 0&&r.set(s.name,i)}this._toolOutputValidatorIndex={stamp:n.stamp,byName:r}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{const t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every(n=>n!==null&&typeof n=="object"))throw new TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};function Ub(e){let t;try{t=JSON.stringify(e)}catch(n){throw new TypeError(`cache value is not JSON-serializable: ${n instanceof Error?n.message:String(n)}`)}if(typeof t!="string")throw new TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}const tp=Symbol.for("mcp.authSeamEscape");function Fe(e){if(typeof e=="object"&&e!==null||typeof e=="function")try{Object.defineProperty(e,tp,{value:!0,configurable:!0})}catch{}return e}function jb(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&e[tp]===!0}const Db=-32022,Zb=new Set([-32001,-32020,-32021]);function Fb(e,t){switch(e.kind){case"result":return Vb(e.result,t);case"rpc-error":return np(e,t);case"http-error":return Hb(e,t);case"network-error":return Ba(e.error,t);case"unusable-reply":return{kind:"error",error:new q(I.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${op(e.error)})`,{cause:e.error},{cause:e.error})};case"auth-required":return{kind:"error",error:e.error};case"closed":return t.transportKind==="stdio"?{kind:"legacy"}:Ba(new Error("Connection closed during the version negotiation probe"),t);case"timeout":return t.transportKind==="stdio"?{kind:"legacy"}:{kind:"error",error:new q(I.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function Vb(e,t){const n=$t(Oi).validateResult("server/discover",e);if(!n.ok)return{kind:"legacy"};const o=n.value.supportedVersions,r=t.clientModernVersions.find(s=>o.includes(s));return r!==void 0?{kind:"modern",version:r,discover:n.value}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:new Ci({supported:[...o],requested:t.requestedVersion})}}function np(e,t){const{code:n,message:o,data:r}=e;if(n===Db){const s=Bb(r);if(s===void 0)return{kind:"legacy"};const i=new Ci({supported:s,requested:Wb(r)??t.requestedVersion},o),a=Rr(s),u=t.clientModernVersions.find(d=>a.includes(d));return u!==void 0?{kind:"corrective",version:u,error:i}:a.length>0?{kind:"error",error:i}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:i}}return Zb.has(n)?{kind:"legacy"}:{kind:"legacy"}}function Hb(e,t){if(e.status===401||e.status===403){const o=e.status===403;return{kind:"error",error:new pt(o?I.ClientHttpForbidden:I.ClientHttpAuthentication,`Version negotiation failed: ${o?"the server denied access (HTTP 403)":"the server requires authorization (HTTP 401)"}`,{status:e.status,statusText:e.statusText,text:e.body})}}if(e.status>=500)return{kind:"error",error:new pt(I.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};const n=Gb(e.body);return n!==void 0?np(n,t):{kind:"legacy"}}function Ba(e,t){return t.environment==="browser"&&Jb(e)?{kind:"legacy"}:{kind:"error",error:new q(I.EraNegotiationFailed,`Version negotiation probe failed: ${op(e)}`,{cause:e},{cause:e})}}function Jb(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function op(e){return e instanceof Error?e.message:String(e)}function Bb(e){if(typeof e!="object"||e===null)return;const t=e.supported;if(!(!Array.isArray(t)||t.length===0||!t.every(n=>typeof n=="string")))return t}function Wb(e){if(typeof e!="object"||e===null)return;const t=e.requested;return typeof t=="string"?t:void 0}function Gb(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null)return;const n=t.error;if(typeof n!="object"||n===null)return;const{code:o,message:r,data:s}=n;if(typeof o=="number")return{code:o,message:typeof r=="string"?r:"",data:s}}const Kb="legacy";function Yb(e,t){const n=e?.mode??Kb;if(n==="legacy")return{kind:"legacy"};const o=e?.probe??{};if(typeof n=="object"){if(!bt(n.pin))throw new TypeError(`versionNegotiation: { pin: '${n.pin}' } is not a modern protocol revision — pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:n.pin,probe:o}}const r=t?Rr(t):[];return{kind:"auto",modernVersions:r.length>0?r:[...yd],fallbackAvailable:t?bd(t).length>0:!0,probe:o}}function Wa(){const e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function Ga(e){return"stderr"in e&&"pid"in e?"stdio":"http"}var Xb=class rp{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(t){this._transport=t,this._savedOnMessage=t.onmessage,this._savedOnError=t.onerror,this._savedOnClose=t.onclose}static async open(t){const n=new rp(t);t.onmessage=o=>{const r=n._pending;if(r!==void 0&&(ko(o)||To(o))&&o.id===r.id){n._pending=void 0,ko(o)?r.resolve({kind:"response",result:o.result}):r.resolve({kind:"response",error:o.error});return}},t.onerror=o=>{n._savedOnError?.(o)},t.onclose=()=>{const o=n._pending;o!==void 0&&(n._pending=void 0,o.resolve({kind:"closed"})),n._closeDelivered=!0,n._savedOnClose?.()};try{await t.start()}catch(o){throw n.detach(),o}return n}async exchange(t,n){const o=`server-discover-probe-${++this._probeCounter}`;return new Promise(r=>{let s=!1;const i=u=>{s||(s=!0,clearTimeout(a),this._pending?.id===o&&(this._pending=void 0),r(u))},a=setTimeout(()=>i({kind:"timeout"}),n);this._pending={id:o,resolve:i},this._transport.send(t(o)).catch(u=>i({kind:"send-error",error:u}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){const t=this._savedOnClose,n=this._transport;let o=!1;const r=()=>{if(!o){o=!0;return}t()};n.onclose=r,$s.set(n,()=>{n.onclose===r&&(n.onclose=t)})}else this._transport.onclose=this._savedOnClose}release(){this.detach();const t=this._transport,n=t.start;let o=!0;t.start=async function(){if(o){o=!1,t.start=n;return}return n.call(t)}}};const $s=new WeakMap;function Ka(e){const t=$s.get(e);$s.delete(e),t?.()}function Qb(e,t,n,o){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:$t(t).outboundEnvelope({protocolVersion:t,clientInfo:n,clientCapabilities:o})}}}function eR(e){return e instanceof q&&e.code===I.ClientHttpUnexpectedContent?!0:e instanceof Error&&e.name==="SyntaxError"}function tR(e,t){switch(e.kind){case"response":return e.error===void 0?{kind:"result",result:e.result}:{kind:"rpc-error",...e.error};case"send-error":{const n=e.error;if(jb(n)||n instanceof it||n instanceof Error&&n.name==="UnauthorizedError")return{kind:"auth-required",error:n};if(n instanceof pt){const o=n.data?.text;return{kind:"http-error",status:n.data.status,body:typeof o=="string"?o:void 0,statusText:n.data.statusText}}return eR(n)?{kind:"unusable-reply",error:n}:{kind:"network-error",error:n}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function sp(e,t){const n=e.probe.timeoutMs??t.defaultTimeoutMs,o=Math.max(0,e.probe.maxRetries??0),r=e.kind==="pin"?[e.version]:e.modernVersions,s=e.kind==="auto"&&e.fallbackAvailable,i=await Xb.open(t.transport),a=async()=>{let d=r[0],l=!1,p=o;for(;;){const h=await i.exchange(v=>Qb(v,d,t.clientInfo,t.capabilities),n);if(h.kind==="timeout"&&p>0){p--;continue}const f=tR(h,n),S=Fb(f,{clientModernVersions:r,requestedVersion:d,fallbackAvailable:s,environment:t.environment,transportKind:t.transportKind});switch(S.kind){case"modern":return{era:"modern",version:S.version,discover:S.discover};case"corrective":if(l)throw S.error;l=!0,d=S.version;continue;case"legacy":{const v=f.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new q(I.EraNegotiationFailed,v===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${v} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new q(I.EraNegotiationFailed,v===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${v} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(v!==void 0&&t.disposableProbe!==!0)throw new q(I.EraNegotiationFailed,`Version negotiation failed: ${v} (this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw S.error}}};let u;try{u=await a()}catch(d){throw i.detach(),d}return i.release(),u}function nR(e){const t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;const n=e._serverParams;return typeof n=="object"&&n!==null&&typeof n.command=="string"?n:void 0}async function oR(e,t,n,o){const r=t.constructor,s=new r({...n,stderr:"ignore"}),i=t.close;let a=!1,u;const d=new Promise((p,h)=>{u=()=>h(Ya())});t.close=async function(){return a=!0,u?.(),i.call(t)};let l;try{const p=sp(e,{...o,transport:s,transportKind:"stdio",disposableProbe:!0});p.catch(()=>{}),l=await Promise.race([p,d])}finally{await rR(s),t.close=i}if(a)throw Ya();return l}function Ya(){return new q(I.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function rR(e){try{const t=e._dispose;await(typeof t=="function"?t.call(e):e.close())}catch{}}function Xa(e){const t=e._meta?.[rn];return uy.Implementation(t)?t:void 0}function dr(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const n=t,o=e.properties;for(const r of Object.keys(o)){const s=o[r];n[r]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(n[r]=s.default),n[r]!==void 0&&dr(s,n[r])}}if(Array.isArray(e.anyOf))for(const n of e.anyOf)typeof n!="boolean"&&dr(n,t);if(Array.isArray(e.oneOf))for(const n of e.oneOf)typeof n!="boolean"&&dr(n,t)}}function sR(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}function iR(e){if(typeof e=="object"&&e!==null&&(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e)||e.kind==="modern"&&Mr.safeParse(e.discover).success))return e;throw new q(I.EraNegotiationFailed,"connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }")}const Qa={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},aR=64;var yR=class extends my{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){const e=new q(I.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(const t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(const e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t),this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new ab,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=ty(t?.inputRequired),this._cache=new Lb(t?.responseCacheStore??new zb,t?.responseCacheStore!==void 0,n=>this._reportStoreError(n),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??aR,t?.listChanged&&(this._listChangedConfig=t.listChanged)}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&bt(this._negotiatedProtocolVersion)&&on(e))return"drop"}_outboundMetaEnvelope(){const e=this._negotiatedProtocolVersion;if(e!==void 0)return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){return this._inputRequiredDriverConfig.autoFulfill?yy({getRequestHandler:n=>this._getRequestHandler(n),buildContext:n=>this.buildContext(n,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t):Promise.reject(new q(I.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance — pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:t.request.method}))}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources","notifications/resources/list_changed",e.resources,async()=>(await this.listResources(void 0,{cacheMode:"refresh"})).resources)}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=fy(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw new Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){return e==="elicitation/create"?async(n,o)=>{const r=$t(this._negotiatedProtocolVersion);let s=r.validateRequest("elicitation/create",n);if(!s.ok&&s.reason==="not-in-era"&&(s=r.validateInputRequest("elicitation/create",n)),!s.ok)throw new Y(s.reason==="not-in-era"?F.InternalError:F.InvalidParams,s.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${s.message}`);const{params:i}=s.value;i.mode=i.mode??"form";const{supportsFormMode:a,supportsUrlMode:u}=sR(this._capabilities.elicitation);if(i.mode==="form"&&!a)throw new Y(F.InvalidParams,"Client does not support form-mode elicitation requests");if(i.mode==="url"&&!u)throw new Y(F.InvalidParams,"Client does not support URL-mode elicitation requests");const d=await t(n,o);let l=r.validateResult("elicitation/create",d);if(!l.ok&&l.reason==="not-in-era"&&(l=r.validateInputResponse("elicitation/create",d)),!l.ok)throw new Y(l.reason==="not-in-era"?F.InternalError:F.InvalidParams,l.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${l.message}`);const p=l.value,h=i.mode==="form"?i.requestedSchema:void 0;if(i.mode==="form"&&p.action==="accept"&&p.content&&h&&this._capabilities.elicitation?.form?.applyDefaults)try{dr(h,p.content)}catch{}return p}:e==="sampling/createMessage"?async(n,o)=>{const r=$t(this._negotiatedProtocolVersion);let s=r.validateRequest("sampling/createMessage",n);if(!s.ok&&s.reason==="not-in-era"&&(s=r.validateInputRequest("sampling/createMessage",n)),!s.ok)throw new Y(s.reason==="not-in-era"?F.InternalError:F.InvalidParams,s.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${s.message}`);const{params:i}=s.value,a=await t(n,o),u=!!(i.tools||i.toolChoice);let d=r.samplingResultVariant(u,a);if(!d.ok&&d.reason==="not-in-era"&&(d=r.validateInputResponse("sampling/createMessage",a)),!d.ok)throw new Y(d.reason==="not-in-era"?F.InternalError:F.InvalidParams,d.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${d.message}`);return d.value}:t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new q(I.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,iR(t.prior),t);const n=Yb(this._versionNegotiation,this._supportedProtocolVersionsOption);return n.kind!=="legacy"?this._connectNegotiated(e,n,t):this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){const n=this._negotiatedProtocolVersion;n!==void 0&&e.setProtocolVersion?.(n);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){const n=bd(this._supportedProtocolVersions);try{const o=n[0];if(o===void 0)throw new q(I.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");const r=await this.request({method:"initialize",params:{protocolVersion:o,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(r===void 0)throw new Error(`Server sent invalid initialize result: ${r}`);if(!n.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=r.protocolVersion,this._listChangedConfig&&this._setupListChangedHandlers(this._listChangedConfig)}catch(o){throw this.close(),o}}async _connectNegotiated(e,t,n){if(e.sessionId!==void 0){await super.connect(e);const r=this._negotiatedProtocolVersion;r!==void 0&&e.setProtocolVersion&&e.setProtocolVersion(r);return}this._resetConnectionState();let o;try{const r=Ga(e),s={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:Wa(),defaultTimeoutMs:n?.timeout??bs},i=r==="stdio"?nR(e):void 0;o=i===void 0?await sp(t,{...s,transport:e,transportKind:r}):await oR(t,e,i,s)}catch(r){throw await e.close().catch(()=>{}),Ka(e),r}if(Ka(e),await super.connect(e),o.era==="legacy"){await this._legacyHandshake(e,n);return}if(this._serverCapabilities=o.discover.capabilities,this._serverVersion=Xa(o.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.discover.instructions,this._discoverResult=o.discover,this._negotiatedProtocolVersion=o.version,e.setProtocolVersion&&e.setProtocolVersion(o.version),this._listChangedConfig){const r=this._listChangedConfig,s=this._serverCapabilities,i={...r.tools&&s?.tools?.listChanged&&{tools:r.tools},...r.prompts&&s?.prompts?.listChanged&&{prompts:r.prompts},...r.resources&&s?.resources?.listChanged&&{resources:r.resources}};let a=!0;try{this._setupListChangedHandlers(i)}catch(d){a=!1,this.onerror?.(d instanceof Error?d:new Error(String(d)))}const u=a?{...i.tools&&{toolsListChanged:!0},...i.prompts&&{promptsListChanged:!0},...i.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(u).length>0){const d=new AbortController,l=()=>d.abort(n?.signal?.reason);n?.signal?.aborted&&l(),n?.signal?.addEventListener("abort",l);try{this._autoOpenedSubscription=await this.listen(u,{timeout:n?.timeout,signal:d.signal})}catch(p){if(n?.signal?.aborted)throw await this.close().catch(()=>{}),p;this.onerror?.(p instanceof Error?p:new Error(String(p)))}finally{n?.signal?.removeEventListener("abort",l)}}}}async _connectFromPrior(e,t,n){if(t.kind==="legacy")return this._connectPlainLegacy(e,n);const o=t.discover;this._resetConnectionState();const r=this._supportedProtocolVersionsOption,s=(r&&Rr(r).length>0?Rr(r):yd).find(i=>o.supportedVersions.includes(i));if(s===void 0)throw new q(I.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(e),this._discoverResult=o,this._serverCapabilities=o.capabilities,this._serverVersion=Xa(o),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.instructions,this._negotiatedProtocolVersion=s,e.setProtocolVersion?.(s),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(i){this.onerror?.(i instanceof Error?i:new Error(String(i)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){const t=this._serverVersion;return t!==void 0?`${t.name}@${t.version}`:e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){const e=this._negotiatedProtocolVersion;if(e!==void 0)return bt(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new q(I.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new q(I.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new q(I.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new q(I.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new q(I.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new q(I.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new q(I.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new q(I.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new q(I.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new q(I.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){const t=await this._requestWithSchema({method:"server/discover"},Mr,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:"completion/complete",params:e},t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:"prompts/list",params:e},t);const n=await this._serveFromCache("prompts/list",void 0,t);return n!==void 0?n:this._listAllPages("prompts/list",e,t,o=>o.prompts)}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(e?.cursor!==void 0)return this.request({method:"resources/list",params:e},t);const n=await this._serveFromCache("resources/list",void 0,t);return n!==void 0?n:this._listAllPages("resources/list",e,t,o=>o.resources)}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:"resources/templates/list",params:e},t);const n=await this._serveFromCache("resources/templates/list",void 0,t);return n!==void 0?n:this._listAllPages("resources/templates/list",e,t,o=>o.resourceTemplates)}async _listAllPages(e,t,n,o,r){const s=n?.cacheMode==="bypass",i=this._cache.captureGeneration(e),a=await this.request({method:e,...t&&{params:{...t}}},n);let u=a.nextCursor,d=a,l=1;for(;u!==void 0;){if(this._listMaxPages!==0&&l>=this._listMaxPages)throw new q(I.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});const p=await this.request({method:e,params:{...t,cursor:u}},n);if(p.nextCursor===u&&JSON.stringify(o(p))===JSON.stringify(o(d)))break;o(a).push(...o(p)),d=p,u=p.nextCursor,l++}return delete a.nextCursor,r?.(a),s||await this._cache.write(e,a,i,this._freshness(a)),a}_freshness(e,t){const n=e,o=typeof n.ttlMs=="number"?n.ttlMs:this._defaultCacheTtlMs,r=n.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,o),Ab),scope:r,params:t}}async _serveFromCache(e,t,n){if(n?.cacheMode==="bypass"||n?.cacheMode==="refresh")return;const o=await this._cache.read(e,t).catch(r=>{this._reportStoreError(r)});if(o!==void 0){if(n?.signal?.aborted){const r=n.signal.reason;throw r instanceof q?r:new q(I.RequestTimeout,String(r))}return o.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:new Error(String(e)))}_compileOutputValidator(e){if(e.outputSchema)try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){const n=t??await this._cache.toolDefinition(e);return n===void 0?void 0:Ma(n.inputSchema)}async readResource(e,t){const n=await this._serveFromCache("resources/read",e.uri,t);if(n!==void 0)return n;const o=this._cache.captureGeneration("resources/read",e.uri),r=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){const s=this._freshness(r,e.uri);s.expiresAt>this._cache.now()?await this._cache.write("resources/read",r,o,s):t?.cacheMode==="refresh"&&await this._cache.evictKey("resources/read",e.uri)}return r}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},t)}async listen(e,t){if(this.transport===void 0)throw new q(I.NotConnected,"Not connected");const n=this._negotiatedProtocolVersion;if(n===void 0||!bt(n))throw new q(I.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${n??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:n});if(t?.signal?.aborted){const z=t.signal.reason;throw z instanceof q?z:new q(I.RequestTimeout,String(z))}const o=new AbortController,r=`listen:${this._nextListenId++}`;let s="opening",i,a,u,d;const l=new Promise((z,J)=>{u=z,d=J});let p;const h=new Promise(z=>{p=z}),f=z=>{if(s==="closed")return;const J=s==="opening";if(i!==void 0&&(clearTimeout(i),i=void 0),"ack"in z){s="open",u(z.ack);return}s="closed",a!==void 0&&t?.signal?.removeEventListener("abort",a),this._listenState.delete(r),o.abort(),p(z.cause),J&&d(z.error??new q(I.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},S=async()=>{o.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:r}}).catch(()=>{})},v=async()=>{s!=="closed"&&(f({cause:"local"}),await S())};this._listenState.set(r,{settle:f});const y=t?.timeout??bs;if(i=setTimeout(()=>{f({cause:"remote",error:new q(I.RequestTimeout,"subscriptions/listen ack timed out",{timeout:y})}),S().catch(()=>{})},y),t?.signal){const z=t.signal;a=()=>{if(s==="closed")return;const J=z.reason;f({cause:"local",error:J instanceof Error?J:new Error(String(J??"Aborted"))}),S().catch(()=>{})},z.addEventListener("abort",a,{once:!0})}const w={jsonrpc:"2.0",id:r,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}},x=z=>{f({cause:"remote",error:z instanceof Error?z:new Error(String(z))})};try{this.transport.send(w,{requestSignal:o.signal,onRequestStreamEnd:()=>f({cause:"remote",error:new Error("subscriptions/listen: stream ended")})}).catch(x)}catch(z){x(z)}return{honoredFilter:await l,close:v,closed:h}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){const n=Object.hasOwn(Qa,e.method)?Qa[e.method]:void 0;if(e.method==="notifications/resources/updated"){const o=e.params?.uri;typeof o=="string"&&this._cache.evictKey("resources/read",o)}else if(n!==void 0)for(const o of n)this._cache.evict(o);if(e.method==="notifications/subscriptions/acknowledged"){const o=e.params?._meta?.[Cu],r=typeof o=="string"?this._listenState.get(o):void 0;if(r!==void 0){const s=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);r.settle({ack:s.ok?s.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){const o=e.params?.requestId,r=typeof o=="string"?this._listenState.get(o):void 0;if(r!==void 0){r.settle({cause:"remote",error:new Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){const t=e.id,n=typeof t=="string"?this._listenState.get(t):void 0;if(n!==void 0){To(e)?n.settle({cause:"remote",error:Y.fromError(e.error.code,e.error.message,e.error.data)}):n.settle({cause:"graceful",error:new q(I.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){const e=new q(I.ConnectionClosed,"Connection closed");for(const t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){const n=this.getProtocolEra()==="modern"&&Wa()!=="browser",o=async()=>{if(!n)return t;let u;try{u=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(l){this._reportStoreError(l)}if(!u?.valid||u.declarations.length===0)return t;const d=Nv(u.declarations,e.arguments);return Object.keys(d).length===0?t:{...t,headers:{...t?.headers,...d}}};let r=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,u=>this._compileOutputValidator(u)).catch(u=>{this._reportStoreError(u)}):this._compileOutputValidator(t.toolDefinition);const s=()=>{if(r===void 0||r.ok)return;const u=r.compileError,d=(u instanceof Error?u.message:String(u)).slice(0,200);throw new Y(F.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${d}`)};s();let i;try{i=await this.request({method:"tools/call",params:e},await o())}catch(u){const d=u instanceof Y&&u.code===ur;if(!n||!d||t?.toolDefinition!==void 0)throw u;const l={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,l).catch(p=>this._reportStoreError(p)),r=await this._cache.outputValidator(e.name,p=>this._compileOutputValidator(p)).catch(p=>{this._reportStoreError(p)}),s(),i=await this.request({method:"tools/call",params:e},await o())}const a=r!==void 0&&r.ok?r.validator:void 0;if(a){if(i.structuredContent===void 0&&!i.isError)throw new Y(F.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent!==void 0&&!i.isError)try{const u=a(i.structuredContent);if(!u.valid)throw new Y(F.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)}catch(u){throw u instanceof Y?u:new Y(F.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)}}return i}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){const o=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(o),o}const n=await this._serveFromCache("tools/list",void 0,t);return n!==void 0?n:this._listAllPages("tools/list",e,t,o=>o.tools,o=>this._excludeInvalidXMcpHeaderTools(o))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||Ga(this.transport)==="stdio")return;const t=e.tools.filter(n=>{const o=Ma(n.inputSchema);return o.valid?!0:(console.warn(`[mcp-sdk] excluding tool '${n.name}' from tools/list: invalid x-mcp-header declaration — ${o.reason}`),!1)});t.length!==e.tools.length&&(e.tools=t)}_setupListChangedHandler(e,t,n,o){const r=qi(Cl,n);if(!r.success)throw new Error(`Invalid ${e} listChanged options: ${r.error.message}`);if(typeof n.onChanged!="function")throw new TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:s,debounceMs:i}=r.data,{onChanged:a}=n,u=async()=>{if(!s){a(null,null);return}try{a(null,await o())}catch(l){a(l instanceof Error?l:new Error(String(l)),null)}},d=()=>{if(i){const l=this._listChangedDebounceTimers.get(e);l&&clearTimeout(l);const p=setTimeout(u,i);this._listChangedDebounceTimers.set(e,p)}else u()};this.setNotificationHandler(t,d)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function cR(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function uR(e){if(e.status!==401)return!1;const t=e.headers.get("www-authenticate")??"";return cR(t)&&/use_dpop_nonce/i.test(t)}const lR=(e,t)=>n=>{const o=typeof e=="function"?e:()=>e;return async(r,s)=>{const i=(s?.method??"GET").toUpperCase(),a=new URL(r.toString()),u=await o();if(!u)return n(r,s);const d=async()=>{const p=await t();if(!p)return n(r,s);const h=new Headers(s?.headers),f=await u.buildProof({htm:i,htu:a,accessToken:p});return h.set("Authorization",`DPoP ${p}`),h.set("DPoP",f),n(r,{...s,headers:h})};let l=await d();return uR(l)&&l.headers.has("dpop-nonce")&&(u.observeNonce(l,a),await l.text?.().catch(()=>{}),l=await d()),u.observeNonce(l,a),l}},dR=e=>lR(async()=>{try{return await e.dpop?.()}catch(t){throw Fe(t)}},async()=>{let t;try{t=await e.tokens()}catch(n){throw Fe(n)}return t?.token_type?.toLowerCase()==="dpop"?t.access_token:void 0}),pR=1,hR={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},mR=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function ec(e,t){if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);const n=new AbortController;if(e.aborted)return n.abort(e.reason),n.signal;if(t.aborted)return n.abort(t.reason),n.signal;const o=()=>{e.removeEventListener("abort",r),t.removeEventListener("abort",s)};function r(){o(),n.abort(e.reason)}function s(){o(),n.abort(t.reason)}return e.addEventListener("abort",r,{once:!0}),t.addEventListener("abort",s,{once:!0}),n.signal}var bR=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,ub(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=db(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop&&(this._fetch=dR(t.authProvider)(t.fetch??fetch))):this._authProvider=t?.authProvider,this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=$y(t?.fetch,t?.requestInit),this._redirectPolicy==="follow"&&(this._fetchWithInit=Cy(this._fetchWithInit)),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??hR,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??pR)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(n){throw Fe(n)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new Fa({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new Fa({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new pt(I.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);const n=await this._oauthProvider.tokens(),o=es(this._scope,n?.scope,e.scope);this._scope=o;const r=pb(o,n?.scope);return Ps(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:o,forceReauthorization:r,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return this._redirectPolicy==="follow"?e:Zr(e)}_unfollowedRedirect(e,t){const n=this._redirectPolicy==="follow"?void 0:Iy(e,t);return n&&`${n} (redirectPolicy: 'same-origin')`}async _commonHeaders(){const e=new Headers(this._requestInit?.headers||void 0);let t;try{t=await this._authProvider?.token()}catch(n){throw Fe(n)}return t&&e.set("Authorization",`Bearer ${t}`),this._sessionId&&e.set("mcp-session-id",this._sessionId),this._protocolVersion&&e.set("mcp-protocol-version",this._protocolVersion),e}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!on(t))return;const n=t.params?._meta?.[wn];if(typeof n!="string")return;e.set("mcp-protocol-version",n),e.set("mcp-method",t.method);const o=Mv(t.method,t.params);o?.value!==void 0&&e.set("mcp-name",Ld(o.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!on(e))return!1;const t=e.params?._meta?.[wn];return typeof t=="string"&&bt(t)}async _startOrAuthSse(e,t=!1,n=0){const{resumptionToken:o,requestSignal:r}=e,s=()=>this._abortController?.signal.aborted===!0||r?.aborted===!0;try{const i=await this._commonHeaders(),a=[...i.get("accept")?.split(",").map(p=>p.trim().toLowerCase())??[],"text/event-stream"];i.set("accept",[...new Set(a)].join(", ")),o&&i.set("last-event-id",o);const u=this._abortController?.signal,d=r!==void 0&&u!==void 0?ec(u,r):r??u,l=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:i,signal:d});if(!l.ok){if(l.status===401&&this._authProvider){if(l.headers.has("www-authenticate")){const{resourceMetadataUrl:h,scope:f}=mo(l);this._resourceMetadataUrl=h,this._scope=es(this._scope,f)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:l,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(h){throw Fe(h)}return await l.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,n)}throw await l.text?.().catch(()=>{}),Fe(t?new pt(I.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:l.statusText}):new it)}if(l.status===403){const{resourceMetadataUrl:h,scope:f,error:S,errorDescription:v}=mo(l);if(S==="insufficient_scope"){const y=await l.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:f,resourceMetadataUrl:h,errorDescription:v,statusText:l.statusText,text:y},n)!=="AUTHORIZED")throw Fe(new it);return this._startOrAuthSse(e,t,n+1)}}if(await l.text?.().catch(()=>{}),l.status===405){e.onRequestStreamEnd?.();return}const p=this._unfollowedRedirect(this._url,l)??l.statusText;throw new pt(I.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${p}`,{status:l.status,statusText:l.statusText})}this._handleSseStream(l.body,e,!0)}catch(i){throw s()||this.onerror?.(i),i}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(n,e),o)}_scheduleReconnection(e,t=0){const n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`)),e.onRequestStreamEnd?.();return}const o=this._getNextReconnectionDelay(t),r=()=>{this._cancelReconnection=void 0,!(this._abortController?.signal.aborted||e.requestSignal?.aborted)&&this._startOrAuthSse(e).catch(s=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`));try{this._scheduleReconnection(e,t+1)}catch(i){this.onerror?.(i instanceof Error?i:new Error(String(i)))}}})};if(this._reconnectionScheduler){const s=this._reconnectionScheduler(r,o,t);this._cancelReconnection=typeof s=="function"?s:void 0}else{const s=setTimeout(r,o);this._cancelReconnection=()=>clearTimeout(s)}}_handleSseStream(e,t,n){if(!e){t.onRequestStreamEnd?.();return}const{onresumptiontoken:o,replayMessageId:r,requestSignal:s,onRequestStreamEnd:i}=t,a=()=>this._abortController?.signal.aborted===!0||s?.aborted===!0;let u,d=!1,l=!1;(async()=>{try{const h=e.pipeThrough(new TextDecoderStream).pipeThrough(new ap({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){const{value:f,done:S}=await h.read();if(S)break;if(f.id&&(u=f.id,d=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{const v=ho.parse(JSON.parse(f.data));(ko(v)||To(v))&&(l=!0,r!==void 0&&(v.id=r)),this.onmessage?.(v)}catch(v){this.onerror?.(v)}}(n||d)&&!l&&this._abortController&&!a()?this._scheduleReconnection({resumptionToken:u,onresumptiontoken:o,replayMessageId:r,requestSignal:s,onRequestStreamEnd:i},0):a()||i?.()}catch(h){if(a())return;if(this.onerror?.(new Error(`SSE stream disconnected: ${h}`)),(n||d)&&!l&&this._abortController&&!a())try{this._scheduleReconnection({resumptionToken:u,onresumptiontoken:o,replayMessageId:r,requestSignal:s,onRequestStreamEnd:i},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`)),i?.()}else i?.()}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new it("finishAuth requires an OAuthClientProvider");const{authorizationCode:n,iss:o}=await hb(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await Ps(this._oauthProvider,{serverUrl:this._url,authorizationCode:n,iss:o,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new it("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,n,o=0){try{const{resumptionToken:r,onresumptiontoken:s}=t||{};if(r){this._startOrAuthSse({resumptionToken:r,replayMessageId:on(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch(y=>this.onerror?.(y));return}const i=await this._commonHeaders();this._applyBodyDerivedHeaders(i,e);const a=Array.isArray(e)?e.some(y=>qa(y)):qa(e);if(a&&i.delete("mcp-session-id"),t?.headers!==void 0)for(const[y,w]of Object.entries(t.headers))mR.has(y.toLowerCase())||i.set(y,w);i.set("content-type","application/json");const u=[...i.get("accept")?.split(",").map(y=>y.trim().toLowerCase())??[],"application/json","text/event-stream"];i.set("accept",[...new Set(u)].join(", "));const d=this._abortController?.signal,l=t?.requestSignal!==void 0&&d!==void 0?ec(d,t.requestSignal):t?.requestSignal??d,p={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(e),signal:l},h=await this._redirects(this._fetch??fetch)(this._url,p);if(a&&h.ok&&(this._sessionId=h.headers.get("mcp-session-id")||void 0),!h.ok){if(h.status===401&&this._authProvider){if(h.headers.has("www-authenticate")){const{resourceMetadataUrl:x,scope:z}=mo(h);this._resourceMetadataUrl=x,this._scope=es(this._scope,z)}if(this._authProvider.onUnauthorized&&!n){try{await this._authProvider.onUnauthorized({response:h,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(x){throw Fe(x)}return await h.text?.().catch(()=>{}),this._send(e,t,!0,o)}throw await h.text?.().catch(()=>{}),Fe(n?new pt(I.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:h.statusText}):new it)}const y=await h.text?.().catch(()=>null);if(h.status===403){const{resourceMetadataUrl:x,scope:z,error:J,errorDescription:B}=mo(h);if(J==="insufficient_scope"){if(await this._stepUpAuthorize({scope:z,resourceMetadataUrl:x,errorDescription:B,statusText:h.statusText,text:y},o)!=="AUTHORIZED")throw Fe(new it);return this._send(e,t,n,o+1)}}if(h.status===400&&typeof y=="string"&&this._isModernEnvelopedRequest(e))try{const x=ho.parse(JSON.parse(y)),z=(Array.isArray(e)?e:[e]).filter(J=>on(J));if(To(x)&&z.some(J=>J.id===x.id)){this.onmessage?.(x);return}}catch{}const w=this._unfollowedRedirect(this._url,h)??y;throw new pt(I.ClientHttpNotImplemented,`Error POSTing to endpoint: ${w}`,{status:h.status,statusText:h.statusText,text:y})}if(h.status===202){await h.text?.().catch(()=>{}),wv(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(y=>this.onerror?.(y));return}const f=(Array.isArray(e)?e:[e]).some(y=>"method"in y&&"id"in y&&y.id!==void 0),S=h.headers.get("content-type"),v=Py(S);if(f)if(v==="text/event-stream")this._handleSseStream(h.body,{onresumptiontoken:s,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(v==="application/json"){const y=await h.json(),w=Array.isArray(y)?y.map(x=>ho.parse(x)):[ho.parse(y)];for(const x of w)this.onmessage?.(x)}else throw await h.text?.().catch(()=>{}),new q(I.ClientHttpUnexpectedContent,`Unexpected content type: ${S}`,{contentType:S});else await h.text?.().catch(()=>{})}catch(r){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(r),r}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await this._redirects(this._fetch??fetch)(this._url,t);if(await n.text?.().catch(()=>{}),!n.ok&&n.status!==405)throw new pt(I.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,n)??n.statusText}`,{status:n.status,statusText:n.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};export{yR as C,bR as S,V as _,g as a,E as b,C as c,yr as d,vR as e,_R as f,SR as g,_ as l,R as n,m as o,$ as r,c as s,gR as t,L as u};