@hyperframes/studio 0.8.15 → 0.8.17

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 (62) hide show
  1. package/dist/assets/hyperframes-player-DejBDgXB.js +459 -0
  2. package/dist/assets/index-BX3KHhGX.js +71 -0
  3. package/dist/assets/{index-DKoZIpw1.js → index-CU6o8PuW.js} +180 -180
  4. package/dist/assets/{index-CVtYYTnA.js → index-CklNVmi3.js} +1 -1
  5. package/dist/assets/{index-CtDg2lB7.js → index-uu4Zd3BU.js} +1 -1
  6. package/dist/index.d.ts +9 -13
  7. package/dist/index.html +1 -1
  8. package/dist/index.js +1660 -1284
  9. package/dist/index.js.map +1 -1
  10. package/package.json +8 -7
  11. package/src/components/EditorShell.tsx +4 -0
  12. package/src/components/editor/DomEditCropHandles.test.tsx +1 -1
  13. package/src/components/editor/DomEditCropHandles.tsx +1 -1
  14. package/src/components/editor/DomEditOverlay.tsx +1 -1
  15. package/src/components/editor/DomEditSelectionChrome.tsx +1 -1
  16. package/src/components/editor/anchoredResizeCommitFeedsOffset.test.ts +38 -4
  17. package/src/components/editor/propertyPanelCommitField.tsx +1 -1
  18. package/src/components/editor/propertyPanelFlatLayoutSection.tsx +3 -3
  19. package/src/components/editor/propertyPanelFlatMaskInsetRows.tsx +1 -1
  20. package/src/components/editor/propertyPanelFlatMediaSection.tsx +1 -1
  21. package/src/components/editor/propertyPanelFlatPrimitives.tsx +1 -1
  22. package/src/components/editor/propertyPanelFlatStyleSections.tsx +8 -8
  23. package/src/components/editor/propertyPanelMediaSection.tsx +1 -1
  24. package/src/components/editor/propertyPanelPrimitives.tsx +1 -1
  25. package/src/components/editor/propertyPanelStyleSections.tsx +1 -1
  26. package/src/components/editor/propertyPanelTypes.ts +1 -1
  27. package/src/components/editor/useDomEditOverlayGestures.ts +8 -2
  28. package/src/components/editor/useInspectorGestureTransaction.ts +3 -3
  29. package/src/components/sidebar/AudioRow.tsx +13 -2
  30. package/src/hooks/domEditCommitRunner.ts +47 -0
  31. package/src/hooks/useDomEditPositionPatchCommit.test.tsx +116 -0
  32. package/src/hooks/useDomEditPositionPatchCommit.ts +6 -1
  33. package/src/hooks/useDomEditTextCommits.test.tsx +175 -21
  34. package/src/hooks/useDomEditTextCommits.ts +17 -9
  35. package/src/hooks/useDomEditWiring.ts +1 -1
  36. package/src/hooks/useDomGeometryCommits.test.tsx +1 -0
  37. package/src/hooks/useDomGeometryCommits.ts +10 -2
  38. package/src/hooks/useDomSelection.test.ts +48 -0
  39. package/src/hooks/useDomSelection.ts +26 -82
  40. package/src/hooks/useDomSelectionTypes.ts +82 -0
  41. package/src/hooks/useElementLifecycleOps.multiDelete.test.tsx +81 -31
  42. package/src/hooks/useElementLifecycleOps.ts +11 -5
  43. package/src/hooks/useGsapSelectionHandlers.ts +4 -2
  44. package/src/hooks/usePanelLayout.test.ts +38 -0
  45. package/src/hooks/usePanelLayout.ts +21 -6
  46. package/src/player/lib/playbackTypes.ts +3 -12
  47. package/src/player/lib/runtimeProtocol.test.ts +1 -0
  48. package/src/utils/studioUiPreferences.ts +11 -0
  49. package/src/webmcp/StudioAgentTools.tsx +46 -0
  50. package/src/webmcp/handles.test.ts +130 -0
  51. package/src/webmcp/handles.ts +129 -0
  52. package/src/webmcp/polyfill.test.ts +98 -0
  53. package/src/webmcp/polyfill.ts +60 -0
  54. package/src/webmcp/registrar.test.ts +150 -0
  55. package/src/webmcp/registrar.ts +115 -0
  56. package/src/webmcp/toolResult.ts +67 -0
  57. package/src/webmcp/tools/lookTools.test.ts +225 -0
  58. package/src/webmcp/tools/lookTools.ts +201 -0
  59. package/src/webmcp/types.ts +90 -0
  60. package/src/webmcp/useStudioAgentTools.test.tsx +221 -0
  61. package/src/webmcp/useStudioAgentTools.ts +119 -0
  62. package/dist/assets/hyperframes-player-BlIp1Y-b.js +0 -459
@@ -0,0 +1,71 @@
1
+ var yd=Object.defineProperty;var mi=e=>{throw TypeError(e)};var bd=(e,t,o)=>t in e?yd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o;var R=(e,t,o)=>bd(e,typeof t!="symbol"?t+"":t,o),Hr=(e,t,o)=>t.has(e)||mi("Cannot "+o);var ne=(e,t,o)=>(Hr(e,t,"read from private field"),o?o.call(e):t.get(e)),pt=(e,t,o)=>t.has(e)?mi("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,o),zt=(e,t,o,n)=>(Hr(e,t,"write to private field"),n?n.call(e,o):t.set(e,o),o),At=(e,t,o)=>(Hr(e,t,"access private method"),o);var hi;const Rd=Object.freeze({status:"aborted"});function v(e,t,o){function n(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);const u=i.prototype,d=Object.keys(u);for(let m=0;m<d.length;m++){const h=d[m];h in a||(a[h]=u[h].bind(a))}}const r=(o==null?void 0:o.Parent)??Object;class s extends r{}Object.defineProperty(s,"name",{value:e});function i(a){var l;const u=o!=null&&o.Parent?new s:this;n(u,a),(l=u._zod).deferred??(l.deferred=[]);for(const d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>{var l,u;return o!=null&&o.Parent&&a instanceof o.Parent?!0:(u=(l=a==null?void 0:a._zod)==null?void 0:l.traits)==null?void 0:u.has(e)}}),Object.defineProperty(i,"name",{value:e}),i}class uo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Pa extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(hi=globalThis).__zod_globalConfig??(hi.__zod_globalConfig={});const Ss=globalThis.__zod_globalConfig;function ft(e){return Ss}function Ca(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,r])=>t.indexOf(+n)===-1).map(([n,r])=>r)}function es(e,t){return typeof t=="bigint"?t.toString():t}function Rr(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function vs(e){return e==null}function _s(e){const t=e.startsWith("^")?1:0,o=e.endsWith("$")?e.length-1:e.length;return e.slice(t,o)}function wd(e,t){const o=e/t,n=Math.round(o),r=Number.EPSILON*Math.max(Math.abs(o),1);return Math.abs(o-n)<r?0:o-n}const fi=Symbol("evaluating");function ee(e,t,o){let n;Object.defineProperty(e,t,{get(){if(n!==fi)return n===void 0&&(n=fi,n=o()),n},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Gt(e,t,o){Object.defineProperty(e,t,{value:o,writable:!0,enumerable:!0,configurable:!0})}function wt(...e){const t={};for(const o of e){const n=Object.getOwnPropertyDescriptors(o);Object.assign(t,n)}return Object.defineProperties({},t)}function gi(e){return JSON.stringify(e)}function Td(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const ka="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function _n(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const $d=Rr(()=>{var e;if(Ss.jitless||typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function bo(e){if(_n(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const o=t.prototype;return!(_n(o)===!1||Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)}function Oa(e){return bo(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Ed=new Set(["string","number","symbol"]);function Ro(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Tt(e,t,o){const n=new e._zod.constr(t??e._zod.def);return(!t||o!=null&&o.parent)&&(n._zod.parent=e),n}function x(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Pd(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const Cd={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]};function kd(e,t){const o=e._zod.def,n=o.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const s=wt(e._zod.def,{get shape(){const i={};for(const a in t){if(!(a in o.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(i[a]=o.shape[a])}return Gt(this,"shape",i),i},checks:[]});return Tt(e,s)}function Od(e,t){const o=e._zod.def,n=o.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=wt(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const a in t){if(!(a in o.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete i[a]}return Gt(this,"shape",i),i},checks:[]});return Tt(e,s)}function Id(e,t){if(!bo(t))throw new Error("Invalid input to extend: expected a plain object");const o=e._zod.def.checks;if(o&&o.length>0){const s=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=wt(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return Gt(this,"shape",s),s}});return Tt(e,r)}function qd(e,t){if(!bo(t))throw new Error("Invalid input to safeExtend: expected a plain object");const o=wt(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Gt(this,"shape",n),n}});return Tt(e,o)}function Nd(e,t){var n;if((n=e._zod.def.checks)!=null&&n.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const o=wt(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Gt(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Tt(e,o)}function Md(e,t,o){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=wt(t._zod.def,{get shape(){const a=t._zod.def.shape,l={...a};if(o)for(const u in o){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);o[u]&&(l[u]=e?new e({type:"optional",innerType:a[u]}):a[u])}else for(const u in a)l[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return Gt(this,"shape",l),l},checks:[]});return Tt(t,i)}function xd(e,t,o){const n=wt(t._zod.def,{get shape(){const r=t._zod.def.shape,s={...r};if(o)for(const i in o){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);o[i]&&(s[i]=new e({type:"nonoptional",innerType:r[i]}))}else for(const i in r)s[i]=new e({type:"nonoptional",innerType:r[i]});return Gt(this,"shape",s),s}});return Tt(t,n)}function co(e,t=0){var o;if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(((o=e.issues[n])==null?void 0:o.continue)!==!0)return!0;return!1}function zd(e,t=0){var o;if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(((o=e.issues[n])==null?void 0:o.continue)===!1)return!0;return!1}function lo(e,t){return t.map(o=>{var n;return(n=o).path??(n.path=[]),o.path.unshift(e),o})}function Gn(e){return typeof e=="string"?e:e==null?void 0:e.message}function gt(e,t,o){var l,u,d,m,h,S;const n=e.message?e.message:Gn((d=(u=(l=e.inst)==null?void 0:l._zod.def)==null?void 0:u.error)==null?void 0:d.call(u,e))??Gn((m=t==null?void 0:t.error)==null?void 0:m.call(t,e))??Gn((h=o.customError)==null?void 0:h.call(o,e))??Gn((S=o.localeError)==null?void 0:S.call(o,e))??"Invalid input",{inst:r,continue:s,input:i,...a}=e;return a.path??(a.path=[]),a.message=n,t!=null&&t.reportInput&&(a.input=i),a}function ys(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function yn(...e){const[t,o,n]=e;return typeof t=="string"?{message:t,code:"custom",input:o,inst:n}:{...t}}const Ia=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,es,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},qa=v("$ZodError",Ia),Na=v("$ZodError",Ia,{Parent:Error});function Ad(e,t=o=>o.message){const o={},n=[];for(const r of e.issues)r.path.length>0?(o[r.path[0]]=o[r.path[0]]||[],o[r.path[0]].push(t(r))):n.push(t(r));return{formErrors:n,fieldErrors:o}}function Ld(e,t=o=>o.message){const o={_errors:[]},n=(r,s=[])=>{for(const i of r.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>n({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{const a=[...s,...i.path];if(a.length===0)o._errors.push(t(i));else{let l=o,u=0;for(;u<a.length;){const d=a[u];u===a.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(t(i))):l[d]=l[d]||{_errors:[]},l=l[d],u++}}}};return n(e),o}const bs=e=>(t,o,n,r)=>{const s=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:o,issues:[]},s);if(i instanceof Promise)throw new uo;if(i.issues.length){const a=new((r==null?void 0:r.Err)??e)(i.issues.map(l=>gt(l,s,ft())));throw ka(a,r==null?void 0:r.callee),a}return i.value},Rs=e=>async(t,o,n,r)=>{const s=n?{...n,async:!0}:{async:!0};let i=t._zod.run({value:o,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){const a=new((r==null?void 0:r.Err)??e)(i.issues.map(l=>gt(l,s,ft())));throw ka(a,r==null?void 0:r.callee),a}return i.value},wr=e=>(t,o,n)=>{const r=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw new uo;return s.issues.length?{success:!1,error:new(e??qa)(s.issues.map(i=>gt(i,r,ft())))}:{success:!0,data:s.value}},jd=wr(Na),Tr=e=>async(t,o,n)=>{const r=n?{...n,async:!0}:{async:!0};let s=t._zod.run({value:o,issues:[]},r);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>gt(i,r,ft())))}:{success:!0,data:s.value}},Zd=Tr(Na),Dd=e=>(t,o,n)=>{const r=n?{...n,direction:"backward"}:{direction:"backward"};return bs(e)(t,o,r)},Hd=e=>(t,o,n)=>bs(e)(t,o,n),Ud=e=>async(t,o,n)=>{const r=n?{...n,direction:"backward"}:{direction:"backward"};return Rs(e)(t,o,r)},Vd=e=>async(t,o,n)=>Rs(e)(t,o,n),Fd=e=>(t,o,n)=>{const r=n?{...n,direction:"backward"}:{direction:"backward"};return wr(e)(t,o,r)},Jd=e=>(t,o,n)=>wr(e)(t,o,n),Bd=e=>async(t,o,n)=>{const r=n?{...n,direction:"backward"}:{direction:"backward"};return Tr(e)(t,o,r)},Wd=e=>async(t,o,n)=>Tr(e)(t,o,n),Gd=/^[cC][0-9a-z]{6,}$/,Yd=/^[0-9a-z]+$/,Kd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Xd=/^[0-9a-vA-V]{20}$/,Qd=/^[A-Za-z0-9]{27}$/,ep=/^[a-zA-Z0-9_-]{21}$/,tp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,op=/^([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})$/,Si=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)$/,np=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,rp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function sp(){return new RegExp(rp,"u")}const ip=/^(?:(?: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])$/,ap=/^(([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}|:))$/,cp=/^((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])$/,lp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,up=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ma=/^[A-Za-z0-9_-]*$/,dp=/^https?$/,pp=/^\+[1-9]\d{6,14}$/,xa="(?:(?:\\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])))",mp=new RegExp(`^${xa}$`);function za(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}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function hp(e){return new RegExp(`^${za(e)}$`)}function fp(e){const t=za({precision:e.precision}),o=["Z"];e.local&&o.push(""),e.offset&&o.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${t}(?:${o.join("|")})`;return new RegExp(`^${xa}T(?:${n})$`)}const gp=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Sp=/^-?\d+$/,Aa=/^-?\d+(?:\.\d+)?$/,vp=/^(?:true|false)$/i,_p=/^null$/i,yp=/^[^A-Z]*$/,bp=/^[^a-z]*$/,Ne=v("$ZodCheck",(e,t)=>{var o;e._zod??(e._zod={}),e._zod.def=t,(o=e._zod).onattach??(o.onattach=[])}),La={number:"number",bigint:"bigint",object:"date"},ja=v("$ZodCheckLessThan",(e,t)=>{Ne.init(e,t);const o=La[typeof t.value];e._zod.onattach.push(n=>{const r=n._zod.bag,s=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:o,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Za=v("$ZodCheckGreaterThan",(e,t)=>{Ne.init(e,t);const o=La[typeof t.value];e._zod.onattach.push(n=>{const r=n._zod.bag,s=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:o,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Rp=v("$ZodCheckMultipleOf",(e,t)=>{Ne.init(e,t),e._zod.onattach.push(o=>{var n;(n=o._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=o=>{if(typeof o.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof o.value=="bigint"?o.value%t.value===BigInt(0):wd(o.value,t.value)===0)||o.issues.push({origin:typeof o.value,code:"not_multiple_of",divisor:t.value,input:o.value,inst:e,continue:!t.abort})}}),wp=v("$ZodCheckNumberFormat",(e,t)=>{var i;Ne.init(e,t),t.format=t.format||"float64";const o=(i=t.format)==null?void 0:i.includes("int"),n=o?"int":"number",[r,s]=Cd[t.format];e._zod.onattach.push(a=>{const l=a._zod.bag;l.format=t.format,l.minimum=r,l.maximum=s,o&&(l.pattern=Sp)}),e._zod.check=a=>{const l=a.value;if(o){if(!Number.isInteger(l)){a.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?a.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):a.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}l<r&&a.issues.push({origin:"number",input:l,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),l>s&&a.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),Tp=v("$ZodCheckMaxLength",(e,t)=>{var o;Ne.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!vs(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const i=ys(r);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),$p=v("$ZodCheckMinLength",(e,t)=>{var o;Ne.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!vs(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const i=ys(r);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ep=v("$ZodCheckLengthEquals",(e,t)=>{var o;Ne.init(e,t),(o=e._zod.def).when??(o.when=n=>{const r=n.value;return!vs(r)&&r.length!==void 0}),e._zod.onattach.push(n=>{const r=n._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=n=>{const r=n.value,s=r.length;if(s===t.length)return;const i=ys(r),a=s>t.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),$r=v("$ZodCheckStringFormat",(e,t)=>{var o,n;Ne.init(e,t),e._zod.onattach.push(r=>{const s=r._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(o=e._zod).check??(o.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})}):(n=e._zod).check??(n.check=()=>{})}),Pp=v("$ZodCheckRegex",(e,t)=>{$r.init(e,t),e._zod.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:"regex",input:o.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Cp=v("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=yp),$r.init(e,t)}),kp=v("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=bp),$r.init(e,t)}),Op=v("$ZodCheckIncludes",(e,t)=>{Ne.init(e,t);const o=Ro(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${o}`:o);t.pattern=n,e._zod.onattach.push(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),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})}}),Ip=v("$ZodCheckStartsWith",(e,t)=>{Ne.init(e,t);const o=new RegExp(`^${Ro(t.prefix)}.*`);t.pattern??(t.pattern=o),e._zod.onattach.push(n=>{const r=n._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(o)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),qp=v("$ZodCheckEndsWith",(e,t)=>{Ne.init(e,t);const o=new RegExp(`.*${Ro(t.suffix)}$`);t.pattern??(t.pattern=o),e._zod.onattach.push(n=>{const r=n._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(o)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Np=v("$ZodCheckOverwrite",(e,t)=>{Ne.init(e,t),e._zod.check=o=>{o.value=t.tx(o.value)}});class Mp{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const n=t.split(`
2
+ `).filter(i=>i),r=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.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,o=this==null?void 0:this.args,r=[...((this==null?void 0:this.content)??[""]).map(s=>` ${s}`)];return new t(...o,r.join(`
3
+ `))}}const xp={major:4,minor:4,patch:3},se=v("$ZodType",(e,t)=>{var r;var o;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=xp;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const s of n)for(const i of s._zod.onattach)i(e);if(n.length===0)(o=e._zod).deferred??(o.deferred=[]),(r=e._zod.deferred)==null||r.push(()=>{e._zod.run=e._zod.parse});else{const s=(a,l,u)=>{let d=co(a),m;for(const h of l){if(h._zod.def.when){if(zd(a)||!h._zod.def.when(a))continue}else if(d)continue;const S=a.issues.length,_=h._zod.check(a);if(_ instanceof Promise&&(u==null?void 0:u.async)===!1)throw new uo;if(m||_ instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await _,a.issues.length!==S&&(d||(d=co(a,S)))});else{if(a.issues.length===S)continue;d||(d=co(a,S))}}return m?m.then(()=>a):a},i=(a,l,u)=>{if(co(a))return a.aborted=!0,a;const d=s(l,n,u);if(d instanceof Promise){if(u.async===!1)throw new uo;return d.then(m=>e._zod.parse(m,u))}return e._zod.parse(d,u)};e._zod.run=(a,l)=>{if(l.skipChecks)return e._zod.parse(a,l);if(l.direction==="backward"){const d=e._zod.parse({value:a.value,issues:[]},{...l,skipChecks:!0});return d instanceof Promise?d.then(m=>i(m,a,l)):i(d,a,l)}const u=e._zod.parse(a,l);if(u instanceof Promise){if(l.async===!1)throw new uo;return u.then(d=>s(d,n,l))}return s(u,n,l)}}ee(e,"~standard",()=>({validate:s=>{var i;try{const a=jd(e,s);return a.success?{value:a.data}:{issues:(i=a.error)==null?void 0:i.issues}}catch{return Zd(e,s).then(l=>{var u;return l.success?{value:l.data}:{issues:(u=l.error)==null?void 0:u.issues}})}},vendor:"zod",version:1}))}),ws=v("$ZodString",(e,t)=>{var o;se.init(e,t),e._zod.pattern=[...((o=e==null?void 0:e._zod.bag)==null?void 0:o.patterns)??[]].pop()??gp(e._zod.bag),e._zod.parse=(n,r)=>{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}}),ae=v("$ZodStringFormat",(e,t)=>{$r.init(e,t),ws.init(e,t)}),zp=v("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=op),ae.init(e,t)}),Ap=v("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Si(n))}else t.pattern??(t.pattern=Si());ae.init(e,t)}),Lp=v("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=np),ae.init(e,t)}),jp=v("$ZodURL",(e,t)=>{ae.init(e,t),e._zod.check=o=>{var n;try{const r=o.value.trim();if(!t.normalize&&((n=t.protocol)==null?void 0:n.source)===dp.source&&!/^https?:\/\//i.test(r)){o.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:o.value,inst:e,continue:!t.abort});return}const s=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(s.hostname)||o.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:o.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||o.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:o.value,inst:e,continue:!t.abort})),t.normalize?o.value=s.href:o.value=r;return}catch{o.issues.push({code:"invalid_format",format:"url",input:o.value,inst:e,continue:!t.abort})}}}),Zp=v("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=sp()),ae.init(e,t)}),Dp=v("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ep),ae.init(e,t)}),Hp=v("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Gd),ae.init(e,t)}),Up=v("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Yd),ae.init(e,t)}),Vp=v("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Kd),ae.init(e,t)}),Fp=v("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Xd),ae.init(e,t)}),Jp=v("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Qd),ae.init(e,t)}),Bp=v("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=fp(t)),ae.init(e,t)}),Wp=v("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=mp),ae.init(e,t)}),Gp=v("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=hp(t)),ae.init(e,t)}),Yp=v("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=tp),ae.init(e,t)}),Kp=v("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ip),ae.init(e,t),e._zod.bag.format="ipv4"}),Xp=v("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ap),ae.init(e,t),e._zod.bag.format="ipv6",e._zod.check=o=>{try{new URL(`http://[${o.value}]`)}catch{o.issues.push({code:"invalid_format",format:"ipv6",input:o.value,inst:e,continue:!t.abort})}}}),Qp=v("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=cp),ae.init(e,t)}),em=v("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=lp),ae.init(e,t),e._zod.check=o=>{const n=o.value.split("/");try{if(n.length!==2)throw new Error;const[r,s]=n;if(!s)throw new Error;const i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${r}]`)}catch{o.issues.push({code:"invalid_format",format:"cidrv6",input:o.value,inst:e,continue:!t.abort})}}});function Da(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const tm=v("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=up),ae.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=o=>{Da(o.value)||o.issues.push({code:"invalid_format",format:"base64",input:o.value,inst:e,continue:!t.abort})}});function om(e){if(!Ma.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),o=t.padEnd(Math.ceil(t.length/4)*4,"=");return Da(o)}const nm=v("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ma),ae.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=o=>{om(o.value)||o.issues.push({code:"invalid_format",format:"base64url",input:o.value,inst:e,continue:!t.abort})}}),rm=v("$ZodE164",(e,t)=>{t.pattern??(t.pattern=pp),ae.init(e,t)});function sm(e,t=null){try{const o=e.split(".");if(o.length!==3)return!1;const[n]=o;if(!n)return!1;const r=JSON.parse(atob(n));return!("typ"in r&&(r==null?void 0:r.typ)!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const im=v("$ZodJWT",(e,t)=>{ae.init(e,t),e._zod.check=o=>{sm(o.value,t.alg)||o.issues.push({code:"invalid_format",format:"jwt",input:o.value,inst:e,continue:!t.abort})}}),Ha=v("$ZodNumber",(e,t)=>{se.init(e,t),e._zod.pattern=e._zod.bag.pattern??Aa,e._zod.parse=(o,n)=>{if(t.coerce)try{o.value=Number(o.value)}catch{}const r=o.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return o;const s=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return o.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...s?{received:s}:{}}),o}}),am=v("$ZodNumberFormat",(e,t)=>{wp.init(e,t),Ha.init(e,t)}),cm=v("$ZodBoolean",(e,t)=>{se.init(e,t),e._zod.pattern=vp,e._zod.parse=(o,n)=>{if(t.coerce)try{o.value=!!o.value}catch{}const r=o.value;return typeof r=="boolean"||o.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),o}}),lm=v("$ZodNull",(e,t)=>{se.init(e,t),e._zod.pattern=_p,e._zod.values=new Set([null]),e._zod.parse=(o,n)=>{const r=o.value;return r===null||o.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),o}}),um=v("$ZodAny",(e,t)=>{se.init(e,t),e._zod.parse=o=>o}),dm=v("$ZodUnknown",(e,t)=>{se.init(e,t),e._zod.parse=o=>o}),pm=v("$ZodNever",(e,t)=>{se.init(e,t),e._zod.parse=(o,n)=>(o.issues.push({expected:"never",code:"invalid_type",input:o.value,inst:e}),o)});function vi(e,t,o){e.issues.length&&t.issues.push(...lo(o,e.issues)),t.value[o]=e.value}const mm=v("$ZodArray",(e,t)=>{se.init(e,t),e._zod.parse=(o,n)=>{const r=o.value;if(!Array.isArray(r))return o.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),o;o.value=Array(r.length);const s=[];for(let i=0;i<r.length;i++){const a=r[i],l=t.element._zod.run({value:a,issues:[]},n);l instanceof Promise?s.push(l.then(u=>vi(u,o,i))):vi(l,o,i)}return s.length?Promise.all(s).then(()=>o):o}});function ar(e,t,o,n,r,s){const i=o in n;if(e.issues.length){if(r&&s&&!i)return;t.issues.push(...lo(o,e.issues))}if(!i&&!r){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[o]});return}e.value===void 0?i&&(t.value[o]=void 0):t.value[o]=e.value}function Ua(e){var n,r,s,i;const t=Object.keys(e.shape);for(const a of t)if(!((i=(s=(r=(n=e.shape)==null?void 0:n[a])==null?void 0:r._zod)==null?void 0:s.traits)!=null&&i.has("$ZodType")))throw new Error(`Invalid element at key "${a}": expected a Zod schema`);const o=Pd(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function Va(e,t,o,n,r,s){const i=[],a=r.keySet,l=r.catchall._zod,u=l.def.type,d=l.optin==="optional",m=l.optout==="optional";for(const h in t){if(h==="__proto__"||a.has(h))continue;if(u==="never"){i.push(h);continue}const S=l.run({value:t[h],issues:[]},n);S instanceof Promise?e.push(S.then(_=>ar(_,o,h,t,d,m))):ar(S,o,h,t,d,m)}return i.length&&o.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s}),e.length?Promise.all(e).then(()=>o):o}const hm=v("$ZodObject",(e,t)=>{se.init(e,t);const o=Object.getOwnPropertyDescriptor(t,"shape");if(!(o!=null&&o.get)){const a=t.shape;Object.defineProperty(t,"shape",{get:()=>{const l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}const n=Rr(()=>Ua(t));ee(e._zod,"propValues",()=>{const a=t.shape,l={};for(const u in a){const d=a[u]._zod;if(d.values){l[u]??(l[u]=new Set);for(const m of d.values)l[u].add(m)}}return l});const r=_n,s=t.catchall;let i;e._zod.parse=(a,l)=>{i??(i=n.value);const u=a.value;if(!r(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};const d=[],m=i.shape;for(const h of i.keys){const S=m[h],_=S._zod.optin==="optional",T=S._zod.optout==="optional",b=S._zod.run({value:u[h],issues:[]},l);b instanceof Promise?d.push(b.then(N=>ar(N,a,h,u,_,T))):ar(b,a,h,u,_,T)}return s?Va(d,u,a,l,n.value,e):d.length?Promise.all(d).then(()=>a):a}}),fm=v("$ZodObjectJIT",(e,t)=>{hm.init(e,t);const o=e._zod.parse,n=Rr(()=>Ua(t)),r=h=>{var w,q;const S=new Mp(["shape","payload","ctx"]),_=n.value,T=W=>{const V=gi(W);return`shape[${V}]._zod.run({ value: input[${V}], issues: [] }, ctx)`};S.write("const input = payload.value;");const b=Object.create(null);let N=0;for(const W of _.keys)b[W]=`key_${N++}`;S.write("const newResult = {};");for(const W of _.keys){const V=b[W],Q=gi(W),X=h[W],G=((w=X==null?void 0:X._zod)==null?void 0:w.optin)==="optional",Y=((q=X==null?void 0:X._zod)==null?void 0:q.optout)==="optional";S.write(`const ${V} = ${T(W)};`),G&&Y?S.write(`
4
+ if (${V}.issues.length) {
5
+ if (${Q} in input) {
6
+ payload.issues = payload.issues.concat(${V}.issues.map(iss => ({
7
+ ...iss,
8
+ path: iss.path ? [${Q}, ...iss.path] : [${Q}]
9
+ })));
10
+ }
11
+ }
12
+
13
+ if (${V}.value === undefined) {
14
+ if (${Q} in input) {
15
+ newResult[${Q}] = undefined;
16
+ }
17
+ } else {
18
+ newResult[${Q}] = ${V}.value;
19
+ }
20
+
21
+ `):G?S.write(`
22
+ if (${V}.issues.length) {
23
+ payload.issues = payload.issues.concat(${V}.issues.map(iss => ({
24
+ ...iss,
25
+ path: iss.path ? [${Q}, ...iss.path] : [${Q}]
26
+ })));
27
+ }
28
+
29
+ if (${V}.value === undefined) {
30
+ if (${Q} in input) {
31
+ newResult[${Q}] = undefined;
32
+ }
33
+ } else {
34
+ newResult[${Q}] = ${V}.value;
35
+ }
36
+
37
+ `):S.write(`
38
+ const ${V}_present = ${Q} in input;
39
+ if (${V}.issues.length) {
40
+ payload.issues = payload.issues.concat(${V}.issues.map(iss => ({
41
+ ...iss,
42
+ path: iss.path ? [${Q}, ...iss.path] : [${Q}]
43
+ })));
44
+ }
45
+ if (!${V}_present && !${V}.issues.length) {
46
+ payload.issues.push({
47
+ code: "invalid_type",
48
+ expected: "nonoptional",
49
+ input: undefined,
50
+ path: [${Q}]
51
+ });
52
+ }
53
+
54
+ if (${V}_present) {
55
+ if (${V}.value === undefined) {
56
+ newResult[${Q}] = undefined;
57
+ } else {
58
+ newResult[${Q}] = ${V}.value;
59
+ }
60
+ }
61
+
62
+ `)}S.write("payload.value = newResult;"),S.write("return payload;");const L=S.compile();return(W,V)=>L(h,W,V)};let s;const i=_n,a=!Ss.jitless,u=a&&$d.value,d=t.catchall;let m;e._zod.parse=(h,S)=>{m??(m=n.value);const _=h.value;return i(_)?a&&u&&(S==null?void 0:S.async)===!1&&S.jitless!==!0?(s||(s=r(t.shape)),h=s(h,S),d?Va([],_,h,S,m,e):h):o(h,S):(h.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),h)}});function _i(e,t,o,n){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const r=e.filter(s=>!co(s));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:o,errors:e.map(s=>s.issues.map(i=>gt(i,n,ft())))}),t)}const Fa=v("$ZodUnion",(e,t)=>{se.init(e,t),ee(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),ee(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),ee(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),ee(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>_s(r.source)).join("|")})$`)}});const o=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,r)=>{if(o)return o(n,r);let s=!1;const i=[];for(const a of t.options){const l=a._zod.run({value:n.value,issues:[]},r);if(l instanceof Promise)i.push(l),s=!0;else{if(l.issues.length===0)return l;i.push(l)}}return s?Promise.all(i).then(a=>_i(a,n,e,r)):_i(i,n,e,r)}}),gm=v("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Fa.init(e,t);const o=e._zod.parse;ee(e._zod,"propValues",()=>{const r={};for(const s of t.options){const i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[a,l]of Object.entries(i)){r[a]||(r[a]=new Set);for(const u of l)r[a].add(u)}}return r});const n=Rr(()=>{var i;const r=t.options,s=new Map;for(const a of r){const l=(i=a._zod.propValues)==null?void 0:i[t.discriminator];if(!l||l.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const u of l){if(s.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);s.set(u,a)}}return s});e._zod.parse=(r,s)=>{const i=r.value;if(!_n(i))return r.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),r;const a=n.value.get(i==null?void 0:i[t.discriminator]);return a?a._zod.run(r,s):t.unionFallback||s.direction==="backward"?o(r,s):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()),input:i,path:[t.discriminator],inst:e}),r)}}),Sm=v("$ZodIntersection",(e,t)=>{se.init(e,t),e._zod.parse=(o,n)=>{const r=o.value,s=t.left._zod.run({value:r,issues:[]},n),i=t.right._zod.run({value:r,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([l,u])=>yi(o,l,u)):yi(o,s,i)}});function ts(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(bo(e)&&bo(t)){const o=Object.keys(t),n=Object.keys(e).filter(s=>o.indexOf(s)!==-1),r={...e,...t};for(const s of n){const i=ts(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 o=[];for(let n=0;n<e.length;n++){const r=e[n],s=t[n],i=ts(r,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};o.push(i.data)}return{valid:!0,data:o}}return{valid:!1,mergeErrorPath:[]}}function yi(e,t,o){const n=new Map;let r;for(const a of t.issues)if(a.code==="unrecognized_keys"){r??(r=a);for(const l of a.keys)n.has(l)||n.set(l,{}),n.get(l).l=!0}else e.issues.push(a);for(const a of o.issues)if(a.code==="unrecognized_keys")for(const l of a.keys)n.has(l)||n.set(l,{}),n.get(l).r=!0;else e.issues.push(a);const s=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&r&&e.issues.push({...r,keys:s}),co(e))return e;const i=ts(t.value,o.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}const vm=v("$ZodRecord",(e,t)=>{se.init(e,t),e._zod.parse=(o,n)=>{const r=o.value;if(!bo(r))return o.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),o;const s=[],i=t.keyType._zod.values;if(i){o.value={};const a=new Set;for(const u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);const d=t.keyType._zod.run({value:u,issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){o.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(S=>gt(S,n,ft())),input:u,path:[u],inst:e});continue}const m=d.value,h=t.valueType._zod.run({value:r[u],issues:[]},n);h instanceof Promise?s.push(h.then(S=>{S.issues.length&&o.issues.push(...lo(u,S.issues)),o.value[m]=S.value})):(h.issues.length&&o.issues.push(...lo(u,h.issues)),o.value[m]=h.value)}let l;for(const u in r)a.has(u)||(l=l??[],l.push(u));l&&l.length>0&&o.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:l})}else{o.value={};for(const a of Reflect.ownKeys(r)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(r,a))continue;let l=t.keyType._zod.run({value:a,issues:[]},n);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Aa.test(a)&&l.issues.length){const m=t.keyType._zod.run({value:Number(a),issues:[]},n);if(m instanceof Promise)throw new Error("Async schemas not supported in object keys currently");m.issues.length===0&&(l=m)}if(l.issues.length){t.mode==="loose"?o.value[a]=r[a]:o.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(m=>gt(m,n,ft())),input:a,path:[a],inst:e});continue}const d=t.valueType._zod.run({value:r[a],issues:[]},n);d instanceof Promise?s.push(d.then(m=>{m.issues.length&&o.issues.push(...lo(a,m.issues)),o.value[l.value]=m.value})):(d.issues.length&&o.issues.push(...lo(a,d.issues)),o.value[l.value]=d.value)}}return s.length?Promise.all(s).then(()=>o):o}}),_m=v("$ZodEnum",(e,t)=>{se.init(e,t);const o=Ca(t.entries),n=new Set(o);e._zod.values=n,e._zod.pattern=new RegExp(`^(${o.filter(r=>Ed.has(typeof r)).map(r=>typeof r=="string"?Ro(r):r.toString()).join("|")})$`),e._zod.parse=(r,s)=>{const i=r.value;return n.has(i)||r.issues.push({code:"invalid_value",values:o,input:i,inst:e}),r}}),ym=v("$ZodLiteral",(e,t)=>{if(se.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const o=new Set(t.values);e._zod.values=o,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?Ro(n):n?Ro(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const s=n.value;return o.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}}),bm=v("$ZodTransform",(e,t)=>{se.init(e,t),e._zod.optin="optional",e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new Pa(e.constructor.name);const r=t.transform(o.value,o);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(i=>(o.value=i,o.fallback=!0,o));if(r instanceof Promise)throw new uo;return o.value=r,o.fallback=!0,o}});function bi(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const Ja=v("$ZodOptional",(e,t)=>{se.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ee(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ee(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${_s(o.source)})?$`):void 0}),e._zod.parse=(o,n)=>{if(t.innerType._zod.optin==="optional"){const r=o.value,s=t.innerType._zod.run(o,n);return s instanceof Promise?s.then(i=>bi(i,r)):bi(s,r)}return o.value===void 0?o:t.innerType._zod.run(o,n)}}),Rm=v("$ZodExactOptional",(e,t)=>{Ja.init(e,t),ee(e._zod,"values",()=>t.innerType._zod.values),ee(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(o,n)=>t.innerType._zod.run(o,n)}),wm=v("$ZodNullable",(e,t)=>{se.init(e,t),ee(e._zod,"optin",()=>t.innerType._zod.optin),ee(e._zod,"optout",()=>t.innerType._zod.optout),ee(e._zod,"pattern",()=>{const o=t.innerType._zod.pattern;return o?new RegExp(`^(${_s(o.source)}|null)$`):void 0}),ee(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(o,n)=>o.value===null?o:t.innerType._zod.run(o,n)}),Tm=v("$ZodDefault",(e,t)=>{se.init(e,t),e._zod.optin="optional",ee(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);if(o.value===void 0)return o.value=t.defaultValue,o;const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(s=>Ri(s,t)):Ri(r,t)}});function Ri(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const $m=v("$ZodPrefault",(e,t)=>{se.init(e,t),e._zod.optin="optional",ee(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>(n.direction==="backward"||o.value===void 0&&(o.value=t.defaultValue),t.innerType._zod.run(o,n))}),Em=v("$ZodNonOptional",(e,t)=>{se.init(e,t),ee(e._zod,"values",()=>{const o=t.innerType._zod.values;return o?new Set([...o].filter(n=>n!==void 0)):void 0}),e._zod.parse=(o,n)=>{const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(s=>wi(s,e)):wi(r,e)}});function wi(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Pm=v("$ZodCatch",(e,t)=>{se.init(e,t),e._zod.optin="optional",ee(e._zod,"optout",()=>t.innerType._zod.optout),ee(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(s=>(o.value=s.value,s.issues.length&&(o.value=t.catchValue({...o,error:{issues:s.issues.map(i=>gt(i,n,ft()))},input:o.value}),o.issues=[],o.fallback=!0),o)):(o.value=r.value,r.issues.length&&(o.value=t.catchValue({...o,error:{issues:r.issues.map(s=>gt(s,n,ft()))},input:o.value}),o.issues=[],o.fallback=!0),o)}}),Ba=v("$ZodPipe",(e,t)=>{se.init(e,t),ee(e._zod,"values",()=>t.in._zod.values),ee(e._zod,"optin",()=>t.in._zod.optin),ee(e._zod,"optout",()=>t.out._zod.optout),ee(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(o,n)=>{if(n.direction==="backward"){const s=t.out._zod.run(o,n);return s instanceof Promise?s.then(i=>Yn(i,t.in,n)):Yn(s,t.in,n)}const r=t.in._zod.run(o,n);return r instanceof Promise?r.then(s=>Yn(s,t.out,n)):Yn(r,t.out,n)}});function Yn(e,t,o){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},o)}const Cm=v("$ZodPreprocess",(e,t)=>{Ba.init(e,t)}),km=v("$ZodReadonly",(e,t)=>{se.init(e,t),ee(e._zod,"propValues",()=>t.innerType._zod.propValues),ee(e._zod,"values",()=>t.innerType._zod.values),ee(e._zod,"optin",()=>{var o,n;return(n=(o=t.innerType)==null?void 0:o._zod)==null?void 0:n.optin}),ee(e._zod,"optout",()=>{var o,n;return(n=(o=t.innerType)==null?void 0:o._zod)==null?void 0:n.optout}),e._zod.parse=(o,n)=>{if(n.direction==="backward")return t.innerType._zod.run(o,n);const r=t.innerType._zod.run(o,n);return r instanceof Promise?r.then(Ti):Ti(r)}});function Ti(e){return e.value=Object.freeze(e.value),e}const Om=v("$ZodLazy",(e,t)=>{se.init(e,t),ee(e._zod,"innerType",()=>{const o=t;return o._cachedInner||(o._cachedInner=t.getter()),o._cachedInner}),ee(e._zod,"pattern",()=>{var o,n;return(n=(o=e._zod.innerType)==null?void 0:o._zod)==null?void 0:n.pattern}),ee(e._zod,"propValues",()=>{var o,n;return(n=(o=e._zod.innerType)==null?void 0:o._zod)==null?void 0:n.propValues}),ee(e._zod,"optin",()=>{var o,n;return((n=(o=e._zod.innerType)==null?void 0:o._zod)==null?void 0:n.optin)??void 0}),ee(e._zod,"optout",()=>{var o,n;return((n=(o=e._zod.innerType)==null?void 0:o._zod)==null?void 0:n.optout)??void 0}),e._zod.parse=(o,n)=>e._zod.innerType._zod.run(o,n)}),Im=v("$ZodCustom",(e,t)=>{Ne.init(e,t),se.init(e,t),e._zod.parse=(o,n)=>o,e._zod.check=o=>{const n=o.value,r=t.fn(n);if(r instanceof Promise)return r.then(s=>$i(s,o,n,e));$i(r,o,n,e)}});function $i(e,t,o,n){if(!e){const r={code:"custom",input:o,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(r.params=n._zod.def.params),t.issues.push(yn(r))}}var Ei;class qm{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...o){const n=o[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const o=this._map.get(t);return o&&typeof o=="object"&&"id"in o&&this._idmap.delete(o.id),this._map.delete(t),this}get(t){const o=t._zod.parent;if(o){const n={...this.get(o)??{}};delete n.id;const r={...n,...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 Nm(){return new qm}(Ei=globalThis).__zod_globalRegistry??(Ei.__zod_globalRegistry=Nm());const mn=globalThis.__zod_globalRegistry;function Mm(e,t){return new e({type:"string",...x(t)})}function Wa(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...x(t)})}function Pi(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...x(t)})}function xm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...x(t)})}function zm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...x(t)})}function Am(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...x(t)})}function Lm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...x(t)})}function Ga(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...x(t)})}function jm(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...x(t)})}function Zm(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...x(t)})}function Dm(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...x(t)})}function Hm(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...x(t)})}function Um(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...x(t)})}function Vm(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...x(t)})}function Fm(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...x(t)})}function Jm(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...x(t)})}function Bm(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...x(t)})}function Wm(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...x(t)})}function Gm(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...x(t)})}function Ym(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...x(t)})}function Km(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...x(t)})}function Xm(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...x(t)})}function Qm(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...x(t)})}function eh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...x(t)})}function th(e,t){return new e({type:"string",format:"date",check:"string_format",...x(t)})}function oh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...x(t)})}function nh(e,t){return new e({type:"string",format:"duration",check:"string_format",...x(t)})}function rh(e,t){return new e({type:"number",checks:[],...x(t)})}function sh(e,t){return new e({type:"number",coerce:!0,checks:[],...x(t)})}function ih(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...x(t)})}function ah(e,t){return new e({type:"boolean",...x(t)})}function ch(e,t){return new e({type:"null",...x(t)})}function lh(e){return new e({type:"any"})}function uh(e){return new e({type:"unknown"})}function dh(e,t){return new e({type:"never",...x(t)})}function Ci(e,t){return new ja({check:"less_than",...x(t),value:e,inclusive:!1})}function Ur(e,t){return new ja({check:"less_than",...x(t),value:e,inclusive:!0})}function ki(e,t){return new Za({check:"greater_than",...x(t),value:e,inclusive:!1})}function Vr(e,t){return new Za({check:"greater_than",...x(t),value:e,inclusive:!0})}function Oi(e,t){return new Rp({check:"multiple_of",...x(t),value:e})}function Ya(e,t){return new Tp({check:"max_length",...x(t),maximum:e})}function cr(e,t){return new $p({check:"min_length",...x(t),minimum:e})}function Ka(e,t){return new Ep({check:"length_equals",...x(t),length:e})}function ph(e,t){return new Pp({check:"string_format",format:"regex",...x(t),pattern:e})}function mh(e){return new Cp({check:"string_format",format:"lowercase",...x(e)})}function hh(e){return new kp({check:"string_format",format:"uppercase",...x(e)})}function fh(e,t){return new Op({check:"string_format",format:"includes",...x(t),includes:e})}function gh(e,t){return new Ip({check:"string_format",format:"starts_with",...x(t),prefix:e})}function Sh(e,t){return new qp({check:"string_format",format:"ends_with",...x(t),suffix:e})}function Co(e){return new Np({check:"overwrite",tx:e})}function vh(e){return Co(t=>t.normalize(e))}function _h(){return Co(e=>e.trim())}function yh(){return Co(e=>e.toLowerCase())}function bh(){return Co(e=>e.toUpperCase())}function Rh(){return Co(e=>Td(e))}function wh(e,t,o){return new e({type:"array",element:t,...x(o)})}function Th(e,t,o){return new e({type:"custom",check:"custom",fn:t,...x(o)})}function $h(e,t){const o=Eh(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(yn(r,n.value,o._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=o),s.continue??(s.continue=!o._zod.def.abort),n.issues.push(yn(s))}},e(n.value,n)),t);return o}function Eh(e,t){const o=new Ne({check:"custom",...x(t)});return o._zod.check=e,o}function lr(e){let t=(e==null?void 0:e.target)??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:(e==null?void 0:e.metadata)??mn,target:t,unrepresentable:(e==null?void 0:e.unrepresentable)??"throw",override:(e==null?void 0:e.override)??(()=>{}),io:(e==null?void 0:e.io)??"output",counter:0,seen:new Map,cycles:(e==null?void 0:e.cycles)??"ref",reused:(e==null?void 0:e.reused)??"inline",external:(e==null?void 0:e.external)??void 0}}function re(e,t,o={path:[],schemaPath:[]}){var d,m;var n;const r=e._zod.def,s=t.seen.get(e);if(s)return s.count++,o.schemaPath.includes(e)&&(s.cycle=o.path),s.schema;const i={schema:{},count:1,cycle:void 0,path:o.path};t.seen.set(e,i);const a=(m=(d=e._zod).toJSONSchema)==null?void 0:m.call(d);if(a)i.schema=a;else{const h={...o,schemaPath:[...o.schemaPath,e],path:o.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,h);else{const _=i.schema,T=t.processors[r.type];if(!T)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);T(e,t,_,h)}const S=e._zod.parent;S&&(i.ref||(i.ref=S),re(S,t,h),t.seen.get(S).isParent=!0)}const l=t.metadataRegistry.get(e);return l&&Object.assign(i.schema,l),t.io==="input"&&ke(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function ur(e,t){var i,a,l,u;const o=e.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const d of e.seen.entries()){const m=(i=e.metadataRegistry.get(d[0]))==null?void 0:i.id;if(m){const h=n.get(m);if(h&&h!==d[0])throw new Error(`Duplicate schema id "${m}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(m,d[0])}}const r=d=>{var T;const m=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const b=(T=e.external.registry.get(d[0]))==null?void 0:T.id,N=e.external.uri??(w=>w);if(b)return{ref:N(b)};const L=d[1].defId??d[1].schema.id??`schema${e.counter++}`;return d[1].defId=L,{defId:L,ref:`${N("__shared")}#/${m}/${L}`}}if(d[1]===o)return{ref:"#"};const S=`#/${m}/`,_=d[1].schema.id??`__schema${e.counter++}`;return{defId:_,ref:S+_}},s=d=>{if(d[1].schema.$ref)return;const m=d[1],{ref:h,defId:S}=r(d);m.def={...m.schema},S&&(m.defId=S);const _=m.schema;for(const T in _)delete _[T];_.$ref=h};if(e.cycles==="throw")for(const d of e.seen.entries()){const m=d[1];if(m.cycle)throw new Error(`Cycle detected: #/${(a=m.cycle)==null?void 0:a.join("/")}/<root>
63
+
64
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const d of e.seen.entries()){const m=d[1];if(t===d[0]){s(d);continue}if(e.external){const S=(l=e.external.registry.get(d[0]))==null?void 0:l.id;if(t!==d[0]&&S){s(d);continue}}if((u=e.metadataRegistry.get(d[0]))==null?void 0:u.id){s(d);continue}if(m.cycle){s(d);continue}if(m.count>1&&e.reused==="ref"){s(d);continue}}}function dr(e,t){var a,l,u,d;const o=e.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=m=>{const h=e.seen.get(m);if(h.ref===null)return;const S=h.def??h.schema,_={...S},T=h.ref;if(h.ref=null,T){n(T);const N=e.seen.get(T),L=N.schema;if(L.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(S.allOf=S.allOf??[],S.allOf.push(L)):Object.assign(S,L),Object.assign(S,_),m._zod.parent===T)for(const q in S)q==="$ref"||q==="allOf"||q in _||delete S[q];if(L.$ref&&N.def)for(const q in S)q==="$ref"||q==="allOf"||q in N.def&&JSON.stringify(S[q])===JSON.stringify(N.def[q])&&delete S[q]}const b=m._zod.parent;if(b&&b!==T){n(b);const N=e.seen.get(b);if(N!=null&&N.schema.$ref&&(S.$ref=N.schema.$ref,N.def))for(const L in S)L==="$ref"||L==="allOf"||L in N.def&&JSON.stringify(S[L])===JSON.stringify(N.def[L])&&delete S[L]}e.override({zodSchema:m,jsonSchema:S,path:h.path??[]})};for(const m of[...e.seen.entries()].reverse())n(m[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,(a=e.external)!=null&&a.uri){const m=(l=e.external.registry.get(t))==null?void 0:l.id;if(!m)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(m)}Object.assign(r,o.def??o.schema);const s=(u=e.metadataRegistry.get(t))==null?void 0:u.id;s!==void 0&&r.id===s&&delete r.id;const i=((d=e.external)==null?void 0:d.defs)??{};for(const m of e.seen.entries()){const h=m[1];h.def&&h.defId&&(h.def.id===h.defId&&delete h.def.id,i[h.defId]=h.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?r.$defs=i:r.definitions=i);try{const m=JSON.parse(JSON.stringify(r));return Object.defineProperty(m,"~standard",{value:{...t["~standard"],jsonSchema:{input:pr(t,"input",e.processors),output:pr(t,"output",e.processors)}},enumerable:!1,writable:!1}),m}catch{throw new Error("Error converting schema to JSON.")}}function ke(e,t){const o=t??{seen:new Set};if(o.seen.has(e))return!1;o.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ke(n.element,o);if(n.type==="set")return ke(n.valueType,o);if(n.type==="lazy")return ke(n.getter(),o);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return ke(n.innerType,o);if(n.type==="intersection")return ke(n.left,o)||ke(n.right,o);if(n.type==="record"||n.type==="map")return ke(n.keyType,o)||ke(n.valueType,o);if(n.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:ke(n.in,o)||ke(n.out,o);if(n.type==="object"){for(const r in n.shape)if(ke(n.shape[r],o))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(ke(r,o))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(ke(r,o))return!0;return!!(n.rest&&ke(n.rest,o))}return!1}const Ph=(e,t={})=>o=>{const n=lr({...o,processors:t});return re(e,n),ur(n,e),dr(n,e)},pr=(e,t,o={})=>n=>{const{libraryOptions:r,target:s}=n??{},i=lr({...r??{},target:s,io:t,processors:o});return re(e,i),ur(i,e),dr(i,e)},Ch={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Xa=(e,t,o,n)=>{const r=o;r.type="string";const{minimum:s,maximum:i,format:a,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof s=="number"&&(r.minLength=s),typeof i=="number"&&(r.maxLength=i),a&&(r.format=Ch[a]??a,r.format===""&&delete r.format,a==="time"&&delete r.format),u&&(r.contentEncoding=u),l&&l.size>0){const d=[...l];d.length===1?r.pattern=d[0].source:d.length>1&&(r.allOf=[...d.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},Qa=(e,t,o,n)=>{const r=o,{minimum:s,maximum:i,format:a,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;typeof a=="string"&&a.includes("int")?r.type="integer":r.type="number";const m=typeof d=="number"&&d>=(s??Number.NEGATIVE_INFINITY),h=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),S=t.target==="draft-04"||t.target==="openapi-3.0";m?S?(r.minimum=d,r.exclusiveMinimum=!0):r.exclusiveMinimum=d:typeof s=="number"&&(r.minimum=s),h?S?(r.maximum=u,r.exclusiveMaximum=!0):r.exclusiveMaximum=u:typeof i=="number"&&(r.maximum=i),typeof l=="number"&&(r.multipleOf=l)},ec=(e,t,o,n)=>{o.type="boolean"},kh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Oh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},tc=(e,t,o,n)=>{t.target==="openapi-3.0"?(o.type="string",o.nullable=!0,o.enum=[null]):o.type="null"},Ih=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},qh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},oc=(e,t,o,n)=>{o.not={}},nc=(e,t,o,n)=>{},rc=(e,t,o,n)=>{},Nh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},sc=(e,t,o,n)=>{const r=e._zod.def,s=Ca(r.entries);s.every(i=>typeof i=="number")&&(o.type="number"),s.every(i=>typeof i=="string")&&(o.type="string"),o.enum=s},ic=(e,t,o,n)=>{const r=e._zod.def,s=[];for(const i of r.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){const i=s[0];o.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?o.enum=[i]:o.const=i}else s.every(i=>typeof i=="number")&&(o.type="number"),s.every(i=>typeof i=="string")&&(o.type="string"),s.every(i=>typeof i=="boolean")&&(o.type="boolean"),s.every(i=>i===null)&&(o.type="null"),o.enum=s},Mh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},xh=(e,t,o,n)=>{const r=o,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=s.source},zh=(e,t,o,n)=>{const r=o,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:i,maximum:a,mime:l}=e._zod.bag;i!==void 0&&(s.minLength=i),a!==void 0&&(s.maxLength=a),l?l.length===1?(s.contentMediaType=l[0],Object.assign(r,s)):(Object.assign(r,s),r.anyOf=l.map(u=>({contentMediaType:u}))):Object.assign(r,s)},Ah=(e,t,o,n)=>{o.type="boolean"},ac=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Lh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},cc=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},jh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Zh=(e,t,o,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},lc=(e,t,o,n)=>{const r=o,s=e._zod.def,{minimum:i,maximum:a}=e._zod.bag;typeof i=="number"&&(r.minItems=i),typeof a=="number"&&(r.maxItems=a),r.type="array",r.items=re(s.element,t,{...n,path:[...n.path,"items"]})},uc=(e,t,o,n)=>{var u;const r=o,s=e._zod.def;r.type="object",r.properties={};const i=s.shape;for(const d in i)r.properties[d]=re(i[d],t,{...n,path:[...n.path,"properties",d]});const a=new Set(Object.keys(i)),l=new Set([...a].filter(d=>{const m=s.shape[d]._zod;return t.io==="input"?m.optin===void 0:m.optout===void 0}));l.size>0&&(r.required=Array.from(l)),((u=s.catchall)==null?void 0:u._zod.def.type)==="never"?r.additionalProperties=!1:s.catchall?s.catchall&&(r.additionalProperties=re(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},dc=(e,t,o,n)=>{const r=e._zod.def,s=r.inclusive===!1,i=r.options.map((a,l)=>re(a,t,{...n,path:[...n.path,s?"oneOf":"anyOf",l]}));s?o.oneOf=i:o.anyOf=i},pc=(e,t,o,n)=>{const r=e._zod.def,s=re(r.left,t,{...n,path:[...n.path,"allOf",0]}),i=re(r.right,t,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,l=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];o.allOf=l},Dh=(e,t,o,n)=>{const r=o,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",l=s.items.map((h,S)=>re(h,t,{...n,path:[...n.path,i,S]})),u=s.rest?re(s.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;t.target==="draft-2020-12"?(r.prefixItems=l,u&&(r.items=u)):t.target==="openapi-3.0"?(r.items={anyOf:l},u&&r.items.anyOf.push(u),r.minItems=l.length,u||(r.maxItems=l.length)):(r.items=l,u&&(r.additionalItems=u));const{minimum:d,maximum:m}=e._zod.bag;typeof d=="number"&&(r.minItems=d),typeof m=="number"&&(r.maxItems=m)},mc=(e,t,o,n)=>{const r=o,s=e._zod.def;r.type="object";const i=s.keyType,a=i._zod.bag,l=a==null?void 0:a.patterns;if(s.mode==="loose"&&l&&l.size>0){const d=re(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});r.patternProperties={};for(const m of l)r.patternProperties[m.source]=d}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=re(s.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=re(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const u=i._zod.values;if(u){const d=[...u].filter(m=>typeof m=="string"||typeof m=="number");d.length>0&&(r.required=d)}},hc=(e,t,o,n)=>{const r=e._zod.def,s=re(r.innerType,t,n),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=r.innerType,o.nullable=!0):o.anyOf=[s,{type:"null"}]},fc=(e,t,o,n)=>{const r=e._zod.def;re(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},gc=(e,t,o,n)=>{const r=e._zod.def;re(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,o.default=JSON.parse(JSON.stringify(r.defaultValue))},Sc=(e,t,o,n)=>{const r=e._zod.def;re(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,t.io==="input"&&(o._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},vc=(e,t,o,n)=>{const r=e._zod.def;re(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType;let i;try{i=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}o.default=i},_c=(e,t,o,n)=>{const r=e._zod.def,s=r.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?r.out:r.in:r.out;re(i,t,n);const a=t.seen.get(e);a.ref=i},yc=(e,t,o,n)=>{const r=e._zod.def;re(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType,o.readOnly=!0},Hh=(e,t,o,n)=>{const r=e._zod.def;re(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},Ts=(e,t,o,n)=>{const r=e._zod.def;re(r.innerType,t,n);const s=t.seen.get(e);s.ref=r.innerType},bc=(e,t,o,n)=>{const r=e._zod.innerType;re(r,t,n);const s=t.seen.get(e);s.ref=r},Ii={string:Xa,number:Qa,boolean:ec,bigint:kh,symbol:Oh,null:tc,undefined:Ih,void:qh,never:oc,any:nc,unknown:rc,date:Nh,enum:sc,literal:ic,nan:Mh,template_literal:xh,file:zh,success:Ah,custom:ac,function:Lh,transform:cc,map:jh,set:Zh,array:lc,object:uc,union:dc,intersection:pc,tuple:Dh,record:mc,nullable:hc,nonoptional:fc,default:gc,prefault:Sc,catch:vc,pipe:_c,readonly:yc,promise:Hh,optional:Ts,lazy:bc};function Rc(e,t){if("_idmap"in e){const n=e,r=lr({...t,processors:Ii}),s={};for(const l of n._idmap.entries()){const[u,d]=l;re(d,r)}const i={},a={registry:n,uri:t==null?void 0:t.uri,defs:s};r.external=a;for(const l of n._idmap.entries()){const[u,d]=l;ur(r,d),i[u]=dr(r,d)}if(Object.keys(s).length>0){const l=r.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[l]:s}}return{schemas:i}}const o=lr({...t,processors:Ii});return re(e,o),ur(o,e),dr(o,e)}const Uh=v("ZodISODateTime",(e,t)=>{Bp.init(e,t),le.init(e,t)});function Cn(e){return eh(Uh,e)}const Vh=v("ZodISODate",(e,t)=>{Wp.init(e,t),le.init(e,t)});function wc(e){return th(Vh,e)}const Fh=v("ZodISOTime",(e,t)=>{Gp.init(e,t),le.init(e,t)});function Jh(e){return oh(Fh,e)}const Bh=v("ZodISODuration",(e,t)=>{Yp.init(e,t),le.init(e,t)});function Wh(e){return nh(Bh,e)}const Gh=(e,t)=>{qa.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:o=>Ld(e,o)},flatten:{value:o=>Ad(e,o)},addIssue:{value:o=>{e.issues.push(o),e.message=JSON.stringify(e.issues,es,2)}},addIssues:{value:o=>{e.issues.push(...o),e.message=JSON.stringify(e.issues,es,2)}},isEmpty:{get(){return e.issues.length===0}}})},We=v("ZodError",Gh,{Parent:Error}),Yh=bs(We),Kh=Rs(We),Tc=wr(We),Xh=Tr(We),Qh=Dd(We),ef=Hd(We),tf=Ud(We),of=Vd(We),nf=Fd(We),rf=Jd(We),sf=Bd(We),af=Wd(We),qi=new WeakMap;function kn(e,t,o){const n=Object.getPrototypeOf(e);let r=qi.get(n);if(r||(r=new Set,qi.set(n,r)),!r.has(t)){r.add(t);for(const s in o){const i=o[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){const a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}const ie=v("ZodType",(e,t)=>(se.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:pr(e,"input"),output:pr(e,"output")}}),e.toJSONSchema=Ph(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(o,n)=>Yh(e,o,n,{callee:e.parse}),e.safeParse=(o,n)=>Tc(e,o,n),e.parseAsync=async(o,n)=>Kh(e,o,n,{callee:e.parseAsync}),e.safeParseAsync=async(o,n)=>Xh(e,o,n),e.spa=e.safeParseAsync,e.encode=(o,n)=>Qh(e,o,n),e.decode=(o,n)=>ef(e,o,n),e.encodeAsync=async(o,n)=>tf(e,o,n),e.decodeAsync=async(o,n)=>of(e,o,n),e.safeEncode=(o,n)=>nf(e,o,n),e.safeDecode=(o,n)=>rf(e,o,n),e.safeEncodeAsync=async(o,n)=>sf(e,o,n),e.safeDecodeAsync=async(o,n)=>af(e,o,n),kn(e,"ZodType",{check(...o){const n=this.def;return this.clone(wt(n,{checks:[...n.checks??[],...o.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...o){return this.check(...o)},clone(o,n){return Tt(this,o,n)},brand(){return this},register(o,n){return o.add(this,n),this},refine(o,n){return this.check(Qf(o,n))},superRefine(o,n){return this.check(eg(o,n))},overwrite(o){return this.check(Co(o))},optional(){return z(this)},exactOptional(){return jf(this)},nullable(){return zi(this)},nullish(){return z(zi(this))},nonoptional(o){return Ff(this,o)},array(){return f(this)},or(o){return I([this,o])},and(o){return Jt(this,o)},transform(o){return Ai(this,Ic(o))},default(o){return Hf(this,o)},prefault(o){return Vf(this,o)},catch(o){return Bf(this,o)},pipe(o){return Ai(this,o)},readonly(){return Yf(this)},describe(o){const n=this.clone();return mn.add(n,{description:o}),n},meta(...o){if(o.length===0)return mn.get(this);const n=this.clone();return mn.add(n,o[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(o){return o(this)}}),Object.defineProperty(e,"description",{get(){var o;return(o=mn.get(e))==null?void 0:o.description},configurable:!0}),e)),$c=v("_ZodString",(e,t)=>{ws.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(n,r,s)=>Xa(e,n,r);const o=e._zod.bag;e.format=o.format??null,e.minLength=o.minimum??null,e.maxLength=o.maximum??null,kn(e,"_ZodString",{regex(...n){return this.check(ph(...n))},includes(...n){return this.check(fh(...n))},startsWith(...n){return this.check(gh(...n))},endsWith(...n){return this.check(Sh(...n))},min(...n){return this.check(cr(...n))},max(...n){return this.check(Ya(...n))},length(...n){return this.check(Ka(...n))},nonempty(...n){return this.check(cr(1,...n))},lowercase(n){return this.check(mh(n))},uppercase(n){return this.check(hh(n))},trim(){return this.check(_h())},normalize(...n){return this.check(vh(...n))},toLowerCase(){return this.check(yh())},toUpperCase(){return this.check(bh())},slugify(){return this.check(Rh())}})}),cf=v("ZodString",(e,t)=>{ws.init(e,t),$c.init(e,t),e.email=o=>e.check(Wa(Ec,o)),e.url=o=>e.check(Ga(Pc,o)),e.jwt=o=>e.check(Qm(Tf,o)),e.emoji=o=>e.check(jm(uf,o)),e.guid=o=>e.check(Pi(Ni,o)),e.uuid=o=>e.check(xm(Kn,o)),e.uuidv4=o=>e.check(zm(Kn,o)),e.uuidv6=o=>e.check(Am(Kn,o)),e.uuidv7=o=>e.check(Lm(Kn,o)),e.nanoid=o=>e.check(Zm(df,o)),e.guid=o=>e.check(Pi(Ni,o)),e.cuid=o=>e.check(Dm(pf,o)),e.cuid2=o=>e.check(Hm(mf,o)),e.ulid=o=>e.check(Um(hf,o)),e.base64=o=>e.check(Ym(bf,o)),e.base64url=o=>e.check(Km(Rf,o)),e.xid=o=>e.check(Vm(ff,o)),e.ksuid=o=>e.check(Fm(gf,o)),e.ipv4=o=>e.check(Jm(Sf,o)),e.ipv6=o=>e.check(Bm(vf,o)),e.cidrv4=o=>e.check(Wm(_f,o)),e.cidrv6=o=>e.check(Gm(yf,o)),e.e164=o=>e.check(Xm(wf,o)),e.datetime=o=>e.check(Cn(o)),e.date=o=>e.check(wc(o)),e.time=o=>e.check(Jh(o)),e.duration=o=>e.check(Wh(o))});function c(e){return Mm(cf,e)}const le=v("ZodStringFormat",(e,t)=>{ae.init(e,t),$c.init(e,t)}),Ec=v("ZodEmail",(e,t)=>{Lp.init(e,t),le.init(e,t)});function lf(e){return Wa(Ec,e)}const Ni=v("ZodGUID",(e,t)=>{zp.init(e,t),le.init(e,t)}),Kn=v("ZodUUID",(e,t)=>{Ap.init(e,t),le.init(e,t)}),Pc=v("ZodURL",(e,t)=>{jp.init(e,t),le.init(e,t)});function Cc(e){return Ga(Pc,e)}const uf=v("ZodEmoji",(e,t)=>{Zp.init(e,t),le.init(e,t)}),df=v("ZodNanoID",(e,t)=>{Dp.init(e,t),le.init(e,t)}),pf=v("ZodCUID",(e,t)=>{Hp.init(e,t),le.init(e,t)}),mf=v("ZodCUID2",(e,t)=>{Up.init(e,t),le.init(e,t)}),hf=v("ZodULID",(e,t)=>{Vp.init(e,t),le.init(e,t)}),ff=v("ZodXID",(e,t)=>{Fp.init(e,t),le.init(e,t)}),gf=v("ZodKSUID",(e,t)=>{Jp.init(e,t),le.init(e,t)}),Sf=v("ZodIPv4",(e,t)=>{Kp.init(e,t),le.init(e,t)}),vf=v("ZodIPv6",(e,t)=>{Xp.init(e,t),le.init(e,t)}),_f=v("ZodCIDRv4",(e,t)=>{Qp.init(e,t),le.init(e,t)}),yf=v("ZodCIDRv6",(e,t)=>{em.init(e,t),le.init(e,t)}),bf=v("ZodBase64",(e,t)=>{tm.init(e,t),le.init(e,t)}),Rf=v("ZodBase64URL",(e,t)=>{nm.init(e,t),le.init(e,t)}),wf=v("ZodE164",(e,t)=>{rm.init(e,t),le.init(e,t)}),Tf=v("ZodJWT",(e,t)=>{im.init(e,t),le.init(e,t)}),$s=v("ZodNumber",(e,t)=>{Ha.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(n,r,s)=>Qa(e,n,r),kn(e,"ZodNumber",{gt(n,r){return this.check(ki(n,r))},gte(n,r){return this.check(Vr(n,r))},min(n,r){return this.check(Vr(n,r))},lt(n,r){return this.check(Ci(n,r))},lte(n,r){return this.check(Ur(n,r))},max(n,r){return this.check(Ur(n,r))},int(n){return this.check(Mi(n))},safe(n){return this.check(Mi(n))},positive(n){return this.check(ki(0,n))},nonnegative(n){return this.check(Vr(0,n))},negative(n){return this.check(Ci(0,n))},nonpositive(n){return this.check(Ur(0,n))},multipleOf(n,r){return this.check(Oi(n,r))},step(n,r){return this.check(Oi(n,r))},finite(){return this}});const o=e._zod.bag;e.minValue=Math.max(o.minimum??Number.NEGATIVE_INFINITY,o.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(o.maximum??Number.POSITIVE_INFINITY,o.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(o.format??"").includes("int")||Number.isSafeInteger(o.multipleOf??.5),e.isFinite=!0,e.format=o.format??null});function y(e){return rh($s,e)}const $f=v("ZodNumberFormat",(e,t)=>{am.init(e,t),$s.init(e,t)});function Mi(e){return ih($f,e)}const Ef=v("ZodBoolean",(e,t)=>{cm.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>ec(e,o,n)});function O(e){return ah(Ef,e)}const Pf=v("ZodNull",(e,t)=>{lm.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>tc(e,o,n)});function bn(e){return ch(Pf,e)}const Cf=v("ZodAny",(e,t)=>{um.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>nc()});function kf(){return lh(Cf)}const Of=v("ZodUnknown",(e,t)=>{dm.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>rc()});function A(){return uh(Of)}const If=v("ZodNever",(e,t)=>{pm.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>oc(e,o,n)});function qf(e){return dh(If,e)}const Nf=v("ZodArray",(e,t)=>{mm.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>lc(e,o,n,r),e.element=t.element,kn(e,"ZodArray",{min(o,n){return this.check(cr(o,n))},nonempty(o){return this.check(cr(1,o))},max(o,n){return this.check(Ya(o,n))},length(o,n){return this.check(Ka(o,n))},unwrap(){return this.element}})});function f(e,t){return wh(Nf,e,t)}const kc=v("ZodObject",(e,t)=>{fm.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>uc(e,o,n,r),ee(e,"shape",()=>t.shape),kn(e,"ZodObject",{keyof(){return F(Object.keys(this._zod.def.shape))},catchall(o){return this.clone({...this._zod.def,catchall:o})},passthrough(){return this.clone({...this._zod.def,catchall:A()})},loose(){return this.clone({...this._zod.def,catchall:A()})},strict(){return this.clone({...this._zod.def,catchall:qf()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(o){return Id(this,o)},safeExtend(o){return qd(this,o)},merge(o){return Nd(this,o)},pick(o){return kd(this,o)},omit(o){return Od(this,o)},partial(...o){return Md(qc,this,o[0])},required(...o){return xd(Nc,this,o[0])}})});function p(e,t){const o={type:"object",shape:e??{},...x(t)};return new kc(o)}function Z(e,t){return new kc({type:"object",shape:e,catchall:A(),...x(t)})}const Oc=v("ZodUnion",(e,t)=>{Fa.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>dc(e,o,n,r),e.options=t.options});function I(e,t){return new Oc({type:"union",options:e,...x(t)})}const Mf=v("ZodDiscriminatedUnion",(e,t)=>{Oc.init(e,t),gm.init(e,t)});function mr(e,t,o){return new Mf({type:"union",options:t,discriminator:e,...x(o)})}const xf=v("ZodIntersection",(e,t)=>{Sm.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>pc(e,o,n,r)});function Jt(e,t){return new xf({type:"intersection",left:e,right:t})}const xi=v("ZodRecord",(e,t)=>{vm.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>mc(e,o,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function E(e,t,o){return!t||!t._zod?new xi({type:"record",keyType:c(),valueType:e,...x(t)}):new xi({type:"record",keyType:e,valueType:t,...x(o)})}const os=v("ZodEnum",(e,t)=>{_m.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(n,r,s)=>sc(e,n,r),e.enum=t.entries,e.options=Object.values(t.entries);const o=new Set(Object.keys(t.entries));e.extract=(n,r)=>{const s={};for(const i of n)if(o.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new os({...t,checks:[],...x(r),entries:s})},e.exclude=(n,r)=>{const s={...t.entries};for(const i of n)if(o.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new os({...t,checks:[],...x(r),entries:s})}});function F(e,t){const o=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new os({type:"enum",entries:o,...x(t)})}const zf=v("ZodLiteral",(e,t)=>{ym.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>ic(e,o,n),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 g(e,t){return new zf({type:"literal",values:Array.isArray(e)?e:[e],...x(t)})}const Af=v("ZodTransform",(e,t)=>{bm.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>cc(e,o),e._zod.parse=(o,n)=>{if(n.direction==="backward")throw new Pa(e.constructor.name);o.addIssue=s=>{if(typeof s=="string")o.issues.push(yn(s,o.value,t));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=o.value),i.inst??(i.inst=e),o.issues.push(yn(i))}};const r=t.transform(o.value,o);return r instanceof Promise?r.then(s=>(o.value=s,o.fallback=!0,o)):(o.value=r,o.fallback=!0,o)}});function Ic(e){return new Af({type:"transform",transform:e})}const qc=v("ZodOptional",(e,t)=>{Ja.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ts(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function z(e){return new qc({type:"optional",innerType:e})}const Lf=v("ZodExactOptional",(e,t)=>{Rm.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Ts(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function jf(e){return new Lf({type:"optional",innerType:e})}const Zf=v("ZodNullable",(e,t)=>{wm.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>hc(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function zi(e){return new Zf({type:"nullable",innerType:e})}const Df=v("ZodDefault",(e,t)=>{Tm.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>gc(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Hf(e,t){return new Df({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Oa(t)}})}const Uf=v("ZodPrefault",(e,t)=>{$m.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>Sc(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Vf(e,t){return new Uf({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Oa(t)}})}const Nc=v("ZodNonOptional",(e,t)=>{Em.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>fc(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Ff(e,t){return new Nc({type:"nonoptional",innerType:e,...x(t)})}const Jf=v("ZodCatch",(e,t)=>{Pm.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>vc(e,o,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Bf(e,t){return new Jf({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Mc=v("ZodPipe",(e,t)=>{Ba.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>_c(e,o,n,r),e.in=t.in,e.out=t.out});function Ai(e,t){return new Mc({type:"pipe",in:e,out:t})}const Wf=v("ZodPreprocess",(e,t)=>{Mc.init(e,t),Cm.init(e,t)}),Gf=v("ZodReadonly",(e,t)=>{km.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>yc(e,o,n,r),e.unwrap=()=>e._zod.def.innerType});function Yf(e){return new Gf({type:"readonly",innerType:e})}const Kf=v("ZodLazy",(e,t)=>{Om.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>bc(e,o,n,r),e.unwrap=()=>e._zod.def.getter()});function Es(e){return new Kf({type:"lazy",getter:e})}const Xf=v("ZodCustom",(e,t)=>{Im.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,r)=>ac(e,o)});function Qf(e,t={}){return Th(Xf,e,t)}function eg(e,t){return $h(e,t)}function Rn(e,t){return new Wf({type:"pipe",in:Ic(e),out:t})}const tg={custom:"custom"};function og(e){return sh($s,e)}const ns="2025-11-25",ng=[ns,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],rg="io.modelcontextprotocol/related-task",Er="io.modelcontextprotocol/protocolVersion",Ps="io.modelcontextprotocol/clientInfo",fn="io.modelcontextprotocol/serverInfo",On="io.modelcontextprotocol/clientCapabilities",sg="io.modelcontextprotocol/subscriptionId",Pr="io.modelcontextprotocol/logLevel",Cr="2.0",wo=Es(()=>I([c(),y(),O(),bn(),E(c(),wo),f(wo)])),he=E(c(),wo),ig=f(wo),Cs=I([c(),y().int()]),ks=c(),xc=p({ttl:y().optional()}),zc=p({taskId:c()}),Os=Z({progressToken:Cs.optional(),[rg]:zc.optional()}),$e=p({_meta:Os.optional()}),In=$e.extend({task:xc.optional()}),fe=p({method:c(),params:$e.loose().optional()}),Me=p({_meta:Os.optional()}),xe=p({method:c(),params:Me.loose().optional()}),Is=Z({get[fn](){return Ir.optional().catch(void 0)}}),ge=Z({_meta:Is.optional()}),ko=I([c(),y().int()]),qs=p({jsonrpc:g(Cr),id:ko,...fe.shape}).strict(),Ns=p({jsonrpc:g(Cr),...xe.shape}).strict(),kr=p({jsonrpc:g(Cr),id:ko,result:ge}).strict(),Or=p({jsonrpc:g(Cr),id:ko.optional(),error:p({code:y().int(),message:c(),data:A().optional()})}).strict(),Ms=I([qs,Ns,kr,Or]),ag=I([kr,Or]),xs=ge.strict(),Ac=Me.extend({requestId:ko.optional(),reason:c().optional()}),zs=xe.extend({method:g("notifications/cancelled"),params:Ac}),Lc=p({src:c(),mimeType:c().optional(),sizes:f(c()).optional(),theme:F(["light","dark"]).optional()}),Oo=p({icons:f(Lc).optional()}),Bt=p({name:c(),title:c().optional()}),Ir=Bt.extend({...Bt.shape,...Oo.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),cg=Jt(p({applyDefaults:O().optional()}),he),lg=Rn(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Jt(p({form:cg.optional(),url:he.optional()}),he.optional())),jc=Z({list:he.optional(),cancel:he.optional(),requests:Z({sampling:Z({createMessage:he.optional()}).optional(),elicitation:Z({create:he.optional()}).optional()}).optional()}),Zc=Z({list:he.optional(),cancel:he.optional(),requests:Z({tools:Z({call:he.optional()}).optional()}).optional()}),Dc=p({experimental:E(c(),he).optional(),sampling:p({context:he.optional(),tools:he.optional()}).optional(),elicitation:lg.optional(),roots:p({listChanged:O().optional()}).optional(),tasks:jc.optional(),extensions:E(c(),he).optional()}),Hc=$e.extend({protocolVersion:c(),capabilities:Dc,clientInfo:Ir}),Uc=fe.extend({method:g("initialize"),params:Hc}),As=p({experimental:E(c(),he).optional(),logging:he.optional(),completions:he.optional(),prompts:p({listChanged:O().optional()}).optional(),resources:p({subscribe:O().optional(),listChanged:O().optional()}).optional(),tools:p({listChanged:O().optional()}).optional(),tasks:Zc.optional(),extensions:E(c(),he).optional()}),Vc=ge.extend({protocolVersion:c(),capabilities:As,serverInfo:Ir,instructions:c().optional()}),Fc=xe.extend({method:g("notifications/initialized"),params:Me.optional()}),Jc=fe.extend({method:g("server/discover"),params:$e.optional()}),Bc=ge.extend({supportedVersions:f(c()),capabilities:As,instructions:c().optional()}),Ls=fe.extend({method:g("ping"),params:$e.optional()}),Wc=p({progress:y(),total:z(y()),message:z(c())}),Gc=p({...Me.shape,...Wc.shape,progressToken:Cs}),js=xe.extend({method:g("notifications/progress"),params:Gc}),Yc=$e.extend({cursor:ks.optional()}),Io=fe.extend({params:Yc.optional()}),qo=ge.extend({nextCursor:ks.optional()}),Zs=p({uri:c(),mimeType:z(c()),_meta:E(c(),A()).optional()}),Ds=Zs.extend({text:c()}),Hs=c().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Us=Zs.extend({blob:Hs}),No=F(["user","assistant"]),Yt=p({audience:f(No).optional(),priority:y().min(0).max(1).optional(),lastModified:Cn({offset:!0}).optional()}),Vs=p({...Bt.shape,...Oo.shape,uri:c(),description:z(c()),mimeType:z(c()),size:z(y()),annotations:Yt.optional(),_meta:z(Z({}))}),Kc=p({...Bt.shape,...Oo.shape,uriTemplate:c(),description:z(c()),mimeType:z(c()),annotations:Yt.optional(),_meta:z(Z({}))}),Xc=Io.extend({method:g("resources/list")}),Qc=qo.extend({resources:f(Vs)}),el=Io.extend({method:g("resources/templates/list")}),tl=qo.extend({resourceTemplates:f(Kc)}),qr=$e.extend({uri:c()}),ol=qr,nl=fe.extend({method:g("resources/read"),params:ol}),rl=ge.extend({contents:f(I([Ds,Us]))}),sl=xe.extend({method:g("notifications/resources/list_changed"),params:Me.optional()}),il=qr,al=fe.extend({method:g("resources/subscribe"),params:il}),cl=qr,ll=fe.extend({method:g("resources/unsubscribe"),params:cl}),Fs=p({toolsListChanged:O().optional(),promptsListChanged:O().optional(),resourcesListChanged:O().optional(),resourceSubscriptions:f(c()).optional()}),ul=$e.extend({notifications:Fs}),dl=fe.extend({method:g("subscriptions/listen"),params:ul}),pl=Me.extend({notifications:Fs}),ml=xe.extend({method:g("notifications/subscriptions/acknowledged"),params:pl}),hl=Is.extend({[sg]:ko}),fl=ge.extend({_meta:hl}),gl=Me.extend({uri:c()}),Sl=xe.extend({method:g("notifications/resources/updated"),params:gl}),vl=p({name:c(),description:z(c()),required:z(O())}),_l=p({...Bt.shape,...Oo.shape,description:z(c()),arguments:z(f(vl)),_meta:z(Z({}))}),yl=Io.extend({method:g("prompts/list")}),bl=qo.extend({prompts:f(_l)}),Rl=$e.extend({name:c(),arguments:E(c(),c()).optional()}),wl=fe.extend({method:g("prompts/get"),params:Rl}),Nr=p({type:g("text"),text:c(),annotations:Yt.optional(),_meta:E(c(),A()).optional()}),Mr=p({type:g("image"),data:Hs,mimeType:c(),annotations:Yt.optional(),_meta:E(c(),A()).optional()}),xr=p({type:g("audio"),data:Hs,mimeType:c(),annotations:Yt.optional(),_meta:E(c(),A()).optional()}),Tl=p({type:g("tool_use"),name:c(),id:c(),input:E(c(),A()),_meta:E(c(),A()).optional()}),$l=p({type:g("resource"),resource:I([Ds,Us]),annotations:Yt.optional(),_meta:E(c(),A()).optional()}),El=Vs.extend({type:g("resource_link")}),zr=I([Nr,Mr,xr,El,$l]),Pl=p({role:No,content:zr}),Cl=ge.extend({description:c().optional(),messages:f(Pl)}),kl=xe.extend({method:g("notifications/prompts/list_changed"),params:Me.optional()}),Ol=p({title:c().optional(),readOnlyHint:O().optional(),destructiveHint:O().optional(),idempotentHint:O().optional(),openWorldHint:O().optional()}),Il=p({taskSupport:F(["required","optional","forbidden"]).optional()}),Js=p({...Bt.shape,...Oo.shape,description:c().optional(),inputSchema:p({type:g("object"),properties:E(c(),wo).optional(),required:f(c()).optional()}).catchall(A()),outputSchema:Z({$schema:c().optional()}).optional(),annotations:Ol.optional(),execution:Il.optional(),_meta:E(c(),A()).optional()}),ql=Io.extend({method:g("tools/list")}),Nl=qo.extend({tools:f(Js)}),Bs=ge.extend({content:f(zr).default([]),structuredContent:A().optional(),isError:O().optional()}),ug=Bs.or(ge.extend({toolResult:A()})),Ml=In.extend({name:c(),arguments:E(c(),A()).optional()}),xl=fe.extend({method:g("tools/call"),params:Ml}),zl=xe.extend({method:g("notifications/tools/list_changed"),params:Me.optional()}),dg=p({autoRefresh:O().default(!0),debounceMs:y().int().nonnegative().default(300)}),wn=F(["debug","info","notice","warning","error","critical","alert","emergency"]),Al=$e.extend({level:wn}),Ll=fe.extend({method:g("logging/setLevel"),params:Al}),jl=Me.extend({level:wn,logger:c().optional(),data:A()}),Zl=xe.extend({method:g("notifications/message"),params:jl}),Dl=p({name:c().optional()}),Hl=p({hints:f(Dl).optional(),costPriority:y().min(0).max(1).optional(),speedPriority:y().min(0).max(1).optional(),intelligencePriority:y().min(0).max(1).optional()}),Ul=p({mode:F(["auto","required","none"]).optional()}),Vl=p({type:g("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:f(zr),structuredContent:A().optional(),isError:O().optional(),_meta:E(c(),A()).optional()}),Fl=mr("type",[Nr,Mr,xr]),Tn=mr("type",[Nr,Mr,xr,Tl,Vl]),Jl=p({role:No,content:I([Tn,f(Tn)]),_meta:E(c(),A()).optional()}),Bl=In.extend({messages:f(Jl),modelPreferences:Hl.optional(),systemPrompt:c().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:y().optional(),maxTokens:y().int(),stopSequences:f(c()).optional(),metadata:he.optional(),tools:f(Js).optional(),toolChoice:Ul.optional()}),Wl=fe.extend({method:g("sampling/createMessage"),params:Bl}),Gl=ge.extend({model:c(),stopReason:z(F(["endTurn","stopSequence","maxTokens"]).or(c())),role:No,content:Fl}),Yl=ge.extend({model:c(),stopReason:z(F(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:No,content:I([Tn,f(Tn)])}),Ws=p({type:g("boolean"),title:c().optional(),description:c().optional(),default:O().optional()}),Ar=p({type:g("string"),title:c().optional(),description:c().optional(),minLength:y().optional(),maxLength:y().optional(),format:F(["email","uri","date","date-time"]).optional(),default:c().optional()}),hr=p({type:F(["number","integer"]),title:c().optional(),description:c().optional(),minimum:y().optional(),maximum:y().optional(),default:y().optional()}),Gs=p({type:g("string"),title:c().optional(),description:c().optional(),enum:f(c()),default:c().optional()}),Ys=p({type:g("string"),title:c().optional(),description:c().optional(),oneOf:f(p({const:c(),title:c()})),default:c().optional()}),Ks=p({type:g("string"),title:c().optional(),description:c().optional(),enum:f(c()),enumNames:f(c()).optional(),default:c().optional()}),Kl=I([Gs,Ys]),Xs=p({type:g("array"),title:c().optional(),description:c().optional(),minItems:y().optional(),maxItems:y().optional(),items:p({type:g("string"),enum:f(c())}),default:f(c()).optional()}),Qs=p({type:g("array"),title:c().optional(),description:c().optional(),minItems:y().optional(),maxItems:y().optional(),items:p({anyOf:f(p({const:c(),title:c()}))}),default:f(c()).optional()}),Xl=I([Xs,Qs]),Ql=I([Ks,Kl,Xl]),ei=I([Ql,Ws,Ar,hr]),Lr=In.extend({mode:g("form").optional(),message:c(),requestedSchema:p({type:g("object"),properties:E(c(),ei),required:f(c()).optional()}).catchall(A())}),eu=In.extend({mode:g("url"),message:c(),elicitationId:c(),url:c().url()}),tu=I([Lr,eu]),ou=fe.extend({method:g("elicitation/create"),params:tu}),nu=Me.extend({elicitationId:c()}),ru=xe.extend({method:g("notifications/elicitation/complete"),params:nu}),su=ge.extend({action:F(["accept","decline","cancel"]),content:Rn(e=>e===null?void 0:e,E(c(),I([c(),y(),O(),f(c())])).optional())}),iu=p({type:g("ref/resource"),uri:c()}),au=p({type:g("ref/prompt"),name:c()}),cu=$e.extend({ref:I([au,iu]),argument:p({name:c(),value:c()}),context:p({arguments:E(c(),c()).optional()}).optional()}),lu=fe.extend({method:g("completion/complete"),params:cu}),uu=ge.extend({completion:Z({values:f(c()).max(100),total:z(y().int()),hasMore:z(O())})}),du=p({uri:c().startsWith("file://"),name:c().optional(),_meta:E(c(),A()).optional()}),pu=fe.extend({method:g("roots/list"),params:$e.optional()}),mu=ge.extend({roots:f(du)}),hu=xe.extend({method:g("notifications/roots/list_changed"),params:Me.optional()}),pg=Z({ttl:y().optional(),pollInterval:y().optional()}),fu=F(["working","input_required","completed","failed","cancelled"]),Mo=p({taskId:c(),status:fu,ttl:I([y(),bn()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:z(y()),statusMessage:z(c())}),mg=ge.extend({task:Mo}),gu=Me.merge(Mo),hg=xe.extend({method:g("notifications/tasks/status"),params:gu}),fg=fe.extend({method:g("tasks/get"),params:$e.extend({taskId:c()})}),gg=ge.merge(Mo),Sg=fe.extend({method:g("tasks/result"),params:$e.extend({taskId:c()})}),vg=ge.loose(),_g=Io.extend({method:g("tasks/list")}),yg=qo.extend({tasks:f(Mo)}),bg=fe.extend({method:g("tasks/cancel"),params:$e.extend({taskId:c()})}),Rg=ge.merge(Mo),wg=I([Ls,Uc,Jc,lu,Ll,wl,yl,Xc,el,nl,al,ll,dl,xl,ql]),Tg=I([zs,js,Fc,hu]),$g=I([xs,Gl,Yl,su,mu]),Eg=I([Ls,Wl,ou,pu]),Pg=I([zs,js,Zl,Sl,sl,zl,kl,ml,ru]),Cg=I([xs,Vc,Bc,uu,Cl,bl,Qc,tl,rl,Bs,Nl,fl]),ye=Cc().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:tg.custom,message:"URL must be parseable",fatal:!0}),Rd}).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"}),kg=Z({resource:c().url(),authorization_servers:f(ye).optional(),jwks_uri:c().url().optional(),scopes_supported:f(c()).optional(),bearer_methods_supported:f(c()).optional(),resource_signing_alg_values_supported:f(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:O().optional(),authorization_details_types_supported:f(c()).optional(),dpop_signing_alg_values_supported:f(c()).optional(),dpop_bound_access_tokens_required:O().optional()}),Su=Z({issuer:c(),authorization_endpoint:ye,token_endpoint:ye,registration_endpoint:ye.optional(),scopes_supported:f(c()).optional(),response_types_supported:f(c()),response_modes_supported:f(c()).optional(),grant_types_supported:f(c()).optional(),token_endpoint_auth_methods_supported:f(c()).optional(),token_endpoint_auth_signing_alg_values_supported:f(c()).optional(),service_documentation:ye.optional(),revocation_endpoint:ye.optional(),revocation_endpoint_auth_methods_supported:f(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:f(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:f(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:f(c()).optional(),code_challenge_methods_supported:f(c()).optional(),client_id_metadata_document_supported:O().optional(),authorization_response_iss_parameter_supported:O().optional().catch(void 0)}),vu=Z({issuer:c(),authorization_endpoint:ye,token_endpoint:ye,userinfo_endpoint:ye.optional(),jwks_uri:ye,registration_endpoint:ye.optional(),scopes_supported:f(c()).optional(),response_types_supported:f(c()),response_modes_supported:f(c()).optional(),grant_types_supported:f(c()).optional(),acr_values_supported:f(c()).optional(),subject_types_supported:f(c()),id_token_signing_alg_values_supported:f(c()),id_token_encryption_alg_values_supported:f(c()).optional(),id_token_encryption_enc_values_supported:f(c()).optional(),userinfo_signing_alg_values_supported:f(c()).optional(),userinfo_encryption_alg_values_supported:f(c()).optional(),userinfo_encryption_enc_values_supported:f(c()).optional(),request_object_signing_alg_values_supported:f(c()).optional(),request_object_encryption_alg_values_supported:f(c()).optional(),request_object_encryption_enc_values_supported:f(c()).optional(),token_endpoint_auth_methods_supported:f(c()).optional(),token_endpoint_auth_signing_alg_values_supported:f(c()).optional(),display_values_supported:f(c()).optional(),claim_types_supported:f(c()).optional(),claims_supported:f(c()).optional(),service_documentation:c().optional(),claims_locales_supported:f(c()).optional(),ui_locales_supported:f(c()).optional(),claims_parameter_supported:O().optional(),request_parameter_supported:O().optional(),request_uri_parameter_supported:O().optional(),require_request_uri_registration:O().optional(),op_policy_uri:ye.optional(),op_tos_uri:ye.optional(),client_id_metadata_document_supported:O().optional(),authorization_response_iss_parameter_supported:O().optional().catch(void 0)}),Og=p({...vu.shape,...Su.pick({code_challenge_methods_supported:!0}).shape}),Ig=p({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:og().optional(),scope:c().optional(),refresh_token:c().optional()}).strip(),qg=p({issued_token_type:g("urn:ietf:params:oauth:token-type:id-jag"),access_token:c(),token_type:c().optional(),expires_in:y().optional(),scope:c().optional()}).strip(),Ng=p({error:c(),error_description:c().optional(),error_uri:c().optional()}),Li=ye.optional().or(g("").transform(()=>{})),_u=p({redirect_uris:f(ye),token_endpoint_auth_method:c().optional(),grant_types:f(c()).optional(),response_types:f(c()).optional(),application_type:c().optional(),client_name:c().optional(),client_uri:ye.optional(),logo_uri:Li,scope:c().optional(),contacts:f(c()).optional(),tos_uri:Li,policy_uri:c().optional(),jwks_uri:ye.optional(),jwks:kf().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),yu=p({client_id:c(),client_secret:c().optional(),client_id_issued_at:y().optional(),client_secret_expires_at:y().optional()}).strip(),Mg=_u.merge(yu),xg=p({error:c(),error_description:c().optional()}).strip(),zg=p({token:c(),token_type_hint:c().optional()}).strip();function bu(e,t,o){return typeof e=="object"&&!!e&&Reflect.get(e,"channel")===t&&Reflect.get(e,"type")==="mcp"&&Reflect.get(e,"direction")===o&&Reflect.has(e,"payload")}function Zt(e,t,o,n,r){e.postMessage({channel:o,type:"mcp",direction:n,payload:r},t)}var Ag=class{constructor(e){R(this,"_started",!1);R(this,"_closed",!1);R(this,"_allowedOrigins");R(this,"_channelId");R(this,"_messageHandler");R(this,"_clientOrigin");R(this,"onclientorigin");R(this,"onclose");R(this,"onerror");R(this,"onmessage");var t;if(!((t=e.allowedOrigins)!=null&&t.length))throw Error("At least one allowed origin must be specified");this._allowedOrigins=new Set(e.allowedOrigins),this._channelId=e.channelId??"mcp-iframe"}get clientOrigin(){return this._clientOrigin}async start(){if(this._closed)throw Error("IframeChildTransport cannot be restarted after it closes");if(this._started)throw Error("Transport already started");this._messageHandler=e=>{var o,n,r;if(e.source!==window.parent||!this._allowedOrigins.has("*")&&!this._allowedOrigins.has(e.origin)||!bu(e.data,this._channelId,"client-to-server"))return;this._clientOrigin!==e.origin&&(this._clientOrigin=e.origin,(o=this.onclientorigin)==null||o.call(this,e.origin));let{payload:t}=e.data;if(t==="mcp-check-ready"){this._broadcastServerReady();return}try{let s=Ms.parse(t);(n=this.onmessage)==null||n.call(this,s)}catch(s){(r=this.onerror)==null||r.call(this,Error(`Invalid message: ${s instanceof Error?s.message:String(s)}`))}},window.addEventListener("message",this._messageHandler),this._started=!0,this._broadcastServerReady()}async send(e,t){if(this._closed)throw Error("Transport is closed");if(!this._started)throw Error("Transport not started");if(!this._clientOrigin){console.debug("[IframeChildTransport] No client connected, message not sent");return}if(window.parent===window){console.debug("[IframeChildTransport] Not running in an iframe, message not sent");return}Zt(window.parent,this._clientOrigin,this._channelId,"server-to-client",e)}async close(){var e;this._closed||(this._closed=!0,this._started=!1,this._messageHandler&&(this._messageHandler=(window.removeEventListener("message",this._messageHandler),void 0)),this._clientOrigin&&window.parent!==window&&Zt(window.parent,this._clientOrigin,this._channelId,"server-to-client","mcp-server-stopped"),(e=this.onclose)==null||e.call(this))}_broadcastServerReady(){window.parent!==window&&Zt(window.parent,"*",this._channelId,"server-to-client","mcp-server-ready")}},Lg=class{constructor(e){R(this,"_started",!1);R(this,"_closed",!1);R(this,"_allowedOrigins");R(this,"_channelId");R(this,"_messageHandler");R(this,"onclose");R(this,"onerror");R(this,"onmessage");var t;if(!((t=e.allowedOrigins)!=null&&t.length))throw Error("At least one allowed origin must be specified");this._allowedOrigins=new Set(e.allowedOrigins),this._channelId=e.channelId??"mcp-default"}async start(){if(this._closed)throw Error("TabServerTransport cannot be restarted after it closes");if(this._started)throw Error("Transport already started");this._messageHandler=e=>{var o,n;if(e.source!==window||!this._allowedOrigins.has("*")&&!this._allowedOrigins.has(e.origin)||!bu(e.data,this._channelId,"client-to-server"))return;let{payload:t}=e.data;if(t==="mcp-check-ready"){Zt(window,"*",this._channelId,"server-to-client","mcp-server-ready");return}try{let r=Ms.parse(t);(o=this.onmessage)==null||o.call(this,r)}catch(r){(n=this.onerror)==null||n.call(this,Error(`Invalid message: ${r instanceof Error?r.message:String(r)}`))}},window.addEventListener("message",this._messageHandler),this._started=!0,Zt(window,"*",this._channelId,"server-to-client","mcp-server-ready")}async send(e,t){if(this._closed)throw Error("Transport is closed");if(!this._started)throw Error("Transport not started");Zt(window,"*",this._channelId,"server-to-client",e)}async close(){var e;this._closed||(this._closed=!0,this._messageHandler&&(this._messageHandler=(window.removeEventListener("message",this._messageHandler),void 0)),this._started&&Zt(window,"*",this._channelId,"server-to-client","mcp-server-stopped"),this._started=!1,(e=this.onclose)==null||e.call(this))}};const ji={type:"object",properties:{}},jg="Failed to parse input arguments",Zi="Tool was executed but the invocation failed. For example, the script function threw an error",Zg=["draft-2020-12","draft-07"],Dg=/^[A-Za-z0-9_.-]{1,128}$/u;function He(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xn(e){if(typeof e=="symbol")throw new TypeError("Symbol values cannot be converted to a DOMString");return String(e)}function Ru(e){const t=Reflect.get(e,"name"),o=Reflect.get(e,"description"),n=Reflect.get(e,"title");if(t===void 0)throw new TypeError('Tool "name" is required');if(o===void 0)throw new TypeError('Tool "description" is required');const r=Reflect.get(e,"annotations"),s=He(r)?r:{},i=Reflect.get(e,"inputSchema"),a=Reflect.get(e,"outputSchema"),l=Reflect.get(e,"execute");return{name:Xn(t),...n===void 0?{}:{title:Xn(n).toWellFormed()},description:Xn(o),...i===void 0?{}:{inputSchema:i},...a===void 0?{}:{outputSchema:a},execute:l,...r===void 0?{}:{annotations:{...s.title===void 0?{}:{title:Xn(s.title).toWellFormed()},readOnlyHint:!!s.readOnlyHint,...s.destructiveHint===void 0?{}:{destructiveHint:!!s.destructiveHint},...s.idempotentHint===void 0?{}:{idempotentHint:!!s.idempotentHint},...s.openWorldHint===void 0?{}:{openWorldHint:!!s.openWorldHint},untrustedContentHint:!!s.untrustedContentHint}}}}function Hg(e){if(!He(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function wu(e,t=new WeakSet){var o;if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e))return!1;t.add(e);try{return((o=Array.isArray(e)?e:Hg(e)?Object.values(e):null)==null?void 0:o.every(n=>wu(n,t)))??!1}catch{return!1}finally{t.delete(e)}}function Ug(e){return wu(e)?e:void 0}function Vg(e){return He(e)&&Array.isArray(e.content)}function Fg(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function rs(e){if(Vg(e))return e;const t=Ug(e);return{content:[{type:"text",text:Fg(e)}],...t===void 0?{}:{structuredContent:t},isError:!1}}function mt(e){return new DOMException(e,"UnknownError")}function Tu(e){return mt(e instanceof Error?`${Zi}: ${e.message}`:Zi)}function De(e){return new DOMException(e,"InvalidStateError")}function $u(e){if(e.name==="")throw De('Tool "name" must be a non-empty string');if(typeof e.name!="string"||!Dg.test(e.name))throw De('Tool "name" must be 1–128 characters and contain only ASCII alphanumeric, underscore, hyphen, or period');if(typeof e.description!="string"||e.description.length===0)throw De('Tool "description" must be a non-empty string');if(typeof e.execute!="function")throw new TypeError('Tool "execute" must be a function')}function ti(e){return{readOnlyHint:e.readOnlyHint??!1,untrustedContentHint:e.untrustedContentHint??!1}}function Eu(e){try{const t=JSON.parse(e);if(Array.isArray(t)||He(t))return t}catch{}throw mt(jg)}function Pu(e){if(typeof e=="object"&&e!==null||typeof e=="function")try{const t=JSON.stringify(e);if(t)return t}catch{}return String(e)||"Operation succeeded"}function fr(e,t,o=()=>t==null?void 0:t.reason){return t?t.aborted?Promise.reject(o()):new Promise((n,r)=>{const s=()=>{i(),r(o())},i=()=>t.removeEventListener("abort",s);t.addEventListener("abort",s,{once:!0}),e.then(a=>{i(),n(a)},a=>{i(),r(a)})}):e}function Jg(e){const t=e.origin==="null"?e:new URL(e.origin),o=t.protocol;if(["https:","wss:","file:","chrome-extension:","moz-extension:"].includes(o))return!0;const n=t.hostname.toLowerCase(),r=n.split("."),s=r.length===4&&r.every(i=>/^\d{1,3}$/u.test(i)&&Number(i)<=255)&&Number(r[0])===127;return n==="::1"||n==="[::1]"||n==="localhost"||n==="localhost."||n.endsWith(".localhost")||n.endsWith(".localhost.")||s}function gr(e){for(const t of e??[]){let o;try{o=new URL(t)}catch{throw new DOMException(`Invalid or untrustworthy origin: ${String(t)}`,"SecurityError")}if(!Jg(o))throw new DOMException(`Invalid or untrustworthy origin: ${t}`,"SecurityError")}}function Dt(e){var s;if(Bg(),!e)return;const t=((s=e.defaultView)==null?void 0:s.DOMException)??DOMException;let o=!1;try{const i=e.defaultView;o=!!(i&&i.document===e)}catch{}if(!o)throw new t("The associated document is not fully active","InvalidStateError");const n=Reflect.get(e,"permissionsPolicy")??Reflect.get(e,"featurePolicy");if(n&&typeof n=="object"){const i=Reflect.get(n,"features"),a=Reflect.get(n,"allowsFeature");if(typeof i=="function"&&typeof a=="function"){const l=Reflect.apply(i,n,[]);if(Array.isArray(l)&&l.includes("tools")){if(Reflect.apply(a,n,["tools"])===!0)return;throw new t("WebMCP is disabled by Permissions Policy","NotAllowedError")}}}const r=e.defaultView;if(!(!r||r.parent===r)){try{r.parent.document;return}catch{}throw new t("WebMCP in cross-origin frames requires native Permissions Policy support","NotAllowedError")}}function Bg(){var e;if(globalThis.originAgentCluster===!1&&((e=globalThis.location)==null?void 0:e.protocol)!=="file:")throw new DOMException("","SecurityError")}function Cu(e){try{if(new URL(String(e)).origin!=="null")return}catch{}throw new DOMException(`Unsupported tool origin: ${String(e)}`,"NotSupportedError")}function ku(e){if(!He(e))return null;const t=e["~standard"];return He(t)?t:null}function Di(e){const t=ku(e);return!!(t&&t.version===1&&typeof t.validate=="function")}function Wg(e){const t=ku(e);return!t||t.version!==1||!He(t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function Gg(e,t){const o={...e};return Object.defineProperty(o,"~standard",{value:t["~standard"]}),o}function Yg(e){for(const t of Zg)try{const o=Sr(e["~standard"].jsonSchema.input({target:t})),n=JSON.parse(o);if(!He(n))throw new TypeError("inputSchema must serialize to an object");return n}catch{}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function Ou(e){if(e===void 0)return{inputSchema:ji};if(Wg(e)){const r=Yg(e),s=Sr(r);return{inputSchema:Di(e)?Gg(r,e):r,registeredInputSchema:s}}if(Di(e))throw new Error("Standard Schema inputSchema must provide ~standard.jsonSchema.input() for tool metadata");if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("inputSchema must be an object");const t=Sr(e),o=JSON.parse(t),n=He(o)?o:void 0;return!n||Object.keys(n).length===0?{inputSchema:ji,registeredInputSchema:t}:{inputSchema:n.type===void 0?{type:"object",...n}:n,registeredInputSchema:t}}function Sr(e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("inputSchema must be an object");const t=JSON.stringify(e);if(t===void 0)throw new TypeError("inputSchema must be JSON-serializable");return t}const oi=new WeakSet,ss=new WeakMap,To=new WeakMap;function Iu(e){return e.isTrusted&&(oi.has(e)||e.eventPhase!==Event.NONE&&e.target instanceof HTMLFormElement&&To.has(e.target))}function Kg(e,t){var n;if(!Iu(e))throw new DOMException("respondWith() is only available during an agent-invoked submit event","InvalidStateError");if(!e.defaultPrevented)throw new DOMException("respondWith() requires preventDefault() during an agent-invoked submit event","InvalidStateError");if(e.eventPhase===Event.NONE)throw new DOMException("respondWith() is only available while the submit event is being dispatched","InvalidStateError");oi.add(e);const o=Promise.resolve(t);ss.set(e,o),e.target instanceof HTMLFormElement&&((n=To.get(e.target))==null||n.respond(e))}const qu=new Set(["email","password","search","tel","text","url"]),Xg=new Set([...qu,"date","datetime-local","month","number","time","week"]);function Nu(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement}function ni(e){return Reflect.get(HTMLFormElement.prototype,"elements",e)}function Fr(e,t){return Reflect.apply(Element.prototype.getAttribute,e,[t])}function is(e,t){return Reflect.apply(Element.prototype.hasAttribute,e,[t])}function Qg(e){return Reflect.get(Node.prototype,"isConnected",e)}function eS(e){return Reflect.get(Element.prototype,"shadowRoot",e)}function tS(e){return Reflect.apply(HTMLFormElement.prototype.checkValidity,e,[])}function oS(e,t){Reflect.apply(HTMLFormElement.prototype.requestSubmit,e,t?[t]:[])}function nS(e){return[...ni(e)].filter(t=>Nu(t)&&!t.matches(":disabled")&&!("readOnly"in t&&t.readOnly&&(t instanceof HTMLTextAreaElement||Xg.has(t.type))))}function Mu(e){const t=new Map;for(const o of nS(e)){const n=o.name.trim(),r=t.get(n);r?r.push(o):t.set(n,[o])}return t}function xu(e){return[...e.labels??[]].map(t=>{var n;const o=t.cloneNode(!0);return o instanceof HTMLElement?(o.querySelectorAll("button, input, meter, output, progress, select, textarea").forEach(r=>r.remove()),((n=o.textContent)==null?void 0:n.trim())??""):""}).filter(Boolean).join("; ")}function rS(e,t){var o;for(let n=(o=t[0])==null?void 0:o.parentElement;n&&n!==e;n=n.parentElement)if(n instanceof HTMLFieldSetElement&&t.every(r=>n.contains(r)))return n}function sS(e,t){var o;if(t.length===1){const n=t[0];return n&&(n.getAttribute("toolparamdescription")||xu(n)||n.getAttribute("aria-description"))||void 0}return((o=rS(e,t))==null?void 0:o.getAttribute("toolparamdescription"))||void 0}function Te(e,t,o,n){const r=sS(t,o),s=r&&n?`${r} (${n})`:r||n;return s?{...e,description:s}:e}function Hi(e,t){const o=e.getAttribute(t);if(o===null||o.trim()==="")return;const n=Number(o);return Number.isFinite(n)?n:void 0}function iS(e,t){const o=e/t;return Math.abs(o-Math.round(o))<Number.EPSILON*16}function zu(e){const t=e.getAttribute("pattern");if(t!==null)try{return new RegExp(t,"v"),t}catch{return}}function Ui(e,t=!0){const o={type:"number"},n=Hi(e,"min"),r=Hi(e,"max");n!==void 0&&(o.minimum=n),r!==void 0&&(o.maximum=r);const s=e.getAttribute("step");if(s!=="any"){const a=s===null||s===""?1:Number(s),l=Number.isFinite(a)&&a>0?a:1,u=Number(e.getAttribute("value"));iS(n??(Number.isFinite(u)?u:0),l)&&(o.multipleOf=l)}const i=t?zu(e):void 0;return i!==void 0&&(o.pattern=i),o}function Vi(e,t){const o=e.getAttribute("step"),n=o===null||o===""?60:Number(o),r=Number.isFinite(n)&&n>0?n:60;return r<1?`${t}(:[0-5][0-9](\\.[0-9]{1,3})?)?$`:r<60?`${t}(:[0-5][0-9])?$`:`${t}$`}function aS(e){return{anyOf:e.map(t=>({type:"string",const:t.value,title:t.textContent??""})),enum:e.map(t=>t.value)}}function Jr(e){return{anyOf:e.map(t=>{const o=xu(t);return{type:"string",const:t.value,...o?{title:o}:{}}}),enum:e.map(t=>t.value)}}function Au(e,t){const o=t[0];if(o){if(t.length>1)return t.every(n=>n instanceof HTMLInputElement)?t.every(n=>n.type==="checkbox")?Te({type:"array",items:{type:"string",...Jr(t)},uniqueItems:!0},e,t):t.every(n=>n.type==="radio")?Te({type:"string",...Jr(t)},e,t):void 0:void 0;if(o instanceof HTMLTextAreaElement)return Te({type:"string"},e,t);if(o instanceof HTMLSelectElement){const n=aS([...o.options]);return Te(o.multiple?{type:"array",items:{type:"string",...n},uniqueItems:!0}:{type:"string",...n},e,t)}if(qu.has(o.type)){const n={type:"string"},r=zu(o);return r!==void 0&&(n.pattern=r),Te(n,e,t)}if(o.type==="hidden")return o.getAttribute("toolparamdescription")?Te({type:"string"},e,t):void 0;if(o.type==="number")return Te(Ui(o),e,t);if(o.type==="range"){const n=Ui(o,!1);return n.minimum??(n.minimum=0),n.maximum??(n.maximum=100),Te(n,e,t)}if(o.type==="checkbox")return Te({type:"boolean"},e,t);if(o.type==="radio")return Te({type:"string",...Jr([o])},e,t);if(o.type==="date")return Te({type:"string",format:"date"},e,t,"Dates MUST be provided in 'YYYY-MM-DD' format.");if(o.type==="month")return Te({type:"string",format:"^[0-9]{4}-(0[1-9]|1[0-2])$"},e,t);if(o.type==="week")return Te({type:"string",format:"^[0-9]{4}-W(0[1-9]|[1-4][0-9]|5[0-3])$"},e,t);if(o.type==="time")return Te({type:"string",format:Vi(o,"^([01][0-9]|2[0-3]):[0-5][0-9]")},e,t);if(o.type==="datetime-local")return Te({type:"string",format:Vi(o,"^[0-9]{4}-(0[1-9]|1[0-2])-[0-9]{2}T([01][0-9]|2[0-3]):[0-5][0-9]")},e,t);if(o.type==="color")return Te({type:"string",format:"^#[0-9a-zA-Z]{6}$"},e,t)}}function cS(e){const t={},o=[];for(const[n,r]of Mu(e)){if(!n)continue;const s=Au(e,r);s&&(Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:s,writable:!0}),r.some(i=>i.required)&&o.push(n))}return{type:"object",properties:t,required:o}}function lS(e){return{name:Fr(e,"toolname")??"",title:Fr(e,"tooltitle")??"",description:Fr(e,"tooldescription")??"",inputSchema:cS(e),autosubmit:is(e,"toolautosubmit")}}function Be(e){if(typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return String(e)}function Lu(e){if(typeof e=="boolean")return e;if(typeof e=="number"&&Number.isInteger(e))return e!==0;if(typeof e=="string"){if(e==="1"||e.toLowerCase()==="true")return!0;if(e==="0"||e.toLowerCase()==="false")return!1}}function Fi(e,t){if(!Array.isArray(e))return!1;const o=new Set(t);for(const n of e){const r=Be(n);if(r===void 0||!o.delete(r))return!1}return!0}function uS(e,t){if(t==="")return e.type!=="number"&&e.type!=="range";const o=e.ownerDocument.createElement("input");return o.type=e.type,o.value=t,o.value!==""}function dS(e,t,o){const n=t[0];if(!n||!Au(e,t))return!1;if(t.length>1){if(!t.every(s=>s instanceof HTMLInputElement))return!1;if(t.every(s=>s.type==="checkbox"))return Fi(o,new Set(t.map(s=>s.value)));if(t.every(s=>s.type==="radio")){const s=Be(o);return s!==void 0&&t.some(i=>i.value===s)}return!1}if(n instanceof HTMLSelectElement){const s=new Set([...n.options].map(a=>a.value));if(n.multiple)return Fi(o,s);const i=Be(o);return i!==void 0&&s.has(i)}if(n instanceof HTMLTextAreaElement)return Be(o)!==void 0;if(n.type==="checkbox")return Lu(o)!==void 0;if(n.type==="radio"){const s=Be(o);return s!==void 0&&n.value===s}const r=Be(o);return r!==void 0&&uS(n,r)}function Lt(e){e.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}function pS(e,t){var n,r;const o=e instanceof HTMLInputElement?HTMLInputElement.prototype:HTMLTextAreaElement.prototype;(r=(n=Object.getOwnPropertyDescriptor(o,"value"))==null?void 0:n.set)==null||r.call(e,t)}function Qn(e,t){var o,n;(n=(o=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"checked"))==null?void 0:o.set)==null||n.call(e,t)}function mS(e,t){const o=e[0];if(!o)return;if(e.length>1&&e.every(r=>r instanceof HTMLInputElement)){if(e.every(i=>i.type==="checkbox")&&Array.isArray(t)){const i=new Set(t.map(Be));for(const a of e){const l=i.has(a.value);a.checked!==l&&(Qn(a,l),Lt(a))}return}const r=Be(t),s=e.find(i=>i.value===r);s&&!s.checked&&(Qn(s,!0),Lt(s));return}if(o instanceof HTMLSelectElement){if(o.multiple&&Array.isArray(t)){const s=new Set(t.map(Be));let i=!1;for(const a of o.options){const l=s.has(a.value);a.selected!==l&&(a.selected=l,i=!0)}i&&Lt(o);return}const r=Be(t);r!==void 0&&o.value!==r&&(o.value=r,Lt(o));return}if(o instanceof HTMLInputElement&&o.type==="checkbox"){const r=Lu(t);r!==void 0&&o.checked!==r&&(Qn(o,r),Lt(o));return}if(o instanceof HTMLInputElement&&o.type==="radio"){Be(t)===o.value&&!o.checked&&(Qn(o,!0),Lt(o));return}const n=Be(t);n!==void 0&&o.value!==n&&(pS(o,n),Lt(o))}function hS(e,t){if(Array.isArray(t))throw new TypeError("Declarative tool input must be an object");const o=Mu(e);for(const[n,r]of Object.entries(t)){const s=o.get(n);if(!s||!dS(e,s,r))throw new TypeError(`Invalid value for declarative form parameter "${n}"`)}for(const[n,r]of Object.entries(t))mS(o.get(n)??[],r)}function fS(e){return[...ni(e)].find(t=>!t.matches(":disabled")&&(t instanceof HTMLButtonElement&&t.type==="submit"||t instanceof HTMLInputElement&&["image","submit"].includes(t.type)))}function gS(e){const t=[...ni(e)].filter(o=>Nu(o)&&o.willValidate&&!o.validity.valid).map(o=>`${o.name.trim()||"{unknown}"}: ${o.validationMessage}`).join(". ");return new DOMException(`Form validation failed: ${t}`,"UnknownError")}function Ji(e){const t=new Event("toolactivated");return Object.defineProperty(t,"toolName",{enumerable:!0,value:e}),t}function SS(e,t,o,n){var s;const{form:r}=e;return(s=e.cancelPending)==null||s.call(e,new DOMException("Tool execution cancelled","UnknownError")),new Promise((i,a)=>{let l=!1;const u=()=>{Reflect.apply(EventTarget.prototype.removeEventListener,r,["invalid",S,!0]),To.delete(r),e.cancelPending===m&&delete e.cancelPending},d=_=>{l||(l=!0,u(),_())},m=_=>d(()=>a(_)),h=_=>{_.then(T=>d(()=>i(T)),T=>d(()=>a(T)))},S=_=>{_.isTrusted&&queueMicrotask(()=>{tS(r)||m(gS(r))})};if(To.set(r,{complete(_){queueMicrotask(()=>{const T=ss.get(_);T?h(T):_.defaultPrevented?m(new DOMException("preventDefault() requires respondWith()","UnknownError")):d(()=>i(void 0))})},direct(){d(()=>i(void 0))},respond(_){queueMicrotask(()=>{const T=ss.get(_);T&&h(T)})}}),e.cancelPending=m,Reflect.apply(EventTarget.prototype.addEventListener,r,["invalid",S,!0]),!o){n==null||n.focus(),window.dispatchEvent(Ji(t));return}try{oS(r,n),window.dispatchEvent(Ji(t))}catch(_){m(_)}})}function vS(e,t){var N,L;let o=!0;const n=new Map,r=new Map,s=new Map,i=w=>{if(!(w instanceof SubmitEvent)||!w.isTrusted||!(w.target instanceof HTMLFormElement))return;const q=To.get(w.target);q&&(oi.add(w),q.complete(w))},a=w=>{if(!w.isTrusted||!(w.target instanceof HTMLFormElement))return;const q=w.target;queueMicrotask(()=>{var W,V;w.defaultPrevented||(V=(W=n.get(q))==null?void 0:W.cancelPending)==null||V.call(W,new DOMException("Tool execution cancelled by form reset","UnknownError"))})};function l(w){var q;(q=s.get(w))==null||q.disconnect(),s.delete(w),w.removeEventListener("reset",a,!0),w.removeEventListener("submit",i,!0)}function u(w){if(s.has(w))return;const q=new MutationObserver(d);s.set(w,q),q.observe(w,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),w.addEventListener("reset",a,!0),w.addEventListener("submit",i,!0)}function d(){var V,Q;u(e);for(const X of s.keys())X instanceof ShadowRoot&&!Reflect.get(Node.prototype,"isConnected",X.host)&&l(X);const w=new Set,q=new Map,W=new Map;for(const X of s.keys())for(const G of X.querySelectorAll("*")){const Y=eS(G);if(Y&&u(Y),!(G instanceof HTMLFormElement)||!is(G,"toolname")||!is(G,"tooldescription")||!Qg(G))continue;const te=G;w.add(te);const pe=lS(te),ue=JSON.stringify(pe),oe=r.get(te);if(oe===ue)continue;const ve=oe!==void 0;r.delete(te);const Se=W.get(pe.name);if(Se&&!ve){r.set(te,ue);continue}if(Se){const _e=q.get(Se);_e&&(r.set(Se,_e.fingerprint),q.delete(Se))}W.set(pe.name,te),q.set(te,{definition:pe,fingerprint:ue})}for(const X of r.keys())w.has(X)||r.delete(X);for(const[X,G]of n)((V=q.get(X))==null?void 0:V.fingerprint)!==G.fingerprint&&((Q=G.cancelPending)==null||Q.call(G,new DOMException("Tool execution cancelled because its form changed","UnknownError")),G.controller.abort(),n.delete(X));for(const[X,{definition:G,fingerprint:Y}]of q){if(n.has(X))continue;const te=new AbortController,pe={controller:te,fingerprint:Y,form:X};n.set(X,pe),t.registerTool({name:G.name,title:G.title,description:G.description,inputSchema:G.inputSchema,execute(ue){const oe=fS(X);if(!G.autosubmit&&!oe)throw new DOMException("A declarative form without toolautosubmit requires a submit button","UnknownError");return hS(X,ue),SS(pe,G.name,G.autosubmit,oe)}},{signal:te.signal}).catch(ue=>{te.abort(),(ue==null?void 0:ue.name)!=="AbortError"&&console.error(`[webmcp] declarative form tool "${G.name}" was not registered:`,ue)})}}let m=()=>{};const h=(N=e.defaultView)==null?void 0:N.Element.prototype,S=h?Object.getOwnPropertyDescriptor(h,"attachShadow"):void 0;if(h&&(S!=null&&S.configurable)){const w=h.attachShadow,q=function(W){const V=w.call(this,W);return o&&V.mode==="open"&&Reflect.get(Node.prototype,"ownerDocument",this)===e&&Reflect.get(Node.prototype,"isConnected",this)&&u(V),V};Object.defineProperty(h,"attachShadow",{...S,value:q}),m=()=>{h.attachShadow===q&&Object.defineProperty(h,"attachShadow",S)}}let _=()=>{};const T=(L=e.defaultView)==null?void 0:L.HTMLFormElement.prototype,b=T?Object.getOwnPropertyDescriptor(T,"submit"):void 0;if(T&&(b!=null&&b.configurable)){const w=T.submit,q=function(){var W;w.call(this),o&&((W=To.get(this))==null||W.direct())};Object.defineProperty(T,"submit",{...b,value:q}),_=()=>{T.submit===q&&Object.defineProperty(T,"submit",b)}}return d(),()=>{var w;o=!1,_(),m();for(const q of s.keys())l(q);r.clear();for(const q of n.values())(w=q.cancelPending)==null||w.call(q,new DOMException("Tool execution cancelled","UnknownError")),q.controller.abort();n.clear()}}const _S="__isWebMCPPolyfill",sr=Symbol("registeredInputSchema"),ln=Symbol("registrationSignal"),Bi=Symbol("registrationAbort"),vr=[];let ir=null,hn=null;function Wi(){var e;return typeof globalThis.origin=="string"?globalThis.origin:((e=globalThis.location)==null?void 0:e.origin)??""}function $o(e,t,o){const n=Object.getOwnPropertyDescriptor(e,t);try{Object.defineProperty(e,t,o)}catch(r){throw Du(),r}vr.push({target:e,key:t,previous:n})}var Qe,Vt,bt,Pn,ho,Rt,et,as,cs,ls,wa,lt=(wa=class extends EventTarget{constructor(t){var o;super();pt(this,et);pt(this,Qe,new Map);pt(this,Vt,null);pt(this,bt,null);pt(this,Pn,t=>{var o;(o=ne(this,bt))==null||o.call(this,t)});pt(this,ho);pt(this,Rt);zt(this,Rt,t),zt(this,ho,((o=t==null?void 0:t.defaultView)==null?void 0:o.DOMException)??DOMException),Object.defineProperty(this,_S,{value:!0,enumerable:!1,writable:!1,configurable:!1})}get ontoolchange(){return ne(this,bt)}set ontoolchange(t){const o=typeof t=="function"?t:null;if(o===null){zt(this,bt,null),super.removeEventListener("toolchange",ne(this,Pn));return}ne(this,bt)===null&&super.addEventListener("toolchange",ne(this,Pn)),zt(this,bt,o)}async registerTool(t,o={}){var s;Dt(ne(this,Rt));const n=o==null?void 0:o.signal,r=bS(t,ne(this,Qe));if(n==null||n.throwIfAborted(),gr(o==null?void 0:o.exposedTo),n==null||n.throwIfAborted(),(s=o==null?void 0:o.exposedTo)!=null&&s.length)throw new(ne(this,ho))("Cross-document tool exposure requires native WebMCP","NotSupportedError");if(ne(this,Qe).set(r.name,r),n){const i=()=>{At(this,et,as).call(this,r.name,r)&&At(this,et,ls).call(this)};r[ln]=n,r[Bi]=i,n.addEventListener("abort",i,{once:!0})}if(await At(this,et,ls).call(this),n!=null&&n.aborted)throw n.reason}async getTools(t={}){var n;if(Dt(ne(this,Rt)),gr(t==null?void 0:t.fromOrigins),(n=t==null?void 0:t.fromOrigins)!=null&&n.length)throw new(ne(this,ho))("Cross-document tool discovery requires native WebMCP","NotSupportedError");const o=[...ne(this,Qe).values()].map(r=>{const s=r[sr],i=s===void 0?void 0:JSON.parse(s);return{name:r.name,title:r.title??"",description:r.description,...He(i)?{inputSchema:i}:{},origin:Wi(),window:globalThis.window,...r.annotations?{annotations:ti(r.annotations)}:{}}}).sort((r,s)=>r.name<s.name?-1:r.name>s.name?1:0);return await new Promise(r=>setTimeout(r,0)),o}async executeTool(t,o,n={}){if(Dt(ne(this,Rt)),t===null||typeof t!="object")throw new TypeError("RegisteredTool must be an object");for(const r of["name","description","window","origin"])if(!(r in t))throw new TypeError(`RegisteredTool.${r} is required`);if(Cu(t.origin),t.window!==globalThis.window||t.origin!==Wi())throw mt(`Tool not found: ${t.name}`);return At(this,et,cs).call(this,t.name,o,n)}static getTestingShim(t){return ne(t,Vt)??zt(t,Vt,new yS(t)),ne(t,Vt)}static getToolInfos(t){return[...ne(t,Qe).values()].map(o=>({name:o.name,description:o.description,...o[sr]===void 0?{}:{inputSchema:o[sr]}}))}static executeToolForTesting(t,o,n,r){var s;return Dt(ne(t,Rt)),At(s=t,et,cs).call(s,o,n,r)}static dispose(t){var o,n;for(const r of ne(t,Qe).keys())At(o=t,et,as).call(o,r);t.ontoolchange=null,(n=ne(t,Vt))==null||n.dispose()}},Qe=new WeakMap,Vt=new WeakMap,bt=new WeakMap,Pn=new WeakMap,ho=new WeakMap,Rt=new WeakMap,et=new WeakSet,as=function(t,o){const n=ne(this,Qe).get(t);if(!n||o&&n!==o)return!1;const r=n[ln],s=n[Bi];return r&&s&&r.removeEventListener("abort",s),ne(this,Qe).delete(t)},cs=async function(t,o,n){var a,l,u,d,m;(a=n==null?void 0:n.signal)==null||a.throwIfAborted();const r=ne(this,Qe).get(t);if(!r)throw mt(`Tool not found: ${t}`);const s=Eu(o);if((l=n==null?void 0:n.signal)==null||l.throwIfAborted(),(u=r[ln])!=null&&u.aborted)throw mt("Tool unregistered");let i;try{const h=r[ln];i=await fr(fr(Promise.resolve(r.execute(s)),h,()=>mt("Tool unregistered")),n==null?void 0:n.signal)}catch(h){throw(d=n==null?void 0:n.signal)!=null&&d.aborted&&h===n.signal.reason||(m=r[ln])!=null&&m.aborted?h:Tu(h)}return Pu(i)},ls=async function(){var t;await new Promise(o=>setTimeout(o,0)),this.dispatchEvent(new Event("toolchange")),(t=ne(this,Vt))==null||t.dispatchToolChange()},wa);const Eo=function(){throw new TypeError("Illegal constructor")};Object.defineProperty(Eo,"name",{value:"ModelContext"});Object.defineProperty(Eo,"prototype",{value:lt.prototype,writable:!1});Object.setPrototypeOf(Eo,EventTarget);Object.defineProperty(lt.prototype,"constructor",{configurable:!0,writable:!0,value:Eo});Object.defineProperty(lt.prototype,Symbol.toStringTag,{configurable:!0,value:"ModelContext"});for(const e of["registerTool","getTools","executeTool","ontoolchange"]){const t=Object.getOwnPropertyDescriptor(lt.prototype,e);t&&Object.defineProperty(lt.prototype,e,{...t,enumerable:!0})}var fo,Ta,yS=(Ta=class extends EventTarget{constructor(t){super();R(this,"_ontoolchange",null);R(this,"ontoolchangeListener",t=>{var o;(o=this._ontoolchange)==null||o.call(this,t)});pt(this,fo);zt(this,fo,t)}listTools(){return lt.getToolInfos(ne(this,fo))}executeTool(t,o,n){return lt.executeToolForTesting(ne(this,fo),t,o,n)}get ontoolchange(){return this._ontoolchange}set ontoolchange(t){const o=typeof t=="function"?t:null;if(o===null){this._ontoolchange=null,super.removeEventListener("toolchange",this.ontoolchangeListener);return}this._ontoolchange===null&&super.addEventListener("toolchange",this.ontoolchangeListener),this._ontoolchange=o}dispatchToolChange(){this.dispatchEvent(new Event("toolchange"))}dispose(){this.ontoolchange=null}},fo=new WeakMap,Ta);function bS(e,t){if(!e||typeof e!="object")throw new TypeError("registerTool(tool) requires a tool object");const o=Ru(e);if($u(o),t.has(o.name))throw De(`Tool already registered: ${o.name}`);const n=o.inputSchema===void 0?void 0:Sr(o.inputSchema);return{name:o.name,...o.title===void 0?{}:{title:o.title},description:o.description,...o.inputSchema===void 0?{}:{inputSchema:o.inputSchema},...o.annotations===void 0?{}:{annotations:o.annotations},execute:r=>Reflect.apply(o.execute,void 0,[r]),...n!==void 0?{[sr]:n}:{}}}let _r=!1;const ju=new WeakMap,{modelContext:Zu}={modelContext(){if(!(this instanceof Document))throw new TypeError("Illegal invocation");return ju.get(this)}};Object.defineProperty(Zu,"name",{value:"get modelContext"});function Gi(e,t){ju.set(e,t),!Object.hasOwn(Document.prototype,"modelContext")&&$o(Document.prototype,"modelContext",{configurable:!0,enumerable:!0,get:Zu})}function RS(e,t){$o(e,"modelContext",{configurable:!0,enumerable:!0,get(){return _r||(_r=!0,console.warn("[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document — use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.")),t}})}function wS(){const e=SubmitEvent.prototype;"agentInvoked"in e||$o(e,"agentInvoked",{configurable:!0,enumerable:!0,get(){return Iu(this)}}),"respondWith"in e||$o(e,"respondWith",{configurable:!0,enumerable:!0,writable:!0,value(t){Kg(this,t)}})}function TS(e){if(globalThis.isSecureContext===!1)return;const t=typeof navigator>"u"?null:navigator,o=typeof document>"u"?null:document;if(!t||!o||typeof window>"u"||o.modelContext)return;const n=t.modelContext;if(vr.length>0&&Du(),n){Gi(o,n);return}const r=Object.getOwnPropertyDescriptor(window,"ModelContext");if(r&&!r.configurable){if(!Object.is(Reflect.get(window,"ModelContext"),Eo))throw new TypeError("Cannot install ModelContext over a non-configurable global")}else $o(window,"ModelContext",{configurable:!0,enumerable:!1,writable:!0,value:Eo});const s=new lt(o);ir=s,Gi(o,s),_r=!1,RS(t,s),wS(),e!=null&&e.installTestingShim&&!t.modelContextTesting&&$o(t,"modelContextTesting",{configurable:!0,enumerable:!0,writable:!1,value:lt.getTestingShim(s)}),hn=vS(o,s)}function Du(){hn==null||hn(),hn=null,ir&&lt.dispose(ir),ir=null;for(const{target:e,key:t,previous:o}of[...vr].reverse())o?Object.defineProperty(e,t,o):Reflect.deleteProperty(e,t);vr.length=0,_r=!1}var $S=Object.create,ri=Object.defineProperty,ES=Object.getOwnPropertyDescriptor,PS=Object.getOwnPropertyNames,CS=Object.getPrototypeOf,kS=Object.prototype.hasOwnProperty,OS=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),IS=(e,t)=>{let o={};for(var n in e)ri(o,n,{get:e[n],enumerable:!0});return o},qS=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var r=PS(t),s=0,i=r.length,a;s<i;s++)a=r[s],!kS.call(e,a)&&a!==o&&ri(e,a,{get:(l=>t[l]).bind(null,a),enumerable:!(n=ES(t,a))||n.enumerable});return e},NS=(e,t,o)=>(o=e!=null?$S(CS(e)):{},qS(ri(o,"default",{value:e,enumerable:!0}),e));const MS=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),Hu=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),xS=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),zS=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function AS(e){return typeof e=="string"&&Hu.has(e.replace(/#$/,""))}function LS(e,t){if(!("$schema"in e)||typeof e.$schema!="string")return"2020-12";const o=e.$schema.replace(/#$/,"");if(MS.has(o))return"2020-12";if(Hu.has(o))return"2019-09";if(xS.has(o)||zS.has(o))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 us=Symbol.for("mcp.sdk.errorBrands");function Uu(e,t){const o=new Set;let n=t;for(;typeof n=="function";){const r=n.mcpBrand;Object.prototype.hasOwnProperty.call(n,"mcpBrand")&&typeof r=="string"&&o.add(r),n=Object.getPrototypeOf(n)}o.size!==0&&Object.defineProperty(e,us,{value:o,enumerable:!1,configurable:!0})}function yr(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,us)){const o=t[us];if(o&&typeof o.has=="function"&&o.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}let K=(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 go,B=(go=class extends Error{static[Symbol.hasInstance](t){return yr(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 yr(this,t)}constructor(t,o,n){super(o),this.code=t,this.data=n,this.name="SdkError",Uu(this,new.target)}},Object.defineProperty(go,"mcpBrand",{value:"mcp.SdkError"}),go);function Yi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function jS(e,t,o){return e==="elicitation"&&t==="form"&&o.form===void 0&&o.url===void 0}function ZS(e){var t;switch(e.method){case"elicitation/create":return((t=e.params)==null?void 0:t.mode)==="url"?{elicitation:{url:{}}}:{elicitation:{form:{}}};case"sampling/createMessage":{const o=e.params;return o!==void 0&&(o.tools!==void 0||o.toolChoice!==void 0)?{sampling:{tools:{}}}:{sampling:{}}}case"roots/list":return{roots:{}};default:return}}function Vu(e,t){const o={};for(const[n,r]of Object.entries(e)){if(r===void 0)continue;const s=t===void 0?void 0:t[n];if(s===void 0){o[n]=r;continue}if(Yi(r)&&Yi(s)){const i={};for(const[a,l]of Object.entries(r))l!==void 0&&s[a]===void 0&&!jS(n,a,s)&&(i[a]=l);Object.keys(i).length>0&&(o[n]=i)}}return Object.keys(o).length>0?o:void 0}const DS="2026-07-28";function jr(e){return e>=DS}function HS(e){return e.filter(t=>!jr(t))}function Ki(e){return e.filter(t=>jr(t))}function Fu(e){var o;const t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(((o=e.content)==null?void 0:o.some(n=>n.type==="text"))??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}const Ju=["task","inputRequests","requestState"];function Bu(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||Ju.some(t=>t in e)?e:{...e,content:[]}}function US(){const e=Es(()=>I([c(),y(),O(),bn(),E(c(),e),f(e)])),t=E(c(),e),o=I([c(),y().int()]),n=c(),r=p({ttl:y().optional()}),s=p({taskId:c()}),i=Z({progressToken:o.optional(),"io.modelcontextprotocol/related-task":s.optional()}),a=p({_meta:i.optional()}),l=a.extend({task:r.optional()}),u=p({method:c(),params:a.loose().optional()}),d=p({_meta:i.optional()}),m=p({method:c(),params:d.loose().optional()}),h=Z({_meta:i.optional()}),S=I([c(),y().int()]),_=h.strict(),T=d.extend({requestId:S.optional(),reason:c().optional()}),b=m.extend({method:g("notifications/cancelled"),params:T}),N=p({src:c(),mimeType:c().optional(),sizes:f(c()).optional(),theme:F(["light","dark"]).optional()}),L=p({icons:f(N).optional()}),w=p({name:c(),title:c().optional()}),q=w.extend({...w.shape,...L.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),W=Jt(p({applyDefaults:O().optional()}),t),V=Rn(we=>we&&typeof we=="object"&&!Array.isArray(we)&&Object.keys(we).length===0?{form:{}}:we,Jt(p({form:W.optional(),url:t.optional()}),t.optional())),Q=Z({list:t.optional(),cancel:t.optional(),requests:Z({sampling:Z({createMessage:t.optional()}).optional(),elicitation:Z({create:t.optional()}).optional()}).optional()}),X=Z({list:t.optional(),cancel:t.optional(),requests:Z({tools:Z({call:t.optional()}).optional()}).optional()}),G=p({experimental:E(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:V.optional(),roots:p({listChanged:O().optional()}).optional(),tasks:Q.optional(),extensions:E(c(),t).optional()}),Y=a.extend({protocolVersion:c(),capabilities:G,clientInfo:q}),te=u.extend({method:g("initialize"),params:Y}),pe=p({experimental:E(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:O().optional()}).optional(),resources:p({subscribe:O().optional(),listChanged:O().optional()}).optional(),tools:p({listChanged:O().optional()}).optional(),tasks:X.optional(),extensions:E(c(),t).optional()}),ue=h.extend({protocolVersion:c(),capabilities:pe,serverInfo:q,instructions:c().optional()}),oe=m.extend({method:g("notifications/initialized"),params:d.optional()}),ve=u.extend({method:g("ping"),params:a.optional()}),Se=p({progress:y(),total:z(y()),message:z(c())}),_e=p({...d.shape,...Se.shape,progressToken:o}),Ue=m.extend({method:g("notifications/progress"),params:_e}),tt=a.extend({cursor:n.optional()}),ze=u.extend({params:tt.optional()}),Ee=h.extend({nextCursor:n.optional()}),ut=p({uri:c(),mimeType:z(c()),_meta:E(c(),A()).optional()}),dt=ut.extend({text:c()}),ot=c().refine(we=>{try{return atob(we),!0}catch{return!1}},{message:"Invalid Base64 string"}),be=ut.extend({blob:ot}),Pe=F(["user","assistant"]),Ce=p({audience:f(Pe).optional(),priority:y().min(0).max(1).optional(),lastModified:Cn({offset:!0}).optional()}),Ge=p({...w.shape,...L.shape,uri:c(),description:z(c()),mimeType:z(c()),size:z(y()),annotations:Ce.optional(),_meta:z(Z({}))}),$t=p({...w.shape,...L.shape,uriTemplate:c(),description:z(c()),mimeType:z(c()),annotations:Ce.optional(),_meta:z(Z({}))}),Ae=ze.extend({method:g("resources/list")}),Le=Ee.extend({resources:f(Ge)}),Oe=ze.extend({method:g("resources/templates/list")}),Ve=Ee.extend({resourceTemplates:f($t)}),Fe=a.extend({uri:c()}),nt=Fe,rt=u.extend({method:g("resources/read"),params:nt}),St=h.extend({contents:f(I([dt,be]))}),st=m.extend({method:g("notifications/resources/list_changed"),params:d.optional()}),Et=Fe,C=u.extend({method:g("resources/subscribe"),params:Et}),it=Fe,j=u.extend({method:g("resources/unsubscribe"),params:it}),M=d.extend({uri:c()}),J=m.extend({method:g("notifications/resources/updated"),params:M}),k=p({name:c(),description:z(c()),required:z(O())}),$=p({...w.shape,...L.shape,description:z(c()),arguments:z(f(k)),_meta:z(Z({}))}),H=ze.extend({method:g("prompts/list")}),D=Ee.extend({prompts:f($)}),me=a.extend({name:c(),arguments:E(c(),c()).optional()}),Pt=u.extend({method:g("prompts/get"),params:me}),at=p({type:g("text"),text:c(),annotations:Ce.optional(),_meta:E(c(),A()).optional()}),Ct=p({type:g("image"),data:ot,mimeType:c(),annotations:Ce.optional(),_meta:E(c(),A()).optional()}),kt=p({type:g("audio"),data:ot,mimeType:c(),annotations:Ce.optional(),_meta:E(c(),A()).optional()}),xo=p({type:g("tool_use"),name:c(),id:c(),input:E(c(),A()),_meta:E(c(),A()).optional()}),vt=p({type:g("resource"),resource:I([dt,be]),annotations:Ce.optional(),_meta:E(c(),A()).optional()}),zo=Ge.extend({type:g("resource_link")}),Je=I([at,Ct,kt,zo,vt]),Kt=p({role:Pe,content:Je}),Xt=h.extend({description:c().optional(),messages:f(Kt)}),Ot=m.extend({method:g("notifications/prompts/list_changed"),params:d.optional()}),Ao=p({title:c().optional(),readOnlyHint:O().optional(),destructiveHint:O().optional(),idempotentHint:O().optional(),openWorldHint:O().optional()}),Qt=p({taskSupport:F(["required","optional","forbidden"]).optional()}),It=p({...w.shape,...L.shape,description:c().optional(),inputSchema:p({type:g("object"),properties:E(c(),e).optional(),required:f(c()).optional()}).catchall(A()),outputSchema:p({type:g("object"),properties:E(c(),e).optional(),required:f(c()).optional()}).catchall(A()).optional(),annotations:Ao.optional(),execution:Qt.optional(),_meta:E(c(),A()).optional()}),eo=ze.extend({method:g("tools/list")}),to=Ee.extend({tools:f(It)}),oo=h.extend({content:f(Je),structuredContent:E(c(),A()).optional(),isError:O().optional()}),Re=l.extend({name:c(),arguments:E(c(),A()).optional()}),Lo=u.extend({method:g("tools/call"),params:Re}),qn=m.extend({method:g("notifications/tools/list_changed"),params:d.optional()}),no=F(["debug","info","notice","warning","error","critical","alert","emergency"]),jo=a.extend({level:no}),Zo=u.extend({method:g("logging/setLevel"),params:jo}),Do=d.extend({level:no,logger:c().optional(),data:A()}),Ho=m.extend({method:g("notifications/message"),params:Do}),Uo=p({name:c().optional()}),Vo=p({hints:f(Uo).optional(),costPriority:y().min(0).max(1).optional(),speedPriority:y().min(0).max(1).optional(),intelligencePriority:y().min(0).max(1).optional()}),Fo=p({mode:F(["auto","required","none"]).optional()}),Nn=p({type:g("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:f(Je),structuredContent:p({}).loose().optional(),isError:O().optional(),_meta:E(c(),A()).optional()}),Jo=mr("type",[at,Ct,kt]),_t=mr("type",[at,Ct,kt,xo,Nn]),Bo=p({role:Pe,content:I([_t,f(_t)]),_meta:E(c(),A()).optional()}),Wo=l.extend({messages:f(Bo),modelPreferences:Vo.optional(),systemPrompt:c().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:y().optional(),maxTokens:y().int(),stopSequences:f(c()).optional(),metadata:t.optional(),tools:f(It).optional(),toolChoice:Fo.optional()}),Go=u.extend({method:g("sampling/createMessage"),params:Wo}),Yo=h.extend({model:c(),stopReason:z(F(["endTurn","stopSequence","maxTokens"]).or(c())),role:Pe,content:Jo}),Ko=h.extend({model:c(),stopReason:z(F(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Pe,content:I([_t,f(_t)])}),Xo=p({type:g("boolean"),title:c().optional(),description:c().optional(),default:O().optional()}),Qo=p({type:g("string"),title:c().optional(),description:c().optional(),minLength:y().optional(),maxLength:y().optional(),format:F(["email","uri","date","date-time"]).optional(),default:c().optional()}),en=p({type:F(["number","integer"]),title:c().optional(),description:c().optional(),minimum:y().optional(),maximum:y().optional(),default:y().optional()}),tn=p({type:g("string"),title:c().optional(),description:c().optional(),enum:f(c()),default:c().optional()}),on=p({type:g("string"),title:c().optional(),description:c().optional(),oneOf:f(p({const:c(),title:c()})),default:c().optional()}),nn=p({type:g("string"),title:c().optional(),description:c().optional(),enum:f(c()),enumNames:f(c()).optional(),default:c().optional()}),rn=I([tn,on]),qt=p({type:g("array"),title:c().optional(),description:c().optional(),minItems:y().optional(),maxItems:y().optional(),items:p({type:g("string"),enum:f(c())}),default:f(c()).optional()}),Nt=p({type:g("array"),title:c().optional(),description:c().optional(),minItems:y().optional(),maxItems:y().optional(),items:p({anyOf:f(p({const:c(),title:c()}))}),default:f(c()).optional()}),Mn=I([qt,Nt]),xn=I([nn,rn,Mn]),je=I([xn,Xo,Qo,en]),Ze=l.extend({mode:g("form").optional(),message:c(),requestedSchema:p({type:g("object"),properties:E(c(),je),required:f(c()).optional()}).catchall(A())}),sn=l.extend({mode:g("url"),message:c(),elicitationId:c(),url:c().url()}),Ye=I([Ze,sn]),zn=u.extend({method:g("elicitation/create"),params:Ye}),An=d.extend({elicitationId:c()}),Ln=m.extend({method:g("notifications/elicitation/complete"),params:An}),jn=h.extend({action:F(["accept","decline","cancel"]),content:Rn(we=>we===null?void 0:we,E(c(),I([c(),y(),O(),f(c())])).optional())}),Zn=p({type:g("ref/resource"),uri:c()}),Dn=p({type:g("ref/prompt"),name:c()}),Hn=a.extend({ref:I([Dn,Zn]),argument:p({name:c(),value:c()}),context:p({arguments:E(c(),c()).optional()}).optional()}),an=u.extend({method:g("completion/complete"),params:Hn}),Un=h.extend({completion:Z({values:f(c()).max(100),total:z(y().int()),hasMore:z(O())})}),Vn=p({uri:c().startsWith("file://"),name:c().optional(),_meta:E(c(),A()).optional()}),ro=u.extend({method:g("roots/list"),params:a.optional()}),cn=h.extend({roots:f(Vn)}),Fn=m.extend({method:g("notifications/roots/list_changed"),params:d.optional()}),Jn=Z({ttl:y().optional(),pollInterval:y().optional()}),Bn=F(["working","input_required","completed","failed","cancelled"]),yt=p({taskId:c(),status:Bn,ttl:I([y(),bn()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:z(y()),statusMessage:z(c())}),Ie=h.extend({task:yt}),Wn=d.merge(yt),Mt=m.extend({method:g("notifications/tasks/status"),params:Wn}),so=u.extend({method:g("tasks/get"),params:a.extend({taskId:c()})}),io=h.merge(yt),ao=u.extend({method:g("tasks/result"),params:a.extend({taskId:c()})}),Dr=h.loose(),qe=ze.extend({method:g("tasks/list")}),de=Ee.extend({tasks:f(yt)}),xt=u.extend({method:g("tasks/cancel"),params:a.extend({taskId:c()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:o,CursorSchema:n,TaskMetadataSchema:r,RelatedTaskMetadataSchema:s,RequestMetaSchema:i,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:l,RequestSchema:u,NotificationsParamsSchema:d,NotificationSchema:m,ResultSchema:h,RequestIdSchema:S,EmptyResultSchema:_,CancelledNotificationParamsSchema:T,CancelledNotificationSchema:b,IconSchema:N,IconsSchema:L,BaseMetadataSchema:w,ImplementationSchema:q,ClientTasksCapabilitySchema:Q,ServerTasksCapabilitySchema:X,ClientCapabilitiesSchema:G,InitializeRequestParamsSchema:Y,InitializeRequestSchema:te,ServerCapabilitiesSchema:pe,InitializeResultSchema:ue,InitializedNotificationSchema:oe,PingRequestSchema:ve,ProgressSchema:Se,ProgressNotificationParamsSchema:_e,ProgressNotificationSchema:Ue,PaginatedRequestParamsSchema:tt,PaginatedRequestSchema:ze,PaginatedResultSchema:Ee,ResourceContentsSchema:ut,TextResourceContentsSchema:dt,BlobResourceContentsSchema:be,RoleSchema:Pe,AnnotationsSchema:Ce,ResourceSchema:Ge,ResourceTemplateSchema:$t,ListResourcesRequestSchema:Ae,ListResourcesResultSchema:Le,ListResourceTemplatesRequestSchema:Oe,ListResourceTemplatesResultSchema:Ve,ResourceRequestParamsSchema:Fe,ReadResourceRequestParamsSchema:nt,ReadResourceRequestSchema:rt,ReadResourceResultSchema:St,ResourceListChangedNotificationSchema:st,SubscribeRequestParamsSchema:Et,SubscribeRequestSchema:C,UnsubscribeRequestParamsSchema:it,UnsubscribeRequestSchema:j,ResourceUpdatedNotificationParamsSchema:M,ResourceUpdatedNotificationSchema:J,PromptArgumentSchema:k,PromptSchema:$,ListPromptsRequestSchema:H,ListPromptsResultSchema:D,GetPromptRequestParamsSchema:me,GetPromptRequestSchema:Pt,TextContentSchema:at,ImageContentSchema:Ct,AudioContentSchema:kt,ToolUseContentSchema:xo,EmbeddedResourceSchema:vt,ResourceLinkSchema:zo,ContentBlockSchema:Je,PromptMessageSchema:Kt,GetPromptResultSchema:Xt,PromptListChangedNotificationSchema:Ot,ToolAnnotationsSchema:Ao,ToolExecutionSchema:Qt,ToolSchema:It,ListToolsRequestSchema:eo,ListToolsResultSchema:to,CallToolResultSchema:oo,CallToolRequestParamsSchema:Re,CallToolRequestSchema:Lo,ToolListChangedNotificationSchema:qn,LoggingLevelSchema:no,SetLevelRequestParamsSchema:jo,SetLevelRequestSchema:Zo,LoggingMessageNotificationParamsSchema:Do,LoggingMessageNotificationSchema:Ho,ModelHintSchema:Uo,ModelPreferencesSchema:Vo,ToolChoiceSchema:Fo,ToolResultContentSchema:Nn,SamplingContentSchema:Jo,SamplingMessageContentBlockSchema:_t,SamplingMessageSchema:Bo,CreateMessageRequestParamsSchema:Wo,CreateMessageRequestSchema:Go,CreateMessageResultSchema:Yo,CreateMessageResultWithToolsSchema:Ko,BooleanSchemaSchema:Xo,StringSchemaSchema:Qo,NumberSchemaSchema:en,UntitledSingleSelectEnumSchemaSchema:tn,TitledSingleSelectEnumSchemaSchema:on,LegacyTitledEnumSchemaSchema:nn,SingleSelectEnumSchemaSchema:rn,UntitledMultiSelectEnumSchemaSchema:qt,TitledMultiSelectEnumSchemaSchema:Nt,MultiSelectEnumSchemaSchema:Mn,EnumSchemaSchema:xn,PrimitiveSchemaDefinitionSchema:je,ElicitRequestFormParamsSchema:Ze,ElicitRequestURLParamsSchema:sn,ElicitRequestParamsSchema:Ye,ElicitRequestSchema:zn,ElicitationCompleteNotificationParamsSchema:An,ElicitationCompleteNotificationSchema:Ln,ElicitResultSchema:jn,ResourceTemplateReferenceSchema:Zn,PromptReferenceSchema:Dn,CompleteRequestParamsSchema:Hn,CompleteRequestSchema:an,CompleteResultSchema:Un,RootSchema:Vn,ListRootsRequestSchema:ro,ListRootsResultSchema:cn,RootsListChangedNotificationSchema:Fn,TaskCreationParamsSchema:Jn,TaskStatusSchema:Bn,TaskSchema:yt,CreateTaskResultSchema:Ie,TaskStatusNotificationParamsSchema:Wn,TaskStatusNotificationSchema:Mt,GetTaskRequestSchema:so,GetTaskResultSchema:io,GetTaskPayloadRequestSchema:ao,GetTaskPayloadResultSchema:Dr,ListTasksRequestSchema:qe,ListTasksResultSchema:de,CancelTaskRequestSchema:xt,CancelTaskResultSchema:h.merge(yt),ClientRequestSchema:I([ve,te,an,Zo,Pt,H,Ae,Oe,rt,C,j,Lo,eo,so,ao,qe,xt]),ClientNotificationSchema:I([b,Ue,oe,Fn,Mt]),ClientResultSchema:I([_,Yo,Ko,jn,cn,io,de,Ie]),ServerRequestSchema:I([ve,Go,zn,ro,so,ao,qe,xt]),ServerNotificationSchema:I([b,Ue,Ho,J,st,qn,Ot,Mt,Ln]),ServerResultSchema:I([_,ue,Un,Xt,D,Le,Ve,St,oo,to,io,de,Ie]),CallToolResultWireSchema:A().superRefine((we,_d)=>{if(!(typeof we!="object"||we===null||Array.isArray(we)||we.content!==void 0)){for(const pi of Ju)if(pi in we){_d.addIssue({code:"custom",message:`content is required when the body carries '${pi}' — another result family cannot default into an empty tools/call success`});return}}}).transform(Bu).pipe(oo)}}let VS;function Wu(){return VS??(VS=US())}function Gu(e){return e.type!=="object"}const FS=new Set(["const","enum","default","examples"]),JS=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function Xi(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}function BS(e){const t=typeof e.$schema=="string"?e.$schema:void 0;if(Xi(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};const o=AS(e.$schema)&&e.$recursiveAnchor!==!0,n=(r,s)=>{if(Array.isArray(r))return r.map(l=>n(l,!1));if(r===null||typeof r!="object"||!s&&Xi(r.$id))return r;const i={};let a=!1;for(const[l,u]of Object.entries(r))s?i[l]=n(u,!1):(l==="$ref"||l==="$dynamicRef")&&typeof u=="string"?i[l]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u:l==="$recursiveRef"&&u==="#"&&o?a=!0:FS.has(l)?i[l]=u:JS.has(l)?i[l]=n(u,!0):i[l]=n(u,!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:n(e,!1)},required:["result"]}}const WS={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},GS={"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},YS={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 si(){if(er)return er;const e=Wu();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 Yu(e){return Object.prototype.hasOwnProperty.call(WS,e)}function Ku(e){return Object.prototype.hasOwnProperty.call(GS,e)}function KS(e){return Object.prototype.hasOwnProperty.call(YS,e)}function XS(e){return KS(e)?si().resultSchemas[e]:void 0}function QS(e){return Yu(e)?si().requestSchemas[e]:void 0}function ev(e){return Ku(e)?si().notificationSchemas[e]:void 0}function ds(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 o=e.safeParse(t);return o.success?{ok:!0,value:o.data}:{ok:!1,reason:"invalid",message:String(o.error)}}const Qi={ok:!1,reason:"not-in-era"};function ea(e){return ds(e)&&ds(e.outputSchema)&&Gu(e.outputSchema)}const ii={era:"2025-11-25",hasRequestMethod:Yu,hasNotificationMethod:Ku,validateRequest:(e,t)=>tr(QS(e),t),validateResult:(e,t)=>tr(XS(e),t),validateNotification:(e,t)=>tr(ev(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>Qi,validateInputResponse:()=>Qi,samplingResultVariant:((e,t)=>{const o=Wu();return tr(e?o.CreateMessageResultWithToolsSchema:o.CreateMessageResultSchema,t)}),outboundEnvelope:e=>{},validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){const o=Fu(e),n=o.structuredContent;if(n===void 0)return o;const r=typeof n!="object"||n===null||Array.isArray(n),s=t!==void 0&&Gu(t);return!r&&!s?o:{...o,structuredContent:{result:n}}},decodeResult(e,t){if(ds(t)&&"resultType"in t){const o={...t};return delete o.resultType,{kind:"complete",result:o}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;const o=t.tools;return!Array.isArray(o)||!o.some(n=>ea(n))?t:{...t,tools:o.map(n=>ea(n)?{...n,outputSchema:BS(n.outputSchema)}:n)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>{}};function tv(){const e=Es(()=>I([c(),y(),O(),bn(),E(c(),e),f(e)])),t=E(c(),e),o=I([c(),y().int()]),n=c(),r=I([c(),y().int()]),s=F(["user","assistant"]),i=F(["debug","info","notice","warning","error","critical","alert","emergency"]),a=c().refine(de=>{try{return atob(de),!0}catch{return!1}},{message:"Invalid Base64 string"}),l=p({ttl:y().optional()}),u=p({taskId:c()}),d=Z({progressToken:o.optional(),"io.modelcontextprotocol/related-task":u.optional()}),m=p({_meta:d.optional()}),h=m.extend({task:l.optional()}),S=p({_meta:d.optional()}),_=p({method:c(),params:S.loose().optional()}),T=p({src:c(),mimeType:c().optional(),sizes:f(c()).optional(),theme:F(["light","dark"]).optional()}),b=p({icons:f(T).optional()}),N=p({name:c(),title:c().optional()}),L=N.extend({...N.shape,...b.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),w=Jt(p({applyDefaults:O().optional()}),t),q=Rn(de=>de&&typeof de=="object"&&!Array.isArray(de)&&Object.keys(de).length===0?{form:{}}:de,Jt(p({form:w.optional(),url:t.optional()}),t.optional())),W=Z({list:t.optional(),cancel:t.optional(),requests:Z({sampling:Z({createMessage:t.optional()}).optional(),elicitation:Z({create:t.optional()}).optional()}).optional()}),V=Z({list:t.optional(),cancel:t.optional(),requests:Z({tools:Z({call:t.optional()}).optional()}).optional()}),Q=p({experimental:E(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:q.optional(),roots:p({listChanged:O().optional()}).optional(),tasks:W.optional(),extensions:E(c(),t).optional()}),X=p({experimental:E(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:O().optional()}).optional(),resources:p({subscribe:O().optional(),listChanged:O().optional()}).optional(),tools:p({listChanged:O().optional()}).optional(),tasks:V.optional(),extensions:E(c(),t).optional()}),G=p({progress:y(),total:z(y()),message:z(c())}),Y=p({...S.shape,...G.shape,progressToken:o}),te=_.extend({method:g("notifications/progress"),params:Y}),pe=S.extend({level:i,logger:c().optional(),data:A()}),ue=_.extend({method:g("notifications/message"),params:pe}),oe=p({uri:c(),mimeType:z(c()),_meta:E(c(),A()).optional()}),ve=oe.extend({text:c()}),Se=oe.extend({blob:a}),_e=p({audience:f(s).optional(),priority:y().min(0).max(1).optional(),lastModified:Cn({offset:!0}).optional()}),Ue=p({...N.shape,...b.shape,uri:c(),description:z(c()),mimeType:z(c()),size:z(y()),annotations:_e.optional(),_meta:z(Z({}))}),tt=p({...N.shape,...b.shape,uriTemplate:c(),description:z(c()),mimeType:z(c()),annotations:_e.optional(),_meta:z(Z({}))}),ze=_.extend({method:g("notifications/resources/list_changed"),params:S.optional()}),Ee=S.extend({uri:c()}),ut=_.extend({method:g("notifications/resources/updated"),params:Ee}),dt=p({name:c(),description:z(c()),required:z(O())}),ot=p({...N.shape,...b.shape,description:z(c()),arguments:z(f(dt)),_meta:z(Z({}))}),be=_.extend({method:g("notifications/prompts/list_changed"),params:S.optional()}),Pe=p({type:g("text"),text:c(),annotations:_e.optional(),_meta:E(c(),A()).optional()}),Ce=p({type:g("image"),data:a,mimeType:c(),annotations:_e.optional(),_meta:E(c(),A()).optional()}),Ge=p({type:g("audio"),data:a,mimeType:c(),annotations:_e.optional(),_meta:E(c(),A()).optional()}),$t=p({type:g("tool_use"),name:c(),id:c(),input:E(c(),A()),_meta:E(c(),A()).optional()}),Ae=p({type:g("resource"),resource:I([ve,Se]),annotations:_e.optional(),_meta:E(c(),A()).optional()}),Le=Ue.extend({type:g("resource_link")}),Oe=I([Pe,Ce,Ge,Le,Ae]),Ve=p({role:s,content:Oe}),Fe=p({title:c().optional(),readOnlyHint:O().optional(),destructiveHint:O().optional(),idempotentHint:O().optional(),openWorldHint:O().optional()}),nt=_.extend({method:g("notifications/tools/list_changed"),params:S.optional()}),rt=p({name:c().optional()}),St=p({hints:f(rt).optional(),costPriority:y().min(0).max(1).optional(),speedPriority:y().min(0).max(1).optional(),intelligencePriority:y().min(0).max(1).optional()}),st=p({mode:F(["auto","required","none"]).optional()}),Et=p({type:g("boolean"),title:c().optional(),description:c().optional(),default:O().optional()}),C=p({type:g("string"),title:c().optional(),description:c().optional(),minLength:y().optional(),maxLength:y().optional(),format:F(["email","uri","date","date-time"]).optional(),default:c().optional()}),it=p({type:F(["number","integer"]),title:c().optional(),description:c().optional(),minimum:y().optional(),maximum:y().optional(),default:y().optional()}),j=p({type:g("string"),title:c().optional(),description:c().optional(),enum:f(c()),default:c().optional()}),M=p({type:g("string"),title:c().optional(),description:c().optional(),oneOf:f(p({const:c(),title:c()})),default:c().optional()}),J=p({type:g("string"),title:c().optional(),description:c().optional(),enum:f(c()),enumNames:f(c()).optional(),default:c().optional()}),k=I([j,M]),$=p({type:g("array"),title:c().optional(),description:c().optional(),minItems:y().optional(),maxItems:y().optional(),items:p({type:g("string"),enum:f(c())}),default:f(c()).optional()}),H=p({type:g("array"),title:c().optional(),description:c().optional(),minItems:y().optional(),maxItems:y().optional(),items:p({anyOf:f(p({const:c(),title:c()}))}),default:f(c()).optional()}),D=I([$,H]),me=I([J,k,D]),Pt=I([me,Et,C,it]),at=h.extend({mode:g("form").optional(),message:c(),requestedSchema:p({type:g("object"),properties:E(c(),Pt),required:f(c()).optional()}).catchall(A())}),Ct=p({type:g("ref/resource"),uri:c()}),kt=p({type:g("ref/prompt"),name:c()}),xo=p({uri:c().startsWith("file://"),name:c().optional(),_meta:E(c(),A()).optional()}),vt=Q.shape,zo=p({experimental:vt.experimental,sampling:vt.sampling,elicitation:vt.elicitation,roots:vt.roots,extensions:vt.extensions}),Je=X.shape,Kt=p({experimental:Je.experimental,logging:Je.logging,completions:Je.completions,prompts:Je.prompts,resources:Je.resources,tools:Je.tools,extensions:Je.extensions}),Xt=Z({progressToken:o.optional(),[Er]:c(),[Ps]:L.optional(),[On]:zo,[Pr]:i.optional()}),Ot=p({...N.shape,...b.shape,description:c().optional(),inputSchema:Z({$schema:c().optional(),type:g("object")}),outputSchema:Z({$schema:c().optional()}).optional(),annotations:Fe.optional(),_meta:E(c(),A()).optional()}),Ao=p({type:g("tool_result"),toolUseId:c(),content:f(Oe),structuredContent:A().optional(),isError:O().optional(),_meta:E(c(),A()).optional()}),Qt=I([Pe,Ce,Ge,$t,Ao]),It=p({role:s,content:I([Qt,f(Qt)]),_meta:E(c(),A()).optional()}),eo=c(),to=Z({[fn]:L.optional().catch(void 0)}),oo=to.optional();function Re(de){return Z({_meta:oo,resultType:eo.default("complete"),...de})}const Lo=Re({}),qn=Re({nextCursor:n.optional()}),no=Re({content:f(Oe),structuredContent:A().optional(),isError:O().optional()}),jo=Re({ttlMs:y().int().min(0),cacheScope:F(["public","private"]),tools:f(Ot),nextCursor:n.optional()}),Zo=Re({ttlMs:y().int().min(0),cacheScope:F(["public","private"]),prompts:f(ot),nextCursor:n.optional()}),Do=Re({description:c().optional(),messages:f(Ve)}),Ho=Re({ttlMs:y().int().min(0),cacheScope:F(["public","private"]),resources:f(Ue),nextCursor:n.optional()}),Uo=Re({ttlMs:y().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:f(tt),nextCursor:n.optional()}),Vo=Re({ttlMs:y().int().min(0),cacheScope:F(["public","private"]),contents:f(I([ve,Se]))}),Fo=Re({completion:p({values:f(c()).max(100),total:y().int().optional(),hasMore:O().optional()}).loose()}),Nn=Re({ttlMs:y().int().min(0),cacheScope:F(["public","private"])}),Jo=Re({ttlMs:y().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:f(c()),capabilities:Kt,instructions:c().optional()}),_t=p({messages:f(It),modelPreferences:St.optional(),systemPrompt:c().optional(),includeContext:F(["none","thisServer","allServers"]).optional(),temperature:y().optional(),maxTokens:y().int(),stopSequences:f(c()).optional(),metadata:t.optional(),tools:f(Ot).optional(),toolChoice:st.optional()}),Bo=p({method:g("sampling/createMessage"),params:_t}),Wo=p({method:g("roots/list"),params:p({_meta:E(c(),A()).optional()}).optional()}),Go=p({...It.shape,model:c(),stopReason:c().optional()}),Yo=p({roots:f(xo)}),Ko=p({action:F(["accept","decline","cancel"]),content:E(c(),I([c(),y(),O(),f(c())])).optional()}),Xo=p({mode:g("url"),message:c(),url:c().url()}),Qo=I([at,Xo]),en=p({method:g("elicitation/create"),params:Qo}),tn=I([Bo,Wo,en]),on=I([Go,Yo,Ko]),nn=E(c(),tn),rn=E(c(),on),qt=Re({inputRequests:nn.optional(),requestState:c().optional()}),Nt={inputResponses:rn.optional(),requestState:c().optional()},Mn=p({_meta:Xt,...Nt}),xn=Z({progressToken:o.optional()});function je(de,xt){return p({method:g(de),params:p({_meta:Xt,...xt})})}function Ze(de,xt){return p({method:g(de),params:p({_meta:xn.optional(),...xt}).optional()})}const sn={name:c(),arguments:E(c(),A()).optional(),...Nt},Ye={cursor:n.optional()},zn=je("tools/call",sn),An=je("tools/list",Ye),Ln=je("prompts/list",Ye),jn=je("prompts/get",{name:c(),arguments:E(c(),c()).optional(),...Nt}),Zn=je("resources/list",Ye),Dn=je("resources/templates/list",Ye),Hn=je("resources/read",{uri:c(),...Nt}),an={ref:I([kt,Ct]),argument:p({name:c(),value:c()}),context:p({arguments:E(c(),c()).optional()}).optional()},Un=je("completion/complete",an),Vn=je("server/discover",{}),ro=p({toolsListChanged:O().optional(),promptsListChanged:O().optional(),resourcesListChanged:O().optional(),resourceSubscriptions:f(c()).optional()}),cn={notifications:ro},Fn=je("subscriptions/listen",cn),Jn=to.extend({"io.modelcontextprotocol/subscriptionId":r}),Bn=Z({_meta:Jn,resultType:eo.default("complete")}),yt={"tools/call":Ze("tools/call",sn),"tools/list":Ze("tools/list",Ye),"prompts/get":Ze("prompts/get",{name:c(),arguments:E(c(),c()).optional()}),"prompts/list":Ze("prompts/list",Ye),"resources/list":Ze("resources/list",Ye),"resources/templates/list":Ze("resources/templates/list",Ye),"resources/read":Ze("resources/read",{uri:c()}),"completion/complete":Ze("completion/complete",an),"server/discover":Ze("server/discover",{}),"subscriptions/listen":Ze("subscriptions/listen",cn)};function Ie(de){return Z({_meta:oo,...de})}const Wn={"tools/call":Ie({content:f(Oe),structuredContent:A().optional(),isError:O().optional()}),"tools/list":Ie({ttlMs:y().int().min(0),cacheScope:F(["public","private"]),tools:f(Ot),nextCursor:n.optional()}),"prompts/get":Ie({description:c().optional(),messages:f(Ve)}),"prompts/list":Ie({ttlMs:y().int().min(0),cacheScope:F(["public","private"]),prompts:f(ot),nextCursor:n.optional()}),"resources/list":Ie({ttlMs:y().int().min(0),cacheScope:F(["public","private"]),resources:f(Ue),nextCursor:n.optional()}),"resources/templates/list":Ie({ttlMs:y().int().min(0),cacheScope:F(["public","private"]),resourceTemplates:f(tt),nextCursor:n.optional()}),"resources/read":Ie({ttlMs:y().int().min(0),cacheScope:F(["public","private"]),contents:f(I([ve,Se]))}),"completion/complete":Ie({completion:p({values:f(c()).max(100),total:y().int().optional(),hasMore:O().optional()}).loose()}),"server/discover":Ie({ttlMs:y().int().min(0).catch(0),cacheScope:F(["public","private"]).catch("private"),supportedVersions:f(c()),capabilities:Kt,instructions:c().optional()}),"subscriptions/listen":Ie({})},Mt=Z({"io.modelcontextprotocol/subscriptionId":r.optional()}),so=p({method:g("notifications/subscriptions/acknowledged"),params:p({_meta:Mt.optional(),notifications:ro})}),io=p({_meta:Mt.optional(),requestId:r,reason:c().optional()}),ao=p({method:g("notifications/cancelled"),params:io}),Dr={"notifications/cancelled":ao,"notifications/progress":te,"notifications/message":ue,"notifications/resources/updated":ut,"notifications/resources/list_changed":ze,"notifications/tools/list_changed":nt,"notifications/prompts/list_changed":be,"notifications/subscriptions/acknowledged":so},qe=de=>p({jsonrpc:g("2.0"),id:I([c(),y().int()]),result:de}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:o,CursorSchema:n,RequestIdSchema:r,RoleSchema:s,LoggingLevelSchema:i,TaskMetadataSchema:l,RelatedTaskMetadataSchema:u,RequestMetaSchema:d,BaseRequestParamsSchema:m,TaskAugmentedRequestParamsSchema:h,NotificationsParamsSchema:S,NotificationSchema:_,IconSchema:T,IconsSchema:b,BaseMetadataSchema:N,ImplementationSchema:L,ClientTasksCapabilitySchema:W,ServerTasksCapabilitySchema:V,ClientCapabilitiesSchema:Q,ServerCapabilitiesSchema:X,ProgressSchema:G,ProgressNotificationParamsSchema:Y,ProgressNotificationSchema:te,LoggingMessageNotificationParamsSchema:pe,LoggingMessageNotificationSchema:ue,ResourceContentsSchema:oe,TextResourceContentsSchema:ve,BlobResourceContentsSchema:Se,AnnotationsSchema:_e,ResourceSchema:Ue,ResourceTemplateSchema:tt,ResourceListChangedNotificationSchema:ze,ResourceUpdatedNotificationParamsSchema:Ee,ResourceUpdatedNotificationSchema:ut,PromptArgumentSchema:dt,PromptSchema:ot,PromptListChangedNotificationSchema:be,TextContentSchema:Pe,ImageContentSchema:Ce,AudioContentSchema:Ge,ToolUseContentSchema:$t,EmbeddedResourceSchema:Ae,ResourceLinkSchema:Le,ContentBlockSchema:Oe,PromptMessageSchema:Ve,ToolAnnotationsSchema:Fe,ToolListChangedNotificationSchema:nt,ModelHintSchema:rt,ModelPreferencesSchema:St,ToolChoiceSchema:st,BooleanSchemaSchema:Et,StringSchemaSchema:C,NumberSchemaSchema:it,UntitledSingleSelectEnumSchemaSchema:j,TitledSingleSelectEnumSchemaSchema:M,LegacyTitledEnumSchemaSchema:J,SingleSelectEnumSchemaSchema:k,UntitledMultiSelectEnumSchemaSchema:$,TitledMultiSelectEnumSchemaSchema:H,MultiSelectEnumSchemaSchema:D,EnumSchemaSchema:me,PrimitiveSchemaDefinitionSchema:Pt,ElicitRequestFormParamsSchema:at,ResourceTemplateReferenceSchema:Ct,PromptReferenceSchema:kt,RootSchema:xo,ClientCapabilities2026Schema:zo,ServerCapabilities2026Schema:Kt,RequestMetaEnvelopeSchema:Xt,ToolSchema:Ot,ToolResultContentSchema:Ao,SamplingMessageContentBlockSchema:Qt,SamplingMessageSchema:It,ResultTypeSchema:eo,ResultMetaSchema:to,ResultSchema:Lo,PaginatedResultSchema:qn,CallToolResultSchema:no,ListToolsResultSchema:jo,ListPromptsResultSchema:Zo,GetPromptResultSchema:Do,ListResourcesResultSchema:Ho,ListResourceTemplatesResultSchema:Uo,ReadResourceResultSchema:Vo,CompleteResultSchema:Fo,CacheableResultSchema:Nn,DiscoverResultSchema:Jo,CreateMessageRequestParamsSchema:_t,CreateMessageRequestSchema:Bo,ListRootsRequestSchema:Wo,CreateMessageResultSchema:Go,ListRootsResultSchema:Yo,ElicitResultSchema:Ko,ElicitRequestURLParamsSchema:Xo,ElicitRequestParamsSchema:Qo,ElicitRequestSchema:en,InputRequestSchema:tn,InputResponseSchema:on,InputRequestsSchema:nn,InputResponsesSchema:rn,InputRequiredResultSchema:qt,InputResponseRequestParamsSchema:Mn,CallToolRequestSchema:zn,ListToolsRequestSchema:An,ListPromptsRequestSchema:Ln,GetPromptRequestSchema:jn,ListResourcesRequestSchema:Zn,ListResourceTemplatesRequestSchema:Dn,ReadResourceRequestSchema:Hn,CompleteRequestSchema:Un,DiscoverRequestSchema:Vn,SubscriptionFilterSchema:ro,SubscriptionsListenRequestSchema:Fn,SubscriptionsListenResultMetaSchema:Jn,SubscriptionsListenResultSchema:Bn,dispatchRequestSchemas:yt,dispatchResultSchemas:Wn,NotificationMetaSchema:Mt,SubscriptionsAcknowledgedNotificationSchema:so,CancelledNotificationParamsSchema:io,CancelledNotificationSchema:ao,notificationSchemas2026:Dr,JSONRPCResultResponseSchema:qe(Lo),CallToolResultResponseSchema:qe(I([no,qt])),ListToolsResultResponseSchema:qe(jo),ListPromptsResultResponseSchema:qe(Zo),GetPromptResultResponseSchema:qe(I([Do,qt])),ListResourcesResultResponseSchema:qe(Ho),ListResourceTemplatesResultResponseSchema:qe(Uo),ReadResourceResultResponseSchema:qe(I([Vo,qt])),CompleteResultResponseSchema:qe(Fo),DiscoverResultResponseSchema:qe(Jo)}}let ov;function Wt(){return ov??(ov=tv())}const nv=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function rv(e){return nv.includes(e)}const po=Symbol("modelcontextprotocol.resultCacheHintFallback");function ps(e,t){if(t===void 0)return e;const o=e[po];if(o===void 0)return{...e,[po]:t};const n={},r=o.ttlMs??t.ttlMs;r!==void 0&&(n.ttlMs=r);const s=o.cacheScope??t.cacheScope;return s!==void 0&&(n.cacheScope=s),{...e,[po]:n}}function sv(e){return e[po]}function ai(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function ci(e){return e==="public"||e==="private"}function Xu(e,t){if(e.ttlMs!==void 0&&!ai(e.ttlMs))throw new RangeError(`Invalid cache hint for ${t}: ttlMs must be a non-negative safe integer (got ${String(e.ttlMs)})`);if(e.cacheScope!==void 0&&!ci(e.cacheScope))throw new RangeError(`Invalid cache hint for ${t}: cacheScope must be 'public' or 'private' (got ${String(e.cacheScope)})`)}let P=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({});var Ft,U=(Ft=class extends Error{static[Symbol.hasInstance](t){return yr(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 yr(this,t)}constructor(t,o,n){super(o),this.code=t,this.data=n,this.name="ProtocolError",Uu(this,new.target)}static fromError(t,o,n){if(t===P.UrlElicitationRequired&&n){const r=n;if(r.elicitations)return new iv(r.elicitations,o)}if(t===P.UnsupportedProtocolVersion&&n){const r=n;if(Array.isArray(r.supported)&&typeof r.requested=="string")return new av({supported:r.supported,requested:r.requested},o)}if(t===P.InvalidParams||t===P.ResourceNotFound){const r=n;if(typeof(r==null?void 0:r.uri)=="string"&&(t===P.ResourceNotFound||Object.keys(r).length===1))return new Qu(r.uri,o)}if(t===P.MissingRequiredClientCapability&&n){const r=n;if(r.requiredCapabilities!==null&&typeof r.requiredCapabilities=="object"&&!Array.isArray(r.requiredCapabilities))return new ed({requiredCapabilities:r.requiredCapabilities},o)}return new Ft(t,o,n)}},Object.defineProperty(Ft,"mcpBrand",{value:"mcp.ProtocolError"}),Ft),So,Qu=(So=class extends U{constructor(t,o=`Resource not found: ${t}`){super(P.InvalidParams,o,{uri:t})}get uri(){return this.data.uri}},Object.defineProperty(So,"mcpBrand",{value:"mcp.ResourceNotFoundError"}),So),vo,iv=(vo=class extends U{constructor(t,o=`URL elicitation${t.length>1?"s":""} required`){super(P.UrlElicitationRequired,o,{elicitations:t})}get elicitations(){var t;return((t=this.data)==null?void 0:t.elicitations)??[]}},Object.defineProperty(vo,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"}),vo),_o,av=(_o=class extends U{constructor(t,o=`Unsupported protocol version: ${t.requested}`){super(P.UnsupportedProtocolVersion,o,t)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Object.defineProperty(_o,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"}),_o),yo,ed=(yo=class extends U{constructor(t,o=`Missing required client capabilities: ${Object.keys(t.requiredCapabilities).join(", ")}`){super(P.MissingRequiredClientCapability,o,t)}get requiredCapabilities(){return this.data.requiredCapabilities}},Object.defineProperty(yo,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"}),yo);const cv=0,lv="private",uv=["tools/call","prompts/get","resources/read"];function dv(e,t){const o=t.resultType;if(o===void 0)return{...t,resultType:"complete"};if(o==="complete"||uv.includes(e))return t;throw new U(P.InternalError,`Handler for ${e} returned resultType '${String(o)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function pv(e,t){const o=sv(t);if(t.resultType!=="complete"||!rv(e))return o===void 0?t:Sv(t);const n=t,r=ai(n.ttlMs)?n.ttlMs:fv(o),s=ci(n.cacheScope)?n.cacheScope:gv(o),i={...n,ttlMs:r,cacheScope:s};return delete i[po],i}function mv(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function hv(e,t){if(t===void 0)return e;const o=e._meta;return o===void 0?{...e,_meta:{[fn]:t}}:!mv(o)||o[fn]!==void 0?e:{...e,_meta:{...o,[fn]:t}}}function fv(e){return e!==void 0&&ai(e.ttlMs)?e.ttlMs:cv}function gv(e){return e!==void 0&&ci(e.cacheScope)?e.cacheScope:lv}function Sv(e){const t={...e};return delete t[po],t}const vv=["elicitation/create","sampling/createMessage","roots/list"];let or;function td(){if(or)return or;const e=Wt();return or={request:{"elicitation/create":p({method:g("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":p({method:g("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":p({method:g("roots/list"),params:Z({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},or}function od(e){return vv.includes(e)}function Br(e){return od(e)?td().request[e]:void 0}function _v(e){return od(e)?td().response[e]:void 0}const nd={"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},yv={"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 rd(e){return Object.prototype.hasOwnProperty.call(nd,e)}function sd(e){return Object.prototype.hasOwnProperty.call(yv,e)}function bv(e){return Object.prototype.hasOwnProperty.call(nd,e)}function Rv(e){return rd(e)?Wt().dispatchRequestSchemas[e]:void 0}function wv(e){return bv(e)?Wt().dispatchResultSchemas[e]:void 0}function Tv(e){return sd(e)?Wt().notificationSchemas2026[e]:void 0}function gn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function un(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};const o=e.safeParse(t);return o.success?{ok:!0,value:o.data}:{ok:!1,reason:"invalid",message:String(o.error)}}const $v={ok:!1,reason:"not-in-era"},Ev=[Er,On];function Pv(e,t){let o=t,n=!1;const r=()=>(n||(o={...o},n=!0),o),s=t.tools;e==="tools/list"&&Array.isArray(s)&&s.some(a=>gn(a)&&"execution"in a)&&(r().tools=s.map(a=>{if(!gn(a)||!("execution"in a))return a;const l={...a};return delete l.execution,l}));const i=t.capabilities;if(gn(i)&&"tasks"in i){const a={...i};delete a.tasks,r().capabilities=a}return o}const li={era:"2026-07-28",hasRequestMethod:rd,hasNotificationMethod:sd,hasInputRequestMethod:e=>Br(e)!==void 0,validateRequest:(e,t)=>un(Rv(e),t),validateResult:(e,t)=>un(wv(e),t),validateNotification:(e,t)=>un(Tv(e),t),validateInputRequest:(e,t)=>un(Br(e),t),validateInputResponse:(e,t)=>un(_v(e),t),samplingResultVariant:()=>$v,outboundEnvelope(e){return{[Er]:e.protocolVersion,[Ps]:e.clientInfo,[On]:e.clientCapabilities,...e.logLevel!==void 0&&{[Pr]:e.logLevel}}},validateEnvelopeMeta(e){const t=[];for(const n of Ev)n in e||t.push({key:n,problem:"missing"});const o=Wt().RequestMetaEnvelopeSchema.safeParse(e);if(!o.success)for(const n of o.error.issues){const r=n.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:n.message})}return t},projectCallToolResult:e=>Fu(e),inputRequestSchema:Br,decodeResult(e,t){if(!gn(t))return{kind:"invalid",error:new B(K.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};const o=t.resultType;if(o===void 0)return{kind:"invalid",error:new B(K.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 o!="string")return{kind:"invalid",error:new B(K.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:o})};if(o==="input_required"){const i=t.inputRequests,a=gn(i)?i:{},l=t.requestState;return Object.keys(a).length===0&&typeof l!="string"?{kind:"invalid",error:new B(K.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 l=="string"&&{requestState:l}}}if(o!=="complete")return{kind:"invalid",error:new B(K.UnsupportedResultType,`Unsupported result type '${o}' for ${e}`,{resultType:o,method:e})};const n=Cv(),r=Object.hasOwn(n,e)?n[e]:void 0;if(r!==void 0){const i=r.safeParse(t);if(!i.success)return{kind:"invalid",error:new B(K.InvalidResult,`Invalid result for ${e}: ${i.error}`,{method:e})}}const s={...t};return delete s.resultType,{kind:"complete",result:s}},encodeResult(e,t,o){return hv(pv(e,dv(e,Pv(e,t))),o)},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=Wt().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(o=>o.message).join("; ")}`}};let nr;function Cv(){if(nr)return nr;const e=Wt();return nr={"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},nr}const id="2026-07-28";function $n(e){return e!==void 0&&jr(e)?li:ii}function ta(e){return e.revision!==void 0?$n(e.revision).era:e.era==="modern"?li.era:ii.era}function Wr(e){return ad.some(t=>t.hasRequestMethod(e))}function Gr(e){return ad.some(t=>t.hasNotificationMethod(e))}const ad=[ii,li];var kv=IS({AnnotationsSchema:()=>Yt,AudioContentSchema:()=>xr,BaseMetadataSchema:()=>Bt,BaseRequestParamsSchema:()=>$e,BlobResourceContentsSchema:()=>Us,BooleanSchemaSchema:()=>Ws,CallToolRequestParamsSchema:()=>Ml,CallToolRequestSchema:()=>xl,CallToolResultSchema:()=>Bs,CancelTaskRequestSchema:()=>bg,CancelTaskResultSchema:()=>Rg,CancelledNotificationParamsSchema:()=>Ac,CancelledNotificationSchema:()=>zs,ClientCapabilitiesSchema:()=>Dc,ClientNotificationSchema:()=>Tg,ClientRequestSchema:()=>wg,ClientResultSchema:()=>$g,ClientTasksCapabilitySchema:()=>jc,CompatibilityCallToolResultSchema:()=>ug,CompleteRequestParamsSchema:()=>cu,CompleteRequestSchema:()=>lu,CompleteResultSchema:()=>uu,ContentBlockSchema:()=>zr,CreateMessageRequestParamsSchema:()=>Bl,CreateMessageRequestSchema:()=>Wl,CreateMessageResultSchema:()=>Gl,CreateMessageResultWithToolsSchema:()=>Yl,CreateTaskResultSchema:()=>mg,CursorSchema:()=>ks,DiscoverRequestSchema:()=>Jc,DiscoverResultSchema:()=>Bc,ElicitRequestFormParamsSchema:()=>Lr,ElicitRequestParamsSchema:()=>tu,ElicitRequestSchema:()=>ou,ElicitRequestURLParamsSchema:()=>eu,ElicitResultSchema:()=>su,ElicitationCompleteNotificationParamsSchema:()=>nu,ElicitationCompleteNotificationSchema:()=>ru,EmbeddedResourceSchema:()=>$l,EmptyResultSchema:()=>xs,EnumSchemaSchema:()=>Ql,GetPromptRequestParamsSchema:()=>Rl,GetPromptRequestSchema:()=>wl,GetPromptResultSchema:()=>Cl,GetTaskPayloadRequestSchema:()=>Sg,GetTaskPayloadResultSchema:()=>vg,GetTaskRequestSchema:()=>fg,GetTaskResultSchema:()=>gg,IconSchema:()=>Lc,IconsSchema:()=>Oo,ImageContentSchema:()=>Mr,ImplementationSchema:()=>Ir,InitializeRequestParamsSchema:()=>Hc,InitializeRequestSchema:()=>Uc,InitializeResultSchema:()=>Vc,InitializedNotificationSchema:()=>Fc,JSONArraySchema:()=>ig,JSONObjectSchema:()=>he,JSONRPCErrorResponseSchema:()=>Or,JSONRPCMessageSchema:()=>Ms,JSONRPCNotificationSchema:()=>Ns,JSONRPCRequestSchema:()=>qs,JSONRPCResponseSchema:()=>ag,JSONRPCResultResponseSchema:()=>kr,JSONValueSchema:()=>wo,LegacyTitledEnumSchemaSchema:()=>Ks,ListChangedOptionsBaseSchema:()=>dg,ListPromptsRequestSchema:()=>yl,ListPromptsResultSchema:()=>bl,ListResourceTemplatesRequestSchema:()=>el,ListResourceTemplatesResultSchema:()=>tl,ListResourcesRequestSchema:()=>Xc,ListResourcesResultSchema:()=>Qc,ListRootsRequestSchema:()=>pu,ListRootsResultSchema:()=>mu,ListTasksRequestSchema:()=>_g,ListTasksResultSchema:()=>yg,ListToolsRequestSchema:()=>ql,ListToolsResultSchema:()=>Nl,LoggingLevelSchema:()=>wn,LoggingMessageNotificationParamsSchema:()=>jl,LoggingMessageNotificationSchema:()=>Zl,ModelHintSchema:()=>Dl,ModelPreferencesSchema:()=>Hl,MultiSelectEnumSchemaSchema:()=>Xl,NotificationSchema:()=>xe,NotificationsParamsSchema:()=>Me,NumberSchemaSchema:()=>hr,PaginatedRequestParamsSchema:()=>Yc,PaginatedRequestSchema:()=>Io,PaginatedResultSchema:()=>qo,PingRequestSchema:()=>Ls,PrimitiveSchemaDefinitionSchema:()=>ei,ProgressNotificationParamsSchema:()=>Gc,ProgressNotificationSchema:()=>js,ProgressSchema:()=>Wc,ProgressTokenSchema:()=>Cs,PromptArgumentSchema:()=>vl,PromptListChangedNotificationSchema:()=>kl,PromptMessageSchema:()=>Pl,PromptReferenceSchema:()=>au,PromptSchema:()=>_l,ReadResourceRequestParamsSchema:()=>ol,ReadResourceRequestSchema:()=>nl,ReadResourceResultSchema:()=>rl,RelatedTaskMetadataSchema:()=>zc,RequestIdSchema:()=>ko,RequestMetaSchema:()=>Os,RequestSchema:()=>fe,ResourceContentsSchema:()=>Zs,ResourceLinkSchema:()=>El,ResourceListChangedNotificationSchema:()=>sl,ResourceRequestParamsSchema:()=>qr,ResourceSchema:()=>Vs,ResourceTemplateReferenceSchema:()=>iu,ResourceTemplateSchema:()=>Kc,ResourceUpdatedNotificationParamsSchema:()=>gl,ResourceUpdatedNotificationSchema:()=>Sl,ResultMetaObjectSchema:()=>Is,ResultSchema:()=>ge,RoleSchema:()=>No,RootSchema:()=>du,RootsListChangedNotificationSchema:()=>hu,SamplingContentSchema:()=>Fl,SamplingMessageContentBlockSchema:()=>Tn,SamplingMessageSchema:()=>Jl,ServerCapabilitiesSchema:()=>As,ServerNotificationSchema:()=>Pg,ServerRequestSchema:()=>Eg,ServerResultSchema:()=>Cg,ServerTasksCapabilitySchema:()=>Zc,SetLevelRequestParamsSchema:()=>Al,SetLevelRequestSchema:()=>Ll,SingleSelectEnumSchemaSchema:()=>Kl,StringSchemaSchema:()=>Ar,SubscribeRequestParamsSchema:()=>il,SubscribeRequestSchema:()=>al,SubscriptionFilterSchema:()=>Fs,SubscriptionsAcknowledgedNotificationParamsSchema:()=>pl,SubscriptionsAcknowledgedNotificationSchema:()=>ml,SubscriptionsListenRequestParamsSchema:()=>ul,SubscriptionsListenRequestSchema:()=>dl,SubscriptionsListenResultMetaSchema:()=>hl,SubscriptionsListenResultSchema:()=>fl,TaskAugmentedRequestParamsSchema:()=>In,TaskCreationParamsSchema:()=>pg,TaskMetadataSchema:()=>xc,TaskSchema:()=>Mo,TaskStatusNotificationParamsSchema:()=>gu,TaskStatusNotificationSchema:()=>hg,TaskStatusSchema:()=>fu,TextContentSchema:()=>Nr,TextResourceContentsSchema:()=>Ds,TitledMultiSelectEnumSchemaSchema:()=>Qs,TitledSingleSelectEnumSchemaSchema:()=>Ys,ToolAnnotationsSchema:()=>Ol,ToolChoiceSchema:()=>Ul,ToolExecutionSchema:()=>Il,ToolListChangedNotificationSchema:()=>zl,ToolResultContentSchema:()=>Vl,ToolSchema:()=>Js,ToolUseContentSchema:()=>Tl,UnsubscribeRequestParamsSchema:()=>cl,UnsubscribeRequestSchema:()=>ll,UntitledMultiSelectEnumSchemaSchema:()=>Xs,UntitledSingleSelectEnumSchemaSchema:()=>Gs});const Ov=e=>qs.safeParse(e).success,Iv=e=>Ns.safeParse(e).success,oa=e=>kr.safeParse(e).success,qv=e=>Or.safeParse(e).success,ht=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";function Nv(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Mv(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const na="x-mcp-header",xv=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,zv=new Set(["string","integer","boolean","number"]);function Av(e){const t=[],o=new Map,n=(s,i,a)=>{if(s===null||typeof s!="object")return;const l=s;if(na in l){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 d=l[na];if(typeof d!="string"||d.length===0)return`${rr(i)}: x-mcp-header MUST be a non-empty string`;if(!xv.test(d))return`${rr(i)}: x-mcp-header '${d}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;const m=typeof l.type=="string"?l.type:void 0;if(m===void 0||!zv.has(m))return`${rr(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${m??"<none>"}`;const h=d.toLowerCase(),S=o.get(h);if(S!==void 0)return`x-mcp-header '${d}' is not case-insensitively unique (also declared as '${S}')`;o.set(h,d),t.push({path:i,headerName:d,type:m})}const u=l.properties;if(u!==null&&typeof u=="object")for(const[d,m]of Object.entries(u)){const h=n(m,[...i,d],a);if(h!==void 0)return h}for(const d of Lv){const m=l[d];if(m===void 0)continue;const h=Array.isArray(m)?m:m!==null&&typeof m=="object"&&jv.has(d)?Object.values(m):[m];for(const S of h){const _=n(S,[...i,`<${d}>`],!1);if(_!==void 0)return _}}},r=n(e,[],!0);return r===void 0?{valid:!0,declarations:t}:{valid:!1,reason:r}}const Lv=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],jv=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function rr(e){return e.length===0?"<root>":e.join(".")}const Yr=-32020;P.InvalidRequest,P.UnsupportedProtocolVersion,P.InvalidParams,P.MethodNotFound,P.InvalidParams,P.MissingRequiredClientCapability;P.ParseError+"",P.InvalidRequest+"",P.MethodNotFound+"",P.UnsupportedProtocolVersion+"",P.MissingRequiredClientCapability+"";function ui(e,t){return Tc(e,t)}function dn(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function Po(e){var o;if(e==null)return!1;const t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof((o=e["~standard"])==null?void 0:o.validate)=="function"}let ra=!1;const ms="draft-2020-12";function Ht(e,t="input"){const o=e["~standard"];let n;if(o.jsonSchema)n=o.jsonSchema[t]({target:ms});else if(o.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().");ra||(ra=!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.")),n=Rc(e,{target:ms,io:t})}else throw new Error(`Schema library "${o.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return n.type!==void 0?n:cd(n)?{type:"object",...n}:n;if(n.type!==void 0&&n.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(n.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...n}}function cd(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(const t of["oneOf","anyOf","allOf"]){const o=e[t];if(Array.isArray(o)&&o.length>0)return o.every(n=>n!==null&&typeof n=="object"&&(n.type==="object"||cd(n)))}return!1}function Zv(e){var t;return(t=e.path)!=null&&t.length?`${e.path.map(o=>String(typeof o=="object"?o.key:o)).join(".")}: ${e.message}`:e.message}async function mo(e,t){const o=await e["~standard"].validate(t);return o.issues&&o.issues.length>0?{success:!1,error:o.issues.map(n=>Zv(n)).join(", ")}:{success:!0,data:o.value}}function Dv(e){const t=Rc(e,{target:ms,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}const Hv=/\\\.\\d\{(\d+)\}/;function Uv(e){const t=Hv.exec(e),o=[void 0,-1,0];return t&&o.push(Number(t[1])),[!1,!0].flatMap(n=>[!1,!0].flatMap(r=>o.map(s=>Cn({local:n,offset:r,precision:s}))))}function Vv(e,t){let o;switch(e){case"email":o=[lf()];break;case"uri":o=[Cc()];break;case"date":o=[wc()];break;case"date-time":o=Uv(t);break}return new Set(o.map(n=>Dv(n)).filter(n=>n!==void 0))}function Fv(e,t,o){return o!=="zod"?!0:Vv(e,t).has(t)}function Jv(e){const t=Ht(e,"input"),o=t.properties||{},n=t.required||[];return Object.entries(o).map(([r,s])=>({name:r,description:s==null?void 0:s.description,required:n.includes(r)}))}function En(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bv(e){try{return Ht(e,"input")}catch(t){const o=t instanceof Error?t.message:String(t);throw new U(P.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${o}`)}}const Wv=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function di(e){return Wv.has(e)||e.startsWith("x-")}const Gv=new Set(["$schema",...Object.keys(Lr.shape.requestedSchema.shape)]),sa={string:dn([Ar,Gs,Ys,Ks]),number:dn([hr]),integer:dn([hr]),boolean:dn([Ws]),array:dn([Xs,Qs])},Yv=new Set(Ar.shape.format.unwrap().options);function Kv(e,t,o,n){if(!En(e))return e;const r=typeof e.type=="string"&&Object.hasOwn(sa,e.type)?sa[e.type]:void 0;if(r===void 0)return e;const s={};for(const[i,a]of Object.entries(e))r.has(i)||di(i)?s[i]=a:i==="pattern"&&e.type==="string"&&typeof e.format=="string"?Yv.has(e.format)?(typeof a!="string"||!Fv(e.format,a,o))&&n.push(`${t}.${i}`):s[i]=a:n.push(`${t}.${i}`);return s}function Xv(e,t){const o={},n=[];for(const[r,s]of Object.entries(e))r==="properties"&&En(s)?o[r]=Object.fromEntries(Object.entries(s).map(([i,a])=>[i,Kv(a,`properties.${i}`,t,n)])):Gv.has(r)?o[r]=s:di(r)||n.push(r);if(n.length>0)throw new U(P.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return o}function Qv(e,t){if(!En(e.properties))return t;const o=Object.entries(e.properties).filter(([,n])=>!ui(ei,n).success).map(([n])=>`properties.${n}`);return o.length>0?o.join(", "):t}function hs(e,t,o=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((n,r)=>hs(n,t[r],`${o}[${r}]`)):!En(e)||!En(t)?[]:Object.entries(e).flatMap(([n,r])=>{const s=o?`${o}.${n}`:n;return Object.prototype.hasOwnProperty.call(t,n)?hs(r,t[n],s):di(n)?[]:[s]})}function e_(e){if(!Po(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};const t=e.requestedSchema["~standard"].vendor,o=Xv(Bv(e.requestedSchema),t),n=ui(Lr.shape.requestedSchema,o);if(!n.success)throw new U(P.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Qv(o,n.error.message)}`);const r=hs(o,n.data);if(r.length>0)throw new U(P.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${r.join(", ")}`);const s=(n.data.required??[]).filter(i=>!Object.prototype.hasOwnProperty.call(n.data.properties,i));if(s.length>0)throw new U(P.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${s.join(", ")}`);return{...e,mode:"form",requestedSchema:n.data}}function t_(e){const t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,o=typeof e.requestState=="string";if(!t&&!o)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(t_,{elicit(e){try{return{method:"elicitation/create",params:e_(e)}}catch(t){throw t instanceof U?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 o_=250;function n_(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function r_(e,t){return new Promise((o,n)=>{if(t!=null&&t.aborted){n(t.reason instanceof B?t.reason:new B(K.RequestTimeout,String(t.reason)));return}const r=setTimeout(()=>{t==null||t.removeEventListener("abort",s),o()},e),s=()=>{clearTimeout(r),n((t==null?void 0:t.reason)instanceof B?t.reason:new B(K.RequestTimeout,String(t==null?void 0:t.reason)))};t==null||t.addEventListener("abort",s,{once:!0})})}function s_(e){const t=new AbortController,o=()=>t.abort(e==null?void 0:e.reason);return e==null||e.addEventListener("abort",o,{once:!0}),e!=null&&e.aborted&&t.abort(e.reason),{signal:t.signal,abort:n=>t.abort(n),dispose:()=>e==null?void 0:e.removeEventListener("abort",o)}}const i_=["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"],a_={IdJagTokenExchangeResponseSchema:qg,OAuthClientInformationFullSchema:Mg,OAuthClientInformationSchema:yu,OAuthClientMetadataSchema:_u,OAuthClientRegistrationErrorSchema:xg,OAuthErrorResponseSchema:Ng,OAuthMetadataSchema:Su,OAuthProtectedResourceMetadataSchema:kg,OAuthTokenRevocationRequestSchema:zg,OAuthTokensSchema:Ig,OpenIdProviderDiscoveryMetadataSchema:Og,OpenIdProviderMetadataSchema:vu},ld={},ud={};function dd(e,t){const o=e.slice(0,-6);ld[o]=t,ud[o]=n=>t.safeParse(n).success}for(const e of i_)dd(e,kv[e]);for(const[e,t]of Object.entries(a_))dd(e,t);Object.freeze(ld);Object.freeze(ud);function c_(e){switch(e){case"initialize":case"notifications/initialized":return $n(void 0);case"server/discover":return $n(id);default:return}}const l_=6e4,u_=[Er,Ps,On,Pr],d_=["inputResponses","requestState"];function ia(e,t){const o=e.params;if(!Sn(o))return{message:e,lifted:{}};const n=o._meta,r=Sn(n)?u_.filter(l=>l in n):[],s=t==="request"?d_.filter(l=>l in o):[];if(r.length===0&&s.length===0)return{message:e,lifted:{}};const i={},a={...o};if(r.length>0&&Sn(n)){const l={},u={...n};for(const d of r)l[d]=n[d],delete u[d];i.envelope=l,Object.keys(u).length>0?a._meta=u:delete a._meta}for(const l of s)l==="inputResponses"&&(i.inputResponses=a[l]),l==="requestState"&&(i.requestState=a[l]),delete a[l];return{message:{...e,params:a},lifted:i}}function aa(e,t){const o=e.validateResult(t,void 0);if(!(!o.ok&&o.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(n){const r=e.validateResult(t,n);return r.ok?{value:r.value}:{issues:[{message:r.reason==="invalid"?r.message:`not-in-era: ${t}`}]}}}}}function Zr(e){return()=>e}const p_=Zr(void 0);function pd(e,t){return{...e,mcpReq:{...e.mcpReq,requestState:Zr(t)}}}var m_=class{constructor(e){R(this,"_transport");R(this,"_requestMessageId",0);R(this,"_requestHandlers",new Map);R(this,"_requestHandlerAbortControllers",new Map);R(this,"_notificationHandlers",new Map);R(this,"_responseHandlers",new Map);R(this,"_progressHandlers",new Map);R(this,"_timeoutInfo",new Map);R(this,"_pendingDebouncedNotifications",new Set);R(this,"_negotiatedProtocolVersion");R(this,"_supportedProtocolVersions");R(this,"onclose");R(this,"onerror");R(this,"fallbackRequestHandler");R(this,"fallbackNotificationHandler");this._options=e,this._supportedProtocolVersions=(e==null?void 0:e.supportedProtocolVersions)??ng,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 o=e.params??{};return{...e,params:{...o,_meta:{...t,...o._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new B(K.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){var t;e.params.requestId&&((t=this._requestHandlerAbortControllers.get(e.params.requestId))==null||t.abort(e.params.reason))}_setupTimeout(e,t,o,n,r=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:o,resetTimeoutOnProgress:r,onTimeout:n})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const o=Date.now()-t.startTime;if(t.maxTotalTimeout&&o>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new B(K.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:o});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,s,i,a;this._transport=e;const t=(r=this.transport)==null?void 0:r.onclose;this._transport.onclose=()=>{try{t==null||t()}finally{this._onclose()}};const o=(s=this.transport)==null?void 0:s.onerror;this._transport.onerror=l=>{o==null||o(l),this._onerror(l)};const n=(i=this._transport)==null?void 0:i.onmessage;this._transport.onmessage=(l,u)=>{n==null||n(l,u),oa(l)||qv(l)?this._onresponse(l):Ov(l)?this._onrequest(l,u):Iv(l)?this._onnotification(l,u):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},(a=e.setSupportedProtocolVersions)==null||a.call(e,this._supportedProtocolVersions),await this._transport.start()}_onclose(){var n;const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();const t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;const o=new B(K.ConnectionClosed,"Connection closed");this._transport=void 0;try{(n=this.onclose)==null||n.call(this)}finally{for(const r of e.values())r(o);for(const r of t.values())r.abort(o)}}_onerror(e){var t;(t=this.onerror)==null||t.call(this,e)}_onnotification(e,t){const{message:o}=ia(e,"notification"),n=this._negotiatedWireCodec();if((t==null?void 0:t.classification)===void 0&&this._shouldDropInbound(e)==="drop")return;if((t==null?void 0:t.classification)!==void 0){const i=ta(t.classification);if(i!==n.era){this._onerror(new Error(`Era mismatch on inbound notification '${o.method}': classified as ${i} but this instance serves ${n.era}`));return}}if(Gr(o.method)&&!n.hasNotificationMethod(o.method))return;const r=this._notificationHandlers.get(o.method),s=this.fallbackNotificationHandler;r===void 0&&s===void 0||Promise.resolve().then(()=>r===void 0?s(o):r(o,n)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,t){var T;const{message:o,lifted:n}=ia(e,"request"),r=this._negotiatedWireCodec();if((t==null?void 0:t.classification)===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}const s=this._transport,i=(b,N,L)=>{const w={jsonrpc:"2.0",id:o.id,error:{code:b,message:N,...L!==void 0&&{data:L}}};s==null||s.send(w).catch(q=>this._onerror(new Error(`Failed to send an error response: ${q}`)))};if((t==null?void 0:t.classification)!==void 0){const b=ta(t.classification);if(b!==r.era){this._onerror(new Error(`Era mismatch on inbound request '${o.method}': classified as ${b} but this instance serves ${r.era}`));const N=t.classification.revision??b;i(P.UnsupportedProtocolVersion,`Unsupported protocol version: ${N}`,{supported:this._supportedProtocolVersions,requested:N});return}}if(Wr(o.method)&&!r.hasRequestMethod(o.method)){i(P.MethodNotFound,"Method not found");return}const a=this._requestHandlers.get(o.method)??this.fallbackRequestHandler;if(a===void 0){i(P.MethodNotFound,"Method not found");return}const l=r.checkInboundEnvelope(n);if(l!==void 0){i(P.InvalidParams,l);return}const u=(b,N)=>this._notificationViaCodec(this._resolveOutboundCodec(b.method),b,{...N,relatedRequestId:o.id}),d=(b,N,L)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(b.method),b,N,{...L,relatedRequestId:o.id}),m=new AbortController;this._requestHandlerAbortControllers.set(o.id,m);const h=n.inputResponses===void 0?void 0:h_(n.inputResponses),S={sessionId:s==null?void 0:s.sessionId,mcpReq:{id:o.id,method:o.method,_meta:(T=o.params)==null?void 0:T._meta,...n.envelope!==void 0&&{envelope:n.envelope},...h!==void 0&&{inputResponses:h.accepted},...h!==void 0&&h.droppedKeys.length>0&&{droppedInputResponseKeys:h.droppedKeys},requestState:n.requestState===void 0?p_:Zr(n.requestState),signal:m.signal,send:((b,N,L)=>{const w=this._resolveOutboundCodec(b.method);if(this._assertOutboundRequestInEra(w,b.method),Po(N))return d(b,N,L);const q=aa(w,b.method);if(q===void 0)throw new TypeError(`'${b.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return d(b,q,N)}),notify:u},http:t!=null&&t.authInfo?{authInfo:t.authInfo}:void 0},_=this.buildContext(S,t);Promise.resolve().then(()=>a(o,_)).then(async b=>{if(m.signal.aborted)return;let N;try{N=r.encodeResult(o.method,b,this._outboundServerInfo())}catch(w){this._onerror(new Error(`Failed to encode result for ${o.method}: ${w}`)),i(P.InternalError,"Internal error");return}const L={result:N,jsonrpc:"2.0",id:o.id};await(s==null?void 0:s.send(L))},async b=>{if(m.signal.aborted)return;const N=Number.isSafeInteger(b.code)?b.code:P.InternalError,L={jsonrpc:"2.0",id:o.id,error:{code:r.encodeErrorCode(N),message:b.message??"Internal error",...b.data!==void 0&&{data:b.data}}};await(s==null?void 0:s.send(L))}).catch(b=>this._onerror(new Error(`Failed to send response: ${b}`))).finally(()=>{this._requestHandlerAbortControllers.get(o.id)===m&&this._requestHandlerAbortControllers.delete(o.id)})}_onprogress(e){const{progressToken:t,...o}=e.params,n=Number(t),r=this._progressHandlers.get(n);if(!r){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const s=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),s(a);return}r(o)}_onresponse(e){const t=Number(e.id),o=this._responseHandlers.get(t);if(o===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),oa(e)?o(e):o(U.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){var e;await((e=this._transport)==null?void 0:e.close())}request(e,t,o){const n=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(n,e.method),Po(t))return this._requestWithSchemaViaCodec(n,e,t,o);const r=aa(n,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(n,e,r,t)}_negotiatedWireCodec(){return $n(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){const t=c_(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Wr(t)&&!e.hasRequestMethod(t))throw new B(K.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,o){const n=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,o)}_requestWithSchemaViaCodec(e,t,o,n){const{relatedRequestId:r,resumptionToken:s,onresumptiontoken:i,headers:a}=n??{},l=Date.now();let u,d;return new Promise((m,h)=>{var V,Q,X,G;const S=Y=>{h(Y)};if(!this._transport){S(new Error("Not connected"));return}if(((V=this._options)==null?void 0:V.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(t.method)}catch(Y){S(Y);return}if((Q=n==null?void 0:n.signal)!=null&&Q.aborted){const Y=n.signal.reason;throw Y instanceof B?Y:new B(K.RequestTimeout,String(Y))}const _=e.era===id&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,T=this._requestMessageId++;d=T;const b={...t,jsonrpc:"2.0",id:T};n!=null&&n.onprogress&&(this._progressHandlers.set(T,n.onprogress),b.params={...t.params,_meta:{...(X=t.params)==null?void 0:X._meta,progressToken:T}});const N=this._envelopeOutbound(b);let L=!1;const w=Y=>{var te;L||(this._progressHandlers.delete(T),_===void 0?(te=this._transport)==null||te.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:T,reason:String(Y)}}),{relatedRequestId:r,resumptionToken:s,onresumptiontoken:i}).catch(pe=>this._onerror(new Error(`Failed to send cancellation: ${pe}`))):_.abort(),h(Y instanceof B?Y:new B(K.RequestTimeout,String(Y))))};this._responseHandlers.set(T,Y=>{var ue;if((ue=n==null?void 0:n.signal)!=null&&ue.aborted)return;if(L=!0,Y instanceof Error)return h(Y);let te;try{te=e.decodeResult(t.method,Y.result)}catch(oe){return h(oe instanceof Error?oe:new Error(String(oe)))}if(te.kind==="invalid")return h(te.error);if(te.kind==="input_required"){if((n==null?void 0:n.allowInputRequired)===!0)return m(f_(te));const oe={codec:e,request:t,resultSchema:o,options:n,flowStartedAt:l,retry:(ve,Se)=>this._requestWithSchemaViaCodec(e,ve===void 0?{method:t.method}:{method:t.method,params:ve},o,Se)};return m(this._resolveNonCompleteResult(te,oe))}const pe=te.result;mo(o,pe).then(oe=>{oe.success?m(oe.data):h(new B(K.InvalidResult,`Invalid result for ${t.method}: ${oe.error}`))},h)}),u=()=>{var Y;return w((Y=n==null?void 0:n.signal)==null?void 0:Y.reason)},(G=n==null?void 0:n.signal)==null||G.addEventListener("abort",u,{once:!0});const q=(n==null?void 0:n.timeout)??l_,W=()=>w(new B(K.RequestTimeout,"Request timed out",{timeout:q}));this._setupTimeout(T,q,n==null?void 0:n.maxTotalTimeout,W,(n==null?void 0:n.resetTimeoutOnProgress)??!1),this._transport.send(N,{relatedRequestId:r,resumptionToken:s,onresumptiontoken:i,headers:a,requestSignal:_==null?void 0:_.signal}).catch(Y=>{this._progressHandlers.delete(T),h(Y)})}).finally(()=>{var m;u&&((m=n==null?void 0:n.signal)==null||m.removeEventListener("abort",u)),d!==void 0&&(this._responseHandlers.delete(d),this._cleanupTimeout(d))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,o){var r;if(!this._transport)throw new B(K.NotConnected,"Not connected");if(Gr(t.method)&&!e.hasNotificationMethod(t.method))throw new B(K.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 n=this._envelopeOutbound({jsonrpc:"2.0",...t});if((((r=this._options)==null?void 0:r.debouncedNotificationMethods)??[]).includes(t.method)&&!t.params&&!(o!=null&&o.relatedRequestId)){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{var s;this._pendingDebouncedNotifications.delete(t.method),this._transport&&((s=this._transport)==null||s.send(n,o).catch(i=>this._onerror(i)))});return}await this._transport.send(n,o)}setRequestHandler(e,t,o){this.assertRequestHandlerCapability(e);let n;if(typeof t=="function"){if(!Wr(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);n=(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 U(P.InternalError,`No wire schema for ${e} in the resolved era`):new Error(a.message);return Promise.resolve(t(a.value,s))}}else if(o)n=async(r,s)=>{const i=await mo(t.params,{...r.params});if(!i.success)throw new U(P.InvalidParams,`Invalid params for ${e}: ${i.error}`);return o(i.data,s)};else throw new TypeError("setRequestHandler: handler is required");this._requestHandlers.set(e,this._wrapHandler(e,n))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.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,o){if(typeof t=="function"){if(!Gr(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,r)=>{const s=r.validateNotification(e,n);if(!s.ok)throw s.reason==="not-in-era"?new U(P.InternalError,`No wire schema for ${e} in the resolved era`):new Error(s.message);return Promise.resolve(t(s.value))});return}if(!o)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async n=>{const r=await mo(t.params,{...n.params});if(!r.success)throw new U(P.InvalidParams,`Invalid params for notification ${e}: ${r.error}`);await o(r.data,n)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Sn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function md(e,t){const o={...e};for(const n in t){const r=n,s=t[r];if(s===void 0)continue;const i=o[r];o[r]=Sn(i)&&Sn(s)?{...i,...s}:s}return o}function ca(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function h_(e){const t={},o=[];if(!ca(e))return{accepted:t,droppedKeys:o};for(const[n,r]of Object.entries(e)){if(!ca(r)||"method"in r||"result"in r){o.push(n);continue}t[n]=r}return{accepted:t,droppedKeys:o}}function f_(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}/*!
65
+ * content-type
66
+ * Copyright(c) 2015 Douglas Christopher Wilson
67
+ * MIT Licensed
68
+ */var g_=OS((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,o=/\\([\u000b\u0020-\u00ff])/g,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=r;function r(a){if(!a)throw new TypeError("argument string is required");var l=typeof a=="object"?s(a):a;if(typeof l!="string")throw new TypeError("argument string is required to be a string");var u=l.indexOf(";"),d=u!==-1?l.slice(0,u).trim():l.trim();if(!n.test(d))throw new TypeError("invalid media type");var m=new i(d.toLowerCase());if(u!==-1){var h,S,_;for(t.lastIndex=u;S=t.exec(l);){if(S.index!==u)throw new TypeError("invalid parameter format");u+=S[0].length,h=S[1].toLowerCase(),_=S[2],_.charCodeAt(0)===34&&(_=_.slice(1,-1),_.indexOf("\\")!==-1&&(_=_.replace(o,"$1"))),m.parameters[h]=_}if(u!==l.length)throw new TypeError("invalid parameter format")}return m}function s(a){var l;if(typeof a.getHeader=="function"?l=a.getHeader("content-type"):typeof a.headers=="object"&&(l=a.headers&&a.headers["content-type"]),typeof l!="string")throw new TypeError("content-type header is missing from object");return l}function i(a){this.parameters=Object.create(null),this.type=a}}));g_();const S_=/^[A-Za-z0-9._-]{1,128}$/;function v_(e){const t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!S_.test(e)){const o=[...e].filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,r,s)=>s.indexOf(n)===r);return t.push(`Tool name contains invalid characters: ${o.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function __(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const o of t)console.warn(` - ${o}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function la(e){const t=v_(e);return __(e,t.warnings),t.isValid}const ua=1e6,Kr=1e6,da=1e4,y_=1e6;var b_=class jt{constructor(t){R(this,"template");R(this,"parts");jt.validateLength(t,ua,"Template"),this.template=t,this.parts=this.parse(t)}static isTemplate(t){return/\{[^}\s]+\}/.test(t)}static validateLength(t,o,n){if(t.length>o)throw new Error(`${n} exceeds maximum length of ${o} characters (got ${t.length})`)}get variableNames(){return this.parts.flatMap(t=>typeof t=="string"?[]:t.names)}toString(){return this.template}parse(t){const o=[];let n="",r=0,s=0;for(;r<t.length;)if(t[r]==="{"){n&&(o.push(n),n="");const i=t.indexOf("}",r);if(i===-1)throw new Error("Unclosed template expression");if(s++,s>da)throw new Error(`Template contains too many expressions (max ${da})`);const a=t.slice(r+1,i),l=this.getOperator(a),u=a.includes("*"),d=this.getNames(a),m=d[0];for(const h of d)jt.validateLength(h,Kr,"Variable name");o.push({name:m,operator:l,names:d,exploded:u}),r=i+1}else n+=t[r],r++;return n&&o.push(n),o}getOperator(t){return["+","#",".","/","?","&"].find(o=>t.startsWith(o))||""}getNames(t){const o=this.getOperator(t);return t.slice(o.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(t,o){return jt.validateLength(t,Kr,"Variable value"),o==="+"||o==="#"?encodeURI(t):encodeURIComponent(t)}expandPart(t,o){if(t.operator==="?"||t.operator==="&"){const s=t.names.map(i=>{const a=o[i];return a===void 0?"":`${i}=${Array.isArray(a)?a.map(l=>this.encodeValue(l,t.operator)).join(","):this.encodeValue(a.toString(),t.operator)}`}).filter(i=>i.length>0);return s.length===0?"":(t.operator==="?"?"?":"&")+s.join("&")}if(t.names.length>1){const s=t.names.map(i=>o[i]).filter(i=>i!==void 0);return s.length===0?"":s.map(i=>Array.isArray(i)?i[0]:i).join(",")}const n=o[t.name];if(n===void 0)return"";const r=(Array.isArray(n)?n:[n]).map(s=>this.encodeValue(s,t.operator));switch(t.operator){case"":return r.join(",");case"+":return r.join(",");case"#":return"#"+r.join(",");case".":return"."+r.join(".");case"/":return"/"+r.join("/");default:return r.join(",")}}expand(t){let o="",n=!1;for(const r of this.parts){if(typeof r=="string"){o+=r;continue}const s=this.expandPart(r,t);s&&(o+=(r.operator==="?"||r.operator==="&")&&n?s.replace("?","&"):s,(r.operator==="?"||r.operator==="&")&&(n=!0))}return o}escapeRegExp(t){return t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(t){const o=[];for(const s of t.names)jt.validateLength(s,Kr,"Variable name");if(t.operator==="?"||t.operator==="&"){for(let s=0;s<t.names.length;s++){const i=t.names[s],a=s===0?"\\"+t.operator:"&";o.push({pattern:a+this.escapeRegExp(i)+"=([^&]+)",name:i})}return o}let n;const r=t.name;switch(t.operator){case"":n=t.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n=String.raw`\.([^/,]+)`;break;case"/":n="/"+(t.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return o.push({pattern:n,name:r}),o}match(t){jt.validateLength(t,ua,"URI");let o="^";const n=[];for(const a of this.parts)if(typeof a=="string")o+=this.escapeRegExp(a);else{const l=this.partToRegExp(a);for(const{pattern:u,name:d}of l)o+=u,n.push({name:d,exploded:a.exploded})}o+="$",jt.validateLength(o,y_,"Generated regex pattern");const r=new RegExp(o),s=t.match(r);if(!s)return null;const i={};for(const[a,l]of n.entries()){const{name:u,exploded:d}=l,m=s[a+1],h=u.replace("*","");i[h]=d&&m.includes(",")?m.split(","):m}return i}};function R_(e){return typeof e=="object"&&e!==null&&"_zod"in e}function w_(e){var t;return typeof e=="object"&&e!==null&&!("_zod"in e)&&"_def"in e&&typeof((t=e._def)==null?void 0:t.typeName)=="string"}function T_(e){if(typeof e!="object"||e===null||Po(e))return!1;const t=Object.getPrototypeOf(e);return t!==Object.prototype&&t!==null?!1:Object.values(e).every(o=>R_(o))}function Xr(e){if(e!==void 0){if(T_(e))return p(e);if(typeof e=="object"&&e!==null&&!Po(e)&&Object.values(e).some(t=>w_(t)))throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.");if(!Po(e))throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).");return e}}function $_(e,t){const o=t.getValidator(e);return{"~standard":{version:1,vendor:"mcp",jsonSchema:{input:()=>e,output:()=>e},validate:n=>{const r=o(n);return r.valid?{value:r.data}:{issues:[{message:r.errorMessage}]}}}}}function vn(e,t){const o=typeof e;if(o!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!vn(e[r],t[r]))return!1;return!0}if(o==="object"){if(!e||!t)return e===t;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const s of n)if(!vn(e[s],t[s]))return!1;return!0}return e===t}function Ke(e){return encodeURI(E_(e))}function E_(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}const P_={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},C_={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},k_={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 O_=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 Ut(e,t=Object.create(null),o=O_,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){const s=e.$id||e.id;if(s){const i=new URL(s,o.href);i.hash.length>1?t[i.href]=e:(i.hash="",n===""?o=i:Ut(e,t,o))}}else if(e!==!0&&e!==!1)return t;const r=o.href+(n?"#"+n:"");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,o.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,o.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,o.href);t[s.href]=e}for(let s in e){if(k_[s])continue;const i=`${n}/${Ke(s)}`,a=e[s];if(Array.isArray(a)){if(P_[s]){const l=a.length;for(let u=0;u<l;u++)Ut(a[u],t,o,`${i}/${u}`)}}else if(C_[s])for(let l in a)Ut(a[l],t,o,`${i}/${Ke(l)}`);else Ut(a,t,o,i)}return t}const I_=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,q_=[0,31,28,31,30,31,30,31,31,30,31,30,31],N_=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,M_=/^(?=.{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,x_=/^(?:[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,z_=/^(?:(?:[^\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,A_=/^(?:(?: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,L_=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,j_=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Z_=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,D_=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,H_=e=>{if(e[0]==='"')return!1;const[t,o,...n]=e.split("@");return!t||!o||n.length!==0||t.length>64||o.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(o)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:o.split(".").every(r=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(r))},U_=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,V_=/^((([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,F_=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 ct(e){return e.test.bind(e)}const pa={date:hd,time:fd.bind(void 0,!1),"date-time":W_,duration:F_,uri:K_,"uri-reference":ct(x_),"uri-template":ct(z_),url:ct(A_),email:H_,hostname:ct(M_),ipv4:ct(U_),ipv6:ct(V_),regex:Q_,uuid:ct(L_),"json-pointer":ct(j_),"json-pointer-uri-fragment":ct(Z_),"relative-json-pointer":ct(D_)};function J_(e){return e%4===0&&(e%100!==0||e%400===0)}function hd(e){const t=e.match(I_);if(!t)return!1;const o=+t[1],n=+t[2],r=+t[3];return n>=1&&n<=12&&r>=1&&r<=(n==2&&J_(o)?29:q_[n])}function fd(e,t){const o=t.match(N_);if(!o)return!1;const n=+o[1],r=+o[2],s=+o[3],i=!!o[5];return(n<=23&&r<=59&&s<=59||n==23&&r==59&&s==60)&&(!e||i)}const B_=/t|\s/i;function W_(e){const t=e.split(B_);return t.length==2&&hd(t[0])&&fd(!0,t[1])}const G_=/\/|:/,Y_=/^(?:[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 K_(e){return G_.test(e)&&Y_.test(e)}const X_=/[^\\]\\Z/;function Q_(e){if(X_.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}function ey(e){let t=0,o=e.length,n=0,r;for(;n<o;)t++,r=e.charCodeAt(n++),r>=55296&&r<=56319&&n<o&&(r=e.charCodeAt(n),(r&64512)==56320&&n++);return t}function ce(e,t,o="2019-09",n=Ut(t),r=!0,s=null,i="#",a="#",l=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 u=typeof e;let d;switch(u){case"boolean":case"number":case"string":d=u;break;case"object":e===null?d="null":Array.isArray(e)?d="array":d="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}const{$ref:m,$recursiveRef:h,$recursiveAnchor:S,type:_,const:T,enum:b,required:N,not:L,anyOf:w,allOf:q,oneOf:W,if:V,then:Q,else:X,format:G,properties:Y,patternProperties:te,additionalProperties:pe,unevaluatedProperties:ue,minProperties:oe,maxProperties:ve,propertyNames:Se,dependentRequired:_e,dependentSchemas:Ue,dependencies:tt,prefixItems:ze,items:Ee,additionalItems:ut,unevaluatedItems:dt,contains:ot,minContains:be,maxContains:Pe,minItems:Ce,maxItems:Ge,uniqueItems:$t,minimum:Ae,maximum:Le,exclusiveMinimum:Oe,exclusiveMaximum:Ve,multipleOf:Fe,minLength:nt,maxLength:rt,pattern:St,__absolute_ref__:st,__absolute_recursive_ref__:Et}=t,C=[];if(S===!0&&s===null&&(s=t),h==="#"){const j=s===null?n[Et]:s,M=`${a}/$recursiveRef`,J=ce(e,s===null?t:s,o,n,r,j,i,M,l);J.valid||C.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:M,error:"A subschema had errors."},...J.errors)}if(m!==void 0){const j=n[st||m];if(j===void 0){let k=`Unresolved $ref "${m}".`;throw st&&st!==m&&(k+=` Absolute URI "${st}".`),k+=`
69
+ Known schemas:
70
+ - ${Object.keys(n).join(`
71
+ - `)}`,new Error(k)}const M=`${a}/$ref`,J=ce(e,j,o,n,r,s,i,M,l);if(J.valid||C.push({instanceLocation:i,keyword:"$ref",keywordLocation:M,error:"A subschema had errors."},...J.errors),o==="4"||o==="7")return{valid:C.length===0,errors:C}}if(Array.isArray(_)){let j=_.length,M=!1;for(let J=0;J<j;J++)if(d===_[J]||_[J]==="integer"&&d==="number"&&e%1===0&&e===e){M=!0;break}M||C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${_.join('", "')}".`})}else _==="integer"?(d!=="number"||e%1||e!==e)&&C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${_}".`}):_!==void 0&&d!==_&&C.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${_}".`});if(T!==void 0&&(d==="object"||d==="array"?vn(e,T)||C.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(T)}.`}):e!==T&&C.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(T)}.`})),b!==void 0&&(d==="object"||d==="array"?b.some(j=>vn(e,j))||C.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(j=>e===j)||C.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),L!==void 0){const j=`${a}/not`;ce(e,L,o,n,r,s,i,j).valid&&C.push({instanceLocation:i,keyword:"not",keywordLocation:j,error:'Instance matched "not" schema.'})}let it=[];if(w!==void 0){const j=`${a}/anyOf`,M=C.length;let J=!1;for(let k=0;k<w.length;k++){const $=w[k],H=Object.create(l),D=ce(e,$,o,n,r,S===!0?s:null,i,`${j}/${k}`,H);C.push(...D.errors),J=J||D.valid,D.valid&&it.push(H)}J?C.length=M:C.splice(M,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:j,error:"Instance does not match any subschemas."})}if(q!==void 0){const j=`${a}/allOf`,M=C.length;let J=!0;for(let k=0;k<q.length;k++){const $=q[k],H=Object.create(l),D=ce(e,$,o,n,r,S===!0?s:null,i,`${j}/${k}`,H);C.push(...D.errors),J=J&&D.valid,D.valid&&it.push(H)}J?C.length=M:C.splice(M,0,{instanceLocation:i,keyword:"allOf",keywordLocation:j,error:"Instance does not match every subschema."})}if(W!==void 0){const j=`${a}/oneOf`,M=C.length,J=W.filter((k,$)=>{const H=Object.create(l),D=ce(e,k,o,n,r,S===!0?s:null,i,`${j}/${$}`,H);return C.push(...D.errors),D.valid&&it.push(H),D.valid}).length;J===1?C.length=M:C.splice(M,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:j,error:`Instance does not match exactly one subschema (${J} matches).`})}if((d==="object"||d==="array")&&Object.assign(l,...it),V!==void 0){const j=`${a}/if`;if(ce(e,V,o,n,r,s,i,j,l).valid){if(Q!==void 0){const M=ce(e,Q,o,n,r,s,i,`${a}/then`,l);M.valid||C.push({instanceLocation:i,keyword:"if",keywordLocation:j,error:'Instance does not match "then" schema.'},...M.errors)}}else if(X!==void 0){const M=ce(e,X,o,n,r,s,i,`${a}/else`,l);M.valid||C.push({instanceLocation:i,keyword:"if",keywordLocation:j,error:'Instance does not match "else" schema.'},...M.errors)}}if(d==="object"){if(N!==void 0)for(const k of N)k in e||C.push({instanceLocation:i,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${k}".`});const j=Object.keys(e);if(oe!==void 0&&j.length<oe&&C.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${oe} properties.`}),ve!==void 0&&j.length>ve&&C.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${ve} properties.`}),Se!==void 0){const k=`${a}/propertyNames`;for(const $ in e){const H=`${i}/${Ke($)}`,D=ce($,Se,o,n,r,s,H,k);D.valid||C.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:k,error:`Property name "${$}" does not match schema.`},...D.errors)}}if(_e!==void 0){const k=`${a}/dependantRequired`;for(const $ in _e)if($ in e){const H=_e[$];for(const D of H)D in e||C.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:k,error:`Instance has "${$}" but does not have "${D}".`})}}if(Ue!==void 0)for(const k in Ue){const $=`${a}/dependentSchemas`;if(k in e){const H=ce(e,Ue[k],o,n,r,s,i,`${$}/${Ke(k)}`,l);H.valid||C.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:$,error:`Instance has "${k}" but does not match dependant schema.`},...H.errors)}}if(tt!==void 0){const k=`${a}/dependencies`;for(const $ in tt)if($ in e){const H=tt[$];if(Array.isArray(H))for(const D of H)D in e||C.push({instanceLocation:i,keyword:"dependencies",keywordLocation:k,error:`Instance has "${$}" but does not have "${D}".`});else{const D=ce(e,H,o,n,r,s,i,`${k}/${Ke($)}`);D.valid||C.push({instanceLocation:i,keyword:"dependencies",keywordLocation:k,error:`Instance has "${$}" but does not match dependant schema.`},...D.errors)}}}const M=Object.create(null);let J=!1;if(Y!==void 0){const k=`${a}/properties`;for(const $ in Y){if(!($ in e))continue;const H=`${i}/${Ke($)}`,D=ce(e[$],Y[$],o,n,r,s,H,`${k}/${Ke($)}`);if(D.valid)l[$]=M[$]=!0;else if(J=r,C.push({instanceLocation:i,keyword:"properties",keywordLocation:k,error:`Property "${$}" does not match schema.`},...D.errors),J)break}}if(!J&&te!==void 0){const k=`${a}/patternProperties`;for(const $ in te){const H=new RegExp($,"u"),D=te[$];for(const me in e){if(!H.test(me))continue;const Pt=`${i}/${Ke(me)}`,at=ce(e[me],D,o,n,r,s,Pt,`${k}/${Ke($)}`);at.valid?l[me]=M[me]=!0:(J=r,C.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:k,error:`Property "${me}" matches pattern "${$}" but does not match associated schema.`},...at.errors))}}}if(!J&&pe!==void 0){const k=`${a}/additionalProperties`;for(const $ in e){if(M[$])continue;const H=`${i}/${Ke($)}`,D=ce(e[$],pe,o,n,r,s,H,k);D.valid?l[$]=!0:(J=r,C.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:k,error:`Property "${$}" does not match additional properties schema.`},...D.errors))}}else if(!J&&ue!==void 0){const k=`${a}/unevaluatedProperties`;for(const $ in e)if(!l[$]){const H=`${i}/${Ke($)}`,D=ce(e[$],ue,o,n,r,s,H,k);D.valid?l[$]=!0:C.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:k,error:`Property "${$}" does not match unevaluated properties schema.`},...D.errors)}}}else if(d==="array"){Ge!==void 0&&e.length>Ge&&C.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${Ge}).`}),Ce!==void 0&&e.length<Ce&&C.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Ce}).`});const j=e.length;let M=0,J=!1;if(ze!==void 0){const k=`${a}/prefixItems`,$=Math.min(ze.length,j);for(;M<$;M++){const H=ce(e[M],ze[M],o,n,r,s,`${i}/${M}`,`${k}/${M}`);if(l[M]=!0,!H.valid&&(J=r,C.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:k,error:"Items did not match schema."},...H.errors),J))break}}if(Ee!==void 0){const k=`${a}/items`;if(Array.isArray(Ee)){const $=Math.min(Ee.length,j);for(;M<$;M++){const H=ce(e[M],Ee[M],o,n,r,s,`${i}/${M}`,`${k}/${M}`);if(l[M]=!0,!H.valid&&(J=r,C.push({instanceLocation:i,keyword:"items",keywordLocation:k,error:"Items did not match schema."},...H.errors),J))break}}else for(;M<j;M++){const $=ce(e[M],Ee,o,n,r,s,`${i}/${M}`,k);if(l[M]=!0,!$.valid&&(J=r,C.push({instanceLocation:i,keyword:"items",keywordLocation:k,error:"Items did not match schema."},...$.errors),J))break}if(!J&&ut!==void 0){const $=`${a}/additionalItems`;for(;M<j;M++){const H=ce(e[M],ut,o,n,r,s,`${i}/${M}`,$);l[M]=!0,H.valid||(J=r,C.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:$,error:"Items did not match additional items schema."},...H.errors))}}}if(ot!==void 0)if(j===0&&be===void 0)C.push({instanceLocation:i,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(be!==void 0&&j<be)C.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${j}) than minContains (${be}).`});else{const k=`${a}/contains`,$=C.length;let H=0;for(let D=0;D<j;D++){const me=ce(e[D],ot,o,n,r,s,`${i}/${D}`,k);me.valid?(l[D]=!0,H++):C.push(...me.errors)}H>=(be||0)&&(C.length=$),be===void 0&&Pe===void 0&&H===0?C.splice($,0,{instanceLocation:i,keyword:"contains",keywordLocation:k,error:"Array does not contain item matching schema."}):be!==void 0&&H<be?C.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${be} items matching schema. Only ${H} items were found.`}):Pe!==void 0&&H>Pe&&C.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Pe} items matching schema. ${H} items were found.`})}if(!J&&dt!==void 0){const k=`${a}/unevaluatedItems`;for(;M<j;M++){if(l[M])continue;const $=ce(e[M],dt,o,n,r,s,`${i}/${M}`,k);l[M]=!0,$.valid||C.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:k,error:"Items did not match unevaluated items schema."},...$.errors)}}if($t)for(let k=0;k<j;k++){const $=e[k],H=typeof $=="object"&&$!==null;for(let D=0;D<j;D++){if(k===D)continue;const me=e[D];($===me||H&&typeof me=="object"&&me!==null&&vn($,me))&&(C.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${k} and ${D}.`}),k=Number.MAX_SAFE_INTEGER,D=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(o==="4"?(Ae!==void 0&&(Oe===!0&&e<=Ae||e<Ae)&&C.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Oe?"or equal to ":""} ${Ae}.`}),Le!==void 0&&(Ve===!0&&e>=Le||e>Le)&&C.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Ve?"or equal to ":""} ${Le}.`})):(Ae!==void 0&&e<Ae&&C.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Ae}.`}),Le!==void 0&&e>Le&&C.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Le}.`}),Oe!==void 0&&e<=Oe&&C.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${Oe}.`}),Ve!==void 0&&e>=Ve&&C.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ve}.`})),Fe!==void 0){const j=e%Fe;Math.abs(0-j)>=11920929e-14&&Math.abs(Fe-j)>=11920929e-14&&C.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Fe}.`})}}else if(d==="string"){const j=nt===void 0&&rt===void 0?0:ey(e);nt!==void 0&&j<nt&&C.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${j} < ${nt}).`}),rt!==void 0&&j>rt&&C.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${j} > ${rt}).`}),St!==void 0&&!new RegExp(St,"u").test(e)&&C.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),G!==void 0&&pa[G]&&!pa[G](e)&&C.push({instanceLocation:i,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${G}".`})}return{valid:C.length===0,errors:C}}var ty=class{constructor(e,t="2019-09",o=!0){R(this,"schema");R(this,"draft");R(this,"shortCircuit");R(this,"lookup");this.schema=e,this.draft=t,this.shortCircuit=o,this.lookup=Ut(e)}validate(e){return ce(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Ut(e,this.lookup)}},gd=class{constructor(e){R(this,"shortcircuit");R(this,"draft");this.shortcircuit=(e==null?void 0:e.shortcircuit)??!0,this.draft=e==null?void 0:e.draft}_draftFor(e){const t=LS(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){const t=new ty(e,this.draft??this._draftFor(e),this.shortcircuit);return o=>{const n=t.validate(o);return n.valid?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:n.errors.map(r=>`${r.instanceLocation}: ${r.error}`).join("; ")}}}};const Sd=Symbol.for("mcp.completable");function ma(e){return!!e&&typeof e=="object"&&Sd in e}function oy(e){var t;return(t=e[Sd])==null?void 0:t.complete}const ny=8,ry=6e5;function sy(e){if((e==null?void 0:e.maxRounds)!==void 0&&(!Number.isInteger(e.maxRounds)||e.maxRounds<1))throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${e.maxRounds})`);if((e==null?void 0:e.roundTimeoutMs)!==void 0&&(!Number.isFinite(e.roundTimeoutMs)||e.roundTimeoutMs<=0))throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${e.roundTimeoutMs})`);return{maxRounds:(e==null?void 0:e.maxRounds)??ny,roundTimeoutMs:(e==null?void 0:e.roundTimeoutMs)??ry,legacyShim:(e==null?void 0:e.legacyShim)??!0}}function vd(e,t,o){if(o===null||typeof o!="object"||typeof o.method!="string")throw new U(P.InternalError,`Handler for ${e} returned an invalid input request '${t}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`);const n=o,r=ZS(n);if(r===void 0)throw new U(P.InternalError,`Handler for ${e} returned an input request '${t}' of kind '${n.method}', which is not an embedded request the 2026-07-28 revision defines`);return{embedded:n,required:r}}function iy(){const e=globalThis.crypto;if((e==null?void 0:e.randomUUID)!==void 0)return e.randomUUID();const t=new Uint8Array(16);e.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;const o=[...t].map(n=>n.toString(16).padStart(2,"0")).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function Qr(e,t){if(e==="tools/call")return{content:[{type:"text",text:t}],isError:!0};throw new U(P.InternalError,t)}var ay=class{constructor(e){this._host=e}async fulfill(e,t,o,n,r){const{maxRounds:s,roundTimeoutMs:i}=this._host,a=n.mcpReq.signal;let l=r,u=0;for(;;){if(u+=1,u>s)return Qr(e,n_(e,s));const d=l.inputRequests,m=d!=null&&Object.keys(d).length>0,h=typeof l.requestState=="string"?l.requestState:void 0;if(!m&&h===void 0)throw new U(P.InternalError,`Handler for ${e} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);let S;if(m){const b=this._host.resolvedClientCapabilities(n),N=[];for(const[w,q]of Object.entries(d)){const{embedded:W,required:V}=vd(e,w,q);if(W.method!=="roots/list"&&W.params===void 0)throw new U(P.InternalError,`Handler for ${e} returned an input request '${w}' of kind '${W.method}' without params`);if(Vu(V,b)!==void 0)return Qr(e,`Cannot request input '${w}' (${W.method}): the client on this 2025-era connection did not declare the required capability${b===void 0?" (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)":""}`);N.push([w,W])}const L=s_(a);try{const w={relatedRequestId:n.mcpReq.id,timeout:i,resetTimeoutOnProgress:!0,onprogress:()=>{},signal:L.signal},q=await Promise.all(N.map(async([W,V])=>{try{return[W,await this._dispatchLeg(V,w)]}catch(Q){throw L.abort(Q),Q}}));S=Object.fromEntries(q)}catch(w){if(a.aborted)throw w;return Qr(e,`Fulfilling input required by '${e}' failed: ${w instanceof Error?w.message:String(w)}`)}finally{L.dispose()}}else await r_(o_,a);let _={...n,mcpReq:{...n.mcpReq,inputResponses:S,droppedInputResponseKeys:void 0,requestState:Zr(h)}};if(h!==void 0){const b=await this._host.verifyRequestState(h,_,e);b!==void 0&&(_=pd(_,b))}const T=await t(o,_);if(!ht(T))return T;l=T}}async _dispatchLeg(e,t){switch(e.method){case"elicitation/create":{let o=e.params;return o.mode==="url"&&o.elicitationId===void 0&&(o={...o,elicitationId:iy()}),await this._host.sendElicitation(o,t)}case"sampling/createMessage":return await this._host.sendSampling(e.params,t);case"roots/list":return await this._host.listRoots(e.params,t)}}};const cy=new Set(["tools/call","prompts/get","resources/read"]);var ly=class extends m_{constructor(t,o){var n;super(o);R(this,"_clientCapabilities");R(this,"_clientVersion");R(this,"_capabilities");R(this,"_instructions");R(this,"_jsonSchemaValidator");R(this,"_cacheHints");R(this,"_requestStateVerify");R(this,"_inputRequiredServing");R(this,"_legacyShim");R(this,"oninitialized");R(this,"_loggingLevels",new Map);R(this,"LOG_LEVEL_SEVERITY",new Map(wn.options.map((t,o)=>[t,o])));R(this,"isMessageIgnored",(t,o)=>{const n=this._loggingLevels.get(o);return n?this.LOG_LEVEL_SEVERITY.get(t)<this.LOG_LEVEL_SEVERITY.get(n):!1});if(this._serverInfo=t,this._capabilities=o!=null&&o.capabilities?{...o.capabilities}:{},this._instructions=o==null?void 0:o.instructions,this._jsonSchemaValidator=(o==null?void 0:o.jsonSchemaValidator)??new gd,this._requestStateVerify=(n=o==null?void 0:o.requestState)==null?void 0:n.verify,this._inputRequiredServing=sy(o==null?void 0:o.inputRequired),(o==null?void 0:o.cacheHints)!==void 0){for(const[r,s]of Object.entries(o.cacheHints))s!==void 0&&Xu(s,`cacheHints['${r}']`);this._cacheHints=o.cacheHints}this.setRequestHandler("initialize",r=>this._oninitialize(r)),this.setNotificationHandler("notifications/initialized",()=>{var r;return(r=this.oninitialized)==null?void 0:r.call(this)}),Ki(this._supportedProtocolVersions).length>0&&this.setRequestHandler("server/discover",()=>this._ondiscover()),this._capabilities.logging&&this._registerLoggingHandler()}_legacyInputRequiredShim(){return this._legacyShim??(this._legacyShim=new ay({maxRounds:this._inputRequiredServing.maxRounds,roundTimeoutMs:this._inputRequiredServing.roundTimeoutMs,resolvedClientCapabilities:t=>this._inputRequestCapabilityView(t),verifyRequestState:(t,o,n)=>this._verifyRequestState(t,o,n),sendElicitation:(t,o)=>this._sendElicitationLeg(t,o,{validateAcceptedContent:!1}),sendSampling:(t,o)=>this.createMessage(t,o),listRoots:(t,o)=>this.listRoots(t,o)}))}_registerLoggingHandler(){this.setRequestHandler("logging/setLevel",async(t,o)=>{var i,a;const n=o.sessionId||((a=(i=o.http)==null?void 0:i.req)==null?void 0:a.headers.get("mcp-session-id"))||void 0,{level:r}=t.params,s=ui(wn,r);return s.success&&this._loggingLevels.set(n,s.data),{}})}buildContext(t,o){const n=t.http||(o==null?void 0:o.request)||(o==null?void 0:o.closeSSEStream)||(o==null?void 0:o.closeStandaloneSSEStream);return{...t,mcpReq:{...t.mcpReq,log:(r,s,i)=>{var l;if(!this._capabilities.logging)return Promise.resolve();let a;if(this._servedModernEra()){if(a=(l=t.mcpReq.envelope)==null?void 0:l[Pr],a===void 0)return Promise.resolve()}else a=this._loggingLevels.get(t.sessionId)??this._loggingLevels.get(void 0);return a!==void 0&&this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(a)?Promise.resolve():t.mcpReq.notify({method:"notifications/message",params:{level:r,data:s,logger:i}})},elicitInput:(r,s)=>this.elicitInput(r,s),requestSampling:(r,s)=>this.createMessage(r,s)},http:n?{...t.http,req:o==null?void 0:o.request,closeSSE:o==null?void 0:o.closeSSEStream,closeStandaloneSSE:o==null?void 0:o.closeStandaloneSSEStream}:void 0}}registerCapabilities(t){if(this.transport)throw new B(K.AlreadyConnected,"Cannot register capabilities after connecting to transport");const o=!!this._capabilities.logging;this._capabilities=md(this._capabilities,t),!o&&this._capabilities.logging&&this._registerLoggingHandler()}_wrapHandler(t,o){var n;if(t!=="tools/call"){const r=(n=this._cacheHints)==null?void 0:n[t],s=cy.has(t);return r===void 0&&!s?async(i,a)=>{const l=await o(i,a);if(ht(l))throw new U(P.InternalError,`Handler for ${t} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return l}:async(i,a)=>{const l=s?await this._invokeInputRequiredCapableHandler(t,o,i,a):await o(i,a);if(ht(l)){if(!s)throw new U(P.InternalError,`Handler for ${t} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`);return l}return r===void 0?l:ps(l,r)}}return async(r,s)=>{const i=$n(this._negotiatedProtocolVersion),a=i.validateRequest("tools/call",r);if(!a.ok)throw new U(a.reason==="not-in-era"?P.InternalError:P.InvalidParams,a.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call request: ${a.message}`);const l=await this._invokeInputRequiredCapableHandler("tools/call",o,r,s);if(ht(l))return l;const u=Bu(l),d=i.validateResult("tools/call",u);if(!d.ok)throw new U(d.reason==="not-in-era"?P.InternalError:P.InvalidParams,d.reason==="not-in-era"?"No wire schema for tools/call in the resolved era":`Invalid tools/call result: ${d.message}`);return d.value}}_servedModernEra(){return this._negotiatedProtocolVersion!==void 0&&jr(this._negotiatedProtocolVersion)}async _invokeInputRequiredCapableHandler(t,o,n,r){const s=this._servedModernEra(),i=r.mcpReq.requestState();if(i!==void 0&&typeof i!="string")throw new U(P.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"});let a=r;if(typeof i=="string"){const h=await this._verifyRequestState(i,r,t);h!==void 0&&(a=pd(r,h))}let l;try{l=await o(n,a)}catch(h){throw h instanceof U&&h.code===P.UrlElicitationRequired&&s?new U(P.InternalError,`URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`):h}if(!ht(l))return l;if(!s){if(!this._inputRequiredServing.legacyShim)throw new U(P.InternalError,`Handler for ${t} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion??ns}, which has no input_required vocabulary`);return await this._legacyInputRequiredShim().fulfill(t,o,n,a,l)}const u=l.inputRequests,d=u!=null&&Object.keys(u).length>0,m=typeof l.requestState=="string";if(!d&&!m)throw new U(P.InternalError,`Handler for ${t} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`);if(d){const h=this._inputRequestCapabilityView(r);for(const[S,_]of Object.entries(u)){const{embedded:T,required:b}=vd(t,S,_),N=Vu(b,h);if(N!==void 0)throw new ed({requiredCapabilities:N},`Cannot request input '${S}' (${T.method}): the request's client capabilities do not declare the required capability`)}}return l}async _verifyRequestState(t,o,n){var r;if(this._requestStateVerify!==void 0)try{return await this._requestStateVerify(t,o)}catch(s){throw(r=this.onerror)==null||r.call(this,new Error(`requestState verification rejected ${n}: ${s instanceof Error?s.message:String(s)}`)),new U(P.InvalidParams,"Invalid or expired requestState",{reason:"invalid_request_state"})}}_inputRequestCapabilityView(t){var o;return this._servedModernEra()?(o=t.mcpReq.envelope)==null?void 0:o[On]:this._clientCapabilities}_assertPushApiInServedEra(t){if(this._servedModernEra())throw new B(K.MethodNotSupportedByProtocolVersion,`Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${t}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`,{method:t,era:"2026-07-28"})}assertCapabilityForMethod(t){var o,n,r;switch(t){case"sampling/createMessage":if(!((o=this._clientCapabilities)!=null&&o.sampling))throw new B(K.CapabilityNotSupported,`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!((n=this._clientCapabilities)!=null&&n.elicitation))throw new B(K.CapabilityNotSupported,`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!((r=this._clientCapabilities)!=null&&r.roots))throw new B(K.CapabilityNotSupported,`Client does not support listing roots (required for ${t})`);break}}assertNotificationCapability(t){var o,n;switch(t){case"notifications/message":if(!this._capabilities.logging)throw new B(K.CapabilityNotSupported,`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new B(K.CapabilityNotSupported,`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new B(K.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new B(K.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!((n=(o=this._clientCapabilities)==null?void 0:o.elicitation)!=null&&n.url))throw new B(K.CapabilityNotSupported,`Client does not support URL elicitation (required for ${t})`);break}}assertRequestHandlerCapability(t){switch(t){case"completion/complete":if(!this._capabilities.completions)throw new B(K.CapabilityNotSupported,`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new B(K.CapabilityNotSupported,`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new B(K.CapabilityNotSupported,`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new B(K.CapabilityNotSupported,`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new B(K.CapabilityNotSupported,`Server does not support tools (required for ${t})`);break}}async _oninitialize(t){var s,i;const o=t.params.protocolVersion;this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo;const n=HS(this._supportedProtocolVersions),r=n.includes(o)?o:n[0]??ns;return this._negotiatedProtocolVersion=r,(i=(s=this.transport)==null?void 0:s.setProtocolVersion)==null||i.call(s,r),{protocolVersion:r,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}_ondiscover(){return{supportedVersions:Ki(this._supportedProtocolVersions),capabilities:uy(this.getCapabilities()),...this._instructions&&{instructions:this._instructions}}}_outboundServerInfo(){return this._serverInfo}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}projectCallToolResult(t,o){return this._wireCodec().projectCallToolResult(t,o)}getCapabilities(){return this._capabilities}async ping(){return this._assertPushApiInServedEra("ping"),this.request({method:"ping"})}async createMessage(t,o){var i,a;if(this._assertPushApiInServedEra("sampling/createMessage"),(t.tools||t.toolChoice)&&!((a=(i=this._clientCapabilities)==null?void 0:i.sampling)!=null&&a.tools))throw new B(K.CapabilityNotSupported,"Client does not support sampling tools capability.");if(t.messages.length>0){const l=t.messages.at(-1),u=Array.isArray(l.content)?l.content:[l.content],d=u.some(_=>_.type==="tool_result"),m=t.messages.length>1?t.messages.at(-2):void 0,h=m?Array.isArray(m.content)?m.content:[m.content]:[],S=h.some(_=>_.type==="tool_use");if(d){if(u.some(_=>_.type!=="tool_result"))throw new U(P.InvalidParams,"The last message must contain only tool_result content if any is present");if(!S)throw new U(P.InvalidParams,"tool_result blocks are not matching any tool_use from the previous message")}if(S){const _=new Set(h.filter(b=>b.type==="tool_use").map(b=>b.id)),T=new Set(u.filter(b=>b.type==="tool_result").map(b=>b.toolUseId));if(_.size!==T.size||![..._].every(b=>T.has(b)))throw new U(P.InvalidParams,"ids of tool_result blocks and tool_use blocks from previous message do not match")}}const n=!!(t.tools||t.toolChoice),r=await this.request({method:"sampling/createMessage",params:t},o),s=this._wireCodec().samplingResultVariant(n,r);if(!s.ok)throw new B(K.InvalidResult,`Invalid sampling/createMessage result: ${s.reason==="invalid"?s.message:s.reason}`);return s.value}async elicitInput(t,o){var n,r,s,i;switch(this._assertPushApiInServedEra("elicitation/create"),t.mode??"form"){case"url":if(!((r=(n=this._clientCapabilities)==null?void 0:n.elicitation)!=null&&r.url))throw new B(K.CapabilityNotSupported,"Client does not support url elicitation.");break;case"form":if(!((i=(s=this._clientCapabilities)==null?void 0:s.elicitation)!=null&&i.form))throw new B(K.CapabilityNotSupported,"Client does not support form elicitation.");break}return this._sendElicitationLeg(t,o)}async _sendElicitationLeg(t,o,n){const r=t.mode??"form",s=(n==null?void 0:n.validateAcceptedContent)??!0;switch(r){case"url":{const i=t;return this.request({method:"elicitation/create",params:i},o)}case"form":{const i=t.mode==="form"?t:{...t,mode:"form"},a=await this.request({method:"elicitation/create",params:i},o);if(s&&a.action==="accept"&&a.content&&i.requestedSchema)try{const l=this._jsonSchemaValidator.getValidator(i.requestedSchema)(a.content);if(!l.valid)throw new U(P.InvalidParams,`Elicitation response content does not match requested schema: ${l.errorMessage}`)}catch(l){throw l instanceof U?l:new U(P.InternalError,`Error validating elicitation response: ${l instanceof Error?l.message:String(l)}`)}return a}}}createElicitationCompletionNotifier(t,o){var n,r;if(!((r=(n=this._clientCapabilities)==null?void 0:n.elicitation)!=null&&r.url))throw new B(K.CapabilityNotSupported,"Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},o)}async listRoots(t,o){return this._assertPushApiInServedEra("roots/list"),this.request({method:"roots/list",params:t},o)}async sendLoggingMessage(t,o){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,o))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};function uy(e){return{...e}}var dy=class{constructor(e,t){R(this,"server");R(this,"_registeredResources",{});R(this,"_registeredResourceTemplates",{});R(this,"_registeredTools",{});R(this,"_registeredPrompts",{});R(this,"_toolInputSchemaJson",{});R(this,"_toolHandlersInitialized",!1);R(this,"_completionHandlerInitialized",!1);R(this,"_resourceHandlersInitialized",!1);R(this,"_promptHandlersInitialized",!1);var o,n,r;this.server=new ly(e,t),(o=t==null?void 0:t.capabilities)!=null&&o.tools&&this.setToolRequestHandlers(),(n=t==null?void 0:t.capabilities)!=null&&n.resources&&this.setResourceRequestHandlers(),(r=t==null?void 0:t.capabilities)!=null&&r.prompts&&this.setPromptRequestHandlers()}toolInputSchemaJson(e){const t=this._registeredTools[e];if(!(t===void 0||!t.enabled)){if(Object.hasOwn(this._toolInputSchemaJson,e))return this._toolInputSchemaJson[e];if(t.inputSchema===void 0)return fa;try{const o=Ht(t.inputSchema,"input");return this._toolInputSchemaJson[e]=o,o}catch{return}}}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){var e;this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler("tools/list"),this.server.assertCanSetRequestHandler("tools/call"),this.server.registerCapabilities({tools:{listChanged:((e=this.server.getCapabilities().tools)==null?void 0:e.listChanged)??!0}}),this.server.setRequestHandler("tools/list",()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,o])=>{const n={name:t,title:o.title,description:o.description,inputSchema:o.inputSchema?Ht(o.inputSchema,"input"):fa,annotations:o.annotations,icons:o.icons,execution:o.execution,_meta:o._meta};return o.outputSchema&&(n.outputSchema=Ht(o.outputSchema,"output")),n})})),this.server.setRequestHandler("tools/call",async(t,o)=>{const n=this._registeredTools[t.params.name];if(!n)throw new U(P.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new U(P.InvalidParams,`Tool ${t.params.name} disabled`);try{const r=await this.validateToolInput(n,t.params.arguments,t.params.name),s=await this.executeToolHandler(n,r,o);return await this.validateToolOutput(n,s,t.params.name),ht(s)?s:this.server.projectCallToolResult(s,n.outputSchemaJson)}catch(r){if(r instanceof U&&r.code===P.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,o){if(!e.inputSchema)return;const n=await mo(e.inputSchema,t??{});if(!n.success)throw new U(P.InvalidParams,`Input validation error: Invalid arguments for tool ${o}: ${n.error}`);return n.data}async validateToolOutput(e,t,o){if(!e.outputSchema||ht(t)||t.isError)return;if(t.structuredContent===void 0)throw new U(P.InvalidParams,`Output validation error: Tool ${o} has an output schema but no structured content was provided`);const n=await mo(e.outputSchema,t.structuredContent);if(!n.success)throw new U(P.InvalidParams,`Output validation error: Invalid structured content for tool ${o}: ${n.error}`)}async executeToolHandler(e,t,o){return e.executor(t,o)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler("completion/complete"),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler("completion/complete",async e=>{switch(e.params.ref.type){case"ref/prompt":return Nv(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Mv(e),this.handleResourceCompletion(e,e.params.ref);default:throw new U(P.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){var s;const o=this._registeredPrompts[t.name];if(!o)throw new U(P.InvalidParams,`Prompt ${t.name} not found`);if(!o.enabled)throw new U(P.InvalidParams,`Prompt ${t.name} disabled`);if(!o.argsSchema)return pn;const n=ya((s=_a(o.argsSchema))==null?void 0:s[e.params.argument.name]);if(!ma(n))return pn;const r=oy(n);return r?va(await r(e.params.argument.value,e.params.context)):pn}async handleResourceCompletion(e,t){const o=Object.values(this._registeredResourceTemplates).find(r=>r.resourceTemplate.uriTemplate.toString()===t.uri);if(!o){if(this._registeredResources[t.uri])return pn;throw new U(P.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const n=o.resourceTemplate.completeCallback(e.params.argument.name);return n?va(await n(e.params.argument.value,e.params.context)):pn}setResourceRequestHandlers(){var e;this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler("resources/list"),this.server.assertCanSetRequestHandler("resources/templates/list"),this.server.assertCanSetRequestHandler("resources/read"),this.server.registerCapabilities({resources:{listChanged:((e=this.server.getCapabilities().resources)==null?void 0:e.listChanged)??!0}}),this.server.setRequestHandler("resources/list",async(t,o)=>{const n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),r=[];for(const s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;const i=await s.resourceTemplate.listCallback(o);for(const a of i.resources)r.push({...s.metadata,...a})}return{resources:[...n,...r]}}),this.server.setRequestHandler("resources/templates/list",async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,o])=>({name:t,uriTemplate:o.resourceTemplate.uriTemplate.toString(),...o.metadata}))})),this.server.setRequestHandler("resources/read",async(t,o)=>{let n;try{n=new URL(t.params.uri)}catch{throw new U(P.InvalidParams,`Resource URI ${t.params.uri} is invalid`,{uri:t.params.uri,reason:"invalid_uri"})}const r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new U(P.InvalidParams,`Resource ${n} disabled`);return ps(await r.readCallback(n,o),r.cacheHint)}for(const s of Object.values(this._registeredResourceTemplates)){const i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return ps(await s.readCallback(n,i,o),s.cacheHint)}throw new Qu(t.params.uri)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){var e;this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler("prompts/list"),this.server.assertCanSetRequestHandler("prompts/get"),this.server.registerCapabilities({prompts:{listChanged:((e=this.server.getCapabilities().prompts)==null?void 0:e.listChanged)??!0}}),this.server.setRequestHandler("prompts/list",()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,o])=>({name:t,title:o.title,description:o.description,arguments:o.argsSchema?Jv(o.argsSchema):void 0,icons:o.icons,_meta:o._meta}))})),this.server.setRequestHandler("prompts/get",async(t,o)=>{const n=this._registeredPrompts[t.params.name];if(!n)throw new U(P.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new U(P.InvalidParams,`Prompt ${t.params.name} disabled`);return n.handler(t.params.arguments,o)}),this._promptHandlersInitialized=!0)}registerResource(e,t,o,n){const r=o.cacheHint;let s=o;if(r!==void 0){Xu(r,`resource ${e}`);const i={...o};delete i.cacheHint,s=i}if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);const i=this._createRegisteredResource(e,o.title,t,s,n);return r!==void 0&&(i.cacheHint=r),this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const i=this._createRegisteredResourceTemplate(e,o.title,t,s,n);return r!==void 0&&(i.cacheHint=r),this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,o,n,r){const s={name:e,title:t,metadata:n,readCallback:r,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:i=>{i.uri!==void 0&&i.uri!==o&&(delete this._registeredResources[o],i.uri&&(this._registeredResources[i.uri]=s)),i.name!==void 0&&(s.name=i.name),i.title!==void 0&&(s.title=i.title),i.metadata!==void 0&&(s.metadata=i.metadata),i.callback!==void 0&&(s.readCallback=i.callback),i.enabled!==void 0&&(s.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[o]=s,s}_createRegisteredResourceTemplate(e,t,o,n,r){const s={resourceTemplate:o,title:t,metadata:n,readCallback:r,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{a.name!==void 0&&a.name!==e&&(delete this._registeredResourceTemplates[e],a.name&&(this._registeredResourceTemplates[a.name]=s)),a.title!==void 0&&(s.title=a.title),a.template!==void 0&&(s.resourceTemplate=a.template),a.metadata!==void 0&&(s.metadata=a.metadata),a.callback!==void 0&&(s.readCallback=a.callback),a.enabled!==void 0&&(s.enabled=a.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;const i=o.uriTemplate.variableNames;return Array.isArray(i)&&i.some(a=>!!o.completeCallback(a))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(e,t,o,n,r,s,i){let a=n,l=r;const u={title:t,description:o,argsSchema:n,icons:s,_meta:i,handler:Sa(e,n,r),enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{d.name!==void 0&&d.name!==e&&(delete this._registeredPrompts[e],d.name&&(this._registeredPrompts[d.name]=u)),d.title!==void 0&&(u.title=d.title),d.description!==void 0&&(u.description=d.description),d.icons!==void 0&&(u.icons=d.icons),d._meta!==void 0&&(u._meta=d._meta);let m=!1;d.argsSchema!==void 0&&(u.argsSchema=d.argsSchema,a=d.argsSchema,m=!0),d.callback!==void 0&&(l=d.callback,m=!0),m&&(u.handler=Sa(e,a,l)),d.enabled!==void 0&&(u.enabled=d.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=u,n){const d=_a(n);d&&Object.values(d).some(m=>ma(ya(m)))&&this.setCompletionRequestHandler()}return u}_createRegisteredTool(e,t,o,n,r,s,i,a,l,u){if(la(e),n!==void 0)try{const h=Ht(n,"input");this._toolInputSchemaJson[e]=h;const S=Av(h);S.valid||console.warn(`[mcp-sdk] tool '${e}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${S.reason}`)}catch{}let d=u;const m={title:t,description:o,inputSchema:n,outputSchema:r,outputSchemaJson:ga(r),annotations:s,icons:i,execution:a,_meta:l,handler:u,executor:ha(n,u),enabled:!0,disable:()=>m.update({enabled:!1}),enable:()=>m.update({enabled:!0}),remove:()=>m.update({name:null}),update:h=>{h.name!==void 0&&h.name!==e&&(typeof h.name=="string"&&la(h.name),delete this._registeredTools[e],delete this._toolInputSchemaJson[e],h.name&&(delete this._toolInputSchemaJson[h.name],this._registeredTools[h.name]=m,e=h.name)),h.title!==void 0&&(m.title=h.title),h.description!==void 0&&(m.description=h.description);let S=!1;h.paramsSchema!==void 0&&(m.inputSchema=h.paramsSchema,delete this._toolInputSchemaJson[e],S=!0),h.callback!==void 0&&(m.handler=h.callback,d=h.callback,S=!0),S&&(m.executor=ha(m.inputSchema,d)),h.outputSchema!==void 0&&(m.outputSchema=h.outputSchema,m.outputSchemaJson=ga(h.outputSchema)),h.annotations!==void 0&&(m.annotations=h.annotations),h.icons!==void 0&&(m.icons=h.icons),h._meta!==void 0&&(m._meta=h._meta),h.enabled!==void 0&&(m.enabled=h.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=m,this.setToolRequestHandlers(),this.sendToolListChanged(),m}registerTool(e,t,o){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:n,description:r,inputSchema:s,outputSchema:i,annotations:a,icons:l,_meta:u}=t;return this._createRegisteredTool(e,n,r,Xr(s),Xr(i),a,l,void 0,u,o)}registerPrompt(e,t,o){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:n,description:r,argsSchema:s,icons:i,_meta:a}=t,l=this._createRegisteredPrompt(e,n,r,Xr(s),o,i,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),l}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},py=class{constructor(e,t){R(this,"_uriTemplate");this._callbacks=t,this._uriTemplate=typeof e=="string"?new b_(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){var t;return(t=this._callbacks.complete)==null?void 0:t[e]}};function ha(e,t){if(e){const n=t;return async(r,s)=>n(r,s)}const o=t;return async(n,r)=>o(r)}const fa={type:"object",properties:{}};function ga(e){if(e!==void 0)try{return Ht(e,"output")}catch{return}}function Sa(e,t,o){if(t){const n=o;return async(r,s)=>{const i=await mo(t,r);if(!i.success)throw new U(P.InvalidParams,`Invalid arguments for prompt ${e}: ${i.error}`);return n(i.data,s)}}else{const n=o;return async(r,s)=>n(s)}}function va(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}const pn={completion:{values:[],hasMore:!1}};function _a(e){const t=e;if(t.shape&&typeof t.shape=="object")return t.shape}function my(e){return(e==null?void 0:e.type)==="optional"}function ya(e){var t;return my(e)?((t=e.def)==null?void 0:t.innerType)??e:e}let hy;function fs(e,t){return $_(e,hy??(hy=new gd))}const fy=Ou(void 0).inputSchema,gs="__isBrowserMcpServer";function gy(e){return typeof e=="object"&&e!==null&&gs in e&&e[gs]===!0}function Sy(e){if(e===null)return{content:[{type:"text",text:"Tool execution interrupted by navigation"}],isError:!0};let t;try{t=JSON.parse(e)}catch{return rs(e)}return ht(t)?t:rs(t)}function vy(e){const t=Object.getOwnPropertyDescriptor(e.inputSchema,"~standard");return t&&!t.enumerable?e.inputSchema:fs(e.inputSchema)}function _y(e){if(!e)return;const{untrustedContentHint:t,...o}=e;return o}function yy(e,t,o){const n=e.annotations?ti(e.annotations):void 0;return{name:e.name,...e.title!==void 0?{title:e.title}:{},description:e.description,...t!==void 0?{inputSchema:t}:{},...n?{annotations:n}:{},execute:o}}var $a,Ea,by=class extends(Ea=EventTarget,$a=gs,Ea){constructor(t,o={}){super();R(this,$a,!0);R(this,"mcpServer");R(this,"native");R(this,"ownerDocument");R(this,"tools",new Map);R(this,"peerOrigin");R(this,"registrations",new Set);R(this,"nativeToolAbortControllers",new Map);R(this,"nativeBackfilledTools",new Map);R(this,"pendingTools",new Map);R(this,"removingNativeTools",new Set);R(this,"nativeSyncQueue",Promise.resolve());R(this,"nativeToolChangeQueue",Promise.resolve());R(this,"nativeToolChangeListener");R(this,"closed",!1);R(this,"closePromise");R(this,"ontoolchangeHandler",null);R(this,"ontoolchangeListener",t=>{var o;(o=this.ontoolchangeHandler)==null||o.call(this,t)});R(this,"registerTool",async(t,o={})=>{var d,m,h,S,_,T,b,N;const n=o??{};if(Dt(this.ownerDocument),this.closed)throw De("BrowserMcpServer is closed");if(!He(t))throw new TypeError("registerTool(tool) requires a tool object");const r=Ru(t),s=this.validateToolDescriptor(r);(d=n.signal)==null||d.throwIfAborted(),gr(n.exposedTo),(m=n.signal)==null||m.throwIfAborted();const i=async(L,w)=>(w==null||w.throwIfAborted(),fr(Promise.resolve().then(()=>Reflect.apply(r.execute,void 0,[L])),w)),a=new AbortController;let l;const u=()=>{this.pendingTools.get(r.name)===a&&this.pendingTools.delete(r.name),l&&this.tools.get(r.name)===l?this.removeTool(r.name):this.abortNativeToolMirror(r.name,a)};(h=n.signal)==null||h.addEventListener("abort",u,{once:!0}),this.pendingTools.set(r.name,a);try{if(await this.registerNativeToolMirror(r,s,n,i,a),this.closed)throw De("BrowserMcpServer is closed");(S=n.signal)==null||S.throwIfAborted(),l=this.registerToolInMcp(r,s,i,n.exposedTo),this.tools.set(r.name,l),this.applyToolExposure(),(_=n.signal)!=null&&_.aborted&&(u(),n.signal.throwIfAborted())}catch(L){throw this.abortNativeToolMirror(r.name,a),(T=n.signal)==null||T.removeEventListener("abort",u),(b=n.signal)==null||b.throwIfAborted(),L}finally{this.pendingTools.get(r.name)===a&&this.pendingTools.delete(r.name)}if(n.signal&&(l.abortSignal=n.signal,l.abortListener=u),this.tools.get(r.name)===l&&(this.native?await this.nativeToolChangeQueue:await this.notifyProducerToolsChanged()),this.closed)throw De("BrowserMcpServer is closed");(N=n.signal)==null||N.throwIfAborted()});const{native:n,...r}=o;this.mcpServer=new dy(t,{...r,capabilities:md(r.capabilities??{},{tools:{listChanged:!0},resources:{listChanged:!0},prompts:{listChanged:!0}})}),this.native=n,this.ownerDocument=globalThis.document??null,n&&typeof n.addEventListener=="function"&&typeof n.removeEventListener=="function"&&(this.nativeToolChangeListener=()=>{this.closed||(this.nativeToolChangeQueue=this.nativeToolChangeQueue.then(async()=>{try{await this.syncNativeTools()}catch(s){console.warn("[BrowserMcpServer] Native WebMCP tool reconciliation failed:",s)}await this.notifyProducerToolsChanged()}))},n.addEventListener("toolchange",this.nativeToolChangeListener))}get ontoolchange(){return this.ontoolchangeHandler}set ontoolchange(t){const o=typeof t=="function"?t:null;if(o===null){this.ontoolchangeHandler=null,super.removeEventListener("toolchange",this.ontoolchangeListener);return}this.ontoolchangeHandler===null&&super.addEventListener("toolchange",this.ontoolchangeListener),this.ontoolchangeHandler=o}async notifyProducerToolsChanged(){this.closed||(await new Promise(t=>setTimeout(t,0)),this.closed||this.dispatchEvent(new Event("toolchange")))}getNativeStandardToolsApi(){const t=this.native;return t&&typeof t.executeTool=="function"?t:void 0}async registerNativeToolMirror(t,o,n,r,s){if(!this.native)return;const i=this.native.registerTool,a=n.signal?AbortSignal.any([n.signal,s.signal]):s.signal,l=o.registeredInputSchema===void 0?void 0:JSON.parse(o.registeredInputSchema);this.nativeToolAbortControllers.set(t.name,s);try{await i.call(this.native,yy(t,l,u=>r(u)),{...n,signal:a})}catch(u){throw s.abort(),this.nativeToolAbortControllers.get(t.name)===s&&this.nativeToolAbortControllers.delete(t.name),u}this.nativeToolAbortControllers.get(t.name)===s&&this.removingNativeTools.delete(t.name)}abortNativeToolMirror(t,o=this.nativeToolAbortControllers.get(t)){!o||this.nativeToolAbortControllers.get(t)!==o||(this.removingNativeTools.add(t),o.abort(),this.nativeToolAbortControllers.delete(t))}validateToolDescriptor(t){if($u(t),this.tools.has(t.name)||this.pendingTools.has(t.name))throw De(`Tool already registered: ${t.name}`);return Ou(t.inputSchema)}registerToolInMcp(t,o,n,r){const s=t.outputSchema===void 0?void 0:structuredClone(t.outputSchema),i=s===void 0?void 0:fs(s),a=_y(t.annotations),l=o.inputSchema.type===void 0||o.inputSchema.type==="object",u=l?this.mcpServer.registerTool(t.name,{...t.title!==void 0?{title:t.title}:{},description:t.description,inputSchema:vy(o),...i?{outputSchema:i}:{},...a?{annotations:a}:{}},async(d,m)=>{const h=await n(d,m.mcpReq.signal);if(ht(h))throw new Error(`WebMCP tool "${t.name}" returned input_required. Multi-round tool flows require BrowserMcpServer.mcpServer.registerTool().`);return rs(h)}):void 0;return r!=null&&r.length&&(u==null||u.disable()),l||console.warn(`[BrowserMcpServer] Tool "${t.name}" remains available through WebMCP but cannot be exposed over MCP because MCP input schemas require an object root.`),{item:{name:t.name,...t.title!==void 0?{title:t.title}:{},description:t.description,inputSchema:o.inputSchema,...s===void 0?{}:{outputSchema:s},...t.annotations?{annotations:t.annotations}:{}},...o.registeredInputSchema!==void 0?{registeredInputSchema:o.registeredInputSchema}:{},execute:n,mcpHandle:u,...r!=null&&r.length?{exposedTo:r}:{}}}removeTool(t,o){var r;const n=this.tools.get(t);n&&(n.abortSignal&&n.abortListener&&n.abortSignal.removeEventListener("abort",n.abortListener),this.tools.delete(t),this.nativeBackfilledTools.delete(t),(r=n.mcpHandle)==null||r.remove(),((o==null?void 0:o.notify)??!0)&&!this.native&&this.notifyProducerToolsChanged()),o!=null&&o.skipNative||this.abortNativeToolMirror(t)}syncNativeTools(){const t=this.nativeSyncQueue.then(async()=>{if(this.closed)return;const o=this.getNativeStandardToolsApi();o&&await this.backfillNativeStandardTools(o)});return this.nativeSyncQueue=t.then(()=>{},()=>{}),t}async backfillNativeStandardTools(t){const o=await t.getTools();if(this.closed)return;const n=new Map,r=new Set(o.map(({name:s})=>s));for(const s of this.removingNativeTools)r.has(s)||this.removingNativeTools.delete(s);for(const s of o){if(n.has(s.name)||this.pendingTools.has(s.name)||this.removingNativeTools.has(s.name))continue;let i=fy;if(s.inputSchema!==void 0)try{const l=typeof s.inputSchema=="string"?s.inputSchema:JSON.stringify(s.inputSchema),u=JSON.parse(l);i=He(u)?u:void 0}catch{i=void 0}if(!i){console.warn(`[BrowserMcpServer] Native tool "${s.name}" was not exposed over MCP because its input schema is malformed.`);continue}const a={name:s.name,...s.title!==void 0?{title:s.title}:{},description:s.description,inputSchema:i,...s.annotations?{annotations:s.annotations}:{}};n.set(s.name,{source:s,item:a,fingerprint:JSON.stringify(a)})}for(const[s,i]of this.nativeBackfilledTools){const a=n.get(s);if(!a||a.fingerprint!==i.fingerprint){this.removeTool(s,{skipNative:!0,notify:!1});continue}this.nativeBackfilledTools.set(s,a)}for(const[s,i]of n){if(this.tools.has(s))continue;const a=async(u,d)=>{var S;const m=(S=this.nativeBackfilledTools.get(s))==null?void 0:S.source;if(!m)throw new Error(`Native tool not found: ${s}`);const h=JSON.stringify(u);return Sy(d?await t.executeTool.call(this.native,m,h,{signal:d}):await t.executeTool.call(this.native,m,h))},l={name:s,...i.item.title!==void 0?{title:i.item.title}:{},description:i.item.description,inputSchema:i.item.inputSchema,...i.item.annotations?{annotations:i.item.annotations}:{},execute:u=>a(u)};try{const u=this.validateToolDescriptor(l);this.tools.set(l.name,this.registerToolInMcp(l,u,a,void 0)),this.nativeBackfilledTools.set(s,i)}catch(u){console.warn(`[BrowserMcpServer] Native tool "${s}" was not exposed over MCP because its schema could not be compiled:`,u)}}}registerResource(t){if(this.closed)throw De("BrowserMcpServer is closed");const o={...t},n={...o.description!==void 0?{description:o.description}:{},...o.mimeType!==void 0?{mimeType:o.mimeType}:{}},r=o.uri.includes("{")?new py(o.uri,{list:void 0}):void 0,s=r?this.mcpServer.registerResource(o.name,r,n,async(i,a)=>o.read(i,a)):this.mcpServer.registerResource(o.name,o.uri,n,async i=>o.read(i));return this.registrations.add(s),{unregister:()=>{this.registrations.delete(s)&&s.remove()}}}registerPrompt(t){if(this.closed)throw De("BrowserMcpServer is closed");const o={...t,...t.argsSchema===void 0?{}:{argsSchema:structuredClone(t.argsSchema)}},n=o.argsSchema===void 0?void 0:fs(o.argsSchema),r=this.mcpServer.registerPrompt(o.name,{...o.description!==void 0?{description:o.description}:{},...n?{argsSchema:n}:{}},async s=>o.get(s??{}));return this.registrations.add(r),{unregister:()=>{this.registrations.delete(r)&&r.remove()}}}listTools(){return structuredClone([...this.tools.values()].map(({item:t})=>t))}async getTools(t){var s,i;if(Dt(this.ownerDocument),this.closed)throw De("BrowserMcpServer is closed");if(this.native)return this.native.getTools(t);if(gr(t==null?void 0:t.fromOrigins),(s=t==null?void 0:t.fromOrigins)!=null&&s.length)throw new DOMException("Cross-document tool discovery requires native WebMCP","NotSupportedError");const o=((i=globalThis.location)==null?void 0:i.origin)??"",n=globalThis.window,r=[...this.tools.values()].map(({item:a,registeredInputSchema:l})=>{const u=l===void 0?void 0:JSON.parse(l);return{name:a.name,title:a.title??"",description:a.description,...He(u)?{inputSchema:u}:{},origin:o,window:n,...a.annotations?{annotations:ti(a.annotations)}:{}}}).sort((a,l)=>a.name<l.name?-1:a.name>l.name?1:0);return await new Promise(a=>setTimeout(a,0)),r}async executeTool(t,o,n){var u,d,m,h;if(Dt(this.ownerDocument),this.closed)throw De("BrowserMcpServer is closed");const r=this.getNativeStandardToolsApi();if(r)return r.executeTool.call(this.native,t,o,n);if(t===null||typeof t!="object")throw new TypeError("RegisteredTool must be an object");for(const S of["name","description","window","origin"])if(!(S in t))throw new TypeError(`RegisteredTool.${S} is required`);Cu(t.origin);const s=((u=globalThis.location)==null?void 0:u.origin)??"",i=globalThis.window;if(t.origin!==s||t.window!==i)throw mt(`Native tool not found: ${t.name}`);(d=n==null?void 0:n.signal)==null||d.throwIfAborted();const a=this.tools.get(t.name);if(!a)throw mt(`Tool not found: ${t.name}`);const l=Eu(o);try{return Pu(await fr(a.execute(l,n==null?void 0:n.signal),a.abortSignal,()=>mt("Tool unregistered")))}catch(S){throw(m=n==null?void 0:n.signal)!=null&&m.aborted&&S===n.signal.reason||(h=a.abortSignal)!=null&&h.aborted?S:Tu(S)}}applyToolExposure(){for(const{exposedTo:t,mcpHandle:o}of this.tools.values()){if(!(t!=null&&t.length)||!o)continue;const n=this.peerOrigin!==void 0&&t.includes(this.peerOrigin);n!==o.enabled&&(n?o.enable():o.disable())}}observePeerOrigin(t){if(!("clientOrigin"in t))return;const o=t;this.peerOrigin=o.clientOrigin,this.applyToolExposure();const n=o.onclientorigin;o.onclientorigin=r=>{n==null||n(r),this.peerOrigin=r,this.applyToolExposure()}}connect(t){return this.closed?Promise.reject(De("BrowserMcpServer is closed")):(this.observePeerOrigin(t),this.mcpServer.connect(t))}close(){return this.closePromise?this.closePromise:(this.closed=!0,this.closePromise=(async()=>{this.native&&this.nativeToolChangeListener&&(this.native.removeEventListener("toolchange",this.nativeToolChangeListener),this.nativeToolChangeListener=void 0);for(const t of this.nativeToolAbortControllers.keys())this.abortNativeToolMirror(t);for(const t of this.tools.keys())this.removeTool(t,{notify:!1});for(const t of this.registrations)t.remove();this.registrations.clear(),this.nativeBackfilledTools.clear(),this.removingNativeTools.clear(),await this.mcpServer.close()})(),this.closePromise)}};let Xe=null;function Ry(){return typeof window<"u"&&typeof window.navigator<"u"}function ba(){return document.modelContext??navigator.modelContext}function Ra(e){const t=Object.getOwnPropertyDescriptor(e,"modelContext");return t?t.configurable===!0:Object.isExtensible(e)}function wy(e){Object.defineProperty(document,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:e}),document.modelContext!==e&&console.error("[WebModelContext] Failed to replace document.modelContext.","Descriptor:",Object.getOwnPropertyDescriptor(document,"modelContext"))}function Ty(e){Object.defineProperty(navigator,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:e}),navigator.modelContext!==e&&console.error("[WebModelContext] Failed to replace navigator.modelContext.","Descriptor:",Object.getOwnPropertyDescriptor(navigator,"modelContext"))}function br(e,t,o){o?Object.defineProperty(e,t,o):Reflect.deleteProperty(e,t)}function $y(e,t,o){try{wy(e),Ty(e)}catch(n){throw br(document,"modelContext",t),br(navigator,"modelContext",o),n}}function Ey(e){if(window.parent!==window&&(e==null?void 0:e.iframeServer)!==!1)return new Ag(typeof(e==null?void 0:e.iframeServer)=="object"?e.iframeServer:{allowedOrigins:["*"]});if((e==null?void 0:e.tabServer)===!1)throw new Error("tabServer transport is disabled and iframe transport was not selected");return new Lg(typeof(e==null?void 0:e.tabServer)=="object"?e.tabServer:{allowedOrigins:["*"]})}function Py(e){if(!Ry()||globalThis.isSecureContext===!1||Xe)return;const t=ba();if(t&&gy(t))return;TS({installTestingShim:(e==null?void 0:e.installTestingShim)??!0});const o=ba();if(!o)throw new Error("modelContext is not available");if(!Ra(document)||!Ra(navigator))return;const n=Ey(e==null?void 0:e.transport),r=new by({name:`${window.location.hostname||"localhost"}-webmcp`,version:"1.0.0"},{native:o}),s=Object.getOwnPropertyDescriptor(document,"modelContext"),i=Object.getOwnPropertyDescriptor(navigator,"modelContext");try{$y(r,s,i),Xe={native:o,server:r,transport:n,previousDocumentModelContextDescriptor:s,previousNavigatorModelContextDescriptor:i}}catch(a){throw r.close(),n.close(),a}(async()=>{try{await r.syncNativeTools()}catch(a){console.warn("[WebModelContext] Native WebMCP tool synchronization failed:",a)}if((Xe==null?void 0:Xe.server)===r)try{await r.connect(n)}catch(a){console.error("[WebModelContext] Failed to connect MCP transport:",a),(Xe==null?void 0:Xe.server)===r&&Cy()}})()}function Cy(){if(!Xe)return;const{server:e,transport:t,previousDocumentModelContextDescriptor:o,previousNavigatorModelContextDescriptor:n}=Xe;Xe=null,e.close(),t.close(),br(document,"modelContext",o),br(navigator,"modelContext",n)}if(typeof window<"u"&&typeof document<"u"){const e=window.__webModelContextOptions;if((e==null?void 0:e.autoInitialize)!==!1)try{Py(e)}catch(t){console.error("[WebModelContext] Auto-initialization failed:",t)}}export{Cy as cleanupWebModelContext,Py as initializeWebModelContext};