@reqvire-org/ads 0.3.45 → 0.3.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -11
- package/dist/a11y.mjs +102 -0
- package/dist/assets.mjs +37 -8
- package/dist/atomic-composition.mjs +3 -2
- package/dist/brand-assets.mjs +48 -11
- package/dist/brands.mjs +82 -0
- package/dist/browser-audit/worker.mjs +45 -0
- package/dist/browser-audit.mjs +117 -0
- package/dist/capture/worker.mjs +2 -1
- package/dist/capture-store.mjs +4 -1
- package/dist/capture.mjs +10 -4
- package/dist/check.mjs +40 -9
- package/dist/cli.mjs +55 -8
- package/dist/color-values.mjs +325 -0
- package/dist/config.mjs +19 -2
- package/dist/contracts/tokens.json +1 -1
- package/dist/control-padding.mjs +93 -0
- package/dist/design-values.mjs +11 -4
- package/dist/finding-rules.mjs +61 -0
- package/dist/foundation.mjs +17 -1
- package/dist/icons.mjs +107 -0
- package/dist/init.mjs +3 -0
- package/dist/mcp/apps.mjs +9 -6
- package/dist/mcp/drafts.mjs +3 -0
- package/dist/mcp/mutations.mjs +17 -1
- package/dist/mcp/preview-widget.bundle.js +45 -39
- package/dist/mcp/project-widget.bundle.js +26 -26
- package/dist/mcp/server.mjs +23 -9
- package/dist/mcp/widget.bundle.js +17 -17
- package/dist/palette-generated.mjs +180 -0
- package/dist/preview-resources.mjs +12 -3
- package/dist/render-color-probe.mjs +148 -0
- package/dist/runtime-contracts.mjs +14 -4
- package/dist/scenarios.mjs +1 -1
- package/dist/showcase/client.bundle.js +28 -28
- package/dist/showcase/icons.js +146 -0
- package/dist/showcase/index.html +2 -1
- package/dist/showcase/style.css +19 -2
- package/dist/skills/README.md +2 -1
- package/dist/skills/ads-break-ui/SKILL.md +6 -5
- package/dist/skills/ads-break-ui/references/atomic-styles.md +12 -12
- package/dist/skills/ads-break-ui/references/captures.md +3 -2
- package/dist/skills/ads-break-ui/references/contracts.md +13 -10
- package/dist/skills/ads-break-ui/references/design-data.md +199 -2
- package/dist/skills/ads-break-ui/references/validation.md +8 -4
- package/dist/skills/ads-designer/SKILL.md +32 -15
- package/dist/skills/ads-designer/references/accessibility.md +77 -0
- package/dist/skills/ads-designer/references/atomic-styles.md +12 -12
- package/dist/skills/ads-designer/references/branding.md +61 -6
- package/dist/skills/ads-designer/references/captures.md +3 -2
- package/dist/skills/ads-designer/references/cli.md +8 -2
- package/dist/skills/ads-designer/references/contracts.md +13 -10
- package/dist/skills/ads-designer/references/design-data.md +199 -2
- package/dist/skills/ads-designer/references/validation.md +8 -4
- package/dist/skills/ads-import/SKILL.md +9 -8
- package/dist/skills/ads-import/references/atomic-styles.md +12 -12
- package/dist/skills/ads-import/references/captures.md +3 -2
- package/dist/skills/ads-import/references/cli.md +8 -2
- package/dist/skills/ads-import/references/contracts.md +13 -10
- package/dist/skills/ads-import/references/design-data.md +199 -2
- package/dist/skills/ads-import/references/tokens.md +7 -3
- package/dist/skills/ads-import/references/validation.md +8 -4
- package/dist/skills/ads-motion/SKILL.md +6 -5
- package/dist/skills/ads-motion/references/atomic-styles.md +12 -12
- package/dist/skills/ads-motion/references/build.md +33 -0
- package/dist/skills/ads-motion/references/captures.md +3 -2
- package/dist/skills/ads-motion/references/contracts.md +13 -10
- package/dist/skills/ads-motion/references/design-data.md +199 -2
- package/dist/skills/ads-motion/references/motion-review.md +2 -2
- package/dist/skills/ads-motion/references/validation.md +8 -4
- package/dist/skills/ads-port/SKILL.md +6 -5
- package/dist/skills/ads-port/references/atomic-styles.md +12 -12
- package/dist/skills/ads-port/references/captures.md +3 -2
- package/dist/skills/ads-port/references/cli.md +8 -2
- package/dist/skills/ads-port/references/contracts.md +13 -10
- package/dist/skills/ads-port/references/design-data.md +199 -2
- package/dist/skills/ads-port/references/validation.md +8 -4
- package/dist/starters/preact/design-system/components/Layout/Grid/Grid.tsx +76 -0
- package/dist/starters/preact/design-system/review/token-preview/TokenPreview.tsx +19 -1
- package/dist/starters/preact/ds.config.json +13 -1
- package/dist/starters/react/ADS.md +43 -10
- package/dist/starters/react/README.md +61 -9
- package/dist/starters/react/design-system/assets/brand/README.md +8 -3
- package/dist/starters/react/design-system/assets/glyphs/README.md +15 -0
- package/dist/starters/react/design-system/assets/glyphs/aliases.json +1 -0
- package/dist/starters/react/design-system/assets/glyphs/check.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/chevron-down.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/chevron-right.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/close.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/external-link.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/info.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/menu.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/plus.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/search.svg +1 -0
- package/dist/starters/react/design-system/assets/glyphs/warning.svg +1 -0
- package/dist/starters/react/design-system/components/Actions/Button/Button.tsx +11 -4
- package/dist/starters/react/design-system/components/Actions/IconButton/IconButton.ads.fixture.ts +9 -0
- package/dist/starters/react/design-system/components/Actions/IconButton/IconButton.ads.scenario.tsx +16 -0
- package/dist/starters/react/design-system/components/Actions/IconButton/IconButton.tsx +44 -0
- package/dist/starters/react/design-system/components/Actions/IconButton/README.md +14 -0
- package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.fixture.ts +6 -0
- package/dist/starters/react/design-system/components/Content/Icon/Icon.ads.scenario.tsx +16 -0
- package/dist/starters/react/design-system/components/Content/Icon/Icon.tsx +42 -0
- package/dist/starters/react/design-system/components/Content/Icon/README.md +17 -0
- package/dist/starters/react/design-system/components/Content/Icon/glyphs.ts +17 -0
- package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +3 -9
- package/dist/starters/react/design-system/components/Content/Logo/README.md +4 -2
- package/dist/starters/react/design-system/components/Forms/TextField/TextField.tsx +9 -5
- package/dist/starters/react/design-system/components/Layout/Grid/Grid.ads.fixture.ts +12 -0
- package/dist/starters/react/design-system/components/Layout/Grid/Grid.ads.scenario.tsx +17 -0
- package/dist/starters/react/design-system/components/Layout/Grid/Grid.tsx +75 -0
- package/dist/starters/react/design-system/components/Layout/Grid/README.md +21 -0
- package/dist/starters/react/design-system/controllers/Palette/Palette.ts +164 -0
- package/dist/starters/react/design-system/index.ts +6 -0
- package/dist/starters/react/design-system/review/brand-preview/BrandPreview.tsx +2 -5
- package/dist/starters/react/design-system/review/grid-cell/GridCell.tsx +18 -0
- package/dist/starters/react/design-system/review/index.ts +1 -0
- package/dist/starters/react/design-system/review/token-preview/TokenPreview.tsx +19 -1
- package/dist/starters/react/design-system/styles.css +1 -0
- package/dist/starters/react/design-system/tokens/Color.ads.fixture.ts +114 -8
- package/dist/starters/react/design-system/tokens/Layout.ads.fixture.ts +23 -0
- package/dist/starters/react/design-system/tokens/{SpaceTypeMotion.ads.scenario.tsx → Layout.ads.scenario.tsx} +1 -1
- package/dist/starters/react/design-system/tokens/Motion.ads.fixture.ts +18 -0
- package/dist/starters/react/design-system/tokens/Motion.ads.scenario.tsx +4 -0
- package/dist/starters/react/design-system/tokens/Shape.ads.fixture.ts +30 -0
- package/dist/starters/react/design-system/tokens/Shape.ads.scenario.tsx +4 -0
- package/dist/starters/react/design-system/tokens/Space.ads.fixture.ts +37 -0
- package/dist/starters/react/design-system/tokens/Space.ads.scenario.tsx +4 -0
- package/dist/starters/react/design-system/tokens/Type.ads.fixture.ts +29 -0
- package/dist/starters/react/design-system/tokens/Type.ads.scenario.tsx +4 -0
- package/dist/starters/react/design-system/tokens/base.css +9 -3
- package/dist/starters/react/design-system/tokens/colors.css +210 -24
- package/dist/starters/react/design-system/tokens/elevation.css +44 -6
- package/dist/starters/react/design-system/tokens/spacing.css +67 -3
- package/dist/starters/react/design-system/tokens/themes.generated.css +142 -0
- package/dist/starters/react/design-system/tokens/themes.generated.ts +402 -0
- package/dist/starters/react/design-system/tokens/typography.css +25 -7
- package/dist/starters/react/ds.config.json +13 -1
- package/dist/style-boundaries.mjs +2 -1
- package/dist/themes-generated.mjs +150 -0
- package/dist/themes-watch.mjs +42 -0
- package/dist/themes.mjs +257 -0
- package/dist/token-export.mjs +69 -0
- package/dist/token-policy.mjs +2 -1
- package/dist/token-quality.mjs +112 -0
- package/dist/tokens.mjs +32 -30
- package/dist/validation.mjs +18 -1
- package/dist/verification/browser.mjs +14 -3
- package/docs/ADS.md +56 -13
- package/docs/ARCHITECTURE.md +82 -10
- package/docs/CACHING.md +2 -3
- package/docs/CHANGELOG.md +149 -13
- package/docs/CONTRACTS.md +13 -10
- package/docs/GUIDE.md +104 -8
- package/docs/MCP.md +46 -27
- package/docs/benchmarks/bun-previews.md +5 -5
- package/docs/benchmarks/{gidi-preview-memory.md → preview-memory.md} +14 -12
- package/docs/benchmarks/turbo-poc.md +24 -6
- package/package.json +2 -1
- package/dist/starters/react/design-system/tokens/SpaceTypeMotion.ads.fixture.ts +0 -36
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
function
|
|
2
|
-
`)}var{create:MS,defineProperty:ha,getOwnPropertyDescriptor:jS,getOwnPropertyNames:LS,getPrototypeOf:US}=Object,ZS=Object.prototype.hasOwnProperty,nd=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),sd=(e,t)=>{let r={};for(var o in e)ha(r,o,{get:e[o],enumerable:!0});if(t)ha(r,Symbol.toStringTag,{value:"Module"});return r},DS=(e,t,r,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(var n=LS(t),i=0,s=n.length,a;i<s;i++)if(a=n[i],!ZS.call(e,a)&&a!==r)ha(e,a,{get:((l)=>t[l]).bind(null,a),enumerable:!(o=jS(t,a))||o.enumerable})}return e},id=(e,t,r)=>(r=e!=null?MS(US(e)):{},DS(t||!e||!e.__esModule?ha(r,"default",{value:e,enumerable:!0}):r,e));var FS=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),ad=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),HS=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),VS=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function cd(e){return typeof e==="string"&&ad.has(e.replace(/#$/,""))}function ld(e,t){if(!("$schema"in e)||typeof e.$schema!=="string")return"2020-12";let r=e.$schema.replace(/#$/,"");if(FS.has(r))return"2020-12";if(ad.has(r))return"2019-09";if(HS.has(r)||VS.has(r))return"draft-7";throw 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}`)}var ud,jc=Object.freeze({status:"aborted"});function _(e,t,r){function o(a,l){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let u=s.prototype,d=Object.keys(u);for(let m=0;m<d.length;m++){let f=d[m];if(!(f in a))a[f]=u[f].bind(a)}}let n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function s(a){var l;let u=r?.Parent?new i:this;o(u,a),(l=u._zod).deferred??(l.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:(a)=>{if(r?.Parent&&a instanceof r.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var JS=Symbol("zod_brand");class kt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class On extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(ud=globalThis).__zod_globalConfig??(ud.__zod_globalConfig={});var io=globalThis.__zod_globalConfig;function je(e){if(e)Object.assign(io,e);return io}function fa(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function Uc(e,t="|"){return e.map((r)=>Hc(r)).join(t)}function Nn(e,t){if(typeof t==="bigint")return t.toString();return t}function qn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function ga(e){return e===null||e===void 0}function Sa(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function pd(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-o)<n)return 0;return r-o}var dd=Symbol("evaluating");function Q(e,t,r){let o=void 0;Object.defineProperty(e,t,{get(){if(o===dd)return;if(o===void 0)o=dd,o=r();return o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function yr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Wt(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function Zc(e){return JSON.stringify(e)}function hd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Dc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function ao(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var md=qn(()=>{if(io.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function vr(e){if(ao(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(ao(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Fc(e){if(vr(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var fd=new Set(["string","number","symbol"]);function Kt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rt(e,t,r){let o=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)o._zod.parent=e;return o}function M(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Hc(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function gd(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Sd={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function BS(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=Wt(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;s[a]=r.shape[a]}return yr(this,"shape",s),s},checks:[]});return rt(e,i)}function WS(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=Wt(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete s[a]}return yr(this,"shape",s),s},checks:[]});return rt(e,i)}function KS(e,t){if(!vr(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=Wt(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return yr(this,"shape",i),i}});return rt(e,n)}function GS(e,t){if(!vr(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=Wt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return yr(this,"shape",o),o}});return rt(e,r)}function YS(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Wt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return yr(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return rt(e,r)}function XS(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let s=Wt(t._zod.def,{get shape(){let a=t._zod.def.shape,l={...a};if(r)for(let u in r){if(!(u in a))throw Error(`Unrecognized key: "${u}"`);if(!r[u])continue;l[u]=e?new e({type:"optional",innerType:a[u]}):a[u]}else for(let u in a)l[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return yr(this,"shape",l),l},checks:[]});return rt(t,s)}function QS(e,t,r){let o=Wt(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in i))throw Error(`Unrecognized key: "${s}"`);if(!r[s])continue;i[s]=new e({type:"nonoptional",innerType:n[s]})}else for(let s in n)i[s]=new e({type:"nonoptional",innerType:n[s]});return yr(this,"shape",i),i}});return rt(t,o)}function zr(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function _d(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Gt(e,t){return t.map((r)=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function ma(e){return typeof e==="string"?e:e?.message}function ot(e,t,r){let o=e.message?e.message:ma(e.inst?._zod.def?.error?.(e))??ma(t?.error?.(e))??ma(r.customError?.(e))??ma(r.localeError?.(e))??"Invalid input",{inst:n,continue:i,input:s,...a}=e;if(a.path??(a.path=[]),a.message=o,t?.reportInput)a.input=s;return a}function _a(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function bd(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function wr(...e){let[t,r,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:o};return{...t}}var yd=(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,Nn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ba=_("$ZodError",yd),Vc=_("$ZodError",yd,{Parent:Error});function Jc(e,t=(r)=>r.message){let r={},o=[];for(let n of e.issues)if(n.path.length>0)r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n));else o.push(t(n));return{formErrors:o,fieldErrors:r}}function Bc(e,t=(r)=>r.message){let r={_errors:[]},o=(n,i=[])=>{for(let s of n.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>o({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")o({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let l=r,u=0;while(u<a.length){let d=a[u];if(u!==a.length-1)l[d]=l[d]||{_errors:[]};else l[d]=l[d]||{_errors:[]},l[d]._errors.push(t(s));l=l[d],u++}}}};return o(e),r}var ya=(e)=>(t,r,o,n)=>{let i=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new kt;if(s.issues.length){let a=new(n?.Err??e)(s.issues.map((l)=>ot(l,i,je())));throw Dc(a,n?.callee),a}return s.value};var va=(e)=>async(t,r,o,n)=>{let i=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)s=await s;if(s.issues.length){let a=new(n?.Err??e)(s.issues.map((l)=>ot(l,i,je())));throw Dc(a,n?.callee),a}return s.value};var An=(e)=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new kt;return i.issues.length?{success:!1,error:new(e??ba)(i.issues.map((s)=>ot(s,n,je())))}:{success:!0,data:i.value}},vd=An(Vc),Mn=(e)=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)i=await i;return i.issues.length?{success:!1,error:new e(i.issues.map((s)=>ot(s,n,je())))}:{success:!0,data:i.value}},zd=Mn(Vc),wd=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return ya(e)(t,r,n)};var Rd=(e)=>(t,r,o)=>ya(e)(t,r,o);var xd=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return va(e)(t,r,n)};var Pd=(e)=>async(t,r,o)=>va(e)(t,r,o);var Td=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return An(e)(t,r,n)};var Ed=(e)=>(t,r,o)=>An(e)(t,r,o);var kd=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Mn(e)(t,r,n)};var $d=(e)=>async(t,r,o)=>Mn(e)(t,r,o);var Cd=/^[cC][0-9a-z]{6,}$/,Id=/^[0-9a-z]+$/,Od=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Nd=/^[0-9a-vA-V]{20}$/,qd=/^[A-Za-z0-9]{27}$/,Ad=/^[a-zA-Z0-9_-]{21}$/,Md=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var jd=/^([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})$/,Wc=(e)=>{if(!e)return/^([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)$/;return 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})$`)};var Ld=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var t_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Ud(){return new RegExp(t_,"u")}var Zd=/^(?:(?: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])$/,Dd=/^(([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}|:))$/;var Fd=/^((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])$/,Hd=/^(([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])$/,Vd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Kc=/^[A-Za-z0-9_-]*$/;var Jd=/^https?$/,Bd=/^\+[1-9]\d{6,14}$/,Wd="(?:(?:\\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])))",Kd=new RegExp(`^${Wd}$`);function Gd(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Yd(e){return new RegExp(`^${Gd(e)}$`)}function Xd(e){let t=Gd({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${Wd}T(?:${o})$`)}var Qd=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var ep=/^-?\d+$/,Gc=/^-?\d+(?:\.\d+)?$/,tp=/^(?:true|false)$/i,rp=/^null$/i;var op=/^undefined$/i;var np=/^[^A-Z]*$/,sp=/^[^a-z]*$/;var ze=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),ip={number:"number",bigint:"bigint",object:"date"},Yc=_("$ZodCheckLessThan",(e,t)=>{ze.init(e,t);let r=ip[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,i=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<i)if(t.inclusive)n.maximum=t.value;else n.exclusiveMaximum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value<=t.value:o.value<t.value)return;o.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Xc=_("$ZodCheckGreaterThan",(e,t)=>{ze.init(e,t);let r=ip[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>i)if(t.inclusive)n.minimum=t.value;else n.exclusiveMinimum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value>=t.value:o.value>t.value)return;o.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ap=_("$ZodCheckMultipleOf",(e,t)=>{ze.init(e,t),e._zod.onattach.push((r)=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):pd(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),cp=_("$ZodCheckNumberFormat",(e,t)=>{ze.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,i]=Sd[t.format];e._zod.onattach.push((s)=>{let a=s._zod.bag;if(a.format=t.format,a.minimum=n,a.maximum=i,r)a.pattern=ep}),e._zod.check=(s)=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}if(a<n)s.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort});if(a>i)s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var lp=_("$ZodCheckMaxLength",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!ga(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<n)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let n=o.value;if(n.length<=t.maximum)return;let s=_a(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),up=_("$ZodCheckMinLength",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!ga(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>n)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let n=o.value;if(n.length>=t.minimum)return;let s=_a(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),dp=_("$ZodCheckLengthEquals",(e,t)=>{var r;ze.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!ga(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=(o)=>{let n=o.value,i=n.length;if(i===t.length)return;let s=_a(n),a=i>t.length;o.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Ln=_("$ZodCheckStringFormat",(e,t)=>{var r,o;if(ze.init(e,t),e._zod.onattach.push((n)=>{let i=n._zod.bag;if(i.format=t.format,t.pattern)i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(o=e._zod).check??(o.check=()=>{})}),pp=_("$ZodCheckRegex",(e,t)=>{Ln.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),hp=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=np),Ln.init(e,t)}),mp=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=sp),Ln.init(e,t)}),fp=_("$ZodCheckIncludes",(e,t)=>{ze.init(e,t);let r=Kt(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push((n)=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),e._zod.check=(n)=>{if(n.value.includes(t.includes,t.position))return;n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),gp=_("$ZodCheckStartsWith",(e,t)=>{ze.init(e,t);let r=new RegExp(`^${Kt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.startsWith(t.prefix))return;o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Sp=_("$ZodCheckEndsWith",(e,t)=>{ze.init(e,t);let r=new RegExp(`.*${Kt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.endsWith(t.suffix))return;o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var _p=_("$ZodCheckOverwrite",(e,t)=>{ze.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class Qc{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
|
|
1
|
+
function ya(e){if(e?.failure?.scope!=="project")return"Preview build failed";if(e.failure.phase==="validation")return"Project validation failed";if(e.failure.phase==="discovery")return"Project scenario discovery failed";return"Project preview build failed"}function md(e=[]){return e.map((t)=>{let r=t.file?t.file+(t.line?`:${t.line}`:"")+(t.column?`:${t.column}`:""):"";return(r?`${r}: `:"")+t.message}).join(`
|
|
2
|
+
`)}var{create:YS,defineProperty:va,getOwnPropertyDescriptor:XS,getOwnPropertyNames:QS,getPrototypeOf:e_}=Object,t_=Object.prototype.hasOwnProperty,fd=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),gd=(e,t)=>{let r={};for(var o in e)va(r,o,{get:e[o],enumerable:!0});if(t)va(r,Symbol.toStringTag,{value:"Module"});return r},r_=(e,t,r,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(var n=QS(t),i=0,s=n.length,a;i<s;i++)if(a=n[i],!t_.call(e,a)&&a!==r)va(e,a,{get:((l)=>t[l]).bind(null,a),enumerable:!(o=XS(t,a))||o.enumerable})}return e},Sd=(e,t,r)=>(r=e!=null?YS(e_(e)):{},r_(t||!e||!e.__esModule?va(r,"default",{value:e,enumerable:!0}):r,e));var o_=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),_d=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),n_=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),s_=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);function bd(e){return typeof e==="string"&&_d.has(e.replace(/#$/,""))}function yd(e,t){if(!("$schema"in e)||typeof e.$schema!=="string")return"2020-12";let r=e.$schema.replace(/#$/,"");if(o_.has(r))return"2020-12";if(_d.has(r))return"2019-09";if(n_.has(r)||s_.has(r))return"draft-7";throw 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}`)}var vd,Wc=Object.freeze({status:"aborted"});function _(e,t,r){function o(a,l){if(!a._zod)Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1});if(a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,l);let u=s.prototype,d=Object.keys(u);for(let m=0;m<d.length;m++){let f=d[m];if(!(f in a))a[f]=u[f].bind(a)}}let n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function s(a){var l;let u=r?.Parent?new i:this;o(u,a),(l=u._zod).deferred??(l.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:(a)=>{if(r?.Parent&&a instanceof r.Parent)return!0;return a?._zod?.traits?.has(e)}}),Object.defineProperty(s,"name",{value:e}),s}var i_=Symbol("zod_brand");class Nt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Un extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(vd=globalThis).__zod_globalConfig??(vd.__zod_globalConfig={});var mo=globalThis.__zod_globalConfig;function Ue(e){if(e)Object.assign(mo,e);return mo}function wa(e){let t=Object.values(e).filter((o)=>typeof o==="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function Gc(e,t="|"){return e.map((r)=>el(r)).join(t)}function Zn(e,t){if(typeof t==="bigint")return t.toString();return t}function Dn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw Error("cached value already set")}}}function Ra(e){return e===null||e===void 0}function xa(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function wd(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-o)<n)return 0;return r-o}var zd=Symbol("evaluating");function ee(e,t,r){let o=void 0;Object.defineProperty(e,t,{get(){if(o===zd)return;if(o===void 0)o=zd,o=r();return o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Tr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function tr(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function Yc(e){return JSON.stringify(e)}function Rd(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Xc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function fo(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var xd=Dn(()=>{if(mo.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Er(e){if(fo(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(fo(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Qc(e){if(Er(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var Pd=new Set(["string","number","symbol"]);function rr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function at(e,t,r){let o=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)o._zod.parent=e;return o}function j(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function el(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Td(e){return Object.keys(e).filter((t)=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Ed={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function a_(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i=tr(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;s[a]=r.shape[a]}return Tr(this,"shape",s),s},checks:[]});return at(e,i)}function c_(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=tr(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw Error(`Unrecognized key: "${a}"`);if(!t[a])continue;delete s[a]}return Tr(this,"shape",s),s},checks:[]});return at(e,i)}function l_(e,t){if(!Er(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=tr(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Tr(this,"shape",i),i}});return at(e,n)}function u_(e,t){if(!Er(t))throw Error("Invalid input to safeExtend: expected a plain object");let r=tr(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return Tr(this,"shape",o),o}});return at(e,r)}function d_(e,t){if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=tr(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return Tr(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return at(e,r)}function p_(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let s=tr(t._zod.def,{get shape(){let a=t._zod.def.shape,l={...a};if(r)for(let u in r){if(!(u in a))throw Error(`Unrecognized key: "${u}"`);if(!r[u])continue;l[u]=e?new e({type:"optional",innerType:a[u]}):a[u]}else for(let u in a)l[u]=e?new e({type:"optional",innerType:a[u]}):a[u];return Tr(this,"shape",l),l},checks:[]});return at(t,s)}function h_(e,t,r){let o=tr(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in i))throw Error(`Unrecognized key: "${s}"`);if(!r[s])continue;i[s]=new e({type:"nonoptional",innerType:n[s]})}else for(let s in n)i[s]=new e({type:"nonoptional",innerType:n[s]});return Tr(this,"shape",i),i}});return at(t,o)}function kr(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function kd(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function or(e,t){return t.map((r)=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function za(e){return typeof e==="string"?e:e?.message}function ct(e,t,r){let o=e.message?e.message:za(e.inst?._zod.def?.error?.(e))??za(t?.error?.(e))??za(r.customError?.(e))??za(r.localeError?.(e))??"Invalid input",{inst:n,continue:i,input:s,...a}=e;if(a.path??(a.path=[]),a.message=o,t?.reportInput)a.input=s;return a}function Pa(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function $d(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function $r(...e){let[t,r,o]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:o};return{...t}}var Cd=(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,Zn,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Ta=_("$ZodError",Cd),tl=_("$ZodError",Cd,{Parent:Error});function rl(e,t=(r)=>r.message){let r={},o=[];for(let n of e.issues)if(n.path.length>0)r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n));else o.push(t(n));return{formErrors:o,fieldErrors:r}}function ol(e,t=(r)=>r.message){let r={_errors:[]},o=(n,i=[])=>{for(let s of n.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>o({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")o({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")o({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let l=r,u=0;while(u<a.length){let d=a[u];if(u!==a.length-1)l[d]=l[d]||{_errors:[]};else l[d]=l[d]||{_errors:[]},l[d]._errors.push(t(s));l=l[d],u++}}}};return o(e),r}var Ea=(e)=>(t,r,o,n)=>{let i=o?{...o,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Nt;if(s.issues.length){let a=new(n?.Err??e)(s.issues.map((l)=>ct(l,i,Ue())));throw Xc(a,n?.callee),a}return s.value};var ka=(e)=>async(t,r,o,n)=>{let i=o?{...o,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)s=await s;if(s.issues.length){let a=new(n?.Err??e)(s.issues.map((l)=>ct(l,i,Ue())));throw Xc(a,n?.callee),a}return s.value};var Fn=(e)=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new Nt;return i.issues.length?{success:!1,error:new(e??Ta)(i.issues.map((s)=>ct(s,n,Ue())))}:{success:!0,data:i.value}},Id=Fn(tl),Hn=(e)=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)i=await i;return i.issues.length?{success:!1,error:new e(i.issues.map((s)=>ct(s,n,Ue())))}:{success:!0,data:i.value}},Od=Hn(tl),Nd=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Ea(e)(t,r,n)};var Ad=(e)=>(t,r,o)=>Ea(e)(t,r,o);var qd=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return ka(e)(t,r,n)};var Md=(e)=>async(t,r,o)=>ka(e)(t,r,o);var jd=(e)=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Fn(e)(t,r,n)};var Ld=(e)=>(t,r,o)=>Fn(e)(t,r,o);var Ud=(e)=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return Hn(e)(t,r,n)};var Zd=(e)=>async(t,r,o)=>Hn(e)(t,r,o);var Dd=/^[cC][0-9a-z]{6,}$/,Fd=/^[0-9a-z]+$/,Hd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Vd=/^[0-9a-vA-V]{20}$/,Jd=/^[A-Za-z0-9]{27}$/,Bd=/^[a-zA-Z0-9_-]{21}$/,Wd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Kd=/^([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})$/,nl=(e)=>{if(!e)return/^([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)$/;return 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})$`)};var Gd=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var f_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Yd(){return new RegExp(f_,"u")}var Xd=/^(?:(?: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])$/,Qd=/^(([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}|:))$/;var ep=/^((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])$/,tp=/^(([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])$/,rp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,sl=/^[A-Za-z0-9_-]*$/;var op=/^https?$/,np=/^\+[1-9]\d{6,14}$/,sp="(?:(?:\\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])))",ip=new RegExp(`^${sp}$`);function ap(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function cp(e){return new RegExp(`^${ap(e)}$`)}function lp(e){let t=ap({precision:e.precision}),r=["Z"];if(e.local)r.push("");if(e.offset)r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${sp}T(?:${o})$`)}var up=(e)=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var dp=/^-?\d+$/,il=/^-?\d+(?:\.\d+)?$/,pp=/^(?:true|false)$/i,hp=/^null$/i;var mp=/^undefined$/i;var fp=/^[^A-Z]*$/,gp=/^[^a-z]*$/;var Re=_("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Sp={number:"number",bigint:"bigint",object:"date"},al=_("$ZodCheckLessThan",(e,t)=>{Re.init(e,t);let r=Sp[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,i=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(t.value<i)if(t.inclusive)n.maximum=t.value;else n.exclusiveMaximum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value<=t.value:o.value<t.value)return;o.issues.push({origin:r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),cl=_("$ZodCheckGreaterThan",(e,t)=>{Re.init(e,t);let r=Sp[typeof t.value];e._zod.onattach.push((o)=>{let n=o._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(t.value>i)if(t.inclusive)n.minimum=t.value;else n.exclusiveMinimum=t.value}),e._zod.check=(o)=>{if(t.inclusive?o.value>=t.value:o.value>t.value)return;o.issues.push({origin:r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_p=_("$ZodCheckMultipleOf",(e,t)=>{Re.init(e,t),e._zod.onattach.push((r)=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?r.value%t.value===BigInt(0):wd(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),bp=_("$ZodCheckNumberFormat",(e,t)=>{Re.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,i]=Ed[t.format];e._zod.onattach.push((s)=>{let a=s._zod.bag;if(a.format=t.format,a.minimum=n,a.maximum=i,r)a.pattern=dp}),e._zod.check=(s)=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}if(a<n)s.issues.push({origin:"number",input:a,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort});if(a>i)s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var yp=_("$ZodCheckMaxLength",(e,t)=>{var r;Re.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!Ra(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;if(t.maximum<n)o._zod.bag.maximum=t.maximum}),e._zod.check=(o)=>{let n=o.value;if(n.length<=t.maximum)return;let s=Pa(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),vp=_("$ZodCheckMinLength",(e,t)=>{var r;Re.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!Ra(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(t.minimum>n)o._zod.bag.minimum=t.minimum}),e._zod.check=(o)=>{let n=o.value;if(n.length>=t.minimum)return;let s=Pa(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),zp=_("$ZodCheckLengthEquals",(e,t)=>{var r;Re.init(e,t),(r=e._zod.def).when??(r.when=(o)=>{let n=o.value;return!Ra(n)&&n.length!==void 0}),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=(o)=>{let n=o.value,i=n.length;if(i===t.length)return;let s=Pa(n),a=i>t.length;o.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),Jn=_("$ZodCheckStringFormat",(e,t)=>{var r,o;if(Re.init(e,t),e._zod.onattach.push((n)=>{let i=n._zod.bag;if(i.format=t.format,t.pattern)i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern)}),t.pattern)(r=e._zod).check??(r.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(o=e._zod).check??(o.check=()=>{})}),wp=_("$ZodCheckRegex",(e,t)=>{Jn.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Rp=_("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=fp),Jn.init(e,t)}),xp=_("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=gp),Jn.init(e,t)}),Pp=_("$ZodCheckIncludes",(e,t)=>{Re.init(e,t);let r=rr(t.includes),o=new RegExp(typeof t.position==="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push((n)=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),e._zod.check=(n)=>{if(n.value.includes(t.includes,t.position))return;n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Tp=_("$ZodCheckStartsWith",(e,t)=>{Re.init(e,t);let r=new RegExp(`^${rr(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.startsWith(t.prefix))return;o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Ep=_("$ZodCheckEndsWith",(e,t)=>{Re.init(e,t);let r=new RegExp(`.*${rr(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push((o)=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=(o)=>{if(o.value.endsWith(t.suffix))return;o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var kp=_("$ZodCheckOverwrite",(e,t)=>{Re.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class ll{constructor(e=[]){if(this.content=[],this.indent=0,this)this.args=e}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
|
|
3
3
|
`).filter((i)=>i),o=Math.min(...r.map((i)=>i.length-i.trimStart().length)),n=r.map((i)=>i.slice(o)).map((i)=>" ".repeat(this.indent*2)+i);for(let i of n)this.content.push(i)}compile(){let e=Function,t=this?.args,o=[...(this?.content??[""]).map((n)=>` ${n}`)];return new e(...t,o.join(`
|
|
4
|
-
`))}}var yp={major:4,minor:4,patch:3};var re=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=yp;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let n of o)for(let i of n._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(s,a,l)=>{let u=zr(s),d;for(let m of a){if(m._zod.def.when){if(_d(s))continue;if(!m._zod.def.when(s))continue}else if(u)continue;let f=s.issues.length,S=m._zod.check(s);if(S instanceof Promise&&l?.async===!1)throw new kt;if(d||S instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await S,s.issues.length===f)return;if(!u)u=zr(s,f)});else{if(s.issues.length===f)continue;if(!u)u=zr(s,f)}}if(d)return d.then(()=>s);return s},i=(s,a,l)=>{if(zr(s))return s.aborted=!0,s;let u=n(a,o,l);if(u instanceof Promise){if(l.async===!1)throw new kt;return u.then((d)=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let u=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>i(d,s,a));return i(u,s,a)}let l=e._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new kt;return l.then((u)=>n(u,o,a))}return n(l,o,a)}}Q(e,"~standard",()=>({validate:(n)=>{try{let i=vd(e,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch(i){return zd(e,n).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Ra=_("$ZodString",(e,t)=>{re.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Qd(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ae=_("$ZodStringFormat",(e,t)=>{Ln.init(e,t),Ra.init(e,t)}),kp=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=jd),ae.init(e,t)}),$p=_("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Wc(o))}else t.pattern??(t.pattern=Wc());ae.init(e,t)}),Cp=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ld),ae.init(e,t)}),Ip=_("$ZodURL",(e,t)=>{ae.init(e,t),e._zod.check=(r)=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===Jd.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let n=new URL(o);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(n.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})}if(t.normalize)r.value=n.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Op=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ud()),ae.init(e,t)}),Np=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ad),ae.init(e,t)}),qp=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Cd),ae.init(e,t)}),Ap=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Id),ae.init(e,t)}),Mp=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Od),ae.init(e,t)}),jp=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Nd),ae.init(e,t)}),Lp=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=qd),ae.init(e,t)}),Up=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Xd(t)),ae.init(e,t)}),Zp=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Kd),ae.init(e,t)}),Dp=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Yd(t)),ae.init(e,t)}),Fp=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Md),ae.init(e,t)}),Hp=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Zd),ae.init(e,t),e._zod.bag.format="ipv4"}),Vp=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Dd),ae.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var Jp=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Fd),ae.init(e,t)}),Bp=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Hd),ae.init(e,t),e._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[n,i]=o;if(!i)throw Error();let s=Number(i);if(`${s}`!==i)throw Error();if(s<0||s>128)throw Error();new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function Wp(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Kp=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Vd),ae.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(Wp(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function r_(e){if(!Kc.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Wp(r)}var Gp=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Kc),ae.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(r_(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Yp=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Bd),ae.init(e,t)});function o_(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(t&&(!("alg"in n)||n.alg!==t))return!1;return!0}catch{return!1}}var Xp=_("$ZodJWT",(e,t)=>{ae.init(e,t),e._zod.check=(r)=>{if(o_(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var tl=_("$ZodNumber",(e,t)=>{re.init(e,t),e._zod.pattern=e._zod.bag.pattern??Gc,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(s){}let n=r.value;if(typeof n==="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i=typeof n==="number"?Number.isNaN(n)?"NaN":!Number.isFinite(n)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}}),Qp=_("$ZodNumberFormat",(e,t)=>{cp.init(e,t),tl.init(e,t)}),eh=_("$ZodBoolean",(e,t)=>{re.init(e,t),e._zod.pattern=tp,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(i){}let n=r.value;if(typeof n==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}});var th=_("$ZodUndefined",(e,t)=>{re.init(e,t),e._zod.pattern=op,e._zod.values=new Set([void 0]),e._zod.parse=(r,o)=>{let n=r.value;if(typeof n>"u")return r;return r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),r}}),rh=_("$ZodNull",(e,t)=>{re.init(e,t),e._zod.pattern=rp,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;if(n===null)return r;return r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),oh=_("$ZodAny",(e,t)=>{re.init(e,t),e._zod.parse=(r)=>r}),nh=_("$ZodUnknown",(e,t)=>{re.init(e,t),e._zod.parse=(r)=>r}),sh=_("$ZodNever",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function vp(e,t,r){if(e.issues.length)t.issues.push(...Gt(r,e.issues));t.value[r]=e.value}var ih=_("$ZodArray",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let i=[];for(let s=0;s<n.length;s++){let a=n[s],l=t.element._zod.run({value:a,issues:[]},o);if(l instanceof Promise)i.push(l.then((u)=>vp(u,r,s)));else vp(l,r,s)}if(i.length)return Promise.all(i).then(()=>r);return r}});function wa(e,t,r,o,n,i){let s=r in o;if(e.issues.length){if(n&&i&&!s)return;t.issues.push(...Gt(r,e.issues))}if(!s&&!n){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(s)t.value[r]=void 0}else t.value[r]=e.value}function ah(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${o}": expected a Zod schema`);let r=gd(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function ch(e,t,r,o,n,i){let s=[],a=n.keySet,l=n.catchall._zod,u=l.def.type,d=l.optin==="optional",m=l.optout==="optional";for(let f in t){if(f==="__proto__")continue;if(a.has(f))continue;if(u==="never"){s.push(f);continue}let S=l.run({value:t[f],issues:[]},o);if(S instanceof Promise)e.push(S.then((b)=>wa(b,r,f,t,d,m)));else wa(S,r,f,t,d,m)}if(s.length)r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i});if(!e.length)return r;return Promise.all(e).then(()=>r)}var n_=_("$ZodObject",(e,t)=>{if(re.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}let o=qn(()=>ah(t));Q(e._zod,"propValues",()=>{let a=t.shape,l={};for(let u in a){let d=a[u]._zod;if(d.values){l[u]??(l[u]=new Set);for(let m of d.values)l[u].add(m)}}return l});let n=ao,i=t.catchall,s;e._zod.parse=(a,l)=>{s??(s=o.value);let u=a.value;if(!n(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};let d=[],m=s.shape;for(let f of s.keys){let S=m[f],b=S._zod.optin==="optional",y=S._zod.optout==="optional",v=S._zod.run({value:u[f],issues:[]},l);if(v instanceof Promise)d.push(v.then((U)=>wa(U,a,f,u,b,y)));else wa(v,a,f,u,b,y)}if(!i)return d.length?Promise.all(d).then(()=>a):a;return ch(d,u,a,l,o.value,e)}}),lh=_("$ZodObjectJIT",(e,t)=>{n_.init(e,t);let r=e._zod.parse,o=qn(()=>ah(t)),n=(f)=>{let S=new Qc(["shape","payload","ctx"]),b=o.value,y=(x)=>{let Z=Zc(x);return`shape[${Z}]._zod.run({ value: input[${Z}], issues: [] }, ctx)`};S.write("const input = payload.value;");let v=Object.create(null),U=0;for(let x of b.keys)v[x]=`key_${U++}`;S.write("const newResult = {};");for(let x of b.keys){let Z=v[x],R=Zc(x),w=f[x],D=w?._zod?.optin==="optional",X=w?._zod?.optout==="optional";if(S.write(`const ${Z} = ${y(x)};`),D&&X)S.write(`
|
|
4
|
+
`))}}var Cp={major:4,minor:4,patch:3};var ne=_("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Cp;let o=[...e._zod.def.checks??[]];if(e._zod.traits.has("$ZodCheck"))o.unshift(e);for(let n of o)for(let i of n._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(s,a,l)=>{let u=kr(s),d;for(let m of a){if(m._zod.def.when){if(kd(s))continue;if(!m._zod.def.when(s))continue}else if(u)continue;let f=s.issues.length,g=m._zod.check(s);if(g instanceof Promise&&l?.async===!1)throw new Nt;if(d||g instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await g,s.issues.length===f)return;if(!u)u=kr(s,f)});else{if(s.issues.length===f)continue;if(!u)u=kr(s,f)}}if(d)return d.then(()=>s);return s},i=(s,a,l)=>{if(kr(s))return s.aborted=!0,s;let u=n(a,o,l);if(u instanceof Promise){if(l.async===!1)throw new Nt;return u.then((d)=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let u=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>i(d,s,a));return i(u,s,a)}let l=e._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new Nt;return l.then((u)=>n(u,o,a))}return n(l,o,a)}}ee(e,"~standard",()=>({validate:(n)=>{try{let i=Id(e,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch(i){return Od(e,n).then((s)=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Ia=_("$ZodString",(e,t)=>{ne.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??up(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch(n){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ce=_("$ZodStringFormat",(e,t)=>{Jn.init(e,t),Ia.init(e,t)}),Up=_("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Kd),ce.init(e,t)}),Zp=_("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=nl(o))}else t.pattern??(t.pattern=nl());ce.init(e,t)}),Dp=_("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Gd),ce.init(e,t)}),Fp=_("$ZodURL",(e,t)=>{ce.init(e,t),e._zod.check=(r)=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===op.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}}let n=new URL(o);if(t.hostname){if(t.hostname.lastIndex=0,!t.hostname.test(n.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})}if(t.protocol){if(t.protocol.lastIndex=0,!t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})}if(t.normalize)r.value=n.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Hp=_("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Yd()),ce.init(e,t)}),Vp=_("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Bd),ce.init(e,t)}),Jp=_("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Dd),ce.init(e,t)}),Bp=_("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Fd),ce.init(e,t)}),Wp=_("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Hd),ce.init(e,t)}),Kp=_("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Vd),ce.init(e,t)}),Gp=_("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Jd),ce.init(e,t)}),Yp=_("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=lp(t)),ce.init(e,t)}),Xp=_("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ip),ce.init(e,t)}),Qp=_("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=cp(t)),ce.init(e,t)}),eh=_("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Wd),ce.init(e,t)}),th=_("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Xd),ce.init(e,t),e._zod.bag.format="ipv4"}),rh=_("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Qd),ce.init(e,t),e._zod.bag.format="ipv6",e._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}});var oh=_("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ep),ce.init(e,t)}),nh=_("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=tp),ce.init(e,t),e._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[n,i]=o;if(!i)throw Error();let s=Number(i);if(`${s}`!==i)throw Error();if(s<0||s>128)throw Error();new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function sh(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var ih=_("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=rp),ce.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=(r)=>{if(sh(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function g_(e){if(!sl.test(e))return!1;let t=e.replace(/[-_]/g,(o)=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return sh(r)}var ah=_("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=sl),ce.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=(r)=>{if(g_(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),ch=_("$ZodE164",(e,t)=>{t.pattern??(t.pattern=np),ce.init(e,t)});function S_(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));if("typ"in n&&n?.typ!=="JWT")return!1;if(!n.alg)return!1;if(t&&(!("alg"in n)||n.alg!==t))return!1;return!0}catch{return!1}}var lh=_("$ZodJWT",(e,t)=>{ce.init(e,t),e._zod.check=(r)=>{if(S_(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var dl=_("$ZodNumber",(e,t)=>{ne.init(e,t),e._zod.pattern=e._zod.bag.pattern??il,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch(s){}let n=r.value;if(typeof n==="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i=typeof n==="number"?Number.isNaN(n)?"NaN":!Number.isFinite(n)?"Infinity":void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}}),uh=_("$ZodNumberFormat",(e,t)=>{bp.init(e,t),dl.init(e,t)}),dh=_("$ZodBoolean",(e,t)=>{ne.init(e,t),e._zod.pattern=pp,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(i){}let n=r.value;if(typeof n==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}});var ph=_("$ZodUndefined",(e,t)=>{ne.init(e,t),e._zod.pattern=mp,e._zod.values=new Set([void 0]),e._zod.parse=(r,o)=>{let n=r.value;if(typeof n>"u")return r;return r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),r}}),hh=_("$ZodNull",(e,t)=>{ne.init(e,t),e._zod.pattern=hp,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;if(n===null)return r;return r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),mh=_("$ZodAny",(e,t)=>{ne.init(e,t),e._zod.parse=(r)=>r}),fh=_("$ZodUnknown",(e,t)=>{ne.init(e,t),e._zod.parse=(r)=>r}),gh=_("$ZodNever",(e,t)=>{ne.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Ip(e,t,r){if(e.issues.length)t.issues.push(...or(r,e.issues));t.value[r]=e.value}var Sh=_("$ZodArray",(e,t)=>{ne.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let i=[];for(let s=0;s<n.length;s++){let a=n[s],l=t.element._zod.run({value:a,issues:[]},o);if(l instanceof Promise)i.push(l.then((u)=>Ip(u,r,s)));else Ip(l,r,s)}if(i.length)return Promise.all(i).then(()=>r);return r}});function Ca(e,t,r,o,n,i){let s=r in o;if(e.issues.length){if(n&&i&&!s)return;t.issues.push(...or(r,e.issues))}if(!s&&!n){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(s)t.value[r]=void 0}else t.value[r]=e.value}function _h(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${o}": expected a Zod schema`);let r=Td(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function bh(e,t,r,o,n,i){let s=[],a=n.keySet,l=n.catchall._zod,u=l.def.type,d=l.optin==="optional",m=l.optout==="optional";for(let f in t){if(f==="__proto__")continue;if(a.has(f))continue;if(u==="never"){s.push(f);continue}let g=l.run({value:t[f],issues:[]},o);if(g instanceof Promise)e.push(g.then((b)=>Ca(b,r,f,t,d,m)));else Ca(g,r,f,t,d,m)}if(s.length)r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i});if(!e.length)return r;return Promise.all(e).then(()=>r)}var __=_("$ZodObject",(e,t)=>{if(ne.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let l={...a};return Object.defineProperty(t,"shape",{value:l}),l}})}let o=Dn(()=>_h(t));ee(e._zod,"propValues",()=>{let a=t.shape,l={};for(let u in a){let d=a[u]._zod;if(d.values){l[u]??(l[u]=new Set);for(let m of d.values)l[u].add(m)}}return l});let n=fo,i=t.catchall,s;e._zod.parse=(a,l)=>{s??(s=o.value);let u=a.value;if(!n(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};let d=[],m=s.shape;for(let f of s.keys){let g=m[f],b=g._zod.optin==="optional",y=g._zod.optout==="optional",v=g._zod.run({value:u[f],issues:[]},l);if(v instanceof Promise)d.push(v.then((L)=>Ca(L,a,f,u,b,y)));else Ca(v,a,f,u,b,y)}if(!i)return d.length?Promise.all(d).then(()=>a):a;return bh(d,u,a,l,o.value,e)}}),yh=_("$ZodObjectJIT",(e,t)=>{__.init(e,t);let r=e._zod.parse,o=Dn(()=>_h(t)),n=(f)=>{let g=new ll(["shape","payload","ctx"]),b=o.value,y=(x)=>{let Z=Yc(x);return`shape[${Z}]._zod.run({ value: input[${Z}], issues: [] }, ctx)`};g.write("const input = payload.value;");let v=Object.create(null),L=0;for(let x of b.keys)v[x]=`key_${L++}`;g.write("const newResult = {};");for(let x of b.keys){let Z=v[x],R=Yc(x),w=f[x],D=w?._zod?.optin==="optional",X=w?._zod?.optout==="optional";if(g.write(`const ${Z} = ${y(x)};`),D&&X)g.write(`
|
|
5
5
|
if (${Z}.issues.length) {
|
|
6
6
|
if (${R} in input) {
|
|
7
7
|
payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
|
|
@@ -19,7 +19,7 @@ function pa(e){if(e?.failure?.scope!=="project")return"Preview build failed";if(
|
|
|
19
19
|
newResult[${R}] = ${Z}.value;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
`);else if(!D)
|
|
22
|
+
`);else if(!D)g.write(`
|
|
23
23
|
const ${Z}_present = ${R} in input;
|
|
24
24
|
if (${Z}.issues.length) {
|
|
25
25
|
payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
|
|
@@ -44,7 +44,7 @@ function pa(e){if(e?.failure?.scope!=="project")return"Preview build failed";if(
|
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
`);else
|
|
47
|
+
`);else g.write(`
|
|
48
48
|
if (${Z}.issues.length) {
|
|
49
49
|
payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
|
|
50
50
|
...iss,
|
|
@@ -60,31 +60,31 @@ function pa(e){if(e?.failure?.scope!=="project")return"Preview build failed";if(
|
|
|
60
60
|
newResult[${R}] = ${Z}.value;
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
-
`)}S.write("payload.value = newResult;"),S.write("return payload;");let H=S.compile();return(x,Z)=>H(f,x,Z)},i,s=ao,a=!io.jitless,u=a&&md.value,d=t.catchall,m;e._zod.parse=(f,S)=>{m??(m=o.value);let b=f.value;if(!s(b))return f.issues.push({expected:"object",code:"invalid_type",input:b,inst:e}),f;if(a&&u&&S?.async===!1&&S.jitless!==!0){if(!i)i=n(t.shape);if(f=i(f,S),!d)return f;return ch([],b,f,S,m,e)}return r(f,S)}});function zp(e,t,r,o){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let n=e.filter((i)=>!zr(i));if(n.length===1)return t.value=n[0].value,n[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((i)=>i.issues.map((s)=>ot(s,o,je())))}),t}var rl=_("$ZodUnion",(e,t)=>{re.init(e,t),Q(e._zod,"optin",()=>t.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),Q(e._zod,"optout",()=>t.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),Q(e._zod,"values",()=>{if(t.options.every((o)=>o._zod.values))return new Set(t.options.flatMap((o)=>Array.from(o._zod.values)));return}),Q(e._zod,"pattern",()=>{if(t.options.every((o)=>o._zod.pattern)){let o=t.options.map((n)=>n._zod.pattern);return new RegExp(`^(${o.map((n)=>Sa(n.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,n)=>{if(r)return r(o,n);let i=!1,s=[];for(let a of t.options){let l=a._zod.run({value:o.value,issues:[]},n);if(l instanceof Promise)s.push(l),i=!0;else{if(l.issues.length===0)return l;s.push(l)}}if(!i)return zp(s,o,e,n);return Promise.all(s).then((a)=>zp(a,o,e,n))}});var uh=_("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,rl.init(e,t);let r=e._zod.parse;Q(e._zod,"propValues",()=>{let n={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,l]of Object.entries(s)){if(!n[a])n[a]=new Set;for(let u of l)n[a].add(u)}}return n});let o=qn(()=>{let n=t.options,i=new Map;for(let s of n){let a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let l of a){if(i.has(l))throw Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});e._zod.parse=(n,i)=>{let s=n.value;if(!ao(s))return n.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),n;let a=o.value.get(s?.[t.discriminator]);if(a)return a._zod.run(n,i);if(t.unionFallback||i.direction==="backward")return r(n,i);return n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(o.value.keys()),input:s,path:[t.discriminator],inst:e}),n}}),dh=_("$ZodIntersection",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value,i=t.left._zod.run({value:n,issues:[]},o),s=t.right._zod.run({value:n,issues:[]},o);if(i instanceof Promise||s instanceof Promise)return Promise.all([i,s]).then(([l,u])=>wp(r,l,u));return wp(r,i,s)}});function el(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(vr(e)&&vr(t)){let r=Object.keys(t),o=Object.keys(e).filter((i)=>r.indexOf(i)!==-1),n={...e,...t};for(let i of o){let s=el(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};n[i]=s.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<e.length;o++){let n=e[o],i=t[o],s=el(n,i);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function wp(e,t,r){let o=new Map,n;for(let a of t.issues)if(a.code==="unrecognized_keys"){n??(n=a);for(let l of a.keys){if(!o.has(l))o.set(l,{});o.get(l).l=!0}}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let l of a.keys){if(!o.has(l))o.set(l,{});o.get(l).r=!0}else e.issues.push(a);let i=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&n)e.issues.push({...n,keys:i});if(zr(e))return e;let s=el(t.value,r.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var ph=_("$ZodRecord",(e,t)=>{re.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!vr(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let i=[],s=t.keyType._zod.values;if(s){r.value={};let a=new Set;for(let u of s)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){a.add(typeof u==="number"?u.toString():u);let d=t.keyType._zod.run({value:u,issues:[]},o);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((S)=>ot(S,o,je())),input:u,path:[u],inst:e});continue}let m=d.value,f=t.valueType._zod.run({value:n[u],issues:[]},o);if(f instanceof Promise)i.push(f.then((S)=>{if(S.issues.length)r.issues.push(...Gt(u,S.issues));r.value[m]=S.value}));else{if(f.issues.length)r.issues.push(...Gt(u,f.issues));r.value[m]=f.value}}let l;for(let u in n)if(!a.has(u))l=l??[],l.push(u);if(l&&l.length>0)r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:l})}else{r.value={};for(let a of Reflect.ownKeys(n)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(n,a))continue;let l=t.keyType._zod.run({value:a,issues:[]},o);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&Gc.test(a)&&l.issues.length){let m=t.keyType._zod.run({value:Number(a),issues:[]},o);if(m instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(m.issues.length===0)l=m}if(l.issues.length){if(t.mode==="loose")r.value[a]=n[a];else r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((m)=>ot(m,o,je())),input:a,path:[a],inst:e});continue}let d=t.valueType._zod.run({value:n[a],issues:[]},o);if(d instanceof Promise)i.push(d.then((m)=>{if(m.issues.length)r.issues.push(...Gt(a,m.issues));r.value[l.value]=m.value}));else{if(d.issues.length)r.issues.push(...Gt(a,d.issues));r.value[l.value]=d.value}}}if(i.length)return Promise.all(i).then(()=>r);return r}});var hh=_("$ZodEnum",(e,t)=>{re.init(e,t);let r=fa(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter((n)=>fd.has(typeof n)).map((n)=>typeof n==="string"?Kt(n):n.toString()).join("|")})$`),e._zod.parse=(n,i)=>{let s=n.value;if(o.has(s))return n;return n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),mh=_("$ZodLiteral",(e,t)=>{if(re.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map((o)=>typeof o==="string"?Kt(o):o?Kt(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,n)=>{let i=o.value;if(r.has(i))return o;return o.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),o}});var fh=_("$ZodTransform",(e,t)=>{re.init(e,t),e._zod.optin="optional",e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new On(e.constructor.name);let n=t.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then((s)=>(r.value=s,r.fallback=!0,r));if(n instanceof Promise)throw new kt;return r.value=n,r.fallback=!0,r}});function Rp(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var ol=_("$ZodOptional",(e,t)=>{re.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Q(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Sa(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(t.innerType._zod.optin==="optional"){let n=r.value,i=t.innerType._zod.run(r,o);if(i instanceof Promise)return i.then((s)=>Rp(s,n));return Rp(i,n)}if(r.value===void 0)return r;return t.innerType._zod.run(r,o)}}),gh=_("$ZodExactOptional",(e,t)=>{ol.init(e,t),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,o)=>t.innerType._zod.run(r,o)}),Sh=_("$ZodNullable",(e,t)=>{re.init(e,t),Q(e._zod,"optin",()=>t.innerType._zod.optin),Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Sa(r.source)}|null)$`):void 0}),Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>{if(r.value===null)return r;return t.innerType._zod.run(r,o)}}),_h=_("$ZodDefault",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>xp(i,t));return xp(n,t)}});function xp(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var bh=_("$ZodPrefault",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,o)}}),yh=_("$ZodNonOptional",(e,t)=>{re.init(e,t),Q(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>Pp(i,e));return Pp(n,e)}});function Pp(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var vh=_("$ZodCatch",(e,t)=>{re.init(e,t),e._zod.optin="optional",Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>{if(r.value=i.value,i.issues.length)r.value=t.catchValue({...r,error:{issues:i.issues.map((s)=>ot(s,o,je()))},input:r.value}),r.issues=[],r.fallback=!0;return r});if(r.value=n.value,n.issues.length)r.value=t.catchValue({...r,error:{issues:n.issues.map((i)=>ot(i,o,je()))},input:r.value}),r.issues=[],r.fallback=!0;return r}});var nl=_("$ZodPipe",(e,t)=>{re.init(e,t),Q(e._zod,"values",()=>t.in._zod.values),Q(e._zod,"optin",()=>t.in._zod.optin),Q(e._zod,"optout",()=>t.out._zod.optout),Q(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,o)=>{if(o.direction==="backward"){let i=t.out._zod.run(r,o);if(i instanceof Promise)return i.then((s)=>za(s,t.in,o));return za(i,t.in,o)}let n=t.in._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>za(i,t.out,o));return za(n,t.out,o)}});function za(e,t,r){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var zh=_("$ZodPreprocess",(e,t)=>{nl.init(e,t)}),wh=_("$ZodReadonly",(e,t)=>{re.init(e,t),Q(e._zod,"propValues",()=>t.innerType._zod.propValues),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"optin",()=>t.innerType?._zod?.optin),Q(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then(Tp);return Tp(n)}});function Tp(e){return e.value=Object.freeze(e.value),e}var Rh=_("$ZodLazy",(e,t)=>{re.init(e,t),Q(e._zod,"innerType",()=>{let r=t;if(!r._cachedInner)r._cachedInner=t.getter();return r._cachedInner}),Q(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Q(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Q(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Q(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,o)=>e._zod.innerType._zod.run(r,o)}),xh=_("$ZodCustom",(e,t)=>{ze.init(e,t),re.init(e,t),e._zod.parse=(r,o)=>r,e._zod.check=(r)=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then((i)=>Ep(i,r,o,e));Ep(n,r,o,e);return}});function Ep(e,t,r,o){if(!e){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};if(o._zod.def.params)n.params=o._zod.def.params;t.issues.push(wr(n))}}var s_=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=bd(n.input),a=o[s]??s;return`Invalid input: expected ${i}, received ${a}`}case"invalid_value":if(n.values.length===1)return`Invalid input: expected ${Hc(n.values[0])}`;return`Invalid option: expected one of ${Uc(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${s.unit??"elements"}`;return`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${s.unit}`;return`Too small: expected ${n.origin} to be ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Uc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":if(n.options&&Array.isArray(n.options)&&n.options.length>0)return`Invalid discriminator value. Expected ${n.options.map((s)=>`'${s}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function sl(){return{localeError:s_()}}var Ph,i_=Symbol("ZodOutput"),a_=Symbol("ZodInput");class Th{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Eh(){return new Th}(Ph=globalThis).__zod_globalRegistry??(Ph.__zod_globalRegistry=Eh());var Yt=globalThis.__zod_globalRegistry;function kh(e,t){return new e({type:"string",...M(t)})}function il(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...M(t)})}function al(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...M(t)})}function $h(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...M(t)})}function Ch(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(t)})}function Ih(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(t)})}function Oh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(t)})}function cl(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...M(t)})}function Nh(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...M(t)})}function qh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(t)})}function Ah(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...M(t)})}function Mh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(t)})}function jh(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...M(t)})}function Lh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...M(t)})}function Uh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(t)})}function Zh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(t)})}function Dh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(t)})}function Fh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(t)})}function Hh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(t)})}function Vh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...M(t)})}function Jh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...M(t)})}function Bh(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...M(t)})}function Wh(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...M(t)})}function Kh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(t)})}function Gh(e,t){return new e({type:"string",format:"date",check:"string_format",...M(t)})}function Yh(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...M(t)})}function Xh(e,t){return new e({type:"string",format:"duration",check:"string_format",...M(t)})}function Qh(e,t){return new e({type:"number",checks:[],...M(t)})}function em(e,t){return new e({type:"number",coerce:!0,checks:[],...M(t)})}function tm(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...M(t)})}function rm(e,t){return new e({type:"boolean",...M(t)})}function om(e,t){return new e({type:"undefined",...M(t)})}function nm(e,t){return new e({type:"null",...M(t)})}function sm(e){return new e({type:"any"})}function im(e){return new e({type:"unknown"})}function am(e,t){return new e({type:"never",...M(t)})}function xa(e,t){return new Yc({check:"less_than",...M(t),value:e,inclusive:!1})}function Un(e,t){return new Yc({check:"less_than",...M(t),value:e,inclusive:!0})}function Pa(e,t){return new Xc({check:"greater_than",...M(t),value:e,inclusive:!1})}function Zn(e,t){return new Xc({check:"greater_than",...M(t),value:e,inclusive:!0})}function Ta(e,t){return new ap({check:"multiple_of",...M(t),value:e})}function Ea(e,t){return new lp({check:"max_length",...M(t),maximum:e})}function co(e,t){return new up({check:"min_length",...M(t),minimum:e})}function ka(e,t){return new dp({check:"length_equals",...M(t),length:e})}function ll(e,t){return new pp({check:"string_format",format:"regex",...M(t),pattern:e})}function ul(e){return new hp({check:"string_format",format:"lowercase",...M(e)})}function dl(e){return new mp({check:"string_format",format:"uppercase",...M(e)})}function pl(e,t){return new fp({check:"string_format",format:"includes",...M(t),includes:e})}function hl(e,t){return new gp({check:"string_format",format:"starts_with",...M(t),prefix:e})}function ml(e,t){return new Sp({check:"string_format",format:"ends_with",...M(t),suffix:e})}function Xt(e){return new _p({check:"overwrite",tx:e})}function fl(e){return Xt((t)=>t.normalize(e))}function gl(){return Xt((e)=>e.trim())}function Sl(){return Xt((e)=>e.toLowerCase())}function _l(){return Xt((e)=>e.toUpperCase())}function bl(){return Xt((e)=>hd(e))}function cm(e,t,r){return new e({type:"array",element:t,...M(r)})}function lm(e,t,r){return new e({type:"custom",check:"custom",fn:t,...M(r)})}function um(e,t){let r=c_((o)=>(o.addIssue=(n)=>{if(typeof n==="string")o.issues.push(wr(n,o.value,r._zod.def));else{let i=n;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=o.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),o.issues.push(wr(i))}},e(o.value,o)),t);return r}function c_(e,t){let r=new ze({check:"custom",...M(t)});return r._zod.check=e,r}function Fn(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??Yt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function oe(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,i=t.seen.get(e);if(i){if(i.count++,r.schemaPath.includes(e))i.cycle=r.path;return i.schema}let s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s);let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,d);else{let f=s.schema,S=t.processors[n.type];if(!S)throw Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);S(e,t,f,d)}let m=e._zod.parent;if(m){if(!s.ref)s.ref=m;oe(m,t,d),t.seen.get(m).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Object.assign(s.schema,l);if(t.io==="input"&&Ne(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(o=s.schema).default??(o.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function Hn(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let l=o.get(a);if(l&&l!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,s[0])}}let n=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let m=e.external.registry.get(s[0])?.id,f=e.external.uri??((b)=>b);if(m)return{ref:f(m)};let S=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=S,{defId:S,ref:`${f("__shared")}#/${a}/${S}`}}if(s[1]===r)return{ref:"#"};let u=`${"#"}/${a}/`,d=s[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},i=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:l,defId:u}=n(s);if(a.def={...a.schema},u)a.defId=u;let d=a.schema;for(let m in d)delete d[m];d.$ref=l};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
63
|
+
`)}g.write("payload.value = newResult;"),g.write("return payload;");let H=g.compile();return(x,Z)=>H(f,x,Z)},i,s=fo,a=!mo.jitless,u=a&&xd.value,d=t.catchall,m;e._zod.parse=(f,g)=>{m??(m=o.value);let b=f.value;if(!s(b))return f.issues.push({expected:"object",code:"invalid_type",input:b,inst:e}),f;if(a&&u&&g?.async===!1&&g.jitless!==!0){if(!i)i=n(t.shape);if(f=i(f,g),!d)return f;return bh([],b,f,g,m,e)}return r(f,g)}});function Op(e,t,r,o){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let n=e.filter((i)=>!kr(i));if(n.length===1)return t.value=n[0].value,n[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((i)=>i.issues.map((s)=>ct(s,o,Ue())))}),t}var pl=_("$ZodUnion",(e,t)=>{ne.init(e,t),ee(e._zod,"optin",()=>t.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),ee(e._zod,"optout",()=>t.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),ee(e._zod,"values",()=>{if(t.options.every((o)=>o._zod.values))return new Set(t.options.flatMap((o)=>Array.from(o._zod.values)));return}),ee(e._zod,"pattern",()=>{if(t.options.every((o)=>o._zod.pattern)){let o=t.options.map((n)=>n._zod.pattern);return new RegExp(`^(${o.map((n)=>xa(n.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(o,n)=>{if(r)return r(o,n);let i=!1,s=[];for(let a of t.options){let l=a._zod.run({value:o.value,issues:[]},n);if(l instanceof Promise)s.push(l),i=!0;else{if(l.issues.length===0)return l;s.push(l)}}if(!i)return Op(s,o,e,n);return Promise.all(s).then((a)=>Op(a,o,e,n))}});var vh=_("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,pl.init(e,t);let r=e._zod.parse;ee(e._zod,"propValues",()=>{let n={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,l]of Object.entries(s)){if(!n[a])n[a]=new Set;for(let u of l)n[a].add(u)}}return n});let o=Dn(()=>{let n=t.options,i=new Map;for(let s of n){let a=s._zod.propValues?.[t.discriminator];if(!a||a.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let l of a){if(i.has(l))throw Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});e._zod.parse=(n,i)=>{let s=n.value;if(!fo(s))return n.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),n;let a=o.value.get(s?.[t.discriminator]);if(a)return a._zod.run(n,i);if(t.unionFallback||i.direction==="backward")return r(n,i);return n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(o.value.keys()),input:s,path:[t.discriminator],inst:e}),n}}),zh=_("$ZodIntersection",(e,t)=>{ne.init(e,t),e._zod.parse=(r,o)=>{let n=r.value,i=t.left._zod.run({value:n,issues:[]},o),s=t.right._zod.run({value:n,issues:[]},o);if(i instanceof Promise||s instanceof Promise)return Promise.all([i,s]).then(([l,u])=>Np(r,l,u));return Np(r,i,s)}});function ul(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(Er(e)&&Er(t)){let r=Object.keys(t),o=Object.keys(e).filter((i)=>r.indexOf(i)!==-1),n={...e,...t};for(let i of o){let s=ul(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};n[i]=s.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<e.length;o++){let n=e[o],i=t[o],s=ul(n,i);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Np(e,t,r){let o=new Map,n;for(let a of t.issues)if(a.code==="unrecognized_keys"){n??(n=a);for(let l of a.keys){if(!o.has(l))o.set(l,{});o.get(l).l=!0}}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let l of a.keys){if(!o.has(l))o.set(l,{});o.get(l).r=!0}else e.issues.push(a);let i=[...o].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&n)e.issues.push({...n,keys:i});if(kr(e))return e;let s=ul(t.value,r.value);if(!s.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var wh=_("$ZodRecord",(e,t)=>{ne.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Er(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:e}),r;let i=[],s=t.keyType._zod.values;if(s){r.value={};let a=new Set;for(let u of s)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){a.add(typeof u==="number"?u.toString():u);let d=t.keyType._zod.run({value:u,issues:[]},o);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((g)=>ct(g,o,Ue())),input:u,path:[u],inst:e});continue}let m=d.value,f=t.valueType._zod.run({value:n[u],issues:[]},o);if(f instanceof Promise)i.push(f.then((g)=>{if(g.issues.length)r.issues.push(...or(u,g.issues));r.value[m]=g.value}));else{if(f.issues.length)r.issues.push(...or(u,f.issues));r.value[m]=f.value}}let l;for(let u in n)if(!a.has(u))l=l??[],l.push(u);if(l&&l.length>0)r.issues.push({code:"unrecognized_keys",input:n,inst:e,keys:l})}else{r.value={};for(let a of Reflect.ownKeys(n)){if(a==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(n,a))continue;let l=t.keyType._zod.run({value:a,issues:[]},o);if(l instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof a==="string"&&il.test(a)&&l.issues.length){let m=t.keyType._zod.run({value:Number(a),issues:[]},o);if(m instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(m.issues.length===0)l=m}if(l.issues.length){if(t.mode==="loose")r.value[a]=n[a];else r.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map((m)=>ct(m,o,Ue())),input:a,path:[a],inst:e});continue}let d=t.valueType._zod.run({value:n[a],issues:[]},o);if(d instanceof Promise)i.push(d.then((m)=>{if(m.issues.length)r.issues.push(...or(a,m.issues));r.value[l.value]=m.value}));else{if(d.issues.length)r.issues.push(...or(a,d.issues));r.value[l.value]=d.value}}}if(i.length)return Promise.all(i).then(()=>r);return r}});var Rh=_("$ZodEnum",(e,t)=>{ne.init(e,t);let r=wa(t.entries),o=new Set(r);e._zod.values=o,e._zod.pattern=new RegExp(`^(${r.filter((n)=>Pd.has(typeof n)).map((n)=>typeof n==="string"?rr(n):n.toString()).join("|")})$`),e._zod.parse=(n,i)=>{let s=n.value;if(o.has(s))return n;return n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),xh=_("$ZodLiteral",(e,t)=>{if(ne.init(e,t),t.values.length===0)throw Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map((o)=>typeof o==="string"?rr(o):o?rr(o.toString()):String(o)).join("|")})$`),e._zod.parse=(o,n)=>{let i=o.value;if(r.has(i))return o;return o.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),o}});var Ph=_("$ZodTransform",(e,t)=>{ne.init(e,t),e._zod.optin="optional",e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Un(e.constructor.name);let n=t.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then((s)=>(r.value=s,r.fallback=!0,r));if(n instanceof Promise)throw new Nt;return r.value=n,r.fallback=!0,r}});function Ap(e,t){if(t===void 0&&(e.issues.length||e.fallback))return{issues:[],value:void 0};return e}var hl=_("$ZodOptional",(e,t)=>{ne.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",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${xa(r.source)})?$`):void 0}),e._zod.parse=(r,o)=>{if(t.innerType._zod.optin==="optional"){let n=r.value,i=t.innerType._zod.run(r,o);if(i instanceof Promise)return i.then((s)=>Ap(s,n));return Ap(i,n)}if(r.value===void 0)return r;return t.innerType._zod.run(r,o)}}),Th=_("$ZodExactOptional",(e,t)=>{hl.init(e,t),ee(e._zod,"values",()=>t.innerType._zod.values),ee(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,o)=>t.innerType._zod.run(r,o)}),Eh=_("$ZodNullable",(e,t)=>{ne.init(e,t),ee(e._zod,"optin",()=>t.innerType._zod.optin),ee(e._zod,"optout",()=>t.innerType._zod.optout),ee(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${xa(r.source)}|null)$`):void 0}),ee(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,o)=>{if(r.value===null)return r;return t.innerType._zod.run(r,o)}}),kh=_("$ZodDefault",(e,t)=>{ne.init(e,t),e._zod.optin="optional",ee(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)return r.value=t.defaultValue,r;let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>qp(i,t));return qp(n,t)}});function qp(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var $h=_("$ZodPrefault",(e,t)=>{ne.init(e,t),e._zod.optin="optional",ee(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,o)}}),Ch=_("$ZodNonOptional",(e,t)=>{ne.init(e,t),ee(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(r,o)=>{let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>Mp(i,e));return Mp(n,e)}});function Mp(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}var Ih=_("$ZodCatch",(e,t)=>{ne.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=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>{if(r.value=i.value,i.issues.length)r.value=t.catchValue({...r,error:{issues:i.issues.map((s)=>ct(s,o,Ue()))},input:r.value}),r.issues=[],r.fallback=!0;return r});if(r.value=n.value,n.issues.length)r.value=t.catchValue({...r,error:{issues:n.issues.map((i)=>ct(i,o,Ue()))},input:r.value}),r.issues=[],r.fallback=!0;return r}});var ml=_("$ZodPipe",(e,t)=>{ne.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=(r,o)=>{if(o.direction==="backward"){let i=t.out._zod.run(r,o);if(i instanceof Promise)return i.then((s)=>$a(s,t.in,o));return $a(i,t.in,o)}let n=t.in._zod.run(r,o);if(n instanceof Promise)return n.then((i)=>$a(i,t.out,o));return $a(n,t.out,o)}});function $a(e,t,r){if(e.issues.length)return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}var Oh=_("$ZodPreprocess",(e,t)=>{ml.init(e,t)}),Nh=_("$ZodReadonly",(e,t)=>{ne.init(e,t),ee(e._zod,"propValues",()=>t.innerType._zod.propValues),ee(e._zod,"values",()=>t.innerType._zod.values),ee(e._zod,"optin",()=>t.innerType?._zod?.optin),ee(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,o)=>{if(o.direction==="backward")return t.innerType._zod.run(r,o);let n=t.innerType._zod.run(r,o);if(n instanceof Promise)return n.then(jp);return jp(n)}});function jp(e){return e.value=Object.freeze(e.value),e}var Ah=_("$ZodLazy",(e,t)=>{ne.init(e,t),ee(e._zod,"innerType",()=>{let r=t;if(!r._cachedInner)r._cachedInner=t.getter();return r._cachedInner}),ee(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),ee(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),ee(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),ee(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,o)=>e._zod.innerType._zod.run(r,o)}),qh=_("$ZodCustom",(e,t)=>{Re.init(e,t),ne.init(e,t),e._zod.parse=(r,o)=>r,e._zod.check=(r)=>{let o=r.value,n=t.fn(o);if(n instanceof Promise)return n.then((i)=>Lp(i,r,o,e));Lp(n,r,o,e);return}});function Lp(e,t,r,o){if(!e){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};if(o._zod.def.params)n.params=o._zod.def.params;t.issues.push($r(n))}}var b_=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},o={nan:"NaN"};return(n)=>{switch(n.code){case"invalid_type":{let i=o[n.expected]??n.expected,s=$d(n.input),a=o[s]??s;return`Invalid input: expected ${i}, received ${a}`}case"invalid_value":if(n.values.length===1)return`Invalid input: expected ${el(n.values[0])}`;return`Invalid option: expected one of ${Gc(n.values,"|")}`;case"too_big":{let i=n.inclusive?"<=":"<",s=t(n.origin);if(s)return`Too big: expected ${n.origin??"value"} to have ${i}${n.maximum.toString()} ${s.unit??"elements"}`;return`Too big: expected ${n.origin??"value"} to be ${i}${n.maximum.toString()}`}case"too_small":{let i=n.inclusive?">=":">",s=t(n.origin);if(s)return`Too small: expected ${n.origin} to have ${i}${n.minimum.toString()} ${s.unit}`;return`Too small: expected ${n.origin} to be ${i}${n.minimum.toString()}`}case"invalid_format":{let i=n;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Gc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":if(n.options&&Array.isArray(n.options)&&n.options.length>0)return`Invalid discriminator value. Expected ${n.options.map((s)=>`'${s}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function fl(){return{localeError:b_()}}var Mh,y_=Symbol("ZodOutput"),v_=Symbol("ZodInput");class jh{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Lh(){return new jh}(Mh=globalThis).__zod_globalRegistry??(Mh.__zod_globalRegistry=Lh());var nr=globalThis.__zod_globalRegistry;function Uh(e,t){return new e({type:"string",...j(t)})}function gl(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...j(t)})}function Sl(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...j(t)})}function Zh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...j(t)})}function Dh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(t)})}function Fh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(t)})}function Hh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(t)})}function _l(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...j(t)})}function Vh(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...j(t)})}function Jh(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(t)})}function Bh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...j(t)})}function Wh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(t)})}function Kh(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...j(t)})}function Gh(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...j(t)})}function Yh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(t)})}function Xh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(t)})}function Qh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(t)})}function em(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(t)})}function tm(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(t)})}function rm(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...j(t)})}function om(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...j(t)})}function nm(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...j(t)})}function sm(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...j(t)})}function im(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(t)})}function am(e,t){return new e({type:"string",format:"date",check:"string_format",...j(t)})}function cm(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...j(t)})}function lm(e,t){return new e({type:"string",format:"duration",check:"string_format",...j(t)})}function um(e,t){return new e({type:"number",checks:[],...j(t)})}function dm(e,t){return new e({type:"number",coerce:!0,checks:[],...j(t)})}function pm(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...j(t)})}function hm(e,t){return new e({type:"boolean",...j(t)})}function mm(e,t){return new e({type:"undefined",...j(t)})}function fm(e,t){return new e({type:"null",...j(t)})}function gm(e){return new e({type:"any"})}function Sm(e){return new e({type:"unknown"})}function _m(e,t){return new e({type:"never",...j(t)})}function Oa(e,t){return new al({check:"less_than",...j(t),value:e,inclusive:!1})}function Bn(e,t){return new al({check:"less_than",...j(t),value:e,inclusive:!0})}function Na(e,t){return new cl({check:"greater_than",...j(t),value:e,inclusive:!1})}function Wn(e,t){return new cl({check:"greater_than",...j(t),value:e,inclusive:!0})}function Aa(e,t){return new _p({check:"multiple_of",...j(t),value:e})}function qa(e,t){return new yp({check:"max_length",...j(t),maximum:e})}function go(e,t){return new vp({check:"min_length",...j(t),minimum:e})}function Ma(e,t){return new zp({check:"length_equals",...j(t),length:e})}function bl(e,t){return new wp({check:"string_format",format:"regex",...j(t),pattern:e})}function yl(e){return new Rp({check:"string_format",format:"lowercase",...j(e)})}function vl(e){return new xp({check:"string_format",format:"uppercase",...j(e)})}function zl(e,t){return new Pp({check:"string_format",format:"includes",...j(t),includes:e})}function wl(e,t){return new Tp({check:"string_format",format:"starts_with",...j(t),prefix:e})}function Rl(e,t){return new Ep({check:"string_format",format:"ends_with",...j(t),suffix:e})}function sr(e){return new kp({check:"overwrite",tx:e})}function xl(e){return sr((t)=>t.normalize(e))}function Pl(){return sr((e)=>e.trim())}function Tl(){return sr((e)=>e.toLowerCase())}function El(){return sr((e)=>e.toUpperCase())}function kl(){return sr((e)=>Rd(e))}function bm(e,t,r){return new e({type:"array",element:t,...j(r)})}function ym(e,t,r){return new e({type:"custom",check:"custom",fn:t,...j(r)})}function vm(e,t){let r=z_((o)=>(o.addIssue=(n)=>{if(typeof n==="string")o.issues.push($r(n,o.value,r._zod.def));else{let i=n;if(i.fatal)i.continue=!1;i.code??(i.code="custom"),i.input??(i.input=o.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),o.issues.push($r(i))}},e(o.value,o)),t);return r}function z_(e,t){let r=new Re({check:"custom",...j(t)});return r._zod.check=e,r}function Gn(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??nr,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function se(e,t,r={path:[],schemaPath:[]}){var o;let n=e._zod.def,i=t.seen.get(e);if(i){if(i.count++,r.schemaPath.includes(e))i.cycle=r.path;return i.schema}let s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s);let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,d);else{let f=s.schema,g=t.processors[n.type];if(!g)throw Error(`[toJSONSchema]: Non-representable type encountered: ${n.type}`);g(e,t,f,d)}let m=e._zod.parent;if(m){if(!s.ref)s.ref=m;se(m,t,d),t.seen.get(m).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)Object.assign(s.schema,l);if(t.io==="input"&&qe(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(o=s.schema).default??(o.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function Yn(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let l=o.get(a);if(l&&l!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);o.set(a,s[0])}}let n=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let m=e.external.registry.get(s[0])?.id,f=e.external.uri??((b)=>b);if(m)return{ref:f(m)};let g=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=g,{defId:g,ref:`${f("__shared")}#/${a}/${g}`}}if(s[1]===r)return{ref:"#"};let u=`${"#"}/${a}/`,d=s[1].schema.id??`__schema${e.counter++}`;return{defId:d,ref:u+d}},i=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:l,defId:u}=n(s);if(a.def={...a.schema},u)a.defId=u;let d=a.schema;for(let m in d)delete d[m];d.$ref=l};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
64
64
|
|
|
65
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){i(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1){if(e.reused==="ref"){i(s);continue}}}}function Vn(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(a)=>{let l=e.seen.get(a);if(l.ref===null)return;let u=l.def??l.schema,d={...u},m=l.ref;if(l.ref=null,m){o(m);let S=e.seen.get(m),b=S.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))u.allOf=u.allOf??[],u.allOf.push(b);else Object.assign(u,b);if(Object.assign(u,d),a._zod.parent===m)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(!(v in d))delete u[v]}if(b.$ref&&S.def)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(v in S.def&&JSON.stringify(u[v])===JSON.stringify(S.def[v]))delete u[v]}}let f=a._zod.parent;if(f&&f!==m){o(f);let S=e.seen.get(f);if(S?.schema.$ref){if(u.$ref=S.schema.$ref,S.def)for(let b in u){if(b==="$ref"||b==="allOf")continue;if(b in S.def&&JSON.stringify(u[b])===JSON.stringify(S.def[b]))delete u[b]}}}e.override({zodSchema:a,jsonSchema:u,path:l.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let n={};if(e.target==="draft-2020-12")n.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")n.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")n.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");n.$id=e.external.uri(a)}Object.assign(n,r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&n.id===i)delete n.id;let s=e.external?.defs??{};for(let a of e.seen.entries()){let l=a[1];if(l.def&&l.defId){if(l.def.id===l.defId)delete l.def.id;s[l.defId]=l.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")n.$defs=s;else n.definitions=s;try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Dn(t,"input",e.processors),output:Dn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function Ne(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Ne(o.element,r);if(o.type==="set")return Ne(o.valueType,r);if(o.type==="lazy")return Ne(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return Ne(o.innerType,r);if(o.type==="intersection")return Ne(o.left,r)||Ne(o.right,r);if(o.type==="record"||o.type==="map")return Ne(o.keyType,r)||Ne(o.valueType,r);if(o.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return Ne(o.in,r)||Ne(o.out,r)}if(o.type==="object"){for(let n in o.shape)if(Ne(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(Ne(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(Ne(n,r))return!0;if(o.rest&&Ne(o.rest,r))return!0;return!1}return!1}var dm=(e,t={})=>(r)=>{let o=Fn({...r,processors:t});return oe(e,o),Hn(o,e),Vn(o,e)},Dn=(e,t,r={})=>(o)=>{let{libraryOptions:n,target:i}=o??{},s=Fn({...n??{},target:i,io:t,processors:r});return oe(e,s),Hn(s,e),Vn(s,e)};var l_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},yl=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof i==="number")n.minLength=i;if(typeof s==="number")n.maxLength=s;if(a){if(n.format=l_[a]??a,n.format==="")delete n.format;if(a==="time")delete n.format}if(u)n.contentEncoding=u;if(l&&l.size>0){let d=[...l];if(d.length===1)n.pattern=d[0].source;else if(d.length>1)n.allOf=[...d.map((m)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))]}},vl=(e,t,r,o)=>{let n=r,{minimum:i,maximum:s,format:a,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))n.type="integer";else n.type="number";let m=typeof d==="number"&&d>=(i??Number.NEGATIVE_INFINITY),f=typeof u==="number"&&u<=(s??Number.POSITIVE_INFINITY),S=t.target==="draft-04"||t.target==="openapi-3.0";if(m)if(S)n.minimum=d,n.exclusiveMinimum=!0;else n.exclusiveMinimum=d;else if(typeof i==="number")n.minimum=i;if(f)if(S)n.maximum=u,n.exclusiveMaximum=!0;else n.exclusiveMaximum=u;else if(typeof s==="number")n.maximum=s;if(typeof l==="number")n.multipleOf=l},zl=(e,t,r,o)=>{r.type="boolean"},hm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},mm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},wl=(e,t,r,o)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},Rl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},fm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},xl=(e,t,r,o)=>{r.not={}},Pl=(e,t,r,o)=>{},Tl=(e,t,r,o)=>{},gm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},El=(e,t,r,o)=>{let n=e._zod.def,i=fa(n.entries);if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";r.enum=i},kl=(e,t,r,o)=>{let n=e._zod.def,i=[];for(let s of n.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else i.push(Number(s));else i.push(s);if(i.length===0);else if(i.length===1){let s=i[0];if(r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[s];else r.const=s}else{if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";if(i.every((s)=>typeof s==="boolean"))r.type="boolean";if(i.every((s)=>s===null))r.type="null";r.enum=i}},Sm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},_m=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},bm=(e,t,r,o)=>{let n=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:l}=e._zod.bag;if(s!==void 0)i.minLength=s;if(a!==void 0)i.maxLength=a;if(l)if(l.length===1)i.contentMediaType=l[0],Object.assign(n,i);else Object.assign(n,i),n.anyOf=l.map((u)=>({contentMediaType:u}));else Object.assign(n,i)},ym=(e,t,r,o)=>{r.type="boolean"},$l=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},vm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},Cl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},zm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},wm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},Il=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")n.minItems=s;if(typeof a==="number")n.maxItems=a;n.type="array",n.items=oe(i.element,t,{...o,path:[...o.path,"items"]})},Ol=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object",n.properties={};let s=i.shape;for(let u in s)n.properties[u]=oe(s[u],t,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(s)),l=new Set([...a].filter((u)=>{let d=i.shape[u]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(l.size>0)n.required=Array.from(l);if(i.catchall?._zod.def.type==="never")n.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")n.additionalProperties=!1}else if(i.catchall)n.additionalProperties=oe(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Nl=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,s=n.options.map((a,l)=>oe(a,t,{...o,path:[...o.path,i?"oneOf":"anyOf",l]}));if(i)r.oneOf=s;else r.anyOf=s},ql=(e,t,r,o)=>{let n=e._zod.def,i=oe(n.left,t,{...o,path:[...o.path,"allOf",0]}),s=oe(n.right,t,{...o,path:[...o.path,"allOf",1]}),a=(u)=>("allOf"in u)&&Object.keys(u).length===1,l=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=l},Rm=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",l=i.items.map((f,S)=>oe(f,t,{...o,path:[...o.path,s,S]})),u=i.rest?oe(i.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(n.prefixItems=l,u)n.items=u}else if(t.target==="openapi-3.0"){if(n.items={anyOf:l},u)n.items.anyOf.push(u);if(n.minItems=l.length,!u)n.maxItems=l.length}else if(n.items=l,u)n.additionalItems=u;let{minimum:d,maximum:m}=e._zod.bag;if(typeof d==="number")n.minItems=d;if(typeof m==="number")n.maxItems=m},Al=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let s=i.keyType,l=s._zod.bag?.patterns;if(i.mode==="loose"&&l&&l.size>0){let d=oe(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let m of l)n.patternProperties[m.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")n.propertyNames=oe(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});n.additionalProperties=oe(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=s._zod.values;if(u){let d=[...u].filter((m)=>typeof m==="string"||typeof m==="number");if(d.length>0)n.required=d}},Ml=(e,t,r,o)=>{let n=e._zod.def,i=oe(n.innerType,t,o),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=n.innerType,r.nullable=!0;else r.anyOf=[i,{type:"null"}]},jl=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Ll=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},Ul=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(n.defaultValue))},Zl=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},Dl=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?n.out:n.in:n.out;oe(s,t,o);let a=t.seen.get(e);a.ref=s},Fl=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},xm=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},$a=(e,t,r,o)=>{let n=e._zod.def;oe(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Hl=(e,t,r,o)=>{let n=e._zod.innerType;oe(n,t,o);let i=t.seen.get(e);i.ref=n},pm={string:yl,number:vl,boolean:zl,bigint:hm,symbol:mm,null:wl,undefined:Rl,void:fm,never:xl,any:Pl,unknown:Tl,date:gm,enum:El,literal:kl,nan:Sm,template_literal:_m,file:bm,success:ym,custom:$l,function:vm,transform:Cl,map:zm,set:wm,array:Il,object:Ol,union:Nl,intersection:ql,tuple:Rm,record:Al,nullable:Ml,nonoptional:jl,default:Ll,prefault:Ul,catch:Zl,pipe:Dl,readonly:Fl,promise:xm,optional:$a,lazy:Hl};function Ca(e,t){if("_idmap"in e){let o=e,n=Fn({...t,processors:pm}),i={};for(let l of o._idmap.entries()){let[u,d]=l;oe(d,n)}let s={},a={registry:o,uri:t?.uri,defs:i};n.external=a;for(let l of o._idmap.entries()){let[u,d]=l;Hn(n,d),s[u]=Vn(n,d)}if(Object.keys(i).length>0){let l=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[l]:i}}return{schemas:s}}let r=Fn({...t,processors:pm});return oe(e,r),Hn(r,e),Vn(r,e)}var S_=_("ZodISODateTime",(e,t)=>{Up.init(e,t),ce.init(e,t)});function uo(e){return Kh(S_,e)}var __=_("ZodISODate",(e,t)=>{Zp.init(e,t),ce.init(e,t)});function Vl(e){return Gh(__,e)}var b_=_("ZodISOTime",(e,t)=>{Dp.init(e,t),ce.init(e,t)});function Pm(e){return Yh(b_,e)}var y_=_("ZodISODuration",(e,t)=>{Fp.init(e,t),ce.init(e,t)});function Tm(e){return Xh(y_,e)}var v_=(e,t)=>{ba.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>Bc(e,r)},flatten:{value:(r)=>Jc(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Nn,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Nn,2)}},isEmpty:{get(){return e.issues.length===0}}})};var Je=_("ZodError",v_,{Parent:Error});var km=ya(Je),$m=va(Je),Oa=An(Je),Cm=Mn(Je),Im=wd(Je),Om=Rd(Je),Nm=xd(Je),qm=Pd(Je),Am=Td(Je),Mm=Ed(Je),jm=kd(Je),Lm=$d(Je);var Um=new WeakMap;function Jn(e,t,r){let o=Object.getPrototypeOf(e),n=Um.get(o);if(!n)n=new Set,Um.set(o,n);if(n.has(t))return;n.add(t);for(let i in r){let s=r[i];Object.defineProperty(o,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var ne=_("ZodType",(e,t)=>(re.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Dn(e,"input"),output:Dn(e,"output")}}),e.toJSONSchema=dm(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,o)=>km(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Oa(e,r,o),e.parseAsync=async(r,o)=>$m(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>Cm(e,r,o),e.spa=e.safeParseAsync,e.encode=(r,o)=>Im(e,r,o),e.decode=(r,o)=>Om(e,r,o),e.encodeAsync=async(r,o)=>Nm(e,r,o),e.decodeAsync=async(r,o)=>qm(e,r,o),e.safeEncode=(r,o)=>Am(e,r,o),e.safeDecode=(r,o)=>Mm(e,r,o),e.safeEncodeAsync=async(r,o)=>jm(e,r,o),e.safeDecodeAsync=async(r,o)=>Lm(e,r,o),Jn(e,"ZodType",{check(...r){let o=this.def;return this.clone(Wt(o,{checks:[...o.checks??[],...r.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,o){return rt(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(ub(r,o))},superRefine(r,o){return this.check(db(r,o))},overwrite(r){return this.check(Xt(r))},optional(){return j(this)},exactOptional(){return G_(this)},nullable(){return Hm(this)},nullish(){return j(Hm(this))},nonoptional(r){return rb(this,r)},array(){return g(this)},or(r){return T([this,r])},and(r){return $t(this,r)},transform(r){return Vm(this,ef(r))},default(r){return Q_(this,r)},prefault(r){return tb(this,r)},catch(r){return nb(this,r)},pipe(r){return Vm(this,r)},readonly(){return ab(this)},describe(r){let o=this.clone();return Yt.add(o,{description:r}),o},meta(...r){if(r.length===0)return Yt.get(this);let o=this.clone();return Yt.add(o,r[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return Yt.get(e)?.description},configurable:!0}),e)),Jm=_("_ZodString",(e,t)=>{Ra.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,i)=>yl(e,o,n,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Jn(e,"_ZodString",{regex(...o){return this.check(ll(...o))},includes(...o){return this.check(pl(...o))},startsWith(...o){return this.check(hl(...o))},endsWith(...o){return this.check(ml(...o))},min(...o){return this.check(co(...o))},max(...o){return this.check(Ea(...o))},length(...o){return this.check(ka(...o))},nonempty(...o){return this.check(co(1,...o))},lowercase(o){return this.check(ul(o))},uppercase(o){return this.check(dl(o))},trim(){return this.check(gl())},normalize(...o){return this.check(fl(...o))},toLowerCase(){return this.check(Sl())},toUpperCase(){return this.check(_l())},slugify(){return this.check(bl())}})}),Bm=_("ZodString",(e,t)=>{Ra.init(e,t),Jm.init(e,t),e.email=(r)=>e.check(il(Wm,r)),e.url=(r)=>e.check(cl(Gm,r)),e.jwt=(r)=>e.check(Wh(M_,r)),e.emoji=(r)=>e.check(Nh(w_,r)),e.guid=(r)=>e.check(al(Zm,r)),e.uuid=(r)=>e.check($h(Na,r)),e.uuidv4=(r)=>e.check(Ch(Na,r)),e.uuidv6=(r)=>e.check(Ih(Na,r)),e.uuidv7=(r)=>e.check(Oh(Na,r)),e.nanoid=(r)=>e.check(qh(R_,r)),e.guid=(r)=>e.check(al(Zm,r)),e.cuid=(r)=>e.check(Ah(x_,r)),e.cuid2=(r)=>e.check(Mh(P_,r)),e.ulid=(r)=>e.check(jh(T_,r)),e.base64=(r)=>e.check(Vh(N_,r)),e.base64url=(r)=>e.check(Jh(q_,r)),e.xid=(r)=>e.check(Lh(E_,r)),e.ksuid=(r)=>e.check(Uh(k_,r)),e.ipv4=(r)=>e.check(Zh($_,r)),e.ipv6=(r)=>e.check(Dh(C_,r)),e.cidrv4=(r)=>e.check(Fh(I_,r)),e.cidrv6=(r)=>e.check(Hh(O_,r)),e.e164=(r)=>e.check(Bh(A_,r)),e.datetime=(r)=>e.check(uo(r)),e.date=(r)=>e.check(Vl(r)),e.time=(r)=>e.check(Pm(r)),e.duration=(r)=>e.check(Tm(r))});function c(e){return kh(Bm,e)}var ce=_("ZodStringFormat",(e,t)=>{ae.init(e,t),Jm.init(e,t)}),Wm=_("ZodEmail",(e,t)=>{Cp.init(e,t),ce.init(e,t)});function Km(e){return il(Wm,e)}var Zm=_("ZodGUID",(e,t)=>{kp.init(e,t),ce.init(e,t)});var Na=_("ZodUUID",(e,t)=>{$p.init(e,t),ce.init(e,t)});var Gm=_("ZodURL",(e,t)=>{Ip.init(e,t),ce.init(e,t)});function qa(e){return cl(Gm,e)}var w_=_("ZodEmoji",(e,t)=>{Op.init(e,t),ce.init(e,t)});var R_=_("ZodNanoID",(e,t)=>{Np.init(e,t),ce.init(e,t)});var x_=_("ZodCUID",(e,t)=>{qp.init(e,t),ce.init(e,t)});var P_=_("ZodCUID2",(e,t)=>{Ap.init(e,t),ce.init(e,t)});var T_=_("ZodULID",(e,t)=>{Mp.init(e,t),ce.init(e,t)});var E_=_("ZodXID",(e,t)=>{jp.init(e,t),ce.init(e,t)});var k_=_("ZodKSUID",(e,t)=>{Lp.init(e,t),ce.init(e,t)});var $_=_("ZodIPv4",(e,t)=>{Hp.init(e,t),ce.init(e,t)});var C_=_("ZodIPv6",(e,t)=>{Vp.init(e,t),ce.init(e,t)});var I_=_("ZodCIDRv4",(e,t)=>{Jp.init(e,t),ce.init(e,t)});var O_=_("ZodCIDRv6",(e,t)=>{Bp.init(e,t),ce.init(e,t)});var N_=_("ZodBase64",(e,t)=>{Kp.init(e,t),ce.init(e,t)});var q_=_("ZodBase64URL",(e,t)=>{Gp.init(e,t),ce.init(e,t)});var A_=_("ZodE164",(e,t)=>{Yp.init(e,t),ce.init(e,t)});var M_=_("ZodJWT",(e,t)=>{Xp.init(e,t),ce.init(e,t)});var Aa=_("ZodNumber",(e,t)=>{tl.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,i)=>vl(e,o,n,i),Jn(e,"ZodNumber",{gt(o,n){return this.check(Pa(o,n))},gte(o,n){return this.check(Zn(o,n))},min(o,n){return this.check(Zn(o,n))},lt(o,n){return this.check(xa(o,n))},lte(o,n){return this.check(Un(o,n))},max(o,n){return this.check(Un(o,n))},int(o){return this.check(Dm(o))},safe(o){return this.check(Dm(o))},positive(o){return this.check(Pa(0,o))},nonnegative(o){return this.check(Zn(0,o))},negative(o){return this.check(xa(0,o))},nonpositive(o){return this.check(Un(0,o))},multipleOf(o,n){return this.check(Ta(o,n))},step(o,n){return this.check(Ta(o,n))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??0.5),e.isFinite=!0,e.format=r.format??null});function z(e){return Qh(Aa,e)}var j_=_("ZodNumberFormat",(e,t)=>{Qp.init(e,t),Aa.init(e,t)});function Dm(e){return tm(j_,e)}var Ym=_("ZodBoolean",(e,t)=>{eh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>zl(e,r,o,n)});function E(e){return rm(Ym,e)}var L_=_("ZodUndefined",(e,t)=>{th.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Rl(e,r,o,n)});function Bl(e){return om(L_,e)}var U_=_("ZodNull",(e,t)=>{rh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>wl(e,r,o,n)});function Rr(e){return nm(U_,e)}var Z_=_("ZodAny",(e,t)=>{oh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Pl(e,r,o,n)});function Ma(){return sm(Z_)}var D_=_("ZodUnknown",(e,t)=>{nh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Tl(e,r,o,n)});function A(){return im(D_)}var F_=_("ZodNever",(e,t)=>{sh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>xl(e,r,o,n)});function Wl(e){return am(F_,e)}var H_=_("ZodArray",(e,t)=>{ih.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n),e.element=t.element,Jn(e,"ZodArray",{min(r,o){return this.check(co(r,o))},nonempty(r){return this.check(co(1,r))},max(r,o){return this.check(Ea(r,o))},length(r,o){return this.check(ka(r,o))},unwrap(){return this.element}})});function g(e,t){return cm(H_,e,t)}var Xm=_("ZodObject",(e,t)=>{lh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n),Q(e,"shape",()=>t.shape),Jn(e,"ZodObject",{keyof(){return K(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},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:Wl()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return KS(this,r)},safeExtend(r){return GS(this,r)},merge(r){return YS(this,r)},pick(r){return BS(this,r)},omit(r){return WS(this,r)},partial(...r){return XS(tf,this,r[0])},required(...r){return QS(rf,this,r[0])}})});function p(e,t){let r={type:"object",shape:e??{},...M(t)};return new Xm(r)}function F(e,t){return new Xm({type:"object",shape:e,catchall:A(),...M(t)})}var Qm=_("ZodUnion",(e,t)=>{rl.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nl(e,r,o,n),e.options=t.options});function T(e,t){return new Qm({type:"union",options:e,...M(t)})}var V_=_("ZodDiscriminatedUnion",(e,t)=>{Qm.init(e,t),uh.init(e,t)});function po(e,t,r){return new V_({type:"union",options:t,discriminator:e,...M(r)})}var J_=_("ZodIntersection",(e,t)=>{dh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n)});function $t(e,t){return new J_({type:"intersection",left:e,right:t})}var Fm=_("ZodRecord",(e,t)=>{ph.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function P(e,t,r){if(!t||!t._zod)return new Fm({type:"record",keyType:c(),valueType:e,...M(t)});return new Fm({type:"record",keyType:e,valueType:t,...M(r)})}var Jl=_("ZodEnum",(e,t)=>{hh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(o,n,i)=>El(e,o,n,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new Jl({...t,checks:[],...M(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let s of o)if(r.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new Jl({...t,checks:[],...M(n),entries:i})}});function K(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new Jl({type:"enum",entries:r,...M(t)})}var B_=_("ZodLiteral",(e,t)=>{mh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>kl(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function h(e,t){return new B_({type:"literal",values:Array.isArray(e)?e:[e],...M(t)})}var W_=_("ZodTransform",(e,t)=>{fh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Cl(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new On(e.constructor.name);r.addIssue=(i)=>{if(typeof i==="string")r.issues.push(wr(i,r.value,t));else{let s=i;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),r.issues.push(wr(s))}};let n=t.transform(r.value,r);if(n instanceof Promise)return n.then((i)=>(r.value=i,r.fallback=!0,r));return r.value=n,r.fallback=!0,r}});function ef(e){return new W_({type:"transform",transform:e})}var tf=_("ZodOptional",(e,t)=>{ol.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$a(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function j(e){return new tf({type:"optional",innerType:e})}var K_=_("ZodExactOptional",(e,t)=>{gh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$a(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function G_(e){return new K_({type:"optional",innerType:e})}var Y_=_("ZodNullable",(e,t)=>{Sh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function Hm(e){return new Y_({type:"nullable",innerType:e})}var X_=_("ZodDefault",(e,t)=>{_h.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Q_(e,t){return new X_({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Fc(t)}})}var eb=_("ZodPrefault",(e,t)=>{bh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function tb(e,t){return new eb({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Fc(t)}})}var rf=_("ZodNonOptional",(e,t)=>{yh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>jl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function rb(e,t){return new rf({type:"nonoptional",innerType:e,...M(t)})}var ob=_("ZodCatch",(e,t)=>{vh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function nb(e,t){return new ob({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var of=_("ZodPipe",(e,t)=>{nl.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dl(e,r,o,n),e.in=t.in,e.out=t.out});function Vm(e,t){return new of({type:"pipe",in:e,out:t})}var sb=_("ZodPreprocess",(e,t)=>{of.init(e,t),zh.init(e,t)}),ib=_("ZodReadonly",(e,t)=>{wh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ab(e){return new ib({type:"readonly",innerType:e})}var cb=_("ZodLazy",(e,t)=>{Rh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hl(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function Bn(e){return new cb({type:"lazy",getter:e})}var lb=_("ZodCustom",(e,t)=>{xh.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(r,o,n)=>$l(e,r,o,n)});function ub(e,t={}){return lm(lb,e,t)}function db(e,t){return um(e,t)}function xr(e,t){return new sb({type:"pipe",in:ef(e),out:t})}var sf={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var nf;(function(e){})(nf||(nf={}));function pb(e){return em(Aa,e)}je(sl());var ho="2025-11-25";var ja=[ho,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],La="io.modelcontextprotocol/related-task",It="io.modelcontextprotocol/protocolVersion",mo="io.modelcontextprotocol/clientInfo",Ot="io.modelcontextprotocol/serverInfo",Pr="io.modelcontextprotocol/clientCapabilities",Wn="io.modelcontextprotocol/subscriptionId",fo="io.modelcontextprotocol/logLevel";var Tr="2.0";var Ct=Bn(()=>T([c(),z(),E(),Rr(),P(c(),Ct),g(Ct)])),ue=P(c(),Ct),Ua=g(Ct),go=T([c(),z().int()]),So=c(),Kn=p({ttl:z().optional()}),Gn=p({taskId:c()}),_o=F({progressToken:go.optional(),[La]:Gn.optional()}),ye=p({_meta:_o.optional()}),er=ye.extend({task:Kn.optional()}),de=p({method:c(),params:ye.loose().optional()}),Te=p({_meta:_o.optional()}),we=p({method:c(),params:Te.loose().optional()}),bo=F({get[Ot](){return _t.optional().catch(void 0)}}),pe=F({_meta:bo.optional()}),nt=T([c(),z().int()]),yo=p({jsonrpc:h(Tr),id:nt,...de.shape}).strict(),vo=p({jsonrpc:h(Tr),...we.shape}).strict(),Er=p({jsonrpc:h(Tr),id:nt,result:pe}).strict(),kr=p({jsonrpc:h(Tr),id:nt.optional(),error:p({code:z().int(),message:c(),data:A().optional()})}).strict(),st=T([yo,vo,Er,kr]),Za=T([Er,kr]),tr=pe.strict(),Yn=Te.extend({requestId:nt.optional(),reason:c().optional()}),zo=we.extend({method:h("notifications/cancelled"),params:Yn}),Xn=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),Nt=p({icons:g(Xn).optional()}),St=p({name:c(),title:c().optional()}),_t=St.extend({...St.shape,...Nt.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),mb=$t(p({applyDefaults:E().optional()}),ue),fb=xr((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)&&Object.keys(e).length===0)return{form:{}};return e},$t(p({form:mb.optional(),url:ue.optional()}),ue.optional())),Da=F({list:ue.optional(),cancel:ue.optional(),requests:F({sampling:F({createMessage:ue.optional()}).optional(),elicitation:F({create:ue.optional()}).optional()}).optional()}),Fa=F({list:ue.optional(),cancel:ue.optional(),requests:F({tools:F({call:ue.optional()}).optional()}).optional()}),Qn=p({experimental:P(c(),ue).optional(),sampling:p({context:ue.optional(),tools:ue.optional()}).optional(),elicitation:fb.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:Da.optional(),extensions:P(c(),ue).optional()}),es=ye.extend({protocolVersion:c(),capabilities:Qn,clientInfo:_t}),wo=de.extend({method:h("initialize"),params:es}),Ro=p({experimental:P(c(),ue).optional(),logging:ue.optional(),completions:ue.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:Fa.optional(),extensions:P(c(),ue).optional()}),ts=pe.extend({protocolVersion:c(),capabilities:Ro,serverInfo:_t,instructions:c().optional()}),xo=we.extend({method:h("notifications/initialized"),params:Te.optional()}),rs=de.extend({method:h("server/discover"),params:ye.optional()}),rr=pe.extend({supportedVersions:g(c()),capabilities:Ro,instructions:c().optional()}),Po=de.extend({method:h("ping"),params:ye.optional()}),os=p({progress:z(),total:j(z()),message:j(c())}),ns=p({...Te.shape,...os.shape,progressToken:go}),To=we.extend({method:h("notifications/progress"),params:ns}),ss=ye.extend({cursor:So.optional()}),qt=de.extend({params:ss.optional()}),At=pe.extend({nextCursor:So.optional()}),Eo=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),ko=Eo.extend({text:c()}),Gl=c().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),$o=Eo.extend({blob:Gl}),Mt=K(["user","assistant"]),bt=p({audience:g(Mt).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),Co=p({...St.shape,...Nt.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:bt.optional(),_meta:j(F({}))}),is=p({...St.shape,...Nt.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:bt.optional(),_meta:j(F({}))}),as=qt.extend({method:h("resources/list")}),cs=At.extend({resources:g(Co)}),ls=qt.extend({method:h("resources/templates/list")}),us=At.extend({resourceTemplates:g(is)}),$r=ye.extend({uri:c()}),ds=$r,ps=de.extend({method:h("resources/read"),params:ds}),hs=pe.extend({contents:g(T([ko,$o]))}),ms=we.extend({method:h("notifications/resources/list_changed"),params:Te.optional()}),fs=$r,gs=de.extend({method:h("resources/subscribe"),params:fs}),Ss=$r,_s=de.extend({method:h("resources/unsubscribe"),params:Ss}),Io=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:g(c()).optional()}),bs=ye.extend({notifications:Io}),ys=de.extend({method:h("subscriptions/listen"),params:bs}),vs=Te.extend({notifications:Io}),zs=we.extend({method:h("notifications/subscriptions/acknowledged"),params:vs}),ws=bo.extend({[Wn]:nt}),Rs=pe.extend({_meta:ws}),xs=Te.extend({uri:c()}),Ps=we.extend({method:h("notifications/resources/updated"),params:xs}),Ts=p({name:c(),description:j(c()),required:j(E())}),Es=p({...St.shape,...Nt.shape,description:j(c()),arguments:j(g(Ts)),_meta:j(F({}))}),ks=qt.extend({method:h("prompts/list")}),$s=At.extend({prompts:g(Es)}),Cs=ye.extend({name:c(),arguments:P(c(),c()).optional()}),Is=de.extend({method:h("prompts/get"),params:Cs}),Cr=p({type:h("text"),text:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Ir=p({type:h("image"),data:Gl,mimeType:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Or=p({type:h("audio"),data:Gl,mimeType:c(),annotations:bt.optional(),_meta:P(c(),A()).optional()}),Os=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),Nr=p({type:h("resource"),resource:T([ko,$o]),annotations:bt.optional(),_meta:P(c(),A()).optional()}),qr=Co.extend({type:h("resource_link")}),yt=T([Cr,Ir,Or,qr,Nr]),Ns=p({role:Mt,content:yt}),qs=pe.extend({description:c().optional(),messages:g(Ns)}),As=we.extend({method:h("notifications/prompts/list_changed"),params:Te.optional()}),Ms=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),js=p({taskSupport:K(["required","optional","forbidden"]).optional()}),or=p({...St.shape,...Nt.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),Ct).optional(),required:g(c()).optional()}).catchall(A()),outputSchema:F({$schema:c().optional()}).optional(),annotations:Ms.optional(),execution:js.optional(),_meta:P(c(),A()).optional()}),Ls=qt.extend({method:h("tools/list")}),Us=At.extend({tools:g(or)}),nr=pe.extend({content:g(yt).default([]),structuredContent:A().optional(),isError:E().optional()}),Ha=nr.or(pe.extend({toolResult:A()})),Zs=er.extend({name:c(),arguments:P(c(),A()).optional()}),Ds=de.extend({method:h("tools/call"),params:Zs}),Fs=we.extend({method:h("notifications/tools/list_changed"),params:Te.optional()}),Hs=p({autoRefresh:E().default(!0),debounceMs:z().int().nonnegative().default(300)}),Oo=K(["debug","info","notice","warning","error","critical","alert","emergency"]),Vs=ye.extend({level:Oo}),Js=de.extend({method:h("logging/setLevel"),params:Vs}),Bs=Te.extend({level:Oo,logger:c().optional(),data:A()}),Ar=we.extend({method:h("notifications/message"),params:Bs}),Ws=p({name:c().optional()}),Ks=p({hints:g(Ws).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),Gs=p({mode:K(["auto","required","none"]).optional()}),Ys=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:g(yt),structuredContent:A().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),Xs=po("type",[Cr,Ir,Or]),Qt=po("type",[Cr,Ir,Or,Os,Ys]),Qs=p({role:Mt,content:T([Qt,g(Qt)]),_meta:P(c(),A()).optional()}),ei=er.extend({messages:g(Qs),modelPreferences:Ks.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:ue.optional(),tools:g(or).optional(),toolChoice:Gs.optional()}),ti=de.extend({method:h("sampling/createMessage"),params:ei}),ri=pe.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Mt,content:Xs}),oi=pe.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Mt,content:T([Qt,g(Qt)])}),No=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),Mr=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),jr=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),qo=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),Ao=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),Mo=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),ni=T([qo,Ao]),jo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),Lo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),si=T([jo,Lo]),ii=T([Mo,ni,si]),Uo=T([ii,No,Mr,jr]),Lr=er.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),Uo),required:g(c()).optional()}).catchall(A())}),ai=er.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),ci=T([Lr,ai]),li=de.extend({method:h("elicitation/create"),params:ci}),ui=Te.extend({elicitationId:c()}),di=we.extend({method:h("notifications/elicitation/complete"),params:ui}),pi=pe.extend({action:K(["accept","decline","cancel"]),content:xr((e)=>e===null?void 0:e,P(c(),T([c(),z(),E(),g(c())])).optional())}),hi=p({type:h("ref/resource"),uri:c()}),mi=p({type:h("ref/prompt"),name:c()}),fi=ye.extend({ref:T([mi,hi]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),gi=de.extend({method:h("completion/complete"),params:fi}),Si=pe.extend({completion:F({values:g(c()).max(100),total:j(z().int()),hasMore:j(E())})}),_i=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),bi=de.extend({method:h("roots/list"),params:ye.optional()}),yi=pe.extend({roots:g(_i)}),vi=we.extend({method:h("notifications/roots/list_changed"),params:Te.optional()}),Va=F({ttl:z().optional(),pollInterval:z().optional()}),zi=K(["working","input_required","completed","failed","cancelled"]),jt=p({taskId:c(),status:zi,ttl:T([z(),Rr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:j(z()),statusMessage:j(c())}),Ja=pe.extend({task:jt}),wi=Te.merge(jt),Ba=we.extend({method:h("notifications/tasks/status"),params:wi}),Wa=de.extend({method:h("tasks/get"),params:ye.extend({taskId:c()})}),Ka=pe.merge(jt),Ga=de.extend({method:h("tasks/result"),params:ye.extend({taskId:c()})}),Ya=pe.loose(),Xa=qt.extend({method:h("tasks/list")}),Qa=At.extend({tasks:g(jt)}),ec=de.extend({method:h("tasks/cancel"),params:ye.extend({taskId:c()})}),tc=pe.merge(jt),rc=T([Po,wo,rs,gi,Js,Is,ks,as,ls,ps,gs,_s,ys,Ds,Ls]),oc=T([zo,To,xo,vi]),nc=T([tr,ri,oi,pi,yi]),sc=T([Po,ti,li,bi]),ic=T([zo,To,Ar,Ps,ms,Fs,As,zs,di]),ac=T([tr,ts,rr,Si,qs,$s,cs,us,hs,nr,Us,Rs]),be=qa().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:sf.custom,message:"URL must be parseable",fatal:!0}),jc}).refine((e)=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Zo=F({resource:c().url(),authorization_servers:g(be).optional(),jwks_uri:c().url().optional(),scopes_supported:g(c()).optional(),bearer_methods_supported:g(c()).optional(),resource_signing_alg_values_supported:g(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:E().optional(),authorization_details_types_supported:g(c()).optional(),dpop_signing_alg_values_supported:g(c()).optional(),dpop_bound_access_tokens_required:E().optional()}),Ur=F({issuer:c(),authorization_endpoint:be,token_endpoint:be,registration_endpoint:be.optional(),scopes_supported:g(c()).optional(),response_types_supported:g(c()),response_modes_supported:g(c()).optional(),grant_types_supported:g(c()).optional(),token_endpoint_auth_methods_supported:g(c()).optional(),token_endpoint_auth_signing_alg_values_supported:g(c()).optional(),service_documentation:be.optional(),revocation_endpoint:be.optional(),revocation_endpoint_auth_methods_supported:g(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:g(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:g(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:g(c()).optional(),code_challenge_methods_supported:g(c()).optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0),dpop_signing_alg_values_supported:g(c()).optional()}),Ri=F({issuer:c(),authorization_endpoint:be,token_endpoint:be,userinfo_endpoint:be.optional(),jwks_uri:be,registration_endpoint:be.optional(),scopes_supported:g(c()).optional(),response_types_supported:g(c()),response_modes_supported:g(c()).optional(),grant_types_supported:g(c()).optional(),acr_values_supported:g(c()).optional(),subject_types_supported:g(c()),id_token_signing_alg_values_supported:g(c()),id_token_encryption_alg_values_supported:g(c()).optional(),id_token_encryption_enc_values_supported:g(c()).optional(),userinfo_signing_alg_values_supported:g(c()).optional(),userinfo_encryption_alg_values_supported:g(c()).optional(),userinfo_encryption_enc_values_supported:g(c()).optional(),request_object_signing_alg_values_supported:g(c()).optional(),request_object_encryption_alg_values_supported:g(c()).optional(),request_object_encryption_enc_values_supported:g(c()).optional(),token_endpoint_auth_methods_supported:g(c()).optional(),token_endpoint_auth_signing_alg_values_supported:g(c()).optional(),display_values_supported:g(c()).optional(),claim_types_supported:g(c()).optional(),claims_supported:g(c()).optional(),service_documentation:c().optional(),claims_locales_supported:g(c()).optional(),ui_locales_supported:g(c()).optional(),claims_parameter_supported:E().optional(),request_parameter_supported:E().optional(),request_uri_parameter_supported:E().optional(),require_request_uri_registration:E().optional(),op_policy_uri:be.optional(),op_tos_uri:be.optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0)}),Do=p({...Ri.shape,...Ur.pick({code_challenge_methods_supported:!0}).shape}),Fo=p({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:pb().optional(),scope:c().optional(),refresh_token:c().optional(),issuer:c().optional().catch(void 0)}).strip(),xi=p({issued_token_type:h("urn:ietf:params:oauth:token-type:id-jag"),access_token:c(),token_type:c().optional(),expires_in:z().optional(),scope:c().optional()}).strip(),Ho=p({error:c(),error_description:c().optional(),error_uri:c().optional()}),Kl=be.optional().or(h("").transform(()=>{return})),Pi=p({redirect_uris:g(be),token_endpoint_auth_method:c().optional(),grant_types:g(c()).optional(),response_types:g(c()).optional(),application_type:c().optional(),client_name:c().optional(),client_uri:be.optional(),logo_uri:Kl,scope:c().optional(),contacts:g(c()).optional(),tos_uri:Kl,policy_uri:c().optional(),jwks_uri:be.optional(),jwks:Ma().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Ti=p({client_id:c(),client_secret:c().optional(),client_id_issued_at:z().optional(),client_secret_expires_at:z().optional(),issuer:c().optional().catch(void 0)}).strip(),Vo=Pi.merge(Ti),cc=p({error:c(),error_description:c().optional()}).strip(),lc=p({token:c(),token_type_hint:c().optional()}).strip();var tu=Symbol.for("mcp.sdk.errorBrands");function Zr(e,t){let r=new Set,o=t;while(typeof o==="function"){let n=o.mcpBrand;if(Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof n==="string")r.add(n);o=Object.getPrototypeOf(o)}if(r.size===0)return;Object.defineProperty(e,tu,{value:r,enumerable:!1,configurable:!0})}function Be(e,t){try{if(typeof t==="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand==="string"&&Object.prototype.hasOwnProperty.call(t,tu)){let r=t[tu];if(r&&typeof r.has==="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var Ut=function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e}({}),Dr=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Be(this,t)}static isInstance(t){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,t)}constructor(t,r,o){super(r);this.code=t,this.errorUri=o,this.name="OAuthError",Zr(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};if(this.errorUri)t.error_uri=this.errorUri;return t}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}},O=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}({}),N=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e,t,r,o){super(t,o);this.code=e,this.data=r,this.name="SdkError",Zr(this,new.target)}},vt=class extends N{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,o){super(e,t,r,o);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function If(e){let t=typeof e==="string"?new URL(e):new URL(e.href);return t.hash="",t}function iu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}function Of({requestedResource:e,configuredResource:t}){let r=typeof e==="string"?new URL(e):new URL(e.href),o=typeof t==="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin)return!1;if(r.pathname.length<o.pathname.length)return!1;let n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(i)}var Nf="2026-07-28",au=[Nf];function Zt(e){return e>=Nf}function cu(e){return e.filter((t)=>!Zt(t))}function Oi(e){return e.filter((t)=>Zt(t))}function qf(e){let t=e.structuredContent;if(t===void 0)return e;if(!(typeof t!=="object"||t===null||Array.isArray(t)))return e;if(e.content?.some((r)=>r.type==="text")??!1)return e;return{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}var Af=["task","inputRequests","requestState"];function gb(e){if(e===null||typeof e!=="object"||Array.isArray(e)||e.content!==void 0||Af.some((t)=>(t in e)))return e;return{...e,content:[]}}function Sb(){let e=Bn(()=>T([c(),z(),E(),Rr(),P(c(),e),g(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=p({ttl:z().optional()}),i=p({taskId:c()}),s=F({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),a=p({_meta:s.optional()}),l=a.extend({task:n.optional()}),u=p({method:c(),params:a.loose().optional()}),d=p({_meta:s.optional()}),m=p({method:c(),params:d.loose().optional()}),f=F({_meta:s.optional()}),S=T([c(),z().int()]),b=f.strict(),y=d.extend({requestId:S.optional(),reason:c().optional()}),v=m.extend({method:h("notifications/cancelled"),params:y}),U=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),H=p({icons:g(U).optional()}),x=p({name:c(),title:c().optional()}),Z=x.extend({...x.shape,...H.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),R=$t(p({applyDefaults:E().optional()}),t),w=xr((Pe)=>{if(Pe&&typeof Pe==="object"&&!Array.isArray(Pe)&&Object.keys(Pe).length===0)return{form:{}};return Pe},$t(p({form:R.optional(),url:t.optional()}),t.optional())),D=F({list:t.optional(),cancel:t.optional(),requests:F({sampling:F({createMessage:t.optional()}).optional(),elicitation:F({create:t.optional()}).optional()}).optional()}),X=F({list:t.optional(),cancel:t.optional(),requests:F({tools:F({call:t.optional()}).optional()}).optional()}),Y=p({experimental:P(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:w.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:D.optional(),extensions:P(c(),t).optional()}),le=a.extend({protocolVersion:c(),capabilities:Y,clientInfo:Z}),Ee=u.extend({method:h("initialize"),params:le}),te=p({experimental:P(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:X.optional(),extensions:P(c(),t).optional()}),ie=f.extend({protocolVersion:c(),capabilities:te,serverInfo:Z,instructions:c().optional()}),ve=m.extend({method:h("notifications/initialized"),params:d.optional()}),ke=u.extend({method:h("ping"),params:a.optional()}),ct=p({progress:z(),total:j(z()),message:j(c())}),qe=p({...d.shape,...ct.shape,progressToken:r}),We=m.extend({method:h("notifications/progress"),params:qe}),lt=a.extend({cursor:o.optional()}),Ze=u.extend({params:lt.optional()}),$e=f.extend({nextCursor:o.optional()}),Tt=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),Et=Tt.extend({text:c()}),ut=c().refine((Pe)=>{try{return atob(Pe),!0}catch{return!1}},{message:"Invalid Base64 string"}),Re=Tt.extend({blob:ut}),Ce=K(["user","assistant"]),Ie=p({audience:g(Ce).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),et=p({...x.shape,...H.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:Ie.optional(),_meta:j(F({}))}),lr=p({...x.shape,...H.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:Ie.optional(),_meta:j(F({}))}),De=Ze.extend({method:h("resources/list")}),Fe=$e.extend({resources:g(et)}),Ae=Ze.extend({method:h("resources/templates/list")}),Ke=$e.extend({resourceTemplates:g(lr)}),Ge=a.extend({uri:c()}),dt=Ge,pt=u.extend({method:h("resources/read"),params:dt}),Ht=f.extend({contents:g(T([Et,Re]))}),ht=m.extend({method:h("notifications/resources/list_changed"),params:d.optional()}),ur=Ge,C=u.extend({method:h("resources/subscribe"),params:ur}),mt=Ge,V=u.extend({method:h("resources/unsubscribe"),params:mt}),q=d.extend({uri:c()}),G=m.extend({method:h("notifications/resources/updated"),params:q}),I=p({name:c(),description:j(c()),required:j(E())}),k=p({...x.shape,...H.shape,description:j(c()),arguments:j(g(I)),_meta:j(F({}))}),B=Ze.extend({method:h("prompts/list")}),J=$e.extend({prompts:g(k)}),ge=a.extend({name:c(),arguments:P(c(),c()).optional()}),dr=u.extend({method:h("prompts/get"),params:ge}),ft=p({type:h("text"),text:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),pr=p({type:h("image"),data:ut,mimeType:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),hr=p({type:h("audio"),data:ut,mimeType:c(),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),nn=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),Vt=p({type:h("resource"),resource:T([Et,Re]),annotations:Ie.optional(),_meta:P(c(),A()).optional()}),sn=et.extend({type:h("resource_link")}),Ye=T([ft,pr,hr,sn,Vt]),Kr=p({role:Ce,content:Ye}),Gr=f.extend({description:c().optional(),messages:g(Kr)}),mr=m.extend({method:h("notifications/prompts/list_changed"),params:d.optional()}),an=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Yr=p({taskSupport:K(["required","optional","forbidden"]).optional()}),fr=p({...x.shape,...H.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:g(c()).optional()}).catchall(A()),outputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:g(c()).optional()}).catchall(A()).optional(),annotations:an.optional(),execution:Yr.optional(),_meta:P(c(),A()).optional()}),Xr=Ze.extend({method:h("tools/list")}),Qr=$e.extend({tools:g(fr)}),eo=f.extend({content:g(Ye),structuredContent:P(c(),A()).optional(),isError:E().optional()}),xe=l.extend({name:c(),arguments:P(c(),A()).optional()}),cn=u.extend({method:h("tools/call"),params:xe}),Gi=m.extend({method:h("notifications/tools/list_changed"),params:d.optional()}),to=K(["debug","info","notice","warning","error","critical","alert","emergency"]),ln=a.extend({level:to}),un=u.extend({method:h("logging/setLevel"),params:ln}),dn=d.extend({level:to,logger:c().optional(),data:A()}),pn=m.extend({method:h("notifications/message"),params:dn}),hn=p({name:c().optional()}),mn=p({hints:g(hn).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),fn=p({mode:K(["auto","required","none"]).optional()}),Yi=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:g(Ye),structuredContent:p({}).loose().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),gn=po("type",[ft,pr,hr]),Jt=po("type",[ft,pr,hr,nn,Yi]),Sn=p({role:Ce,content:T([Jt,g(Jt)]),_meta:P(c(),A()).optional()}),_n=l.extend({messages:g(Sn),modelPreferences:mn.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:t.optional(),tools:g(fr).optional(),toolChoice:fn.optional()}),bn=u.extend({method:h("sampling/createMessage"),params:_n}),yn=f.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Ce,content:gn}),vn=f.extend({model:c(),stopReason:j(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Ce,content:T([Jt,g(Jt)])}),zn=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),wn=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),Rn=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),xn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),Pn=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),Tn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),En=T([xn,Pn]),gr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),Sr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),Xi=T([gr,Sr]),Qi=T([Tn,En,Xi]),He=T([Qi,zn,wn,Rn]),Ve=l.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),He),required:g(c()).optional()}).catchall(A())}),kn=l.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),tt=T([Ve,kn]),ea=u.extend({method:h("elicitation/create"),params:tt}),ta=d.extend({elicitationId:c()}),ra=m.extend({method:h("notifications/elicitation/complete"),params:ta}),oa=f.extend({action:K(["accept","decline","cancel"]),content:xr((Pe)=>Pe===null?void 0:Pe,P(c(),T([c(),z(),E(),g(c())])).optional())}),na=p({type:h("ref/resource"),uri:c()}),sa=p({type:h("ref/prompt"),name:c()}),ia=a.extend({ref:T([sa,na]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),$n=u.extend({method:h("completion/complete"),params:ia}),aa=f.extend({completion:F({values:g(c()).max(100),total:j(z().int()),hasMore:j(E())})}),ca=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),ro=u.extend({method:h("roots/list"),params:a.optional()}),Cn=f.extend({roots:g(ca)}),la=m.extend({method:h("notifications/roots/list_changed"),params:d.optional()}),ua=F({ttl:z().optional(),pollInterval:z().optional()}),In=K(["working","input_required","completed","failed","cancelled"]),Bt=p({taskId:c(),status:In,ttl:T([z(),Rr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:j(z()),statusMessage:j(c())}),Me=f.extend({task:Bt}),da=d.merge(Bt),_r=m.extend({method:h("notifications/tasks/status"),params:da}),oo=u.extend({method:h("tasks/get"),params:a.extend({taskId:c()})}),no=f.merge(Bt),so=u.extend({method:h("tasks/result"),params:a.extend({taskId:c()})}),Mc=f.loose(),Oe=Ze.extend({method:h("tasks/list")}),fe=$e.extend({tasks:g(Bt)}),br=u.extend({method:h("tasks/cancel"),params:a.extend({taskId:c()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:n,RelatedTaskMetadataSchema:i,RequestMetaSchema:s,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:l,RequestSchema:u,NotificationsParamsSchema:d,NotificationSchema:m,ResultSchema:f,RequestIdSchema:S,EmptyResultSchema:b,CancelledNotificationParamsSchema:y,CancelledNotificationSchema:v,IconSchema:U,IconsSchema:H,BaseMetadataSchema:x,ImplementationSchema:Z,ClientTasksCapabilitySchema:D,ServerTasksCapabilitySchema:X,ClientCapabilitiesSchema:Y,InitializeRequestParamsSchema:le,InitializeRequestSchema:Ee,ServerCapabilitiesSchema:te,InitializeResultSchema:ie,InitializedNotificationSchema:ve,PingRequestSchema:ke,ProgressSchema:ct,ProgressNotificationParamsSchema:qe,ProgressNotificationSchema:We,PaginatedRequestParamsSchema:lt,PaginatedRequestSchema:Ze,PaginatedResultSchema:$e,ResourceContentsSchema:Tt,TextResourceContentsSchema:Et,BlobResourceContentsSchema:Re,RoleSchema:Ce,AnnotationsSchema:Ie,ResourceSchema:et,ResourceTemplateSchema:lr,ListResourcesRequestSchema:De,ListResourcesResultSchema:Fe,ListResourceTemplatesRequestSchema:Ae,ListResourceTemplatesResultSchema:Ke,ResourceRequestParamsSchema:Ge,ReadResourceRequestParamsSchema:dt,ReadResourceRequestSchema:pt,ReadResourceResultSchema:Ht,ResourceListChangedNotificationSchema:ht,SubscribeRequestParamsSchema:ur,SubscribeRequestSchema:C,UnsubscribeRequestParamsSchema:mt,UnsubscribeRequestSchema:V,ResourceUpdatedNotificationParamsSchema:q,ResourceUpdatedNotificationSchema:G,PromptArgumentSchema:I,PromptSchema:k,ListPromptsRequestSchema:B,ListPromptsResultSchema:J,GetPromptRequestParamsSchema:ge,GetPromptRequestSchema:dr,TextContentSchema:ft,ImageContentSchema:pr,AudioContentSchema:hr,ToolUseContentSchema:nn,EmbeddedResourceSchema:Vt,ResourceLinkSchema:sn,ContentBlockSchema:Ye,PromptMessageSchema:Kr,GetPromptResultSchema:Gr,PromptListChangedNotificationSchema:mr,ToolAnnotationsSchema:an,ToolExecutionSchema:Yr,ToolSchema:fr,ListToolsRequestSchema:Xr,ListToolsResultSchema:Qr,CallToolResultSchema:eo,CallToolRequestParamsSchema:xe,CallToolRequestSchema:cn,ToolListChangedNotificationSchema:Gi,LoggingLevelSchema:to,SetLevelRequestParamsSchema:ln,SetLevelRequestSchema:un,LoggingMessageNotificationParamsSchema:dn,LoggingMessageNotificationSchema:pn,ModelHintSchema:hn,ModelPreferencesSchema:mn,ToolChoiceSchema:fn,ToolResultContentSchema:Yi,SamplingContentSchema:gn,SamplingMessageContentBlockSchema:Jt,SamplingMessageSchema:Sn,CreateMessageRequestParamsSchema:_n,CreateMessageRequestSchema:bn,CreateMessageResultSchema:yn,CreateMessageResultWithToolsSchema:vn,BooleanSchemaSchema:zn,StringSchemaSchema:wn,NumberSchemaSchema:Rn,UntitledSingleSelectEnumSchemaSchema:xn,TitledSingleSelectEnumSchemaSchema:Pn,LegacyTitledEnumSchemaSchema:Tn,SingleSelectEnumSchemaSchema:En,UntitledMultiSelectEnumSchemaSchema:gr,TitledMultiSelectEnumSchemaSchema:Sr,MultiSelectEnumSchemaSchema:Xi,EnumSchemaSchema:Qi,PrimitiveSchemaDefinitionSchema:He,ElicitRequestFormParamsSchema:Ve,ElicitRequestURLParamsSchema:kn,ElicitRequestParamsSchema:tt,ElicitRequestSchema:ea,ElicitationCompleteNotificationParamsSchema:ta,ElicitationCompleteNotificationSchema:ra,ElicitResultSchema:oa,ResourceTemplateReferenceSchema:na,PromptReferenceSchema:sa,CompleteRequestParamsSchema:ia,CompleteRequestSchema:$n,CompleteResultSchema:aa,RootSchema:ca,ListRootsRequestSchema:ro,ListRootsResultSchema:Cn,RootsListChangedNotificationSchema:la,TaskCreationParamsSchema:ua,TaskStatusSchema:In,TaskSchema:Bt,CreateTaskResultSchema:Me,TaskStatusNotificationParamsSchema:da,TaskStatusNotificationSchema:_r,GetTaskRequestSchema:oo,GetTaskResultSchema:no,GetTaskPayloadRequestSchema:so,GetTaskPayloadResultSchema:Mc,ListTasksRequestSchema:Oe,ListTasksResultSchema:fe,CancelTaskRequestSchema:br,CancelTaskResultSchema:f.merge(Bt),ClientRequestSchema:T([ke,Ee,$n,un,dr,B,De,Ae,pt,C,V,cn,Xr,oo,so,Oe,br]),ClientNotificationSchema:T([v,We,ve,la,_r]),ClientResultSchema:T([b,yn,vn,oa,Cn,no,fe,Me]),ServerRequestSchema:T([ke,bn,ea,ro,oo,so,Oe,br]),ServerNotificationSchema:T([v,We,pn,G,ht,Gi,mr,_r,ra]),ServerResultSchema:T([b,ie,aa,Gr,J,Fe,Ke,Ht,eo,Qr,no,fe,Me]),CallToolResultWireSchema:A().superRefine((Pe,AS)=>{if(typeof Pe!=="object"||Pe===null||Array.isArray(Pe)||Pe.content!==void 0)return;for(let rd of Af)if(rd in Pe){AS.addIssue({code:"custom",message:`content is required when the body carries '${rd}' — another result family cannot default into an empty tools/call success`});return}}).transform(gb).pipe(eo)}}var _b;function Mf(){return _b??=Sb()}function jf(e){return e.type!=="object"}var bb=new Set(["const","enum","default","examples"]),yb=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function _f(e){return e!==void 0&&!(typeof e==="string"&&e.startsWith("#"))}function vb(e){let t=typeof e.$schema==="string"?e.$schema:void 0;if(_f(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=cd(e.$schema)&&e.$recursiveAnchor!==!0,o=(n,i)=>{if(Array.isArray(n))return n.map((l)=>o(l,!1));if(n===null||typeof n!=="object")return n;if(!i&&_f(n.$id))return n;let s={},a=!1;for(let[l,u]of Object.entries(n))if(i)s[l]=o(u,!1);else if((l==="$ref"||l==="$dynamicRef")&&typeof u==="string")s[l]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u;else if(l==="$recursiveRef"&&u==="#"&&r)a=!0;else if(bb.has(l))s[l]=u;else if(yb.has(l))s[l]=o(u,!0);else s[l]=o(u,!1);if(a)if("$ref"in s)s.allOf=[...Array.isArray(s.allOf)?s.allOf:[],{$ref:"#/properties/result"}];else s.$ref="#/properties/result";return s};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}var Lf={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},Uf={"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},zb={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},uc;function lu(){if(uc)return uc;let e=Mf();return uc={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}},uc}function Zf(e){return Object.prototype.hasOwnProperty.call(Lf,e)}function Df(e){return Object.prototype.hasOwnProperty.call(Uf,e)}function wb(e){return Object.prototype.hasOwnProperty.call(zb,e)}function Rb(e){return wb(e)?lu().resultSchemas[e]:void 0}function xb(e){return Zf(e)?lu().requestSchemas[e]:void 0}function Pb(e){return Df(e)?lu().notificationSchemas[e]:void 0}var kx=Object.keys(Lf),$x=Object.keys(Uf);function ru(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function dc(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var bf={ok:!1,reason:"not-in-era"};function yf(e){return ru(e)&&ru(e.outputSchema)&&jf(e.outputSchema)}function vf(e){return e}var uu={era:"2025-11-25",hasRequestMethod:Zf,hasNotificationMethod:Df,validateRequest:(e,t)=>dc(xb(e),t),validateResult:(e,t)=>dc(Rb(e),t),validateNotification:(e,t)=>dc(Pb(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>bf,validateInputResponse:()=>bf,samplingResultVariant:(e,t)=>{let r=Mf();return dc(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)},outboundEnvelope:(e)=>{return},validateEnvelopeMeta:(e)=>[],projectCallToolResult(e,t){let r=qf(e),o=r.structuredContent;if(o===void 0)return r;let n=typeof o!=="object"||o===null||Array.isArray(o),i=t!==void 0&&jf(t);if(!n&&!i)return r;return{...r,structuredContent:{result:o}}},decodeResult(e,t){if(ru(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:vf(r)}}return{kind:"complete",result:vf(t)}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;if(!Array.isArray(r)||!r.some((o)=>yf(o)))return t;return{...t,tools:r.map((o)=>yf(o)?{...o,outputSchema:vb(o.outputSchema)}:o)}},encodeErrorCode:(e)=>e===-32002?-32602:e,checkInboundEnvelope:(e)=>{return}};function Tb(){let e=Bn(()=>T([c(),z(),E(),Rr(),P(c(),e),g(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=T([c(),z().int()]),i=K(["user","assistant"]),s=K(["debug","info","notice","warning","error","critical","alert","emergency"]),a=c().refine((fe)=>{try{return atob(fe),!0}catch{return!1}},{message:"Invalid Base64 string"}),l=p({ttl:z().optional()}),u=p({taskId:c()}),d=F({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),m=p({_meta:d.optional()}),f=m.extend({task:l.optional()}),S=p({_meta:d.optional()}),b=p({method:c(),params:S.loose().optional()}),y=p({src:c(),mimeType:c().optional(),sizes:g(c()).optional(),theme:K(["light","dark"]).optional()}),v=p({icons:g(y).optional()}),U=p({name:c(),title:c().optional()}),H=U.extend({...U.shape,...v.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),x=$t(p({applyDefaults:E().optional()}),t),Z=xr((fe)=>{if(fe&&typeof fe==="object"&&!Array.isArray(fe)&&Object.keys(fe).length===0)return{form:{}};return fe},$t(p({form:x.optional(),url:t.optional()}),t.optional())),R=F({list:t.optional(),cancel:t.optional(),requests:F({sampling:F({createMessage:t.optional()}).optional(),elicitation:F({create:t.optional()}).optional()}).optional()}),w=F({list:t.optional(),cancel:t.optional(),requests:F({tools:F({call:t.optional()}).optional()}).optional()}),D=p({experimental:P(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:Z.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:R.optional(),extensions:P(c(),t).optional()}),X=p({experimental:P(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:w.optional(),extensions:P(c(),t).optional()}),Y=p({progress:z(),total:j(z()),message:j(c())}),le=p({...S.shape,...Y.shape,progressToken:r}),Ee=b.extend({method:h("notifications/progress"),params:le}),te=S.extend({level:s,logger:c().optional(),data:A()}),ie=b.extend({method:h("notifications/message"),params:te}),ve=p({uri:c(),mimeType:j(c()),_meta:P(c(),A()).optional()}),ke=ve.extend({text:c()}),ct=ve.extend({blob:a}),qe=p({audience:g(i).optional(),priority:z().min(0).max(1).optional(),lastModified:uo({offset:!0}).optional()}),We=p({...U.shape,...v.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(z()),annotations:qe.optional(),_meta:j(F({}))}),lt=p({...U.shape,...v.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:qe.optional(),_meta:j(F({}))}),Ze=b.extend({method:h("notifications/resources/list_changed"),params:S.optional()}),$e=S.extend({uri:c()}),Tt=b.extend({method:h("notifications/resources/updated"),params:$e}),Et=p({name:c(),description:j(c()),required:j(E())}),ut=p({...U.shape,...v.shape,description:j(c()),arguments:j(g(Et)),_meta:j(F({}))}),Re=b.extend({method:h("notifications/prompts/list_changed"),params:S.optional()}),Ce=p({type:h("text"),text:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),Ie=p({type:h("image"),data:a,mimeType:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),et=p({type:h("audio"),data:a,mimeType:c(),annotations:qe.optional(),_meta:P(c(),A()).optional()}),lr=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),A()),_meta:P(c(),A()).optional()}),De=p({type:h("resource"),resource:T([ke,ct]),annotations:qe.optional(),_meta:P(c(),A()).optional()}),Fe=We.extend({type:h("resource_link")}),Ae=T([Ce,Ie,et,Fe,De]),Ke=p({role:i,content:Ae}),Ge=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),dt=b.extend({method:h("notifications/tools/list_changed"),params:S.optional()}),pt=p({name:c().optional()}),Ht=p({hints:g(pt).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),ht=p({mode:K(["auto","required","none"]).optional()}),ur=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),C=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),mt=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),V=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),default:c().optional()}),q=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:g(p({const:c(),title:c()})),default:c().optional()}),G=p({type:h("string"),title:c().optional(),description:c().optional(),enum:g(c()),enumNames:g(c()).optional(),default:c().optional()}),I=T([V,q]),k=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:g(c())}),default:g(c()).optional()}),B=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:g(p({const:c(),title:c()}))}),default:g(c()).optional()}),J=T([k,B]),ge=T([G,I,J]),dr=T([ge,ur,C,mt]),ft=f.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),dr),required:g(c()).optional()}).catchall(A())}),pr=p({type:h("ref/resource"),uri:c()}),hr=p({type:h("ref/prompt"),name:c()}),nn=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),A()).optional()}),Vt=D.shape,sn=p({experimental:Vt.experimental,sampling:Vt.sampling,elicitation:Vt.elicitation,roots:Vt.roots,extensions:Vt.extensions}),Ye=X.shape,Kr=p({experimental:Ye.experimental,logging:Ye.logging,completions:Ye.completions,prompts:Ye.prompts,resources:Ye.resources,tools:Ye.tools,extensions:Ye.extensions}),Gr=F({progressToken:r.optional(),[It]:c(),[mo]:H.optional(),[Pr]:sn,[fo]:s.optional()}),mr=p({...U.shape,...v.shape,description:c().optional(),inputSchema:F({$schema:c().optional(),type:h("object")}),outputSchema:F({$schema:c().optional()}).optional(),annotations:Ge.optional(),_meta:P(c(),A()).optional()}),an=p({type:h("tool_result"),toolUseId:c(),content:g(Ae),structuredContent:A().optional(),isError:E().optional(),_meta:P(c(),A()).optional()}),Yr=T([Ce,Ie,et,lr,an]),fr=p({role:i,content:T([Yr,g(Yr)]),_meta:P(c(),A()).optional()}),Xr=c(),Qr=F({[Ot]:H.optional().catch(void 0)}),eo=Qr.optional();function xe(fe){return F({_meta:eo,resultType:Xr.default("complete"),...fe})}let cn=xe({}),Gi=xe({nextCursor:o.optional()}),to=xe({content:g(Ae),structuredContent:A().optional(),isError:E().optional()}),ln=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:g(mr),nextCursor:o.optional()}),un=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:g(ut),nextCursor:o.optional()}),dn=xe({description:c().optional(),messages:g(Ke)}),pn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:g(We),nextCursor:o.optional()}),hn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:g(lt),nextCursor:o.optional()}),mn=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:g(T([ke,ct]))}),fn=xe({completion:p({values:g(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),Yi=xe({ttlMs:z().int().min(0),cacheScope:K(["public","private"])}),gn=xe({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:g(c()),capabilities:Kr,instructions:c().optional()}),Jt=p({messages:g(fr),modelPreferences:Ht.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:g(c()).optional(),metadata:t.optional(),tools:g(mr).optional(),toolChoice:ht.optional()}),Sn=p({method:h("sampling/createMessage"),params:Jt}),_n=p({method:h("roots/list"),params:p({_meta:P(c(),A()).optional()}).optional()}),bn=p({...fr.shape,model:c(),stopReason:c().optional()}),yn=p({roots:g(nn)}),vn=p({action:K(["accept","decline","cancel"]),content:P(c(),T([c(),z(),E(),g(c())])).optional()}),zn=p({mode:h("url"),message:c(),url:c().url()}),wn=T([ft,zn]),Rn=p({method:h("elicitation/create"),params:wn}),xn=T([Sn,_n,Rn]),Pn=T([bn,yn,vn]),Tn=P(c(),xn),En=P(c(),Pn),gr=xe({inputRequests:Tn.optional(),requestState:c().optional()}),Sr={inputResponses:En.optional(),requestState:c().optional()},Xi=p({_meta:Gr,...Sr}),Qi=F({progressToken:r.optional()});function He(fe,br){return p({method:h(fe),params:p({_meta:Gr,...br})})}function Ve(fe,br){return p({method:h(fe),params:p({_meta:Qi.optional(),...br}).optional()})}let kn={name:c(),arguments:P(c(),A()).optional(),...Sr},tt={cursor:o.optional()},ea=He("tools/call",kn),ta=He("tools/list",tt),ra=He("prompts/list",tt),oa=He("prompts/get",{name:c(),arguments:P(c(),c()).optional(),...Sr}),na=He("resources/list",tt),sa=He("resources/templates/list",tt),ia=He("resources/read",{uri:c(),...Sr}),$n={ref:T([hr,pr]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()},aa=He("completion/complete",$n),ca=He("server/discover",{}),ro=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:g(c()).optional()}),Cn={notifications:ro},la=He("subscriptions/listen",Cn),ua=Qr.extend({"io.modelcontextprotocol/subscriptionId":n}),In=F({_meta:ua,resultType:Xr.default("complete")}),Bt={"tools/call":Ve("tools/call",kn),"tools/list":Ve("tools/list",tt),"prompts/get":Ve("prompts/get",{name:c(),arguments:P(c(),c()).optional()}),"prompts/list":Ve("prompts/list",tt),"resources/list":Ve("resources/list",tt),"resources/templates/list":Ve("resources/templates/list",tt),"resources/read":Ve("resources/read",{uri:c()}),"completion/complete":Ve("completion/complete",$n),"server/discover":Ve("server/discover",{}),"subscriptions/listen":Ve("subscriptions/listen",Cn)};function Me(fe){return F({_meta:eo,...fe})}let da={"tools/call":Me({content:g(Ae),structuredContent:A().optional(),isError:E().optional()}),"tools/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:g(mr),nextCursor:o.optional()}),"prompts/get":Me({description:c().optional(),messages:g(Ke)}),"prompts/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:g(ut),nextCursor:o.optional()}),"resources/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:g(We),nextCursor:o.optional()}),"resources/templates/list":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:g(lt),nextCursor:o.optional()}),"resources/read":Me({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:g(T([ke,ct]))}),"completion/complete":Me({completion:p({values:g(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":Me({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:g(c()),capabilities:Kr,instructions:c().optional()}),"subscriptions/listen":Me({})},_r=F({"io.modelcontextprotocol/subscriptionId":n.optional()}),oo=p({method:h("notifications/subscriptions/acknowledged"),params:p({_meta:_r.optional(),notifications:ro})}),no=p({_meta:_r.optional(),requestId:n,reason:c().optional()}),so=p({method:h("notifications/cancelled"),params:no}),Mc={"notifications/cancelled":so,"notifications/progress":Ee,"notifications/message":ie,"notifications/resources/updated":Tt,"notifications/resources/list_changed":Ze,"notifications/tools/list_changed":dt,"notifications/prompts/list_changed":Re,"notifications/subscriptions/acknowledged":oo},Oe=(fe)=>p({jsonrpc:h("2.0"),id:T([c(),z().int()]),result:fe}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:n,RoleSchema:i,LoggingLevelSchema:s,TaskMetadataSchema:l,RelatedTaskMetadataSchema:u,RequestMetaSchema:d,BaseRequestParamsSchema:m,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:S,NotificationSchema:b,IconSchema:y,IconsSchema:v,BaseMetadataSchema:U,ImplementationSchema:H,ClientTasksCapabilitySchema:R,ServerTasksCapabilitySchema:w,ClientCapabilitiesSchema:D,ServerCapabilitiesSchema:X,ProgressSchema:Y,ProgressNotificationParamsSchema:le,ProgressNotificationSchema:Ee,LoggingMessageNotificationParamsSchema:te,LoggingMessageNotificationSchema:ie,ResourceContentsSchema:ve,TextResourceContentsSchema:ke,BlobResourceContentsSchema:ct,AnnotationsSchema:qe,ResourceSchema:We,ResourceTemplateSchema:lt,ResourceListChangedNotificationSchema:Ze,ResourceUpdatedNotificationParamsSchema:$e,ResourceUpdatedNotificationSchema:Tt,PromptArgumentSchema:Et,PromptSchema:ut,PromptListChangedNotificationSchema:Re,TextContentSchema:Ce,ImageContentSchema:Ie,AudioContentSchema:et,ToolUseContentSchema:lr,EmbeddedResourceSchema:De,ResourceLinkSchema:Fe,ContentBlockSchema:Ae,PromptMessageSchema:Ke,ToolAnnotationsSchema:Ge,ToolListChangedNotificationSchema:dt,ModelHintSchema:pt,ModelPreferencesSchema:Ht,ToolChoiceSchema:ht,BooleanSchemaSchema:ur,StringSchemaSchema:C,NumberSchemaSchema:mt,UntitledSingleSelectEnumSchemaSchema:V,TitledSingleSelectEnumSchemaSchema:q,LegacyTitledEnumSchemaSchema:G,SingleSelectEnumSchemaSchema:I,UntitledMultiSelectEnumSchemaSchema:k,TitledMultiSelectEnumSchemaSchema:B,MultiSelectEnumSchemaSchema:J,EnumSchemaSchema:ge,PrimitiveSchemaDefinitionSchema:dr,ElicitRequestFormParamsSchema:ft,ResourceTemplateReferenceSchema:pr,PromptReferenceSchema:hr,RootSchema:nn,ClientCapabilities2026Schema:sn,ServerCapabilities2026Schema:Kr,RequestMetaEnvelopeSchema:Gr,ToolSchema:mr,ToolResultContentSchema:an,SamplingMessageContentBlockSchema:Yr,SamplingMessageSchema:fr,ResultTypeSchema:Xr,ResultMetaSchema:Qr,ResultSchema:cn,PaginatedResultSchema:Gi,CallToolResultSchema:to,ListToolsResultSchema:ln,ListPromptsResultSchema:un,GetPromptResultSchema:dn,ListResourcesResultSchema:pn,ListResourceTemplatesResultSchema:hn,ReadResourceResultSchema:mn,CompleteResultSchema:fn,CacheableResultSchema:Yi,DiscoverResultSchema:gn,CreateMessageRequestParamsSchema:Jt,CreateMessageRequestSchema:Sn,ListRootsRequestSchema:_n,CreateMessageResultSchema:bn,ListRootsResultSchema:yn,ElicitResultSchema:vn,ElicitRequestURLParamsSchema:zn,ElicitRequestParamsSchema:wn,ElicitRequestSchema:Rn,InputRequestSchema:xn,InputResponseSchema:Pn,InputRequestsSchema:Tn,InputResponsesSchema:En,InputRequiredResultSchema:gr,InputResponseRequestParamsSchema:Xi,CallToolRequestSchema:ea,ListToolsRequestSchema:ta,ListPromptsRequestSchema:ra,GetPromptRequestSchema:oa,ListResourcesRequestSchema:na,ListResourceTemplatesRequestSchema:sa,ReadResourceRequestSchema:ia,CompleteRequestSchema:aa,DiscoverRequestSchema:ca,SubscriptionFilterSchema:ro,SubscriptionsListenRequestSchema:la,SubscriptionsListenResultMetaSchema:ua,SubscriptionsListenResultSchema:In,dispatchRequestSchemas:Bt,dispatchResultSchemas:da,NotificationMetaSchema:_r,SubscriptionsAcknowledgedNotificationSchema:oo,CancelledNotificationParamsSchema:no,CancelledNotificationSchema:so,notificationSchemas2026:Mc,JSONRPCResultResponseSchema:Oe(cn),CallToolResultResponseSchema:Oe(T([to,gr])),ListToolsResultResponseSchema:Oe(ln),ListPromptsResultResponseSchema:Oe(un),GetPromptResultResponseSchema:Oe(T([dn,gr])),ListResourcesResultResponseSchema:Oe(pn),ListResourceTemplatesResultResponseSchema:Oe(hn),ReadResourceResultResponseSchema:Oe(T([mn,gr])),CompleteResultResponseSchema:Oe(fn),DiscoverResultResponseSchema:Oe(gn),SubscriptionsListenResultResponseSchema:Oe(In)}}var Eb;function sr(){return Eb??=Tb()}var kb=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function $b(e){return kb.includes(e)}var du=Symbol("modelcontextprotocol.resultCacheHintFallback");function Cb(e){return e[du]}function Ff(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function Hf(e){return e==="public"||e==="private"}var W=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}({}),ee=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Be(this,t)}static isInstance(t){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,t)}constructor(t,r,o){super(r);this.code=t,this.data=o,this.name="ProtocolError",Zr(this,new.target)}static fromError(t,r,o){if(t===W.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new Jf(n.elicitations,r)}if(t===W.UnsupportedProtocolVersion&&o){let n=o;if(Array.isArray(n.supported)&&typeof n.requested==="string")return new gc({supported:n.supported,requested:n.requested},r)}if(t===W.InvalidParams||t===W.ResourceNotFound){let n=o;if(typeof n?.uri==="string"&&(t===W.ResourceNotFound||Object.keys(n).length===1))return new Vf(n.uri,r)}if(t===W.MissingRequiredClientCapability&&o){let n=o;if(n.requiredCapabilities!==null&&typeof n.requiredCapabilities==="object"&&!Array.isArray(n.requiredCapabilities))return new Bf({requiredCapabilities:n.requiredCapabilities},r)}return new e(t,r,o)}},Vf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(W.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Jf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(W.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},gc=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(W.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Bf=class extends ee{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(W.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},Ib=0,Ob="private",Nb=["tools/call","prompts/get","resources/read"];function qb(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete")return t;if(Nb.includes(e))return t;throw new ee(W.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function Ab(e,t){let r=Cb(t);if(t.resultType!=="complete"||!$b(e))return r===void 0?t:Zb(t);let o=t,n=Ff(o.ttlMs)?o.ttlMs:Lb(r),i=Hf(o.cacheScope)?o.cacheScope:Ub(r),s={...o,ttlMs:n,cacheScope:i};return delete s[du],s}function Mb(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function jb(e,t){if(t===void 0)return e;let r=e._meta;if(r===void 0)return{...e,_meta:{[Ot]:t}};if(!Mb(r))return e;if(r[Ot]!==void 0)return e;return{...e,_meta:{...r,[Ot]:t}}}function Lb(e){return e!==void 0&&Ff(e.ttlMs)?e.ttlMs:Ib}function Ub(e){return e!==void 0&&Hf(e.cacheScope)?e.cacheScope:Ob}function Zb(e){let t={...e};return delete t[du],t}var Db=["elicitation/create","sampling/createMessage","roots/list"],pc;function Wf(){if(pc)return pc;let e=sr();return pc={request:{"elicitation/create":p({method:h("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":p({method:h("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":p({method:h("roots/list"),params:F({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},pc}function Kf(e){return Db.includes(e)}function Yl(e){return Kf(e)?Wf().request[e]:void 0}function Fb(e){return Kf(e)?Wf().response[e]:void 0}var pu={"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},Gf={"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 Yf(e){return Object.prototype.hasOwnProperty.call(pu,e)}function Xf(e){return Object.prototype.hasOwnProperty.call(Gf,e)}function Hb(e){return Object.prototype.hasOwnProperty.call(pu,e)}function Vb(e){return Yf(e)?sr().dispatchRequestSchemas[e]:void 0}function Jb(e){return Hb(e)?sr().dispatchResultSchemas[e]:void 0}function Bb(e){return Xf(e)?sr().notificationSchemas2026[e]:void 0}var Cx=Object.keys(pu),Ix=Object.keys(Gf);function $i(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Ei(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var Wb={ok:!1,reason:"not-in-era"},Kb=[It,Pr];function Gb(e,t){let r=t,o=!1,n=()=>{if(!o)r={...r},o=!0;return r},i=t.tools;if(e==="tools/list"&&Array.isArray(i)&&i.some((a)=>$i(a)&&("execution"in a)))n().tools=i.map((a)=>{if(!$i(a)||!("execution"in a))return a;let l={...a};return delete l.execution,l});let s=t.capabilities;if($i(s)&&"tasks"in s){let a={...s};delete a.tasks,n().capabilities=a}return r}var hu={era:"2026-07-28",hasRequestMethod:Yf,hasNotificationMethod:Xf,hasInputRequestMethod:(e)=>Yl(e)!==void 0,validateRequest:(e,t)=>Ei(Vb(e),t),validateResult:(e,t)=>Ei(Jb(e),t),validateNotification:(e,t)=>Ei(Bb(e),t),validateInputRequest:(e,t)=>Ei(Yl(e),t),validateInputResponse:(e,t)=>Ei(Fb(e),t),samplingResultVariant:()=>Wb,outboundEnvelope(e){return{[It]:e.protocolVersion,[mo]:e.clientInfo,[Pr]:e.clientCapabilities,...e.logLevel!==void 0&&{[fo]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of Kb)if(!(o in e))t.push({key:o,problem:"missing"});let r=sr().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let n=o.path.map(String),i=n.length>0?n.join("."):"_meta";if(n.length===1&&t.some((s)=>s.key===i&&s.problem==="missing"))continue;t.push({key:i,problem:o.message})}return t},projectCallToolResult:(e)=>qf(e),inputRequestSchema:Yl,decodeResult(e,t){if(!$i(t))return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new N(O.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 r!=="string")return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let s=t.inputRequests,a=$i(s)?s:{},l=t.requestState,u=t._meta===void 0?void 0:sr().ResultMetaSchema.safeParse(t._meta),d=u?.success?u.data:void 0;if(Object.keys(a).length===0&&typeof l!=="string")return{kind:"invalid",error:new N(O.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"})};return{kind:"input_required",inputRequests:a,...typeof l==="string"&&{requestState:l},...d!==void 0&&{_meta:d}}}if(r!=="complete")return{kind:"invalid",error:new N(O.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=Yb(),n=Object.hasOwn(o,e)?o[e]:void 0;if(n!==void 0){let s=n.safeParse(t);if(!s.success)return{kind:"invalid",error:new N(O.InvalidResult,`Invalid result for ${e}: ${s.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return jb(Ab(e,qb(e,Gb(e,t))),r)},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)";let t=sr().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map((r)=>r.message).join("; ")}`}},hc;function Yb(){if(hc)return hc;let e=sr();return hc={"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},hc}var Sc="2026-07-28";function Lt(e){return e!==void 0&&Zt(e)?hu:uu}function zf(e){if(e.revision!==void 0)return Lt(e.revision).era;return e.era==="modern"?hu.era:uu.era}function Xl(e){return Qf.some((t)=>t.hasRequestMethod(e))}function Ql(e){return Qf.some((t)=>t.hasNotificationMethod(e))}function wf(e){return e==="tasks/get"||e==="tasks/cancel"}var Qf=[uu,hu],Xb=sd({AnnotationsSchema:()=>bt,AudioContentSchema:()=>Or,BaseMetadataSchema:()=>St,BaseRequestParamsSchema:()=>ye,BlobResourceContentsSchema:()=>$o,BooleanSchemaSchema:()=>No,CallToolRequestParamsSchema:()=>Zs,CallToolRequestSchema:()=>Ds,CallToolResultSchema:()=>nr,CancelTaskRequestSchema:()=>ec,CancelTaskResultSchema:()=>tc,CancelledNotificationParamsSchema:()=>Yn,CancelledNotificationSchema:()=>zo,ClientCapabilitiesSchema:()=>Qn,ClientNotificationSchema:()=>oc,ClientRequestSchema:()=>rc,ClientResultSchema:()=>nc,ClientTasksCapabilitySchema:()=>Da,CompatibilityCallToolResultSchema:()=>Ha,CompleteRequestParamsSchema:()=>fi,CompleteRequestSchema:()=>gi,CompleteResultSchema:()=>Si,ContentBlockSchema:()=>yt,CreateMessageRequestParamsSchema:()=>ei,CreateMessageRequestSchema:()=>ti,CreateMessageResultSchema:()=>ri,CreateMessageResultWithToolsSchema:()=>oi,CreateTaskResultSchema:()=>Ja,CursorSchema:()=>So,DiscoverRequestSchema:()=>rs,DiscoverResultSchema:()=>rr,ElicitRequestFormParamsSchema:()=>Lr,ElicitRequestParamsSchema:()=>ci,ElicitRequestSchema:()=>li,ElicitRequestURLParamsSchema:()=>ai,ElicitResultSchema:()=>pi,ElicitationCompleteNotificationParamsSchema:()=>ui,ElicitationCompleteNotificationSchema:()=>di,EmbeddedResourceSchema:()=>Nr,EmptyResultSchema:()=>tr,EnumSchemaSchema:()=>ii,GetPromptRequestParamsSchema:()=>Cs,GetPromptRequestSchema:()=>Is,GetPromptResultSchema:()=>qs,GetTaskPayloadRequestSchema:()=>Ga,GetTaskPayloadResultSchema:()=>Ya,GetTaskRequestSchema:()=>Wa,GetTaskResultSchema:()=>Ka,IconSchema:()=>Xn,IconsSchema:()=>Nt,ImageContentSchema:()=>Ir,ImplementationSchema:()=>_t,InitializeRequestParamsSchema:()=>es,InitializeRequestSchema:()=>wo,InitializeResultSchema:()=>ts,InitializedNotificationSchema:()=>xo,JSONArraySchema:()=>Ua,JSONObjectSchema:()=>ue,JSONRPCErrorResponseSchema:()=>kr,JSONRPCMessageSchema:()=>st,JSONRPCNotificationSchema:()=>vo,JSONRPCRequestSchema:()=>yo,JSONRPCResponseSchema:()=>Za,JSONRPCResultResponseSchema:()=>Er,JSONValueSchema:()=>Ct,LegacyTitledEnumSchemaSchema:()=>Mo,ListChangedOptionsBaseSchema:()=>Hs,ListPromptsRequestSchema:()=>ks,ListPromptsResultSchema:()=>$s,ListResourceTemplatesRequestSchema:()=>ls,ListResourceTemplatesResultSchema:()=>us,ListResourcesRequestSchema:()=>as,ListResourcesResultSchema:()=>cs,ListRootsRequestSchema:()=>bi,ListRootsResultSchema:()=>yi,ListTasksRequestSchema:()=>Xa,ListTasksResultSchema:()=>Qa,ListToolsRequestSchema:()=>Ls,ListToolsResultSchema:()=>Us,LoggingLevelSchema:()=>Oo,LoggingMessageNotificationParamsSchema:()=>Bs,LoggingMessageNotificationSchema:()=>Ar,ModelHintSchema:()=>Ws,ModelPreferencesSchema:()=>Ks,MultiSelectEnumSchemaSchema:()=>si,NotificationSchema:()=>we,NotificationsParamsSchema:()=>Te,NumberSchemaSchema:()=>jr,PaginatedRequestParamsSchema:()=>ss,PaginatedRequestSchema:()=>qt,PaginatedResultSchema:()=>At,PingRequestSchema:()=>Po,PrimitiveSchemaDefinitionSchema:()=>Uo,ProgressNotificationParamsSchema:()=>ns,ProgressNotificationSchema:()=>To,ProgressSchema:()=>os,ProgressTokenSchema:()=>go,PromptArgumentSchema:()=>Ts,PromptListChangedNotificationSchema:()=>As,PromptMessageSchema:()=>Ns,PromptReferenceSchema:()=>mi,PromptSchema:()=>Es,ReadResourceRequestParamsSchema:()=>ds,ReadResourceRequestSchema:()=>ps,ReadResourceResultSchema:()=>hs,RelatedTaskMetadataSchema:()=>Gn,RequestIdSchema:()=>nt,RequestMetaSchema:()=>_o,RequestSchema:()=>de,ResourceContentsSchema:()=>Eo,ResourceLinkSchema:()=>qr,ResourceListChangedNotificationSchema:()=>ms,ResourceRequestParamsSchema:()=>$r,ResourceSchema:()=>Co,ResourceTemplateReferenceSchema:()=>hi,ResourceTemplateSchema:()=>is,ResourceUpdatedNotificationParamsSchema:()=>xs,ResourceUpdatedNotificationSchema:()=>Ps,ResultMetaObjectSchema:()=>bo,ResultSchema:()=>pe,RoleSchema:()=>Mt,RootSchema:()=>_i,RootsListChangedNotificationSchema:()=>vi,SamplingContentSchema:()=>Xs,SamplingMessageContentBlockSchema:()=>Qt,SamplingMessageSchema:()=>Qs,ServerCapabilitiesSchema:()=>Ro,ServerNotificationSchema:()=>ic,ServerRequestSchema:()=>sc,ServerResultSchema:()=>ac,ServerTasksCapabilitySchema:()=>Fa,SetLevelRequestParamsSchema:()=>Vs,SetLevelRequestSchema:()=>Js,SingleSelectEnumSchemaSchema:()=>ni,StringSchemaSchema:()=>Mr,SubscribeRequestParamsSchema:()=>fs,SubscribeRequestSchema:()=>gs,SubscriptionFilterSchema:()=>Io,SubscriptionsAcknowledgedNotificationParamsSchema:()=>vs,SubscriptionsAcknowledgedNotificationSchema:()=>zs,SubscriptionsListenRequestParamsSchema:()=>bs,SubscriptionsListenRequestSchema:()=>ys,SubscriptionsListenResultMetaSchema:()=>ws,SubscriptionsListenResultSchema:()=>Rs,TaskAugmentedRequestParamsSchema:()=>er,TaskCreationParamsSchema:()=>Va,TaskMetadataSchema:()=>Kn,TaskSchema:()=>jt,TaskStatusNotificationParamsSchema:()=>wi,TaskStatusNotificationSchema:()=>Ba,TaskStatusSchema:()=>zi,TextContentSchema:()=>Cr,TextResourceContentsSchema:()=>ko,TitledMultiSelectEnumSchemaSchema:()=>Lo,TitledSingleSelectEnumSchemaSchema:()=>Ao,ToolAnnotationsSchema:()=>Ms,ToolChoiceSchema:()=>Gs,ToolExecutionSchema:()=>js,ToolListChangedNotificationSchema:()=>Fs,ToolResultContentSchema:()=>Ys,ToolSchema:()=>or,ToolUseContentSchema:()=>Os,UnsubscribeRequestParamsSchema:()=>Ss,UnsubscribeRequestSchema:()=>_s,UntitledMultiSelectEnumSchemaSchema:()=>jo,UntitledSingleSelectEnumSchemaSchema:()=>qo});var Fr=(e)=>yo.safeParse(e).success,eg=(e)=>vo.safeParse(e).success,Bo=(e)=>Er.safeParse(e).success,Wo=(e)=>kr.safeParse(e).success;var tg=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var mu=(e)=>wo.safeParse(e).success,rg=(e)=>xo.safeParse(e).success;var Qb="Mcp-Param-",Rf="x-mcp-header",ey=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,ty=new Set(["string","integer","boolean","number"]);function fu(e){let t=[],r=new Map,o=(i,s,a)=>{if(i===null||typeof i!=="object")return;let l=i;if(Rf in l){if(!a||s.length===0)return`${mc(s)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let d=l[Rf];if(typeof d!=="string"||d.length===0)return`${mc(s)}: x-mcp-header MUST be a non-empty string`;if(!ey.test(d))return`${mc(s)}: x-mcp-header '${d}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let m=typeof l.type==="string"?l.type:void 0;if(m===void 0||!ty.has(m))return`${mc(s)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${m??"<none>"}`;let f=d.toLowerCase(),S=r.get(f);if(S!==void 0)return`x-mcp-header '${d}' is not case-insensitively unique (also declared as '${S}')`;r.set(f,d),t.push({path:s,headerName:d,type:m})}let u=l.properties;if(u!==null&&typeof u==="object")for(let[d,m]of Object.entries(u)){let f=o(m,[...s,d],a);if(f!==void 0)return f}for(let d of ry){let m=l[d];if(m===void 0)continue;let f=Array.isArray(m)?m:m!==null&&typeof m==="object"&&oy.has(d)?Object.values(m):[m];for(let S of f){let b=o(S,[...s,`<${d}>`],!1);if(b!==void 0)return b}}},n=o(e,[],!0);return n===void 0?{valid:!0,declarations:t}:{valid:!1,reason:n}}var ry=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],oy=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function mc(e){return e.length===0?"<root>":e.join(".")}var og="=?base64?",ng="?=";function ny(e){if(typeof e==="string")return e;if(typeof e==="boolean")return e?"true":"false";if(typeof e==="number"){if(!Number.isFinite(e))return;if(Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}function sy(e){if(e.length===0)return!0;if(e.startsWith(og)&&e.endsWith(ng))return!0;if(e!==e.trim())return!0;for(let t=0;t<e.length;t++){let r=e.codePointAt(t);if(r===9||r>=32&&r<=126)continue;return!0}return!1}function iy(e){let t=new TextEncoder().encode(e),r="";for(let o of t)r+=String.fromCodePoint(o);return btoa(r)}function gu(e){return sy(e)?`${og}${iy(e)}${ng}`:e}function ay(e,t){let r=e;for(let o of t){if(r===null||typeof r!=="object")return;r=r[o]}return r}function sg(e,t){let r={};for(let o of e){let n=ay(t,o.path);if(n===void 0||n===null)continue;let i=ny(n);if(i===void 0)continue;r[`${Qb}${o.headerName}`]=gu(i)}return r}var Jo=-32020,Ox=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32000],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[W.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Jo,W.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[W.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[W.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[W.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Jo],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half — including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[W.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Jo],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],Nx={[W.ParseError]:400,[W.InvalidRequest]:400,[W.MethodNotFound]:404,[W.UnsupportedProtocolVersion]:400,[W.MissingRequiredClientCapability]:400,[Jo]:400},xf={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function ig(e,t){let r=Object.hasOwn(xf,e)?xf[e]:void 0;if(r===void 0)return;let o=cy(t)?t[r]:void 0;return{field:r,value:typeof o==="string"?o:void 0}}function cy(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function _c(e,t){return Oa(e,t)}function ki(e){return new Set(e.flatMap((t)=>Object.keys(t.shape)))}function ou(e){if(e==null)return!1;let t=typeof e;if(t!=="object"&&t!=="function")return!1;if(!("~standard"in e))return!1;return typeof e["~standard"]?.validate==="function"}var Pf=!1,nu="draft-2020-12";function ly(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:nu});else if(r.vendor==="zod"){if(!("_zod"in e))throw Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");if(!Pf)Pf=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.");o=Ca(e,{target:nu,io:t})}else throw Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output"){if(o.type!==void 0)return o;return ag(o)?{type:"object",...o}:o}if(o.type!==void 0&&o.type!=="object")throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}function ag(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every((o)=>o!==null&&typeof o==="object"&&(o.type==="object"||ag(o)))}return!1}function uy(e){if(!e.path?.length)return e.message;return`${e.path.map((t)=>String(typeof t==="object"?t.key:t)).join(".")}: ${e.message}`}async function eu(e,t){let r=await e["~standard"].validate(t);if(r.issues&&r.issues.length>0)return{success:!1,error:r.issues.map((o)=>uy(o)).join(", ")};return{success:!0,data:r.value}}function dy(e){let t=Ca(e,{target:nu,io:"input"});return typeof t.pattern==="string"?t.pattern:void 0}var py=/\\\.\\d\{(\d+)\}/;function hy(e){let t=py.exec(e),r=[void 0,-1,0];if(t)r.push(Number(t[1]));return[!1,!0].flatMap((o)=>[!1,!0].flatMap((n)=>r.map((i)=>uo({local:o,offset:n,precision:i}))))}function my(e,t){let r;switch(e){case"email":r=[Km()];break;case"uri":r=[qa()];break;case"date":r=[Vl()];break;case"date-time":r=hy(t);break}return new Set(r.map((o)=>dy(o)).filter((o)=>o!==void 0))}function fy(e,t,r){if(r!=="zod")return!0;return my(e,t).has(t)}function Ii(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function gy(e){try{return ly(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new ee(W.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}var Sy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function Su(e){return Sy.has(e)||e.startsWith("x-")}var _y=new Set(["$schema",...Object.keys(Lr.shape.requestedSchema.shape)]),Tf={string:ki([Mr,qo,Ao,Mo]),number:ki([jr]),integer:ki([jr]),boolean:ki([No]),array:ki([jo,Lo])},by=new Set(Mr.shape.format.unwrap().options);function yy(e,t,r,o){if(!Ii(e))return e;let n=typeof e.type==="string"&&Object.hasOwn(Tf,e.type)?Tf[e.type]:void 0;if(n===void 0)return e;let i={};for(let[s,a]of Object.entries(e))if(n.has(s)||Su(s))i[s]=a;else if(s==="pattern"&&e.type==="string"&&typeof e.format==="string"){if(!by.has(e.format))i[s]=a;else if(typeof a!=="string"||!fy(e.format,a,r))o.push(`${t}.${s}`)}else o.push(`${t}.${s}`);return i}function vy(e,t){let r={},o=[];for(let[n,i]of Object.entries(e))if(n==="properties"&&Ii(i))r[n]=Object.fromEntries(Object.entries(i).map(([s,a])=>[s,yy(a,`properties.${s}`,t,o)]));else if(_y.has(n))r[n]=i;else if(!Su(n))o.push(n);if(o.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}function zy(e,t){if(!Ii(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!_c(Uo,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}function su(e,t,r=""){if(Array.isArray(e)&&Array.isArray(t))return e.flatMap((o,n)=>su(o,t[n],`${r}[${n}]`));if(!Ii(e)||!Ii(t))return[];return Object.entries(e).flatMap(([o,n])=>{let i=r?`${r}.${o}`:o;if(!Object.prototype.hasOwnProperty.call(t,o))return Su(o)?[]:[i];return su(n,t[o],i)})}function wy(e){if(!ou(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=vy(gy(e.requestedSchema),t),o=_c(Lr.shape.requestedSchema,r);if(!o.success)throw new ee(W.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${zy(r,o.error.message)}`);let n=su(r,o.data);if(n.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);let i=(o.data.required??[]).filter((s)=>!Object.prototype.hasOwnProperty.call(o.data.properties,s));if(i.length>0)throw new ee(W.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function Ry(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState==="string";if(!t&&!r)throw TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}var qx=Object.assign(Ry,{elicit(e){try{return{method:"elicitation/create",params:wy(e)}}catch(t){throw t instanceof ee?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"}}});var xy=!0,Py=10,Ty=250;function cg(e){return{autoFulfill:e?.autoFulfill??xy,maxRounds:e?.maxRounds??Py}}function Ey(e,t,r){let o=t!==void 0&&Object.keys(t).length>0;if(!o&&r===void 0)return e;return{...e,...o&&{inputResponses:t},...r!==void 0&&{requestState:r}}}function ky(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function $y(e,t){return new Promise((r,o)=>{if(t?.aborted){o(t.reason instanceof N?t.reason:new N(O.RequestTimeout,String(t.reason)));return}let n=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(n),o(t?.reason instanceof N?t.reason:new N(O.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",i,{once:!0})})}function Cy(e){let t=new AbortController,r=()=>t.abort(e?.reason);if(e?.addEventListener("abort",r,{once:!0}),e?.aborted)t.abort(e.reason);return{signal:t.signal,abort:(o)=>t.abort(o),dispose:()=>e?.removeEventListener("abort",r)}}async function Iy(e){let{config:t,method:r,originalParams:o,requestOptions:n,hooks:i,signal:s}=e,a=e.flowStartedAt??Date.now(),l=e.firstPayload,u=0;while(!0){if(u+=1,u>t.maxRounds)throw new N(O.InputRequiredRoundsExceeded,ky(r,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:l.inputRequests,...l.requestState!==void 0&&{requestState:l.requestState}}});n.onprogress?.({progress:u,message:`Fulfilling input required by '${r}' (round ${u})`});let d=Object.entries(l.inputRequests??{}),m;if(d.length>0){let b=Cy(s);try{let y=await Promise.all(d.map(async([v,U])=>{try{return[v,await i.dispatchInputRequest(v,U,b.signal)]}catch(H){throw b.abort(H),H}}));m=Object.fromEntries(y)}finally{b.dispose()}}else await $y(Ty,s);let f={...n.timeout!==void 0&&{timeout:n.timeout}};if(n.maxTotalTimeout!==void 0){let b=Date.now()-a,y=n.maxTotalTimeout-b;if(y<=0)throw new N(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:b});f.maxTotalTimeout=y}let S=await i.retry(Ey(o,m,l.requestState),f);if(tg(S)){l={inputRequests:S.inputRequests??{},...S.requestState!==void 0&&{requestState:S.requestState}};continue}return S}}var Oy=["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"],Ny={IdJagTokenExchangeResponseSchema:xi,OAuthClientInformationFullSchema:Vo,OAuthClientInformationSchema:Ti,OAuthClientMetadataSchema:Pi,OAuthClientRegistrationErrorSchema:cc,OAuthErrorResponseSchema:Ho,OAuthMetadataSchema:Ur,OAuthProtectedResourceMetadataSchema:Zo,OAuthTokenRevocationRequestSchema:lc,OAuthTokensSchema:Fo,OpenIdProviderDiscoveryMetadataSchema:Do,OpenIdProviderMetadataSchema:Ri},lg={},ug={};function dg(e,t){let r=e.slice(0,-6);lg[r]=t,ug[r]=(o)=>t.safeParse(o).success}for(let e of Oy)dg(e,Xb[e]);for(let[e,t]of Object.entries(Ny))dg(e,t);var qy=Object.freeze(lg),pg=Object.freeze(ug);function Ay(e){switch(e){case"initialize":case"notifications/initialized":return Lt(void 0);case"server/discover":return Lt(Sc);default:return}}var bc=60000,My=[It,mo,Pr,fo],jy=["inputResponses","requestState"];function Ef(e,t){let r=e.params;if(!Ci(r))return{message:e,lifted:{}};let o=r._meta,n=Ci(o)?My.filter((l)=>(l in o)):[],i=t==="request"?jy.filter((l)=>(l in r)):[];if(n.length===0&&i.length===0)return{message:e,lifted:{}};let s={},a={...r};if(n.length>0&&Ci(o)){let l={},u={...o};for(let d of n)l[d]=o[d],delete u[d];if(s.envelope=l,Object.keys(u).length>0)a._meta=u;else delete a._meta}for(let l of i){if(l==="inputResponses")s.inputResponses=a[l];if(l==="requestState")s.requestState=a[l];delete a[l]}return{message:{...e,params:a},lifted:s}}function kf(e,t){let r=e.validateResult(t,void 0);if(!r.ok&&r.reason==="not-in-era")return;return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let n=e.validateResult(t,o);if(n.ok)return{value:n.value};return{issues:[{message:n.reason==="invalid"?n.message:`not-in-era: ${t}`}]}}}}}function _u(e){return()=>e}var Ly=_u(void 0),Uy,yc=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{Uy=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??ja,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){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new N(O.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){if(e.params.requestId===void 0)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new N(O.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=(n)=>{r?.(n),this._onerror(n)};let o=this._transport?.onmessage;this._transport.onmessage=(n,i)=>{if(o?.(n,i),Bo(n)||Wo(n))this._onresponse(n);else if(Fr(n))this._onrequest(n,i);else if(eg(n))this._onnotification(n,i);else this._onerror(Error(`Unknown message type: ${JSON.stringify(n)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new N(O.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(r);for(let o of t.values())o.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=Ef(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let s=zf(t.classification);if(s!==o.era){this._onerror(Error(`Era mismatch on inbound notification '${r.method}': classified as ${s} but this instance serves ${o.era}`));return}}if(Ql(r.method)&&!o.hasNotificationMethod(r.method))return;let n=this._notificationHandlers.get(r.method),i=this.fallbackNotificationHandler;if(n===void 0&&i===void 0)return;Promise.resolve().then(()=>n===void 0?i(r):n(r,o)).catch((s)=>this._onerror(Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){let{message:r,lifted:o}=Ef(e,"request"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let i=this._transport,s=(y,v,U)=>{let H={jsonrpc:"2.0",id:r.id,error:{code:y,message:v,...U!==void 0&&{data:U}}};i?.send(H).catch((x)=>this._onerror(Error(`Failed to send an error response: ${x}`)))};if(t?.classification!==void 0){let y=zf(t.classification);if(y!==n.era){this._onerror(Error(`Era mismatch on inbound request '${r.method}': classified as ${y} but this instance serves ${n.era}`));let v=t.classification.revision??y;s(W.UnsupportedProtocolVersion,`Unsupported protocol version: ${v}`,{supported:this._supportedProtocolVersions,requested:v});return}}if(Xl(r.method)&&!n.hasRequestMethod(r.method)&&!(wf(r.method)&&this._customSchemaRequestMethods.has(r.method))){s(W.MethodNotFound,"Method not found");return}let a=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(a===void 0){s(W.MethodNotFound,"Method not found");return}let l=n.checkInboundEnvelope(o);if(l!==void 0){s(W.InvalidParams,l);return}let u=(y,v)=>this._notificationViaCodec(this._resolveOutboundCodec(y.method),y,{...v,relatedRequestId:r.id}),d=(y,v,U)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(y.method),y,v,{...U,relatedRequestId:r.id}),m=new AbortController;this._requestHandlerAbortControllers.set(r.id,m);let f=o.inputResponses===void 0?void 0:Zy(o.inputResponses),S={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:o.requestState===void 0?Ly:_u(o.requestState),signal:m.signal,send:(y,v,U)=>{let H=this._resolveOutboundCodec(y.method);if(this._assertOutboundRequestInEra(H,y.method),ou(v))return d(y,v,U);let x=kf(H,y.method);if(x===void 0)throw TypeError(`'${y.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return d(y,x,v)},notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},b=this.buildContext(S,t);Promise.resolve().then(()=>a(r,b)).then(async(y)=>{if(m.signal.aborted)return;let v;try{v=n.encodeResult(r.method,y,this._outboundServerInfo())}catch(H){this._onerror(Error(`Failed to encode result for ${r.method}: ${H}`)),s(W.InternalError,"Internal error");return}let U={result:v,jsonrpc:"2.0",id:r.id};await i?.send(U)},async(y)=>{if(m.signal.aborted)return;let v=Number.isSafeInteger(y.code)?y.code:W.InternalError,U={jsonrpc:"2.0",id:r.id,error:{code:n.encodeErrorCode(v),message:y.message??"Internal error",...y.data!==void 0&&{data:y.data}}};await i?.send(U)}).catch((y)=>this._onerror(Error(`Failed to send response: ${y}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(r.id)===m)this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),n=this._progressHandlers.get(o);if(!n){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(a);return}n(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Bo(e))r(e);else r(ee.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let o=this._resolveOutboundCodec(e.method);if(ou(t)){if(!wf(e.method))this._assertOutboundRequestInEra(o,e.method);return this._requestWithSchemaViaCodec(o,e,t,r)}this._assertOutboundRequestInEra(o,e.method);let n=kf(o,e.method);if(n===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(o,e,n,t)}_negotiatedWireCodec(){return Lt(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Ay(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Xl(t)&&!e.hasRequestMethod(t))throw new N(O.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r)}_requestWithSchemaViaCodec(e,t,r,o){let{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s,headers:a}=o??{},l=Date.now(),u,d;return new Promise((m,f)=>{let S=(w)=>{f(w)};if(!this._transport){S(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(w){S(w);return}if(o?.signal?.aborted){let w=o.signal.reason;throw w instanceof N?w:new N(O.RequestTimeout,String(w))}let b=e.era===Sc&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,y=this._requestMessageId++;d=y;let v={...t,jsonrpc:"2.0",id:y};if(o?.onprogress)this._progressHandlers.set(y,o.onprogress),v.params={...t.params,_meta:{...t.params?._meta,progressToken:y}};let U=this._envelopeOutbound(v),H=!1,x=(w)=>{if(H)return;if(this._progressHandlers.delete(y),b===void 0){if(t.method!=="initialize")this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:y,reason:String(w)}}),{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s}).catch((D)=>this._onerror(Error(`Failed to send cancellation: ${D}`)))}else b.abort();f(w instanceof N?w:new N(O.RequestTimeout,String(w)))};this._responseHandlers.set(y,(w)=>{if(o?.signal?.aborted)return;if(H=!0,w instanceof Error)return f(w);let D;try{D=e.decodeResult(t.method,w.result)}catch(Y){return f(Y instanceof Error?Y:Error(String(Y)))}if(D.kind==="invalid")return f(D.error);if(D.kind==="input_required"){if(o?.allowInputRequired===!0)return m(Vy(D));let Y={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:l,retry:(le,Ee)=>this._requestWithSchemaViaCodec(e,le===void 0?{method:t.method}:{method:t.method,params:le},r,Ee)};return m(this._resolveNonCompleteResult(D,Y))}let X=D.result;eu(r,X).then((Y)=>{if(Y.success)m(Y.data);else f(new N(O.InvalidResult,`Invalid result for ${t.method}: ${Y.error}`))},f)}),u=()=>x(o?.signal?.reason),o?.signal?.addEventListener("abort",u,{once:!0});let Z=o?.timeout??bc,R=()=>x(new N(O.RequestTimeout,"Request timed out",{timeout:Z}));this._setupTimeout(y,Z,o?.maxTotalTimeout,R,o?.resetTimeoutOnProgress??!1),this._transport.send(U,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s,headers:a,requestSignal:b?.signal}).catch((w)=>{this._progressHandlers.delete(y),f(w)})}).finally(()=>{if(u)o?.signal?.removeEventListener("abort",u);if(d!==void 0)this._responseHandlers.delete(d),this._cleanupTimeout(d)})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new N(O.NotConnected,"Not connected");if(Ql(t.method)&&!e.hasNotificationMethod(t.method))throw new N(O.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);let o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;this._transport?.send(o,r).catch((n)=>this._onerror(n))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t==="function"){if(!Xl(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=(n,i)=>{let s=this._negotiatedWireCodec(),a=s.validateRequest(e,n);if(!a.ok&&a.reason==="not-in-era")a=s.validateInputRequest(e,n);if(!a.ok){if(a.reason==="not-in-era")throw new ee(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(a.message)}return Promise.resolve(t(a.value,i))}}else if(r)o=async(n,i)=>{let s=await eu(t.params,{...n.params});if(!s.success)throw new ee(W.InvalidParams,`Invalid params for ${e}: ${s.error}`);return r(s.data,i)};else throw TypeError("setRequestHandler: handler is required");if(typeof t==="function")this._customSchemaRequestMethods.delete(e);else this._customSchemaRequestMethods.add(e);this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t==="function"){if(!Ql(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,n)=>{let i=n.validateNotification(e,o);if(!i.ok){if(i.reason==="not-in-era")throw new ee(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(i.message)}return Promise.resolve(t(i.value))});return}if(!r)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async(o)=>{let n=await eu(t.params,{...o.params});if(!n.success)throw new ee(W.InvalidParams,`Invalid params for notification ${e}: ${n.error}`);await r(n.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Ci(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function hg(e,t){let r={...e};for(let o in t){let n=o,i=t[n];if(i===void 0)continue;let s=r[n];r[n]=Ci(s)&&Ci(i)?{...s,...i}:i}return r}function fc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Zy(e){let t={},r=[];if(!fc(e))return{accepted:t,droppedKeys:r};for(let[o,n]of Object.entries(e)){if(!fc(n)||"method"in n||"result"in n){r.push(o);continue}t[o]=n}return{accepted:t,droppedKeys:r}}function $f(e){throw new N(O.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function Dy(e,t,r,o,n){return{sessionId:n,mcpReq:{id:e,method:t,_meta:r?._meta,requestState:_u(void 0),signal:o,send:()=>$f("send"),notify:()=>$f("notify")}}}async function Fy(e,t,r,o,n){if(!fc(o)||typeof o.method!=="string")throw new N(O.InvalidResult,`Invalid input request '${r}': each inputRequests entry must be an embedded request object with a method`,{key:r});let i=o.method;if(!t.hasInputRequestMethod(i))throw new N(O.InvalidResult,`Invalid input request '${r}': '${i}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:r,method:i});let s=e.getRequestHandler(i);if(s===void 0)throw new N(O.CapabilityNotSupported,`Cannot fulfil input request '${r}': no handler is registered for '${i}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:r,method:i});let a=fc(o.params)?o.params:void 0;return await s({jsonrpc:"2.0",id:r,method:i,...a!==void 0&&{params:a}},e.buildContext(Dy(r,i,a,n,e.sessionId)))}function Hy(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function mg(e,t,r,o){let{codec:n,request:i,options:s,flowStartedAt:a}=o,l={inputRequests:r.inputRequests,...r.requestState!==void 0&&{requestState:r.requestState}},u={dispatchInputRequest:(d,m,f)=>Fy(e,n,d,m,f),retry:(d,m)=>o.retry(d,Hy(s,m))};return Iy({config:t,method:i.method,originalParams:i.params,firstPayload:l,flowStartedAt:a,signal:s?.signal,requestOptions:{...s?.timeout!==void 0&&{timeout:s.timeout},...s?.maxTotalTimeout!==void 0&&{maxTotalTimeout:s.maxTotalTimeout},...s?.onprogress!==void 0&&{onprogress:s.onprogress}},hooks:u})}function Vy(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}/*!
|
|
65
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){i(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1){if(e.reused==="ref"){i(s);continue}}}}function Xn(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(a)=>{let l=e.seen.get(a);if(l.ref===null)return;let u=l.def??l.schema,d={...u},m=l.ref;if(l.ref=null,m){o(m);let g=e.seen.get(m),b=g.schema;if(b.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))u.allOf=u.allOf??[],u.allOf.push(b);else Object.assign(u,b);if(Object.assign(u,d),a._zod.parent===m)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(!(v in d))delete u[v]}if(b.$ref&&g.def)for(let v in u){if(v==="$ref"||v==="allOf")continue;if(v in g.def&&JSON.stringify(u[v])===JSON.stringify(g.def[v]))delete u[v]}}let f=a._zod.parent;if(f&&f!==m){o(f);let g=e.seen.get(f);if(g?.schema.$ref){if(u.$ref=g.schema.$ref,g.def)for(let b in u){if(b==="$ref"||b==="allOf")continue;if(b in g.def&&JSON.stringify(u[b])===JSON.stringify(g.def[b]))delete u[b]}}}e.override({zodSchema:a,jsonSchema:u,path:l.path??[]})};for(let a of[...e.seen.entries()].reverse())o(a[0]);let n={};if(e.target==="draft-2020-12")n.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")n.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")n.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");n.$id=e.external.uri(a)}Object.assign(n,r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&n.id===i)delete n.id;let s=e.external?.defs??{};for(let a of e.seen.entries()){let l=a[1];if(l.def&&l.defId){if(l.def.id===l.defId)delete l.def.id;s[l.defId]=l.def}}if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")n.$defs=s;else n.definitions=s;try{let a=JSON.parse(JSON.stringify(n));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Kn(t,"input",e.processors),output:Kn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function qe(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let o=e._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return qe(o.element,r);if(o.type==="set")return qe(o.valueType,r);if(o.type==="lazy")return qe(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return qe(o.innerType,r);if(o.type==="intersection")return qe(o.left,r)||qe(o.right,r);if(o.type==="record"||o.type==="map")return qe(o.keyType,r)||qe(o.valueType,r);if(o.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return qe(o.in,r)||qe(o.out,r)}if(o.type==="object"){for(let n in o.shape)if(qe(o.shape[n],r))return!0;return!1}if(o.type==="union"){for(let n of o.options)if(qe(n,r))return!0;return!1}if(o.type==="tuple"){for(let n of o.items)if(qe(n,r))return!0;if(o.rest&&qe(o.rest,r))return!0;return!1}return!1}var zm=(e,t={})=>(r)=>{let o=Gn({...r,processors:t});return se(e,o),Yn(o,e),Xn(o,e)},Kn=(e,t,r={})=>(o)=>{let{libraryOptions:n,target:i}=o??{},s=Gn({...n??{},target:i,io:t,processors:r});return se(e,s),Yn(s,e),Xn(s,e)};var w_={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},$l=(e,t,r,o)=>{let n=r;n.type="string";let{minimum:i,maximum:s,format:a,patterns:l,contentEncoding:u}=e._zod.bag;if(typeof i==="number")n.minLength=i;if(typeof s==="number")n.maxLength=s;if(a){if(n.format=w_[a]??a,n.format==="")delete n.format;if(a==="time")delete n.format}if(u)n.contentEncoding=u;if(l&&l.size>0){let d=[...l];if(d.length===1)n.pattern=d[0].source;else if(d.length>1)n.allOf=[...d.map((m)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))]}},Cl=(e,t,r,o)=>{let n=r,{minimum:i,maximum:s,format:a,multipleOf:l,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;if(typeof a==="string"&&a.includes("int"))n.type="integer";else n.type="number";let m=typeof d==="number"&&d>=(i??Number.NEGATIVE_INFINITY),f=typeof u==="number"&&u<=(s??Number.POSITIVE_INFINITY),g=t.target==="draft-04"||t.target==="openapi-3.0";if(m)if(g)n.minimum=d,n.exclusiveMinimum=!0;else n.exclusiveMinimum=d;else if(typeof i==="number")n.minimum=i;if(f)if(g)n.maximum=u,n.exclusiveMaximum=!0;else n.exclusiveMaximum=u;else if(typeof s==="number")n.maximum=s;if(typeof l==="number")n.multipleOf=l},Il=(e,t,r,o)=>{r.type="boolean"},Rm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},xm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},Ol=(e,t,r,o)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},Nl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},Pm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},Al=(e,t,r,o)=>{r.not={}},ql=(e,t,r,o)=>{},Ml=(e,t,r,o)=>{},Tm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},jl=(e,t,r,o)=>{let n=e._zod.def,i=wa(n.entries);if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";r.enum=i},Ll=(e,t,r,o)=>{let n=e._zod.def,i=[];for(let s of n.values)if(s===void 0){if(t.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s==="bigint")if(t.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else i.push(Number(s));else i.push(s);if(i.length===0);else if(i.length===1){let s=i[0];if(r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[s];else r.const=s}else{if(i.every((s)=>typeof s==="number"))r.type="number";if(i.every((s)=>typeof s==="string"))r.type="string";if(i.every((s)=>typeof s==="boolean"))r.type="boolean";if(i.every((s)=>s===null))r.type="null";r.enum=i}},Em=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},km=(e,t,r,o)=>{let n=r,i=e._zod.pattern;if(!i)throw Error("Pattern not found in template literal");n.type="string",n.pattern=i.source},$m=(e,t,r,o)=>{let n=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:l}=e._zod.bag;if(s!==void 0)i.minLength=s;if(a!==void 0)i.maxLength=a;if(l)if(l.length===1)i.contentMediaType=l[0],Object.assign(n,i);else Object.assign(n,i),n.anyOf=l.map((u)=>({contentMediaType:u}));else Object.assign(n,i)},Cm=(e,t,r,o)=>{r.type="boolean"},Ul=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},Im=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},Zl=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},Om=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},Nm=(e,t,r,o)=>{if(t.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},Dl=(e,t,r,o)=>{let n=r,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;if(typeof s==="number")n.minItems=s;if(typeof a==="number")n.maxItems=a;n.type="array",n.items=se(i.element,t,{...o,path:[...o.path,"items"]})},Fl=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object",n.properties={};let s=i.shape;for(let u in s)n.properties[u]=se(s[u],t,{...o,path:[...o.path,"properties",u]});let a=new Set(Object.keys(s)),l=new Set([...a].filter((u)=>{let d=i.shape[u]._zod;if(t.io==="input")return d.optin===void 0;else return d.optout===void 0}));if(l.size>0)n.required=Array.from(l);if(i.catchall?._zod.def.type==="never")n.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")n.additionalProperties=!1}else if(i.catchall)n.additionalProperties=se(i.catchall,t,{...o,path:[...o.path,"additionalProperties"]})},Hl=(e,t,r,o)=>{let n=e._zod.def,i=n.inclusive===!1,s=n.options.map((a,l)=>se(a,t,{...o,path:[...o.path,i?"oneOf":"anyOf",l]}));if(i)r.oneOf=s;else r.anyOf=s},Vl=(e,t,r,o)=>{let n=e._zod.def,i=se(n.left,t,{...o,path:[...o.path,"allOf",0]}),s=se(n.right,t,{...o,path:[...o.path,"allOf",1]}),a=(u)=>("allOf"in u)&&Object.keys(u).length===1,l=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=l},Am=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="array";let s=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",l=i.items.map((f,g)=>se(f,t,{...o,path:[...o.path,s,g]})),u=i.rest?se(i.rest,t,{...o,path:[...o.path,a,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;if(t.target==="draft-2020-12"){if(n.prefixItems=l,u)n.items=u}else if(t.target==="openapi-3.0"){if(n.items={anyOf:l},u)n.items.anyOf.push(u);if(n.minItems=l.length,!u)n.maxItems=l.length}else if(n.items=l,u)n.additionalItems=u;let{minimum:d,maximum:m}=e._zod.bag;if(typeof d==="number")n.minItems=d;if(typeof m==="number")n.maxItems=m},Jl=(e,t,r,o)=>{let n=r,i=e._zod.def;n.type="object";let s=i.keyType,l=s._zod.bag?.patterns;if(i.mode==="loose"&&l&&l.size>0){let d=se(i.valueType,t,{...o,path:[...o.path,"patternProperties","*"]});n.patternProperties={};for(let m of l)n.patternProperties[m.source]=d}else{if(t.target==="draft-07"||t.target==="draft-2020-12")n.propertyNames=se(i.keyType,t,{...o,path:[...o.path,"propertyNames"]});n.additionalProperties=se(i.valueType,t,{...o,path:[...o.path,"additionalProperties"]})}let u=s._zod.values;if(u){let d=[...u].filter((m)=>typeof m==="string"||typeof m==="number");if(d.length>0)n.required=d}},Bl=(e,t,r,o)=>{let n=e._zod.def,i=se(n.innerType,t,o),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=n.innerType,r.nullable=!0;else r.anyOf=[i,{type:"null"}]},Wl=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},Kl=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))},Gl=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);if(i.ref=n.innerType,t.io==="input")r._prefault=JSON.parse(JSON.stringify(n.defaultValue))},Yl=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType;let s;try{s=n.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},Xl=(e,t,r,o)=>{let n=e._zod.def,i=n.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?n.out:n.in:n.out;se(s,t,o);let a=t.seen.get(e);a.ref=s},Ql=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType,r.readOnly=!0},qm=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},ja=(e,t,r,o)=>{let n=e._zod.def;se(n.innerType,t,o);let i=t.seen.get(e);i.ref=n.innerType},eu=(e,t,r,o)=>{let n=e._zod.innerType;se(n,t,o);let i=t.seen.get(e);i.ref=n},wm={string:$l,number:Cl,boolean:Il,bigint:Rm,symbol:xm,null:Ol,undefined:Nl,void:Pm,never:Al,any:ql,unknown:Ml,date:Tm,enum:jl,literal:Ll,nan:Em,template_literal:km,file:$m,success:Cm,custom:Ul,function:Im,transform:Zl,map:Om,set:Nm,array:Dl,object:Fl,union:Hl,intersection:Vl,tuple:Am,record:Jl,nullable:Bl,nonoptional:Wl,default:Kl,prefault:Gl,catch:Yl,pipe:Xl,readonly:Ql,promise:qm,optional:ja,lazy:eu};function La(e,t){if("_idmap"in e){let o=e,n=Gn({...t,processors:wm}),i={};for(let l of o._idmap.entries()){let[u,d]=l;se(d,n)}let s={},a={registry:o,uri:t?.uri,defs:i};n.external=a;for(let l of o._idmap.entries()){let[u,d]=l;Yn(n,d),s[u]=Xn(n,d)}if(Object.keys(i).length>0){let l=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[l]:i}}return{schemas:s}}let r=Gn({...t,processors:wm});return se(e,r),Yn(r,e),Xn(r,e)}var C_=_("ZodISODateTime",(e,t)=>{Yp.init(e,t),le.init(e,t)});function _o(e){return im(C_,e)}var I_=_("ZodISODate",(e,t)=>{Xp.init(e,t),le.init(e,t)});function tu(e){return am(I_,e)}var O_=_("ZodISOTime",(e,t)=>{Qp.init(e,t),le.init(e,t)});function Mm(e){return cm(O_,e)}var N_=_("ZodISODuration",(e,t)=>{eh.init(e,t),le.init(e,t)});function jm(e){return lm(N_,e)}var A_=(e,t)=>{Ta.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:(r)=>ol(e,r)},flatten:{value:(r)=>rl(e,r)},addIssue:{value:(r)=>{e.issues.push(r),e.message=JSON.stringify(e.issues,Zn,2)}},addIssues:{value:(r)=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,Zn,2)}},isEmpty:{get(){return e.issues.length===0}}})};var We=_("ZodError",A_,{Parent:Error});var Um=Ea(We),Zm=ka(We),Za=Fn(We),Dm=Hn(We),Fm=Nd(We),Hm=Ad(We),Vm=qd(We),Jm=Md(We),Bm=jd(We),Wm=Ld(We),Km=Ud(We),Gm=Zd(We);var Ym=new WeakMap;function Qn(e,t,r){let o=Object.getPrototypeOf(e),n=Ym.get(o);if(!n)n=new Set,Ym.set(o,n);if(n.has(t))return;n.add(t);for(let i in r){let s=r[i];Object.defineProperty(o,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}var ie=_("ZodType",(e,t)=>(ne.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Kn(e,"input"),output:Kn(e,"output")}}),e.toJSONSchema=zm(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(r,o)=>Um(e,r,o,{callee:e.parse}),e.safeParse=(r,o)=>Za(e,r,o),e.parseAsync=async(r,o)=>Zm(e,r,o,{callee:e.parseAsync}),e.safeParseAsync=async(r,o)=>Dm(e,r,o),e.spa=e.safeParseAsync,e.encode=(r,o)=>Fm(e,r,o),e.decode=(r,o)=>Hm(e,r,o),e.encodeAsync=async(r,o)=>Vm(e,r,o),e.decodeAsync=async(r,o)=>Jm(e,r,o),e.safeEncode=(r,o)=>Bm(e,r,o),e.safeDecode=(r,o)=>Wm(e,r,o),e.safeEncodeAsync=async(r,o)=>Km(e,r,o),e.safeDecodeAsync=async(r,o)=>Gm(e,r,o),Qn(e,"ZodType",{check(...r){let o=this.def;return this.clone(tr(o,{checks:[...o.checks??[],...r.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,o){return at(this,r,o)},brand(){return this},register(r,o){return r.add(this,o),this},refine(r,o){return this.check(Rb(r,o))},superRefine(r,o){return this.check(xb(r,o))},overwrite(r){return this.check(sr(r))},optional(){return U(this)},exactOptional(){return ub(this)},nullable(){return tf(this)},nullish(){return U(tf(this))},nonoptional(r){return gb(this,r)},array(){return S(this)},or(r){return T([this,r])},and(r){return At(this,r)},transform(r){return rf(this,pf(r))},default(r){return hb(this,r)},prefault(r){return fb(this,r)},catch(r){return _b(this,r)},pipe(r){return rf(this,r)},readonly(){return vb(this)},describe(r){let o=this.clone();return nr.add(o,{description:r}),o},meta(...r){if(r.length===0)return nr.get(this);let o=this.clone();return nr.add(o,r[0]),o},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(e,"description",{get(){return nr.get(e)?.description},configurable:!0}),e)),of=_("_ZodString",(e,t)=>{Ia.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,i)=>$l(e,o,n,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,Qn(e,"_ZodString",{regex(...o){return this.check(bl(...o))},includes(...o){return this.check(zl(...o))},startsWith(...o){return this.check(wl(...o))},endsWith(...o){return this.check(Rl(...o))},min(...o){return this.check(go(...o))},max(...o){return this.check(qa(...o))},length(...o){return this.check(Ma(...o))},nonempty(...o){return this.check(go(1,...o))},lowercase(o){return this.check(yl(o))},uppercase(o){return this.check(vl(o))},trim(){return this.check(Pl())},normalize(...o){return this.check(xl(...o))},toLowerCase(){return this.check(Tl())},toUpperCase(){return this.check(El())},slugify(){return this.check(kl())}})}),nf=_("ZodString",(e,t)=>{Ia.init(e,t),of.init(e,t),e.email=(r)=>e.check(gl(sf,r)),e.url=(r)=>e.check(_l(cf,r)),e.jwt=(r)=>e.check(sm(Y_,r)),e.emoji=(r)=>e.check(Vh(M_,r)),e.guid=(r)=>e.check(Sl(Xm,r)),e.uuid=(r)=>e.check(Zh(Da,r)),e.uuidv4=(r)=>e.check(Dh(Da,r)),e.uuidv6=(r)=>e.check(Fh(Da,r)),e.uuidv7=(r)=>e.check(Hh(Da,r)),e.nanoid=(r)=>e.check(Jh(j_,r)),e.guid=(r)=>e.check(Sl(Xm,r)),e.cuid=(r)=>e.check(Bh(L_,r)),e.cuid2=(r)=>e.check(Wh(U_,r)),e.ulid=(r)=>e.check(Kh(Z_,r)),e.base64=(r)=>e.check(rm(W_,r)),e.base64url=(r)=>e.check(om(K_,r)),e.xid=(r)=>e.check(Gh(D_,r)),e.ksuid=(r)=>e.check(Yh(F_,r)),e.ipv4=(r)=>e.check(Xh(H_,r)),e.ipv6=(r)=>e.check(Qh(V_,r)),e.cidrv4=(r)=>e.check(em(J_,r)),e.cidrv6=(r)=>e.check(tm(B_,r)),e.e164=(r)=>e.check(nm(G_,r)),e.datetime=(r)=>e.check(_o(r)),e.date=(r)=>e.check(tu(r)),e.time=(r)=>e.check(Mm(r)),e.duration=(r)=>e.check(jm(r))});function c(e){return Uh(nf,e)}var le=_("ZodStringFormat",(e,t)=>{ce.init(e,t),of.init(e,t)}),sf=_("ZodEmail",(e,t)=>{Dp.init(e,t),le.init(e,t)});function af(e){return gl(sf,e)}var Xm=_("ZodGUID",(e,t)=>{Up.init(e,t),le.init(e,t)});var Da=_("ZodUUID",(e,t)=>{Zp.init(e,t),le.init(e,t)});var cf=_("ZodURL",(e,t)=>{Fp.init(e,t),le.init(e,t)});function Fa(e){return _l(cf,e)}var M_=_("ZodEmoji",(e,t)=>{Hp.init(e,t),le.init(e,t)});var j_=_("ZodNanoID",(e,t)=>{Vp.init(e,t),le.init(e,t)});var L_=_("ZodCUID",(e,t)=>{Jp.init(e,t),le.init(e,t)});var U_=_("ZodCUID2",(e,t)=>{Bp.init(e,t),le.init(e,t)});var Z_=_("ZodULID",(e,t)=>{Wp.init(e,t),le.init(e,t)});var D_=_("ZodXID",(e,t)=>{Kp.init(e,t),le.init(e,t)});var F_=_("ZodKSUID",(e,t)=>{Gp.init(e,t),le.init(e,t)});var H_=_("ZodIPv4",(e,t)=>{th.init(e,t),le.init(e,t)});var V_=_("ZodIPv6",(e,t)=>{rh.init(e,t),le.init(e,t)});var J_=_("ZodCIDRv4",(e,t)=>{oh.init(e,t),le.init(e,t)});var B_=_("ZodCIDRv6",(e,t)=>{nh.init(e,t),le.init(e,t)});var W_=_("ZodBase64",(e,t)=>{ih.init(e,t),le.init(e,t)});var K_=_("ZodBase64URL",(e,t)=>{ah.init(e,t),le.init(e,t)});var G_=_("ZodE164",(e,t)=>{ch.init(e,t),le.init(e,t)});var Y_=_("ZodJWT",(e,t)=>{lh.init(e,t),le.init(e,t)});var Ha=_("ZodNumber",(e,t)=>{dl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,i)=>Cl(e,o,n,i),Qn(e,"ZodNumber",{gt(o,n){return this.check(Na(o,n))},gte(o,n){return this.check(Wn(o,n))},min(o,n){return this.check(Wn(o,n))},lt(o,n){return this.check(Oa(o,n))},lte(o,n){return this.check(Bn(o,n))},max(o,n){return this.check(Bn(o,n))},int(o){return this.check(Qm(o))},safe(o){return this.check(Qm(o))},positive(o){return this.check(Na(0,o))},nonnegative(o){return this.check(Wn(0,o))},negative(o){return this.check(Oa(0,o))},nonpositive(o){return this.check(Bn(0,o))},multipleOf(o,n){return this.check(Aa(o,n))},step(o,n){return this.check(Aa(o,n))},finite(){return this}});let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??0.5),e.isFinite=!0,e.format=r.format??null});function z(e){return um(Ha,e)}var X_=_("ZodNumberFormat",(e,t)=>{uh.init(e,t),Ha.init(e,t)});function Qm(e){return pm(X_,e)}var lf=_("ZodBoolean",(e,t)=>{dh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Il(e,r,o,n)});function E(e){return hm(lf,e)}var Q_=_("ZodUndefined",(e,t)=>{ph.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Nl(e,r,o,n)});function ou(e){return mm(Q_,e)}var eb=_("ZodNull",(e,t)=>{hh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ol(e,r,o,n)});function Cr(e){return fm(eb,e)}var tb=_("ZodAny",(e,t)=>{mh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ql(e,r,o,n)});function Va(){return gm(tb)}var rb=_("ZodUnknown",(e,t)=>{fh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ml(e,r,o,n)});function M(){return Sm(rb)}var ob=_("ZodNever",(e,t)=>{gh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Al(e,r,o,n)});function nu(e){return _m(ob,e)}var nb=_("ZodArray",(e,t)=>{Sh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Dl(e,r,o,n),e.element=t.element,Qn(e,"ZodArray",{min(r,o){return this.check(go(r,o))},nonempty(r){return this.check(go(1,r))},max(r,o){return this.check(qa(r,o))},length(r,o){return this.check(Ma(r,o))},unwrap(){return this.element}})});function S(e,t){return bm(nb,e,t)}var uf=_("ZodObject",(e,t)=>{yh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Fl(e,r,o,n),ee(e,"shape",()=>t.shape),Qn(e,"ZodObject",{keyof(){return K(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:M()})},loose(){return this.clone({...this._zod.def,catchall:M()})},strict(){return this.clone({...this._zod.def,catchall:nu()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return l_(this,r)},safeExtend(r){return u_(this,r)},merge(r){return d_(this,r)},pick(r){return a_(this,r)},omit(r){return c_(this,r)},partial(...r){return p_(hf,this,r[0])},required(...r){return h_(mf,this,r[0])}})});function p(e,t){let r={type:"object",shape:e??{},...j(t)};return new uf(r)}function F(e,t){return new uf({type:"object",shape:e,catchall:M(),...j(t)})}var df=_("ZodUnion",(e,t)=>{pl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Hl(e,r,o,n),e.options=t.options});function T(e,t){return new df({type:"union",options:e,...j(t)})}var sb=_("ZodDiscriminatedUnion",(e,t)=>{df.init(e,t),vh.init(e,t)});function bo(e,t,r){return new sb({type:"union",options:t,discriminator:e,...j(r)})}var ib=_("ZodIntersection",(e,t)=>{zh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Vl(e,r,o,n)});function At(e,t){return new ib({type:"intersection",left:e,right:t})}var ef=_("ZodRecord",(e,t)=>{wh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Jl(e,r,o,n),e.keyType=t.keyType,e.valueType=t.valueType});function P(e,t,r){if(!t||!t._zod)return new ef({type:"record",keyType:c(),valueType:e,...j(t)});return new ef({type:"record",keyType:e,valueType:t,...j(r)})}var ru=_("ZodEnum",(e,t)=>{Rh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(o,n,i)=>jl(e,o,n,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(o,n)=>{let i={};for(let s of o)if(r.has(s))i[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new ru({...t,checks:[],...j(n),entries:i})},e.exclude=(o,n)=>{let i={...t.entries};for(let s of o)if(r.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new ru({...t,checks:[],...j(n),entries:i})}});function K(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((o)=>[o,o])):e;return new ru({type:"enum",entries:r,...j(t)})}var ab=_("ZodLiteral",(e,t)=>{xh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ll(e,r,o,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function h(e,t){return new ab({type:"literal",values:Array.isArray(e)?e:[e],...j(t)})}var cb=_("ZodTransform",(e,t)=>{Ph.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Zl(e,r,o,n),e._zod.parse=(r,o)=>{if(o.direction==="backward")throw new Un(e.constructor.name);r.addIssue=(i)=>{if(typeof i==="string")r.issues.push($r(i,r.value,t));else{let s=i;if(s.fatal)s.continue=!1;s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),r.issues.push($r(s))}};let n=t.transform(r.value,r);if(n instanceof Promise)return n.then((i)=>(r.value=i,r.fallback=!0,r));return r.value=n,r.fallback=!0,r}});function pf(e){return new cb({type:"transform",transform:e})}var hf=_("ZodOptional",(e,t)=>{hl.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ja(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function U(e){return new hf({type:"optional",innerType:e})}var lb=_("ZodExactOptional",(e,t)=>{Th.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>ja(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function ub(e){return new lb({type:"optional",innerType:e})}var db=_("ZodNullable",(e,t)=>{Eh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Bl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function tf(e){return new db({type:"nullable",innerType:e})}var pb=_("ZodDefault",(e,t)=>{kh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Kl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function hb(e,t){return new pb({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Qc(t)}})}var mb=_("ZodPrefault",(e,t)=>{$h.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Gl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function fb(e,t){return new mb({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Qc(t)}})}var mf=_("ZodNonOptional",(e,t)=>{Ch.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Wl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function gb(e,t){return new mf({type:"nonoptional",innerType:e,...j(t)})}var Sb=_("ZodCatch",(e,t)=>{Ih.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Yl(e,r,o,n),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _b(e,t){return new Sb({type:"catch",innerType:e,catchValue:typeof t==="function"?t:()=>t})}var ff=_("ZodPipe",(e,t)=>{ml.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Xl(e,r,o,n),e.in=t.in,e.out=t.out});function rf(e,t){return new ff({type:"pipe",in:e,out:t})}var bb=_("ZodPreprocess",(e,t)=>{ff.init(e,t),Oh.init(e,t)}),yb=_("ZodReadonly",(e,t)=>{Nh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ql(e,r,o,n),e.unwrap=()=>e._zod.def.innerType});function vb(e){return new yb({type:"readonly",innerType:e})}var zb=_("ZodLazy",(e,t)=>{Ah.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>eu(e,r,o,n),e.unwrap=()=>e._zod.def.getter()});function es(e){return new zb({type:"lazy",getter:e})}var wb=_("ZodCustom",(e,t)=>{qh.init(e,t),ie.init(e,t),e._zod.processJSONSchema=(r,o,n)=>Ul(e,r,o,n)});function Rb(e,t={}){return ym(wb,e,t)}function xb(e,t){return vm(e,t)}function Ir(e,t){return new bb({type:"pipe",in:pf(e),out:t})}var Sf={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var gf;(function(e){})(gf||(gf={}));function Pb(e){return dm(Ha,e)}Ue(fl());var yo="2025-11-25";var Ja=[yo,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ba="io.modelcontextprotocol/related-task",Mt="io.modelcontextprotocol/protocolVersion",vo="io.modelcontextprotocol/clientInfo",jt="io.modelcontextprotocol/serverInfo",Or="io.modelcontextprotocol/clientCapabilities",ts="io.modelcontextprotocol/subscriptionId",zo="io.modelcontextprotocol/logLevel";var Nr="2.0";var qt=es(()=>T([c(),z(),E(),Cr(),P(c(),qt),S(qt)])),de=P(c(),qt),Wa=S(qt),wo=T([c(),z().int()]),Ro=c(),rs=p({ttl:z().optional()}),os=p({taskId:c()}),xo=F({progressToken:wo.optional(),[Ba]:os.optional()}),ze=p({_meta:xo.optional()}),ar=ze.extend({task:rs.optional()}),pe=p({method:c(),params:ze.loose().optional()}),ke=p({_meta:xo.optional()}),xe=p({method:c(),params:ke.loose().optional()}),Po=F({get[jt](){return Rt.optional().catch(void 0)}}),he=F({_meta:Po.optional()}),lt=T([c(),z().int()]),To=p({jsonrpc:h(Nr),id:lt,...pe.shape}).strict(),Eo=p({jsonrpc:h(Nr),...xe.shape}).strict(),Ar=p({jsonrpc:h(Nr),id:lt,result:he}).strict(),qr=p({jsonrpc:h(Nr),id:lt.optional(),error:p({code:z().int(),message:c(),data:M().optional()})}).strict(),ut=T([To,Eo,Ar,qr]),Ka=T([Ar,qr]),cr=he.strict(),ns=ke.extend({requestId:lt.optional(),reason:c().optional()}),ko=xe.extend({method:h("notifications/cancelled"),params:ns}),ss=p({src:c(),mimeType:c().optional(),sizes:S(c()).optional(),theme:K(["light","dark"]).optional()}),Lt=p({icons:S(ss).optional()}),wt=p({name:c(),title:c().optional()}),Rt=wt.extend({...wt.shape,...Lt.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),Eb=At(p({applyDefaults:E().optional()}),de),kb=Ir((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)&&Object.keys(e).length===0)return{form:{}};return e},At(p({form:Eb.optional(),url:de.optional()}),de.optional())),Ga=F({list:de.optional(),cancel:de.optional(),requests:F({sampling:F({createMessage:de.optional()}).optional(),elicitation:F({create:de.optional()}).optional()}).optional()}),Ya=F({list:de.optional(),cancel:de.optional(),requests:F({tools:F({call:de.optional()}).optional()}).optional()}),is=p({experimental:P(c(),de).optional(),sampling:p({context:de.optional(),tools:de.optional()}).optional(),elicitation:kb.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:Ga.optional(),extensions:P(c(),de).optional()}),as=ze.extend({protocolVersion:c(),capabilities:is,clientInfo:Rt}),$o=pe.extend({method:h("initialize"),params:as}),Co=p({experimental:P(c(),de).optional(),logging:de.optional(),completions:de.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:Ya.optional(),extensions:P(c(),de).optional()}),cs=he.extend({protocolVersion:c(),capabilities:Co,serverInfo:Rt,instructions:c().optional()}),Io=xe.extend({method:h("notifications/initialized"),params:ke.optional()}),ls=pe.extend({method:h("server/discover"),params:ze.optional()}),lr=he.extend({supportedVersions:S(c()),capabilities:Co,instructions:c().optional()}),Oo=pe.extend({method:h("ping"),params:ze.optional()}),us=p({progress:z(),total:U(z()),message:U(c())}),ds=p({...ke.shape,...us.shape,progressToken:wo}),No=xe.extend({method:h("notifications/progress"),params:ds}),ps=ze.extend({cursor:Ro.optional()}),Ut=pe.extend({params:ps.optional()}),Zt=he.extend({nextCursor:Ro.optional()}),Ao=p({uri:c(),mimeType:U(c()),_meta:P(c(),M()).optional()}),qo=Ao.extend({text:c()}),iu=c().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mo=Ao.extend({blob:iu}),Dt=K(["user","assistant"]),xt=p({audience:S(Dt).optional(),priority:z().min(0).max(1).optional(),lastModified:_o({offset:!0}).optional()}),jo=p({...wt.shape,...Lt.shape,uri:c(),description:U(c()),mimeType:U(c()),size:U(z()),annotations:xt.optional(),_meta:U(F({}))}),hs=p({...wt.shape,...Lt.shape,uriTemplate:c(),description:U(c()),mimeType:U(c()),annotations:xt.optional(),_meta:U(F({}))}),ms=Ut.extend({method:h("resources/list")}),fs=Zt.extend({resources:S(jo)}),gs=Ut.extend({method:h("resources/templates/list")}),Ss=Zt.extend({resourceTemplates:S(hs)}),Mr=ze.extend({uri:c()}),_s=Mr,bs=pe.extend({method:h("resources/read"),params:_s}),ys=he.extend({contents:S(T([qo,Mo]))}),vs=xe.extend({method:h("notifications/resources/list_changed"),params:ke.optional()}),zs=Mr,ws=pe.extend({method:h("resources/subscribe"),params:zs}),Rs=Mr,xs=pe.extend({method:h("resources/unsubscribe"),params:Rs}),Lo=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:S(c()).optional()}),Ps=ze.extend({notifications:Lo}),Ts=pe.extend({method:h("subscriptions/listen"),params:Ps}),Es=ke.extend({notifications:Lo}),ks=xe.extend({method:h("notifications/subscriptions/acknowledged"),params:Es}),$s=Po.extend({[ts]:lt}),Cs=he.extend({_meta:$s}),Is=ke.extend({uri:c()}),Os=xe.extend({method:h("notifications/resources/updated"),params:Is}),Ns=p({name:c(),description:U(c()),required:U(E())}),As=p({...wt.shape,...Lt.shape,description:U(c()),arguments:U(S(Ns)),_meta:U(F({}))}),qs=Ut.extend({method:h("prompts/list")}),Ms=Zt.extend({prompts:S(As)}),js=ze.extend({name:c(),arguments:P(c(),c()).optional()}),Ls=pe.extend({method:h("prompts/get"),params:js}),jr=p({type:h("text"),text:c(),annotations:xt.optional(),_meta:P(c(),M()).optional()}),Lr=p({type:h("image"),data:iu,mimeType:c(),annotations:xt.optional(),_meta:P(c(),M()).optional()}),Ur=p({type:h("audio"),data:iu,mimeType:c(),annotations:xt.optional(),_meta:P(c(),M()).optional()}),Us=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),M()),_meta:P(c(),M()).optional()}),Zr=p({type:h("resource"),resource:T([qo,Mo]),annotations:xt.optional(),_meta:P(c(),M()).optional()}),Dr=jo.extend({type:h("resource_link")}),Pt=T([jr,Lr,Ur,Dr,Zr]),Zs=p({role:Dt,content:Pt}),Ds=he.extend({description:c().optional(),messages:S(Zs)}),Fs=xe.extend({method:h("notifications/prompts/list_changed"),params:ke.optional()}),Hs=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Vs=p({taskSupport:K(["required","optional","forbidden"]).optional()}),ur=p({...wt.shape,...Lt.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),qt).optional(),required:S(c()).optional()}).catchall(M()),outputSchema:F({$schema:c().optional()}).optional(),annotations:Hs.optional(),execution:Vs.optional(),_meta:P(c(),M()).optional()}),Js=Ut.extend({method:h("tools/list")}),Bs=Zt.extend({tools:S(ur)}),dr=he.extend({content:S(Pt).default([]),structuredContent:M().optional(),isError:E().optional()}),Xa=dr.or(he.extend({toolResult:M()})),Ws=ar.extend({name:c(),arguments:P(c(),M()).optional()}),Ks=pe.extend({method:h("tools/call"),params:Ws}),Gs=xe.extend({method:h("notifications/tools/list_changed"),params:ke.optional()}),Ys=p({autoRefresh:E().default(!0),debounceMs:z().int().nonnegative().default(300)}),Uo=K(["debug","info","notice","warning","error","critical","alert","emergency"]),Xs=ze.extend({level:Uo}),Qs=pe.extend({method:h("logging/setLevel"),params:Xs}),ei=ke.extend({level:Uo,logger:c().optional(),data:M()}),Fr=xe.extend({method:h("notifications/message"),params:ei}),ti=p({name:c().optional()}),ri=p({hints:S(ti).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),oi=p({mode:K(["auto","required","none"]).optional()}),ni=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:S(Pt),structuredContent:M().optional(),isError:E().optional(),_meta:P(c(),M()).optional()}),si=bo("type",[jr,Lr,Ur]),ir=bo("type",[jr,Lr,Ur,Us,ni]),ii=p({role:Dt,content:T([ir,S(ir)]),_meta:P(c(),M()).optional()}),ai=ar.extend({messages:S(ii),modelPreferences:ri.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:S(c()).optional(),metadata:de.optional(),tools:S(ur).optional(),toolChoice:oi.optional()}),ci=pe.extend({method:h("sampling/createMessage"),params:ai}),li=he.extend({model:c(),stopReason:U(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Dt,content:si}),ui=he.extend({model:c(),stopReason:U(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Dt,content:T([ir,S(ir)])}),Zo=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),Hr=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),Vr=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),Do=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),default:c().optional()}),Fo=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:S(p({const:c(),title:c()})),default:c().optional()}),Ho=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),enumNames:S(c()).optional(),default:c().optional()}),di=T([Do,Fo]),Vo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:S(c())}),default:S(c()).optional()}),Jo=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:S(p({const:c(),title:c()}))}),default:S(c()).optional()}),pi=T([Vo,Jo]),hi=T([Ho,di,pi]),Bo=T([hi,Zo,Hr,Vr]),Jr=ar.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),Bo),required:S(c()).optional()}).catchall(M())}),mi=ar.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),fi=T([Jr,mi]),gi=pe.extend({method:h("elicitation/create"),params:fi}),Si=ke.extend({elicitationId:c()}),_i=xe.extend({method:h("notifications/elicitation/complete"),params:Si}),bi=he.extend({action:K(["accept","decline","cancel"]),content:Ir((e)=>e===null?void 0:e,P(c(),T([c(),z(),E(),S(c())])).optional())}),yi=p({type:h("ref/resource"),uri:c()}),vi=p({type:h("ref/prompt"),name:c()}),zi=ze.extend({ref:T([vi,yi]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),wi=pe.extend({method:h("completion/complete"),params:zi}),Ri=he.extend({completion:F({values:S(c()).max(100),total:U(z().int()),hasMore:U(E())})}),xi=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),M()).optional()}),Pi=pe.extend({method:h("roots/list"),params:ze.optional()}),Ti=he.extend({roots:S(xi)}),Ei=xe.extend({method:h("notifications/roots/list_changed"),params:ke.optional()}),Qa=F({ttl:z().optional(),pollInterval:z().optional()}),ki=K(["working","input_required","completed","failed","cancelled"]),Ft=p({taskId:c(),status:ki,ttl:T([z(),Cr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:U(z()),statusMessage:U(c())}),ec=he.extend({task:Ft}),$i=ke.merge(Ft),tc=xe.extend({method:h("notifications/tasks/status"),params:$i}),rc=pe.extend({method:h("tasks/get"),params:ze.extend({taskId:c()})}),oc=he.merge(Ft),nc=pe.extend({method:h("tasks/result"),params:ze.extend({taskId:c()})}),sc=he.loose(),ic=Ut.extend({method:h("tasks/list")}),ac=Zt.extend({tasks:S(Ft)}),cc=pe.extend({method:h("tasks/cancel"),params:ze.extend({taskId:c()})}),lc=he.merge(Ft),uc=T([Oo,$o,ls,wi,Qs,Ls,qs,ms,gs,bs,ws,xs,Ts,Ks,Js]),dc=T([ko,No,Io,Ei]),pc=T([cr,li,ui,bi,Ti]),hc=T([Oo,ci,gi,Pi]),mc=T([ko,No,Fr,Os,vs,Gs,Fs,ks,_i]),fc=T([cr,cs,lr,Ri,Ds,Ms,fs,Ss,ys,dr,Bs,Cs]),ve=Fa().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Sf.custom,message:"URL must be parseable",fatal:!0}),Wc}).refine((e)=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Wo=F({resource:c().url(),authorization_servers:S(ve).optional(),jwks_uri:c().url().optional(),scopes_supported:S(c()).optional(),bearer_methods_supported:S(c()).optional(),resource_signing_alg_values_supported:S(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:E().optional(),authorization_details_types_supported:S(c()).optional(),dpop_signing_alg_values_supported:S(c()).optional(),dpop_bound_access_tokens_required:E().optional()}),Br=F({issuer:c(),authorization_endpoint:ve,token_endpoint:ve,registration_endpoint:ve.optional(),scopes_supported:S(c()).optional(),response_types_supported:S(c()),response_modes_supported:S(c()).optional(),grant_types_supported:S(c()).optional(),token_endpoint_auth_methods_supported:S(c()).optional(),token_endpoint_auth_signing_alg_values_supported:S(c()).optional(),service_documentation:ve.optional(),revocation_endpoint:ve.optional(),revocation_endpoint_auth_methods_supported:S(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:S(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:S(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:S(c()).optional(),code_challenge_methods_supported:S(c()).optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0),dpop_signing_alg_values_supported:S(c()).optional()}),Ci=F({issuer:c(),authorization_endpoint:ve,token_endpoint:ve,userinfo_endpoint:ve.optional(),jwks_uri:ve,registration_endpoint:ve.optional(),scopes_supported:S(c()).optional(),response_types_supported:S(c()),response_modes_supported:S(c()).optional(),grant_types_supported:S(c()).optional(),acr_values_supported:S(c()).optional(),subject_types_supported:S(c()),id_token_signing_alg_values_supported:S(c()),id_token_encryption_alg_values_supported:S(c()).optional(),id_token_encryption_enc_values_supported:S(c()).optional(),userinfo_signing_alg_values_supported:S(c()).optional(),userinfo_encryption_alg_values_supported:S(c()).optional(),userinfo_encryption_enc_values_supported:S(c()).optional(),request_object_signing_alg_values_supported:S(c()).optional(),request_object_encryption_alg_values_supported:S(c()).optional(),request_object_encryption_enc_values_supported:S(c()).optional(),token_endpoint_auth_methods_supported:S(c()).optional(),token_endpoint_auth_signing_alg_values_supported:S(c()).optional(),display_values_supported:S(c()).optional(),claim_types_supported:S(c()).optional(),claims_supported:S(c()).optional(),service_documentation:c().optional(),claims_locales_supported:S(c()).optional(),ui_locales_supported:S(c()).optional(),claims_parameter_supported:E().optional(),request_parameter_supported:E().optional(),request_uri_parameter_supported:E().optional(),require_request_uri_registration:E().optional(),op_policy_uri:ve.optional(),op_tos_uri:ve.optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0)}),Ko=p({...Ci.shape,...Br.pick({code_challenge_methods_supported:!0}).shape}),Go=p({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:Pb().optional(),scope:c().optional(),refresh_token:c().optional(),issuer:c().optional().catch(void 0)}).strip(),Ii=p({issued_token_type:h("urn:ietf:params:oauth:token-type:id-jag"),access_token:c(),token_type:c().optional(),expires_in:z().optional(),scope:c().optional()}).strip(),Yo=p({error:c(),error_description:c().optional(),error_uri:c().optional()}),su=ve.optional().or(h("").transform(()=>{return})),Oi=p({redirect_uris:S(ve),token_endpoint_auth_method:c().optional(),grant_types:S(c()).optional(),response_types:S(c()).optional(),application_type:c().optional(),client_name:c().optional(),client_uri:ve.optional(),logo_uri:su,scope:c().optional(),contacts:S(c()).optional(),tos_uri:su,policy_uri:c().optional(),jwks_uri:ve.optional(),jwks:Va().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Ni=p({client_id:c(),client_secret:c().optional(),client_id_issued_at:z().optional(),client_secret_expires_at:z().optional(),issuer:c().optional().catch(void 0)}).strip(),Xo=Oi.merge(Ni),gc=p({error:c(),error_description:c().optional()}).strip(),Sc=p({token:c(),token_type_hint:c().optional()}).strip();var du=Symbol.for("mcp.sdk.errorBrands");function Wr(e,t){let r=new Set,o=t;while(typeof o==="function"){let n=o.mcpBrand;if(Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof n==="string")r.add(n);o=Object.getPrototypeOf(o)}if(r.size===0)return;Object.defineProperty(e,du,{value:r,enumerable:!1,configurable:!0})}function Ke(e,t){try{if(typeof t==="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand==="string"&&Object.prototype.hasOwnProperty.call(t,du)){let r=t[du];if(r&&typeof r.has==="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var Vt=function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e.InvalidDpopProof="invalid_dpop_proof",e.UseDpopNonce="use_dpop_nonce",e}({}),Kr=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Ke(this,t)}static isInstance(t){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ke(this,t)}constructor(t,r,o){super(r);this.code=t,this.errorUri=o,this.name="OAuthError",Wr(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};if(this.errorUri)t.error_uri=this.errorUri;return t}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}},N=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}({}),A=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Ke(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ke(this,e)}constructor(e,t,r,o){super(t,o);this.code=e,this.data=r,this.name="SdkError",Wr(this,new.target)}},Tt=class extends A{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r,o){super(e,t,r,o);this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};function Ff(e){let t=typeof e==="string"?new URL(e):new URL(e.href);return t.hash="",t}function gu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}function Hf({requestedResource:e,configuredResource:t}){let r=typeof e==="string"?new URL(e):new URL(e.href),o=typeof t==="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin)return!1;if(r.pathname.length<o.pathname.length)return!1;let n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(i)}var Vf="2026-07-28",Su=[Vf];function Jt(e){return e>=Vf}function _u(e){return e.filter((t)=>!Jt(t))}function Ui(e){return e.filter((t)=>Jt(t))}function Jf(e){let t=e.structuredContent;if(t===void 0)return e;if(!(typeof t!=="object"||t===null||Array.isArray(t)))return e;if(e.content?.some((r)=>r.type==="text")??!1)return e;return{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}var Bf=["task","inputRequests","requestState"];function $b(e){if(e===null||typeof e!=="object"||Array.isArray(e)||e.content!==void 0||Bf.some((t)=>(t in e)))return e;return{...e,content:[]}}function Cb(){let e=es(()=>T([c(),z(),E(),Cr(),P(c(),e),S(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=p({ttl:z().optional()}),i=p({taskId:c()}),s=F({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),a=p({_meta:s.optional()}),l=a.extend({task:n.optional()}),u=p({method:c(),params:a.loose().optional()}),d=p({_meta:s.optional()}),m=p({method:c(),params:d.loose().optional()}),f=F({_meta:s.optional()}),g=T([c(),z().int()]),b=f.strict(),y=d.extend({requestId:g.optional(),reason:c().optional()}),v=m.extend({method:h("notifications/cancelled"),params:y}),L=p({src:c(),mimeType:c().optional(),sizes:S(c()).optional(),theme:K(["light","dark"]).optional()}),H=p({icons:S(L).optional()}),x=p({name:c(),title:c().optional()}),Z=x.extend({...x.shape,...H.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),R=At(p({applyDefaults:E().optional()}),t),w=Ir((Ee)=>{if(Ee&&typeof Ee==="object"&&!Array.isArray(Ee)&&Object.keys(Ee).length===0)return{form:{}};return Ee},At(p({form:R.optional(),url:t.optional()}),t.optional())),D=F({list:t.optional(),cancel:t.optional(),requests:F({sampling:F({createMessage:t.optional()}).optional(),elicitation:F({create:t.optional()}).optional()}).optional()}),X=F({list:t.optional(),cancel:t.optional(),requests:F({tools:F({call:t.optional()}).optional()}).optional()}),Y=p({experimental:P(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:w.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:D.optional(),extensions:P(c(),t).optional()}),ue=a.extend({protocolVersion:c(),capabilities:Y,clientInfo:Z}),$e=u.extend({method:h("initialize"),params:ue}),oe=p({experimental:P(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:X.optional(),extensions:P(c(),t).optional()}),ae=f.extend({protocolVersion:c(),capabilities:oe,serverInfo:Z,instructions:c().optional()}),we=m.extend({method:h("notifications/initialized"),params:d.optional()}),Ce=u.extend({method:h("ping"),params:a.optional()}),mt=p({progress:z(),total:U(z()),message:U(c())}),Me=p({...d.shape,...mt.shape,progressToken:r}),Ye=m.extend({method:h("notifications/progress"),params:Me}),ft=a.extend({cursor:o.optional()}),Fe=u.extend({params:ft.optional()}),Ie=f.extend({nextCursor:o.optional()}),It=p({uri:c(),mimeType:U(c()),_meta:P(c(),M()).optional()}),Ot=It.extend({text:c()}),gt=c().refine((Ee)=>{try{return atob(Ee),!0}catch{return!1}},{message:"Invalid Base64 string"}),Pe=It.extend({blob:gt}),Oe=K(["user","assistant"]),Ne=p({audience:S(Oe).optional(),priority:z().min(0).max(1).optional(),lastModified:_o({offset:!0}).optional()}),st=p({...x.shape,...H.shape,uri:c(),description:U(c()),mimeType:U(c()),size:U(z()),annotations:Ne.optional(),_meta:U(F({}))}),gr=p({...x.shape,...H.shape,uriTemplate:c(),description:U(c()),mimeType:U(c()),annotations:Ne.optional(),_meta:U(F({}))}),He=Fe.extend({method:h("resources/list")}),Ve=Ie.extend({resources:S(st)}),je=Fe.extend({method:h("resources/templates/list")}),Xe=Ie.extend({resourceTemplates:S(gr)}),Qe=a.extend({uri:c()}),St=Qe,_t=u.extend({method:h("resources/read"),params:St}),Yt=f.extend({contents:S(T([Ot,Pe]))}),bt=m.extend({method:h("notifications/resources/list_changed"),params:d.optional()}),Sr=Qe,I=u.extend({method:h("resources/subscribe"),params:Sr}),yt=Qe,V=u.extend({method:h("resources/unsubscribe"),params:yt}),q=d.extend({uri:c()}),G=m.extend({method:h("notifications/resources/updated"),params:q}),O=p({name:c(),description:U(c()),required:U(E())}),C=p({...x.shape,...H.shape,description:U(c()),arguments:U(S(O)),_meta:U(F({}))}),B=Fe.extend({method:h("prompts/list")}),J=Ie.extend({prompts:S(C)}),_e=a.extend({name:c(),arguments:P(c(),c()).optional()}),_r=u.extend({method:h("prompts/get"),params:_e}),vt=p({type:h("text"),text:c(),annotations:Ne.optional(),_meta:P(c(),M()).optional()}),br=p({type:h("image"),data:gt,mimeType:c(),annotations:Ne.optional(),_meta:P(c(),M()).optional()}),yr=p({type:h("audio"),data:gt,mimeType:c(),annotations:Ne.optional(),_meta:P(c(),M()).optional()}),pn=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),M()),_meta:P(c(),M()).optional()}),Xt=p({type:h("resource"),resource:T([Ot,Pe]),annotations:Ne.optional(),_meta:P(c(),M()).optional()}),hn=st.extend({type:h("resource_link")}),et=T([vt,br,yr,hn,Xt]),ro=p({role:Oe,content:et}),oo=f.extend({description:c().optional(),messages:S(ro)}),vr=m.extend({method:h("notifications/prompts/list_changed"),params:d.optional()}),mn=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),no=p({taskSupport:K(["required","optional","forbidden"]).optional()}),zr=p({...x.shape,...H.shape,description:c().optional(),inputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:S(c()).optional()}).catchall(M()),outputSchema:p({type:h("object"),properties:P(c(),e).optional(),required:S(c()).optional()}).catchall(M()).optional(),annotations:mn.optional(),execution:no.optional(),_meta:P(c(),M()).optional()}),so=Fe.extend({method:h("tools/list")}),io=Ie.extend({tools:S(zr)}),ao=f.extend({content:S(et),structuredContent:P(c(),M()).optional(),isError:E().optional()}),Te=l.extend({name:c(),arguments:P(c(),M()).optional()}),fn=u.extend({method:h("tools/call"),params:Te}),na=m.extend({method:h("notifications/tools/list_changed"),params:d.optional()}),co=K(["debug","info","notice","warning","error","critical","alert","emergency"]),gn=a.extend({level:co}),Sn=u.extend({method:h("logging/setLevel"),params:gn}),_n=d.extend({level:co,logger:c().optional(),data:M()}),bn=m.extend({method:h("notifications/message"),params:_n}),yn=p({name:c().optional()}),vn=p({hints:S(yn).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),zn=p({mode:K(["auto","required","none"]).optional()}),sa=p({type:h("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:S(et),structuredContent:p({}).loose().optional(),isError:E().optional(),_meta:P(c(),M()).optional()}),wn=bo("type",[vt,br,yr]),Qt=bo("type",[vt,br,yr,pn,sa]),Rn=p({role:Oe,content:T([Qt,S(Qt)]),_meta:P(c(),M()).optional()}),xn=l.extend({messages:S(Rn),modelPreferences:vn.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:S(c()).optional(),metadata:t.optional(),tools:S(zr).optional(),toolChoice:zn.optional()}),Pn=u.extend({method:h("sampling/createMessage"),params:xn}),Tn=f.extend({model:c(),stopReason:U(K(["endTurn","stopSequence","maxTokens"]).or(c())),role:Oe,content:wn}),En=f.extend({model:c(),stopReason:U(K(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Oe,content:T([Qt,S(Qt)])}),kn=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),$n=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),Cn=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),In=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),default:c().optional()}),On=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:S(p({const:c(),title:c()})),default:c().optional()}),Nn=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),enumNames:S(c()).optional(),default:c().optional()}),An=T([In,On]),wr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:S(c())}),default:S(c()).optional()}),Rr=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:S(p({const:c(),title:c()}))}),default:S(c()).optional()}),ia=T([wr,Rr]),aa=T([Nn,An,ia]),Je=T([aa,kn,$n,Cn]),Be=l.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),Je),required:S(c()).optional()}).catchall(M())}),qn=l.extend({mode:h("url"),message:c(),elicitationId:c(),url:c().url()}),it=T([Be,qn]),ca=u.extend({method:h("elicitation/create"),params:it}),la=d.extend({elicitationId:c()}),ua=m.extend({method:h("notifications/elicitation/complete"),params:la}),da=f.extend({action:K(["accept","decline","cancel"]),content:Ir((Ee)=>Ee===null?void 0:Ee,P(c(),T([c(),z(),E(),S(c())])).optional())}),pa=p({type:h("ref/resource"),uri:c()}),ha=p({type:h("ref/prompt"),name:c()}),ma=a.extend({ref:T([ha,pa]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()}),Mn=u.extend({method:h("completion/complete"),params:ma}),fa=f.extend({completion:F({values:S(c()).max(100),total:U(z().int()),hasMore:U(E())})}),ga=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),M()).optional()}),lo=u.extend({method:h("roots/list"),params:a.optional()}),jn=f.extend({roots:S(ga)}),Sa=m.extend({method:h("notifications/roots/list_changed"),params:d.optional()}),_a=F({ttl:z().optional(),pollInterval:z().optional()}),Ln=K(["working","input_required","completed","failed","cancelled"]),er=p({taskId:c(),status:Ln,ttl:T([z(),Cr()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:U(z()),statusMessage:U(c())}),Le=f.extend({task:er}),ba=d.merge(er),xr=m.extend({method:h("notifications/tasks/status"),params:ba}),uo=u.extend({method:h("tasks/get"),params:a.extend({taskId:c()})}),po=f.merge(er),ho=u.extend({method:h("tasks/result"),params:a.extend({taskId:c()})}),Bc=f.loose(),Ae=Fe.extend({method:h("tasks/list")}),ge=Ie.extend({tasks:S(er)}),Pr=u.extend({method:h("tasks/cancel"),params:a.extend({taskId:c()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,TaskMetadataSchema:n,RelatedTaskMetadataSchema:i,RequestMetaSchema:s,BaseRequestParamsSchema:a,TaskAugmentedRequestParamsSchema:l,RequestSchema:u,NotificationsParamsSchema:d,NotificationSchema:m,ResultSchema:f,RequestIdSchema:g,EmptyResultSchema:b,CancelledNotificationParamsSchema:y,CancelledNotificationSchema:v,IconSchema:L,IconsSchema:H,BaseMetadataSchema:x,ImplementationSchema:Z,ClientTasksCapabilitySchema:D,ServerTasksCapabilitySchema:X,ClientCapabilitiesSchema:Y,InitializeRequestParamsSchema:ue,InitializeRequestSchema:$e,ServerCapabilitiesSchema:oe,InitializeResultSchema:ae,InitializedNotificationSchema:we,PingRequestSchema:Ce,ProgressSchema:mt,ProgressNotificationParamsSchema:Me,ProgressNotificationSchema:Ye,PaginatedRequestParamsSchema:ft,PaginatedRequestSchema:Fe,PaginatedResultSchema:Ie,ResourceContentsSchema:It,TextResourceContentsSchema:Ot,BlobResourceContentsSchema:Pe,RoleSchema:Oe,AnnotationsSchema:Ne,ResourceSchema:st,ResourceTemplateSchema:gr,ListResourcesRequestSchema:He,ListResourcesResultSchema:Ve,ListResourceTemplatesRequestSchema:je,ListResourceTemplatesResultSchema:Xe,ResourceRequestParamsSchema:Qe,ReadResourceRequestParamsSchema:St,ReadResourceRequestSchema:_t,ReadResourceResultSchema:Yt,ResourceListChangedNotificationSchema:bt,SubscribeRequestParamsSchema:Sr,SubscribeRequestSchema:I,UnsubscribeRequestParamsSchema:yt,UnsubscribeRequestSchema:V,ResourceUpdatedNotificationParamsSchema:q,ResourceUpdatedNotificationSchema:G,PromptArgumentSchema:O,PromptSchema:C,ListPromptsRequestSchema:B,ListPromptsResultSchema:J,GetPromptRequestParamsSchema:_e,GetPromptRequestSchema:_r,TextContentSchema:vt,ImageContentSchema:br,AudioContentSchema:yr,ToolUseContentSchema:pn,EmbeddedResourceSchema:Xt,ResourceLinkSchema:hn,ContentBlockSchema:et,PromptMessageSchema:ro,GetPromptResultSchema:oo,PromptListChangedNotificationSchema:vr,ToolAnnotationsSchema:mn,ToolExecutionSchema:no,ToolSchema:zr,ListToolsRequestSchema:so,ListToolsResultSchema:io,CallToolResultSchema:ao,CallToolRequestParamsSchema:Te,CallToolRequestSchema:fn,ToolListChangedNotificationSchema:na,LoggingLevelSchema:co,SetLevelRequestParamsSchema:gn,SetLevelRequestSchema:Sn,LoggingMessageNotificationParamsSchema:_n,LoggingMessageNotificationSchema:bn,ModelHintSchema:yn,ModelPreferencesSchema:vn,ToolChoiceSchema:zn,ToolResultContentSchema:sa,SamplingContentSchema:wn,SamplingMessageContentBlockSchema:Qt,SamplingMessageSchema:Rn,CreateMessageRequestParamsSchema:xn,CreateMessageRequestSchema:Pn,CreateMessageResultSchema:Tn,CreateMessageResultWithToolsSchema:En,BooleanSchemaSchema:kn,StringSchemaSchema:$n,NumberSchemaSchema:Cn,UntitledSingleSelectEnumSchemaSchema:In,TitledSingleSelectEnumSchemaSchema:On,LegacyTitledEnumSchemaSchema:Nn,SingleSelectEnumSchemaSchema:An,UntitledMultiSelectEnumSchemaSchema:wr,TitledMultiSelectEnumSchemaSchema:Rr,MultiSelectEnumSchemaSchema:ia,EnumSchemaSchema:aa,PrimitiveSchemaDefinitionSchema:Je,ElicitRequestFormParamsSchema:Be,ElicitRequestURLParamsSchema:qn,ElicitRequestParamsSchema:it,ElicitRequestSchema:ca,ElicitationCompleteNotificationParamsSchema:la,ElicitationCompleteNotificationSchema:ua,ElicitResultSchema:da,ResourceTemplateReferenceSchema:pa,PromptReferenceSchema:ha,CompleteRequestParamsSchema:ma,CompleteRequestSchema:Mn,CompleteResultSchema:fa,RootSchema:ga,ListRootsRequestSchema:lo,ListRootsResultSchema:jn,RootsListChangedNotificationSchema:Sa,TaskCreationParamsSchema:_a,TaskStatusSchema:Ln,TaskSchema:er,CreateTaskResultSchema:Le,TaskStatusNotificationParamsSchema:ba,TaskStatusNotificationSchema:xr,GetTaskRequestSchema:uo,GetTaskResultSchema:po,GetTaskPayloadRequestSchema:ho,GetTaskPayloadResultSchema:Bc,ListTasksRequestSchema:Ae,ListTasksResultSchema:ge,CancelTaskRequestSchema:Pr,CancelTaskResultSchema:f.merge(er),ClientRequestSchema:T([Ce,$e,Mn,Sn,_r,B,He,je,_t,I,V,fn,so,uo,ho,Ae,Pr]),ClientNotificationSchema:T([v,Ye,we,Sa,xr]),ClientResultSchema:T([b,Tn,En,da,jn,po,ge,Le]),ServerRequestSchema:T([Ce,Pn,ca,lo,uo,ho,Ae,Pr]),ServerNotificationSchema:T([v,Ye,bn,G,bt,na,vr,xr,ua]),ServerResultSchema:T([b,ae,fa,oo,J,Ve,Xe,Yt,ao,io,po,ge,Le]),CallToolResultWireSchema:M().superRefine((Ee,GS)=>{if(typeof Ee!=="object"||Ee===null||Array.isArray(Ee)||Ee.content!==void 0)return;for(let hd of Bf)if(hd in Ee){GS.addIssue({code:"custom",message:`content is required when the body carries '${hd}' — another result family cannot default into an empty tools/call success`});return}}).transform($b).pipe(ao)}}var Ib;function Wf(){return Ib??=Cb()}function Kf(e){return e.type!=="object"}var Ob=new Set(["const","enum","default","examples"]),Nb=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);function kf(e){return e!==void 0&&!(typeof e==="string"&&e.startsWith("#"))}function Ab(e){let t=typeof e.$schema==="string"?e.$schema:void 0;if(kf(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=bd(e.$schema)&&e.$recursiveAnchor!==!0,o=(n,i)=>{if(Array.isArray(n))return n.map((l)=>o(l,!1));if(n===null||typeof n!=="object")return n;if(!i&&kf(n.$id))return n;let s={},a=!1;for(let[l,u]of Object.entries(n))if(i)s[l]=o(u,!1);else if((l==="$ref"||l==="$dynamicRef")&&typeof u==="string")s[l]=u==="#"?"#/properties/result":u.startsWith("#/")?`#/properties/result${u.slice(1)}`:u;else if(l==="$recursiveRef"&&u==="#"&&r)a=!0;else if(Ob.has(l))s[l]=u;else if(Nb.has(l))s[l]=o(u,!0);else s[l]=o(u,!1);if(a)if("$ref"in s)s.allOf=[...Array.isArray(s.allOf)?s.allOf:[],{$ref:"#/properties/result"}];else s.$ref="#/properties/result";return s};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}var Gf={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},Yf={"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},qb={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},_c;function bu(){if(_c)return _c;let e=Wf();return _c={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}},_c}function Xf(e){return Object.prototype.hasOwnProperty.call(Gf,e)}function Qf(e){return Object.prototype.hasOwnProperty.call(Yf,e)}function Mb(e){return Object.prototype.hasOwnProperty.call(qb,e)}function jb(e){return Mb(e)?bu().resultSchemas[e]:void 0}function Lb(e){return Xf(e)?bu().requestSchemas[e]:void 0}function Ub(e){return Qf(e)?bu().notificationSchemas[e]:void 0}var Yx=Object.keys(Gf),Xx=Object.keys(Yf);function pu(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function bc(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var $f={ok:!1,reason:"not-in-era"};function Cf(e){return pu(e)&&pu(e.outputSchema)&&Kf(e.outputSchema)}function If(e){return e}var yu={era:"2025-11-25",hasRequestMethod:Xf,hasNotificationMethod:Qf,validateRequest:(e,t)=>bc(Lb(e),t),validateResult:(e,t)=>bc(jb(e),t),validateNotification:(e,t)=>bc(Ub(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>$f,validateInputResponse:()=>$f,samplingResultVariant:(e,t)=>{let r=Wf();return bc(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)},outboundEnvelope:(e)=>{return},validateEnvelopeMeta:(e)=>[],projectCallToolResult(e,t){let r=Jf(e),o=r.structuredContent;if(o===void 0)return r;let n=typeof o!=="object"||o===null||Array.isArray(o),i=t!==void 0&&Kf(t);if(!n&&!i)return r;return{...r,structuredContent:{result:o}}},decodeResult(e,t){if(pu(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:If(r)}}return{kind:"complete",result:If(t)}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;if(!Array.isArray(r)||!r.some((o)=>Cf(o)))return t;return{...t,tools:r.map((o)=>Cf(o)?{...o,outputSchema:Ab(o.outputSchema)}:o)}},encodeErrorCode:(e)=>e===-32002?-32602:e,checkInboundEnvelope:(e)=>{return}};function Zb(){let e=es(()=>T([c(),z(),E(),Cr(),P(c(),e),S(e)])),t=P(c(),e),r=T([c(),z().int()]),o=c(),n=T([c(),z().int()]),i=K(["user","assistant"]),s=K(["debug","info","notice","warning","error","critical","alert","emergency"]),a=c().refine((ge)=>{try{return atob(ge),!0}catch{return!1}},{message:"Invalid Base64 string"}),l=p({ttl:z().optional()}),u=p({taskId:c()}),d=F({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),m=p({_meta:d.optional()}),f=m.extend({task:l.optional()}),g=p({_meta:d.optional()}),b=p({method:c(),params:g.loose().optional()}),y=p({src:c(),mimeType:c().optional(),sizes:S(c()).optional(),theme:K(["light","dark"]).optional()}),v=p({icons:S(y).optional()}),L=p({name:c(),title:c().optional()}),H=L.extend({...L.shape,...v.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),x=At(p({applyDefaults:E().optional()}),t),Z=Ir((ge)=>{if(ge&&typeof ge==="object"&&!Array.isArray(ge)&&Object.keys(ge).length===0)return{form:{}};return ge},At(p({form:x.optional(),url:t.optional()}),t.optional())),R=F({list:t.optional(),cancel:t.optional(),requests:F({sampling:F({createMessage:t.optional()}).optional(),elicitation:F({create:t.optional()}).optional()}).optional()}),w=F({list:t.optional(),cancel:t.optional(),requests:F({tools:F({call:t.optional()}).optional()}).optional()}),D=p({experimental:P(c(),t).optional(),sampling:p({context:t.optional(),tools:t.optional()}).optional(),elicitation:Z.optional(),roots:p({listChanged:E().optional()}).optional(),tasks:R.optional(),extensions:P(c(),t).optional()}),X=p({experimental:P(c(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:p({listChanged:E().optional()}).optional(),resources:p({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:p({listChanged:E().optional()}).optional(),tasks:w.optional(),extensions:P(c(),t).optional()}),Y=p({progress:z(),total:U(z()),message:U(c())}),ue=p({...g.shape,...Y.shape,progressToken:r}),$e=b.extend({method:h("notifications/progress"),params:ue}),oe=g.extend({level:s,logger:c().optional(),data:M()}),ae=b.extend({method:h("notifications/message"),params:oe}),we=p({uri:c(),mimeType:U(c()),_meta:P(c(),M()).optional()}),Ce=we.extend({text:c()}),mt=we.extend({blob:a}),Me=p({audience:S(i).optional(),priority:z().min(0).max(1).optional(),lastModified:_o({offset:!0}).optional()}),Ye=p({...L.shape,...v.shape,uri:c(),description:U(c()),mimeType:U(c()),size:U(z()),annotations:Me.optional(),_meta:U(F({}))}),ft=p({...L.shape,...v.shape,uriTemplate:c(),description:U(c()),mimeType:U(c()),annotations:Me.optional(),_meta:U(F({}))}),Fe=b.extend({method:h("notifications/resources/list_changed"),params:g.optional()}),Ie=g.extend({uri:c()}),It=b.extend({method:h("notifications/resources/updated"),params:Ie}),Ot=p({name:c(),description:U(c()),required:U(E())}),gt=p({...L.shape,...v.shape,description:U(c()),arguments:U(S(Ot)),_meta:U(F({}))}),Pe=b.extend({method:h("notifications/prompts/list_changed"),params:g.optional()}),Oe=p({type:h("text"),text:c(),annotations:Me.optional(),_meta:P(c(),M()).optional()}),Ne=p({type:h("image"),data:a,mimeType:c(),annotations:Me.optional(),_meta:P(c(),M()).optional()}),st=p({type:h("audio"),data:a,mimeType:c(),annotations:Me.optional(),_meta:P(c(),M()).optional()}),gr=p({type:h("tool_use"),name:c(),id:c(),input:P(c(),M()),_meta:P(c(),M()).optional()}),He=p({type:h("resource"),resource:T([Ce,mt]),annotations:Me.optional(),_meta:P(c(),M()).optional()}),Ve=Ye.extend({type:h("resource_link")}),je=T([Oe,Ne,st,Ve,He]),Xe=p({role:i,content:je}),Qe=p({title:c().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),St=b.extend({method:h("notifications/tools/list_changed"),params:g.optional()}),_t=p({name:c().optional()}),Yt=p({hints:S(_t).optional(),costPriority:z().min(0).max(1).optional(),speedPriority:z().min(0).max(1).optional(),intelligencePriority:z().min(0).max(1).optional()}),bt=p({mode:K(["auto","required","none"]).optional()}),Sr=p({type:h("boolean"),title:c().optional(),description:c().optional(),default:E().optional()}),I=p({type:h("string"),title:c().optional(),description:c().optional(),minLength:z().optional(),maxLength:z().optional(),format:K(["email","uri","date","date-time"]).optional(),default:c().optional()}),yt=p({type:K(["number","integer"]),title:c().optional(),description:c().optional(),minimum:z().optional(),maximum:z().optional(),default:z().optional()}),V=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),default:c().optional()}),q=p({type:h("string"),title:c().optional(),description:c().optional(),oneOf:S(p({const:c(),title:c()})),default:c().optional()}),G=p({type:h("string"),title:c().optional(),description:c().optional(),enum:S(c()),enumNames:S(c()).optional(),default:c().optional()}),O=T([V,q]),C=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({type:h("string"),enum:S(c())}),default:S(c()).optional()}),B=p({type:h("array"),title:c().optional(),description:c().optional(),minItems:z().optional(),maxItems:z().optional(),items:p({anyOf:S(p({const:c(),title:c()}))}),default:S(c()).optional()}),J=T([C,B]),_e=T([G,O,J]),_r=T([_e,Sr,I,yt]),vt=f.extend({mode:h("form").optional(),message:c(),requestedSchema:p({type:h("object"),properties:P(c(),_r),required:S(c()).optional()}).catchall(M())}),br=p({type:h("ref/resource"),uri:c()}),yr=p({type:h("ref/prompt"),name:c()}),pn=p({uri:c().startsWith("file://"),name:c().optional(),_meta:P(c(),M()).optional()}),Xt=D.shape,hn=p({experimental:Xt.experimental,sampling:Xt.sampling,elicitation:Xt.elicitation,roots:Xt.roots,extensions:Xt.extensions}),et=X.shape,ro=p({experimental:et.experimental,logging:et.logging,completions:et.completions,prompts:et.prompts,resources:et.resources,tools:et.tools,extensions:et.extensions}),oo=F({progressToken:r.optional(),[Mt]:c(),[vo]:H.optional(),[Or]:hn,[zo]:s.optional()}),vr=p({...L.shape,...v.shape,description:c().optional(),inputSchema:F({$schema:c().optional(),type:h("object")}),outputSchema:F({$schema:c().optional()}).optional(),annotations:Qe.optional(),_meta:P(c(),M()).optional()}),mn=p({type:h("tool_result"),toolUseId:c(),content:S(je),structuredContent:M().optional(),isError:E().optional(),_meta:P(c(),M()).optional()}),no=T([Oe,Ne,st,gr,mn]),zr=p({role:i,content:T([no,S(no)]),_meta:P(c(),M()).optional()}),so=c(),io=F({[jt]:H.optional().catch(void 0)}),ao=io.optional();function Te(ge){return F({_meta:ao,resultType:so.default("complete"),...ge})}let fn=Te({}),na=Te({nextCursor:o.optional()}),co=Te({content:S(je),structuredContent:M().optional(),isError:E().optional()}),gn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:S(vr),nextCursor:o.optional()}),Sn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:S(gt),nextCursor:o.optional()}),_n=Te({description:c().optional(),messages:S(Xe)}),bn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:S(Ye),nextCursor:o.optional()}),yn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:S(ft),nextCursor:o.optional()}),vn=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:S(T([Ce,mt]))}),zn=Te({completion:p({values:S(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),sa=Te({ttlMs:z().int().min(0),cacheScope:K(["public","private"])}),wn=Te({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:S(c()),capabilities:ro,instructions:c().optional()}),Qt=p({messages:S(zr),modelPreferences:Yt.optional(),systemPrompt:c().optional(),includeContext:K(["none","thisServer","allServers"]).optional(),temperature:z().optional(),maxTokens:z().int(),stopSequences:S(c()).optional(),metadata:t.optional(),tools:S(vr).optional(),toolChoice:bt.optional()}),Rn=p({method:h("sampling/createMessage"),params:Qt}),xn=p({method:h("roots/list"),params:p({_meta:P(c(),M()).optional()}).optional()}),Pn=p({...zr.shape,model:c(),stopReason:c().optional()}),Tn=p({roots:S(pn)}),En=p({action:K(["accept","decline","cancel"]),content:P(c(),T([c(),z(),E(),S(c())])).optional()}),kn=p({mode:h("url"),message:c(),url:c().url()}),$n=T([vt,kn]),Cn=p({method:h("elicitation/create"),params:$n}),In=T([Rn,xn,Cn]),On=T([Pn,Tn,En]),Nn=P(c(),In),An=P(c(),On),wr=Te({inputRequests:Nn.optional(),requestState:c().optional()}),Rr={inputResponses:An.optional(),requestState:c().optional()},ia=p({_meta:oo,...Rr}),aa=F({progressToken:r.optional()});function Je(ge,Pr){return p({method:h(ge),params:p({_meta:oo,...Pr})})}function Be(ge,Pr){return p({method:h(ge),params:p({_meta:aa.optional(),...Pr}).optional()})}let qn={name:c(),arguments:P(c(),M()).optional(),...Rr},it={cursor:o.optional()},ca=Je("tools/call",qn),la=Je("tools/list",it),ua=Je("prompts/list",it),da=Je("prompts/get",{name:c(),arguments:P(c(),c()).optional(),...Rr}),pa=Je("resources/list",it),ha=Je("resources/templates/list",it),ma=Je("resources/read",{uri:c(),...Rr}),Mn={ref:T([yr,br]),argument:p({name:c(),value:c()}),context:p({arguments:P(c(),c()).optional()}).optional()},fa=Je("completion/complete",Mn),ga=Je("server/discover",{}),lo=p({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:S(c()).optional()}),jn={notifications:lo},Sa=Je("subscriptions/listen",jn),_a=io.extend({"io.modelcontextprotocol/subscriptionId":n}),Ln=F({_meta:_a,resultType:so.default("complete")}),er={"tools/call":Be("tools/call",qn),"tools/list":Be("tools/list",it),"prompts/get":Be("prompts/get",{name:c(),arguments:P(c(),c()).optional()}),"prompts/list":Be("prompts/list",it),"resources/list":Be("resources/list",it),"resources/templates/list":Be("resources/templates/list",it),"resources/read":Be("resources/read",{uri:c()}),"completion/complete":Be("completion/complete",Mn),"server/discover":Be("server/discover",{}),"subscriptions/listen":Be("subscriptions/listen",jn)};function Le(ge){return F({_meta:ao,...ge})}let ba={"tools/call":Le({content:S(je),structuredContent:M().optional(),isError:E().optional()}),"tools/list":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),tools:S(vr),nextCursor:o.optional()}),"prompts/get":Le({description:c().optional(),messages:S(Xe)}),"prompts/list":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),prompts:S(gt),nextCursor:o.optional()}),"resources/list":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resources:S(Ye),nextCursor:o.optional()}),"resources/templates/list":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),resourceTemplates:S(ft),nextCursor:o.optional()}),"resources/read":Le({ttlMs:z().int().min(0),cacheScope:K(["public","private"]),contents:S(T([Ce,mt]))}),"completion/complete":Le({completion:p({values:S(c()).max(100),total:z().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":Le({ttlMs:z().int().min(0).catch(0),cacheScope:K(["public","private"]).catch("private"),supportedVersions:S(c()),capabilities:ro,instructions:c().optional()}),"subscriptions/listen":Le({})},xr=F({"io.modelcontextprotocol/subscriptionId":n.optional()}),uo=p({method:h("notifications/subscriptions/acknowledged"),params:p({_meta:xr.optional(),notifications:lo})}),po=p({_meta:xr.optional(),requestId:n,reason:c().optional()}),ho=p({method:h("notifications/cancelled"),params:po}),Bc={"notifications/cancelled":ho,"notifications/progress":$e,"notifications/message":ae,"notifications/resources/updated":It,"notifications/resources/list_changed":Fe,"notifications/tools/list_changed":St,"notifications/prompts/list_changed":Pe,"notifications/subscriptions/acknowledged":uo},Ae=(ge)=>p({jsonrpc:h("2.0"),id:T([c(),z().int()]),result:ge}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:o,RequestIdSchema:n,RoleSchema:i,LoggingLevelSchema:s,TaskMetadataSchema:l,RelatedTaskMetadataSchema:u,RequestMetaSchema:d,BaseRequestParamsSchema:m,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:g,NotificationSchema:b,IconSchema:y,IconsSchema:v,BaseMetadataSchema:L,ImplementationSchema:H,ClientTasksCapabilitySchema:R,ServerTasksCapabilitySchema:w,ClientCapabilitiesSchema:D,ServerCapabilitiesSchema:X,ProgressSchema:Y,ProgressNotificationParamsSchema:ue,ProgressNotificationSchema:$e,LoggingMessageNotificationParamsSchema:oe,LoggingMessageNotificationSchema:ae,ResourceContentsSchema:we,TextResourceContentsSchema:Ce,BlobResourceContentsSchema:mt,AnnotationsSchema:Me,ResourceSchema:Ye,ResourceTemplateSchema:ft,ResourceListChangedNotificationSchema:Fe,ResourceUpdatedNotificationParamsSchema:Ie,ResourceUpdatedNotificationSchema:It,PromptArgumentSchema:Ot,PromptSchema:gt,PromptListChangedNotificationSchema:Pe,TextContentSchema:Oe,ImageContentSchema:Ne,AudioContentSchema:st,ToolUseContentSchema:gr,EmbeddedResourceSchema:He,ResourceLinkSchema:Ve,ContentBlockSchema:je,PromptMessageSchema:Xe,ToolAnnotationsSchema:Qe,ToolListChangedNotificationSchema:St,ModelHintSchema:_t,ModelPreferencesSchema:Yt,ToolChoiceSchema:bt,BooleanSchemaSchema:Sr,StringSchemaSchema:I,NumberSchemaSchema:yt,UntitledSingleSelectEnumSchemaSchema:V,TitledSingleSelectEnumSchemaSchema:q,LegacyTitledEnumSchemaSchema:G,SingleSelectEnumSchemaSchema:O,UntitledMultiSelectEnumSchemaSchema:C,TitledMultiSelectEnumSchemaSchema:B,MultiSelectEnumSchemaSchema:J,EnumSchemaSchema:_e,PrimitiveSchemaDefinitionSchema:_r,ElicitRequestFormParamsSchema:vt,ResourceTemplateReferenceSchema:br,PromptReferenceSchema:yr,RootSchema:pn,ClientCapabilities2026Schema:hn,ServerCapabilities2026Schema:ro,RequestMetaEnvelopeSchema:oo,ToolSchema:vr,ToolResultContentSchema:mn,SamplingMessageContentBlockSchema:no,SamplingMessageSchema:zr,ResultTypeSchema:so,ResultMetaSchema:io,ResultSchema:fn,PaginatedResultSchema:na,CallToolResultSchema:co,ListToolsResultSchema:gn,ListPromptsResultSchema:Sn,GetPromptResultSchema:_n,ListResourcesResultSchema:bn,ListResourceTemplatesResultSchema:yn,ReadResourceResultSchema:vn,CompleteResultSchema:zn,CacheableResultSchema:sa,DiscoverResultSchema:wn,CreateMessageRequestParamsSchema:Qt,CreateMessageRequestSchema:Rn,ListRootsRequestSchema:xn,CreateMessageResultSchema:Pn,ListRootsResultSchema:Tn,ElicitResultSchema:En,ElicitRequestURLParamsSchema:kn,ElicitRequestParamsSchema:$n,ElicitRequestSchema:Cn,InputRequestSchema:In,InputResponseSchema:On,InputRequestsSchema:Nn,InputResponsesSchema:An,InputRequiredResultSchema:wr,InputResponseRequestParamsSchema:ia,CallToolRequestSchema:ca,ListToolsRequestSchema:la,ListPromptsRequestSchema:ua,GetPromptRequestSchema:da,ListResourcesRequestSchema:pa,ListResourceTemplatesRequestSchema:ha,ReadResourceRequestSchema:ma,CompleteRequestSchema:fa,DiscoverRequestSchema:ga,SubscriptionFilterSchema:lo,SubscriptionsListenRequestSchema:Sa,SubscriptionsListenResultMetaSchema:_a,SubscriptionsListenResultSchema:Ln,dispatchRequestSchemas:er,dispatchResultSchemas:ba,NotificationMetaSchema:xr,SubscriptionsAcknowledgedNotificationSchema:uo,CancelledNotificationParamsSchema:po,CancelledNotificationSchema:ho,notificationSchemas2026:Bc,JSONRPCResultResponseSchema:Ae(fn),CallToolResultResponseSchema:Ae(T([co,wr])),ListToolsResultResponseSchema:Ae(gn),ListPromptsResultResponseSchema:Ae(Sn),GetPromptResultResponseSchema:Ae(T([_n,wr])),ListResourcesResultResponseSchema:Ae(bn),ListResourceTemplatesResultResponseSchema:Ae(yn),ReadResourceResultResponseSchema:Ae(T([vn,wr])),CompleteResultResponseSchema:Ae(zn),DiscoverResultResponseSchema:Ae(wn),SubscriptionsListenResultResponseSchema:Ae(Ln)}}var Db;function pr(){return Db??=Zb()}var Fb=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];function Hb(e){return Fb.includes(e)}var vu=Symbol("modelcontextprotocol.resultCacheHintFallback");function Vb(e){return e[vu]}function eg(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function tg(e){return e==="public"||e==="private"}var W=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}({}),re=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Ke(this,t)}static isInstance(t){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ke(this,t)}constructor(t,r,o){super(r);this.code=t,this.data=o,this.name="ProtocolError",Wr(this,new.target)}static fromError(t,r,o){if(t===W.UrlElicitationRequired&&o){let n=o;if(n.elicitations)return new og(n.elicitations,r)}if(t===W.UnsupportedProtocolVersion&&o){let n=o;if(Array.isArray(n.supported)&&typeof n.requested==="string")return new Rc({supported:n.supported,requested:n.requested},r)}if(t===W.InvalidParams||t===W.ResourceNotFound){let n=o;if(typeof n?.uri==="string"&&(t===W.ResourceNotFound||Object.keys(n).length===1))return new rg(n.uri,r)}if(t===W.MissingRequiredClientCapability&&o){let n=o;if(n.requiredCapabilities!==null&&typeof n.requiredCapabilities==="object"&&!Array.isArray(n.requiredCapabilities))return new ng({requiredCapabilities:n.requiredCapabilities},r)}return new e(t,r,o)}},rg=class extends re{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(W.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},og=class extends re{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(W.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Rc=class extends re{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(W.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},ng=class extends re{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(W.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},Jb=0,Bb="private",Wb=["tools/call","prompts/get","resources/read"];function Kb(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete")return t;if(Wb.includes(e))return t;throw new re(W.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function Gb(e,t){let r=Vb(t);if(t.resultType!=="complete"||!Hb(e))return r===void 0?t:ty(t);let o=t,n=eg(o.ttlMs)?o.ttlMs:Qb(r),i=tg(o.cacheScope)?o.cacheScope:ey(r),s={...o,ttlMs:n,cacheScope:i};return delete s[vu],s}function Yb(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Xb(e,t){if(t===void 0)return e;let r=e._meta;if(r===void 0)return{...e,_meta:{[jt]:t}};if(!Yb(r))return e;if(r[jt]!==void 0)return e;return{...e,_meta:{...r,[jt]:t}}}function Qb(e){return e!==void 0&&eg(e.ttlMs)?e.ttlMs:Jb}function ey(e){return e!==void 0&&tg(e.cacheScope)?e.cacheScope:Bb}function ty(e){let t={...e};return delete t[vu],t}var ry=["elicitation/create","sampling/createMessage","roots/list"],yc;function sg(){if(yc)return yc;let e=pr();return yc={request:{"elicitation/create":p({method:h("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":p({method:h("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":p({method:h("roots/list"),params:F({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},yc}function ig(e){return ry.includes(e)}function au(e){return ig(e)?sg().request[e]:void 0}function oy(e){return ig(e)?sg().response[e]:void 0}var zu={"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},ag={"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 cg(e){return Object.prototype.hasOwnProperty.call(zu,e)}function lg(e){return Object.prototype.hasOwnProperty.call(ag,e)}function ny(e){return Object.prototype.hasOwnProperty.call(zu,e)}function sy(e){return cg(e)?pr().dispatchRequestSchemas[e]:void 0}function iy(e){return ny(e)?pr().dispatchResultSchemas[e]:void 0}function ay(e){return lg(e)?pr().notificationSchemas2026[e]:void 0}var Qx=Object.keys(zu),eP=Object.keys(ag);function Mi(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Ai(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}var cy={ok:!1,reason:"not-in-era"},ly=[Mt,Or];function uy(e,t){let r=t,o=!1,n=()=>{if(!o)r={...r},o=!0;return r},i=t.tools;if(e==="tools/list"&&Array.isArray(i)&&i.some((a)=>Mi(a)&&("execution"in a)))n().tools=i.map((a)=>{if(!Mi(a)||!("execution"in a))return a;let l={...a};return delete l.execution,l});let s=t.capabilities;if(Mi(s)&&"tasks"in s){let a={...s};delete a.tasks,n().capabilities=a}return r}var wu={era:"2026-07-28",hasRequestMethod:cg,hasNotificationMethod:lg,hasInputRequestMethod:(e)=>au(e)!==void 0,validateRequest:(e,t)=>Ai(sy(e),t),validateResult:(e,t)=>Ai(iy(e),t),validateNotification:(e,t)=>Ai(ay(e),t),validateInputRequest:(e,t)=>Ai(au(e),t),validateInputResponse:(e,t)=>Ai(oy(e),t),samplingResultVariant:()=>cy,outboundEnvelope(e){return{[Mt]:e.protocolVersion,[vo]:e.clientInfo,[Or]:e.clientCapabilities,...e.logLevel!==void 0&&{[zo]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of ly)if(!(o in e))t.push({key:o,problem:"missing"});let r=pr().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let o of r.error.issues){let n=o.path.map(String),i=n.length>0?n.join("."):"_meta";if(n.length===1&&t.some((s)=>s.key===i&&s.problem==="missing"))continue;t.push({key:i,problem:o.message})}return t},projectCallToolResult:(e)=>Jf(e),inputRequestSchema:au,decodeResult(e,t){if(!Mi(t))return{kind:"invalid",error:new A(N.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new A(N.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 r!=="string")return{kind:"invalid",error:new A(N.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let s=t.inputRequests,a=Mi(s)?s:{},l=t.requestState,u=t._meta===void 0?void 0:pr().ResultMetaSchema.safeParse(t._meta),d=u?.success?u.data:void 0;if(Object.keys(a).length===0&&typeof l!=="string")return{kind:"invalid",error:new A(N.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"})};return{kind:"input_required",inputRequests:a,...typeof l==="string"&&{requestState:l},...d!==void 0&&{_meta:d}}}if(r!=="complete")return{kind:"invalid",error:new A(N.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let o=dy(),n=Object.hasOwn(o,e)?o[e]:void 0;if(n!==void 0){let s=n.safeParse(t);if(!s.success)return{kind:"invalid",error:new A(N.InvalidResult,`Invalid result for ${e}: ${s.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return Xb(Gb(e,Kb(e,uy(e,t))),r)},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)";let t=pr().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map((r)=>r.message).join("; ")}`}},vc;function dy(){if(vc)return vc;let e=pr();return vc={"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},vc}var xc="2026-07-28";function Ht(e){return e!==void 0&&Jt(e)?wu:yu}function Of(e){if(e.revision!==void 0)return Ht(e.revision).era;return e.era==="modern"?wu.era:yu.era}function cu(e){return ug.some((t)=>t.hasRequestMethod(e))}function lu(e){return ug.some((t)=>t.hasNotificationMethod(e))}function Nf(e){return e==="tasks/get"||e==="tasks/cancel"}var ug=[yu,wu],py=gd({AnnotationsSchema:()=>xt,AudioContentSchema:()=>Ur,BaseMetadataSchema:()=>wt,BaseRequestParamsSchema:()=>ze,BlobResourceContentsSchema:()=>Mo,BooleanSchemaSchema:()=>Zo,CallToolRequestParamsSchema:()=>Ws,CallToolRequestSchema:()=>Ks,CallToolResultSchema:()=>dr,CancelTaskRequestSchema:()=>cc,CancelTaskResultSchema:()=>lc,CancelledNotificationParamsSchema:()=>ns,CancelledNotificationSchema:()=>ko,ClientCapabilitiesSchema:()=>is,ClientNotificationSchema:()=>dc,ClientRequestSchema:()=>uc,ClientResultSchema:()=>pc,ClientTasksCapabilitySchema:()=>Ga,CompatibilityCallToolResultSchema:()=>Xa,CompleteRequestParamsSchema:()=>zi,CompleteRequestSchema:()=>wi,CompleteResultSchema:()=>Ri,ContentBlockSchema:()=>Pt,CreateMessageRequestParamsSchema:()=>ai,CreateMessageRequestSchema:()=>ci,CreateMessageResultSchema:()=>li,CreateMessageResultWithToolsSchema:()=>ui,CreateTaskResultSchema:()=>ec,CursorSchema:()=>Ro,DiscoverRequestSchema:()=>ls,DiscoverResultSchema:()=>lr,ElicitRequestFormParamsSchema:()=>Jr,ElicitRequestParamsSchema:()=>fi,ElicitRequestSchema:()=>gi,ElicitRequestURLParamsSchema:()=>mi,ElicitResultSchema:()=>bi,ElicitationCompleteNotificationParamsSchema:()=>Si,ElicitationCompleteNotificationSchema:()=>_i,EmbeddedResourceSchema:()=>Zr,EmptyResultSchema:()=>cr,EnumSchemaSchema:()=>hi,GetPromptRequestParamsSchema:()=>js,GetPromptRequestSchema:()=>Ls,GetPromptResultSchema:()=>Ds,GetTaskPayloadRequestSchema:()=>nc,GetTaskPayloadResultSchema:()=>sc,GetTaskRequestSchema:()=>rc,GetTaskResultSchema:()=>oc,IconSchema:()=>ss,IconsSchema:()=>Lt,ImageContentSchema:()=>Lr,ImplementationSchema:()=>Rt,InitializeRequestParamsSchema:()=>as,InitializeRequestSchema:()=>$o,InitializeResultSchema:()=>cs,InitializedNotificationSchema:()=>Io,JSONArraySchema:()=>Wa,JSONObjectSchema:()=>de,JSONRPCErrorResponseSchema:()=>qr,JSONRPCMessageSchema:()=>ut,JSONRPCNotificationSchema:()=>Eo,JSONRPCRequestSchema:()=>To,JSONRPCResponseSchema:()=>Ka,JSONRPCResultResponseSchema:()=>Ar,JSONValueSchema:()=>qt,LegacyTitledEnumSchemaSchema:()=>Ho,ListChangedOptionsBaseSchema:()=>Ys,ListPromptsRequestSchema:()=>qs,ListPromptsResultSchema:()=>Ms,ListResourceTemplatesRequestSchema:()=>gs,ListResourceTemplatesResultSchema:()=>Ss,ListResourcesRequestSchema:()=>ms,ListResourcesResultSchema:()=>fs,ListRootsRequestSchema:()=>Pi,ListRootsResultSchema:()=>Ti,ListTasksRequestSchema:()=>ic,ListTasksResultSchema:()=>ac,ListToolsRequestSchema:()=>Js,ListToolsResultSchema:()=>Bs,LoggingLevelSchema:()=>Uo,LoggingMessageNotificationParamsSchema:()=>ei,LoggingMessageNotificationSchema:()=>Fr,ModelHintSchema:()=>ti,ModelPreferencesSchema:()=>ri,MultiSelectEnumSchemaSchema:()=>pi,NotificationSchema:()=>xe,NotificationsParamsSchema:()=>ke,NumberSchemaSchema:()=>Vr,PaginatedRequestParamsSchema:()=>ps,PaginatedRequestSchema:()=>Ut,PaginatedResultSchema:()=>Zt,PingRequestSchema:()=>Oo,PrimitiveSchemaDefinitionSchema:()=>Bo,ProgressNotificationParamsSchema:()=>ds,ProgressNotificationSchema:()=>No,ProgressSchema:()=>us,ProgressTokenSchema:()=>wo,PromptArgumentSchema:()=>Ns,PromptListChangedNotificationSchema:()=>Fs,PromptMessageSchema:()=>Zs,PromptReferenceSchema:()=>vi,PromptSchema:()=>As,ReadResourceRequestParamsSchema:()=>_s,ReadResourceRequestSchema:()=>bs,ReadResourceResultSchema:()=>ys,RelatedTaskMetadataSchema:()=>os,RequestIdSchema:()=>lt,RequestMetaSchema:()=>xo,RequestSchema:()=>pe,ResourceContentsSchema:()=>Ao,ResourceLinkSchema:()=>Dr,ResourceListChangedNotificationSchema:()=>vs,ResourceRequestParamsSchema:()=>Mr,ResourceSchema:()=>jo,ResourceTemplateReferenceSchema:()=>yi,ResourceTemplateSchema:()=>hs,ResourceUpdatedNotificationParamsSchema:()=>Is,ResourceUpdatedNotificationSchema:()=>Os,ResultMetaObjectSchema:()=>Po,ResultSchema:()=>he,RoleSchema:()=>Dt,RootSchema:()=>xi,RootsListChangedNotificationSchema:()=>Ei,SamplingContentSchema:()=>si,SamplingMessageContentBlockSchema:()=>ir,SamplingMessageSchema:()=>ii,ServerCapabilitiesSchema:()=>Co,ServerNotificationSchema:()=>mc,ServerRequestSchema:()=>hc,ServerResultSchema:()=>fc,ServerTasksCapabilitySchema:()=>Ya,SetLevelRequestParamsSchema:()=>Xs,SetLevelRequestSchema:()=>Qs,SingleSelectEnumSchemaSchema:()=>di,StringSchemaSchema:()=>Hr,SubscribeRequestParamsSchema:()=>zs,SubscribeRequestSchema:()=>ws,SubscriptionFilterSchema:()=>Lo,SubscriptionsAcknowledgedNotificationParamsSchema:()=>Es,SubscriptionsAcknowledgedNotificationSchema:()=>ks,SubscriptionsListenRequestParamsSchema:()=>Ps,SubscriptionsListenRequestSchema:()=>Ts,SubscriptionsListenResultMetaSchema:()=>$s,SubscriptionsListenResultSchema:()=>Cs,TaskAugmentedRequestParamsSchema:()=>ar,TaskCreationParamsSchema:()=>Qa,TaskMetadataSchema:()=>rs,TaskSchema:()=>Ft,TaskStatusNotificationParamsSchema:()=>$i,TaskStatusNotificationSchema:()=>tc,TaskStatusSchema:()=>ki,TextContentSchema:()=>jr,TextResourceContentsSchema:()=>qo,TitledMultiSelectEnumSchemaSchema:()=>Jo,TitledSingleSelectEnumSchemaSchema:()=>Fo,ToolAnnotationsSchema:()=>Hs,ToolChoiceSchema:()=>oi,ToolExecutionSchema:()=>Vs,ToolListChangedNotificationSchema:()=>Gs,ToolResultContentSchema:()=>ni,ToolSchema:()=>ur,ToolUseContentSchema:()=>Us,UnsubscribeRequestParamsSchema:()=>Rs,UnsubscribeRequestSchema:()=>xs,UntitledMultiSelectEnumSchemaSchema:()=>Vo,UntitledSingleSelectEnumSchemaSchema:()=>Do});var Gr=(e)=>To.safeParse(e).success,dg=(e)=>Eo.safeParse(e).success,en=(e)=>Ar.safeParse(e).success,tn=(e)=>qr.safeParse(e).success;var pg=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required";var Ru=(e)=>$o.safeParse(e).success,hg=(e)=>Io.safeParse(e).success;var hy="Mcp-Param-",Af="x-mcp-header",my=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,fy=new Set(["string","integer","boolean","number"]);function xu(e){let t=[],r=new Map,o=(i,s,a)=>{if(i===null||typeof i!=="object")return;let l=i;if(Af in l){if(!a||s.length===0)return`${zc(s)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let d=l[Af];if(typeof d!=="string"||d.length===0)return`${zc(s)}: x-mcp-header MUST be a non-empty string`;if(!my.test(d))return`${zc(s)}: x-mcp-header '${d}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let m=typeof l.type==="string"?l.type:void 0;if(m===void 0||!fy.has(m))return`${zc(s)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${m??"<none>"}`;let f=d.toLowerCase(),g=r.get(f);if(g!==void 0)return`x-mcp-header '${d}' is not case-insensitively unique (also declared as '${g}')`;r.set(f,d),t.push({path:s,headerName:d,type:m})}let u=l.properties;if(u!==null&&typeof u==="object")for(let[d,m]of Object.entries(u)){let f=o(m,[...s,d],a);if(f!==void 0)return f}for(let d of gy){let m=l[d];if(m===void 0)continue;let f=Array.isArray(m)?m:m!==null&&typeof m==="object"&&Sy.has(d)?Object.values(m):[m];for(let g of f){let b=o(g,[...s,`<${d}>`],!1);if(b!==void 0)return b}}},n=o(e,[],!0);return n===void 0?{valid:!0,declarations:t}:{valid:!1,reason:n}}var gy=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],Sy=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function zc(e){return e.length===0?"<root>":e.join(".")}var mg="=?base64?",fg="?=";function _y(e){if(typeof e==="string")return e;if(typeof e==="boolean")return e?"true":"false";if(typeof e==="number"){if(!Number.isFinite(e))return;if(Number.isInteger(e)&&!Number.isSafeInteger(e))return;return String(e)}}function by(e){if(e.length===0)return!0;if(e.startsWith(mg)&&e.endsWith(fg))return!0;if(e!==e.trim())return!0;for(let t=0;t<e.length;t++){let r=e.codePointAt(t);if(r===9||r>=32&&r<=126)continue;return!0}return!1}function yy(e){let t=new TextEncoder().encode(e),r="";for(let o of t)r+=String.fromCodePoint(o);return btoa(r)}function Pu(e){return by(e)?`${mg}${yy(e)}${fg}`:e}function vy(e,t){let r=e;for(let o of t){if(r===null||typeof r!=="object")return;r=r[o]}return r}function gg(e,t){let r={};for(let o of e){let n=vy(t,o.path);if(n===void 0||n===null)continue;let i=_y(n);if(i===void 0)continue;r[`${hy}${o.headerName}`]=Pu(i)}return r}var Qo=-32020,tP=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32000],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[W.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Qo,W.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[W.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[W.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[W.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Qo],conformance:["http-header-validation"],rationale:"SEP-2243 standard `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The spec requires `MCP-Protocol-Version` and `Mcp-Method` on every modern *request* POST (`Mcp-Name` only for the methods that mirror `params.name` / `params.uri` / `params.taskId`, see `MCP_NAME_HEADER_SOURCE`) and names them in that order, so a request missing several is answered by the earliest. Notification POSTs are exempt: the presence half runs on requests only, so a modern-enveloped notification is dispatched even with no standard headers at all. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half — including the missing `MCP-Protocol-Version` cell, which cannot live on the edge rung without breaking body-primary classification. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[W.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Qo],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],rP={[W.ParseError]:400,[W.InvalidRequest]:400,[W.MethodNotFound]:404,[W.UnsupportedProtocolVersion]:400,[W.MissingRequiredClientCapability]:400,[Qo]:400},qf={"tools/call":"name","prompts/get":"name","resources/read":"uri","tasks/get":"taskId","tasks/update":"taskId","tasks/cancel":"taskId"};function Sg(e,t){let r=Object.hasOwn(qf,e)?qf[e]:void 0;if(r===void 0)return;let o=zy(t)?t[r]:void 0;return{field:r,value:typeof o==="string"?o:void 0}}function zy(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Pc(e,t){return Za(e,t)}function qi(e){return new Set(e.flatMap((t)=>Object.keys(t.shape)))}function hu(e){if(e==null)return!1;let t=typeof e;if(t!=="object"&&t!=="function")return!1;if(!("~standard"in e))return!1;return typeof e["~standard"]?.validate==="function"}var Mf=!1,mu="draft-2020-12";function wy(e,t="input"){let r=e["~standard"],o;if(r.jsonSchema)o=r.jsonSchema[t]({target:mu});else if(r.vendor==="zod"){if(!("_zod"in e))throw Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");if(!Mf)Mf=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.");o=La(e,{target:mu,io:t})}else throw Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output"){if(o.type!==void 0)return o;return _g(o)?{type:"object",...o}:o}if(o.type!==void 0&&o.type!=="object")throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}function _g(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every((o)=>o!==null&&typeof o==="object"&&(o.type==="object"||_g(o)))}return!1}function Ry(e){if(!e.path?.length)return e.message;return`${e.path.map((t)=>String(typeof t==="object"?t.key:t)).join(".")}: ${e.message}`}async function uu(e,t){let r=await e["~standard"].validate(t);if(r.issues&&r.issues.length>0)return{success:!1,error:r.issues.map((o)=>Ry(o)).join(", ")};return{success:!0,data:r.value}}function xy(e){let t=La(e,{target:mu,io:"input"});return typeof t.pattern==="string"?t.pattern:void 0}var Py=/\\\.\\d\{(\d+)\}/;function Ty(e){let t=Py.exec(e),r=[void 0,-1,0];if(t)r.push(Number(t[1]));return[!1,!0].flatMap((o)=>[!1,!0].flatMap((n)=>r.map((i)=>_o({local:o,offset:n,precision:i}))))}function Ey(e,t){let r;switch(e){case"email":r=[af()];break;case"uri":r=[Fa()];break;case"date":r=[tu()];break;case"date-time":r=Ty(t);break}return new Set(r.map((o)=>xy(o)).filter((o)=>o!==void 0))}function ky(e,t,r){if(r!=="zod")return!0;return Ey(e,t).has(t)}function Li(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function $y(e){try{return wy(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new re(W.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}var Cy=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);function Tu(e){return Cy.has(e)||e.startsWith("x-")}var Iy=new Set(["$schema",...Object.keys(Jr.shape.requestedSchema.shape)]),jf={string:qi([Hr,Do,Fo,Ho]),number:qi([Vr]),integer:qi([Vr]),boolean:qi([Zo]),array:qi([Vo,Jo])},Oy=new Set(Hr.shape.format.unwrap().options);function Ny(e,t,r,o){if(!Li(e))return e;let n=typeof e.type==="string"&&Object.hasOwn(jf,e.type)?jf[e.type]:void 0;if(n===void 0)return e;let i={};for(let[s,a]of Object.entries(e))if(n.has(s)||Tu(s))i[s]=a;else if(s==="pattern"&&e.type==="string"&&typeof e.format==="string"){if(!Oy.has(e.format))i[s]=a;else if(typeof a!=="string"||!ky(e.format,a,r))o.push(`${t}.${s}`)}else o.push(`${t}.${s}`);return i}function Ay(e,t){let r={},o=[];for(let[n,i]of Object.entries(e))if(n==="properties"&&Li(i))r[n]=Object.fromEntries(Object.entries(i).map(([s,a])=>[s,Ny(a,`properties.${s}`,t,o)]));else if(Iy.has(n))r[n]=i;else if(!Tu(n))o.push(n);if(o.length>0)throw new re(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return r}function qy(e,t){if(!Li(e.properties))return t;let r=Object.entries(e.properties).filter(([,o])=>!Pc(Bo,o).success).map(([o])=>`properties.${o}`);return r.length>0?r.join(", "):t}function fu(e,t,r=""){if(Array.isArray(e)&&Array.isArray(t))return e.flatMap((o,n)=>fu(o,t[n],`${r}[${n}]`));if(!Li(e)||!Li(t))return[];return Object.entries(e).flatMap(([o,n])=>{let i=r?`${r}.${o}`:o;if(!Object.prototype.hasOwnProperty.call(t,o))return Tu(o)?[]:[i];return fu(n,t[o],i)})}function My(e){if(!hu(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=Ay($y(e.requestedSchema),t),o=Pc(Jr.shape.requestedSchema,r);if(!o.success)throw new re(W.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${qy(r,o.error.message)}`);let n=fu(r,o.data);if(n.length>0)throw new re(W.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);let i=(o.data.required??[]).filter((s)=>!Object.prototype.hasOwnProperty.call(o.data.properties,s));if(i.length>0)throw new re(W.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function jy(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState==="string";if(!t&&!r)throw TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}var oP=Object.assign(jy,{elicit(e){try{return{method:"elicitation/create",params:My(e)}}catch(t){throw t instanceof re?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"}}});var Ly=!0,Uy=10,Zy=250;function bg(e){return{autoFulfill:e?.autoFulfill??Ly,maxRounds:e?.maxRounds??Uy}}function Dy(e,t,r){let o=t!==void 0&&Object.keys(t).length>0;if(!o&&r===void 0)return e;return{...e,...o&&{inputResponses:t},...r!==void 0&&{requestState:r}}}function Fy(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Hy(e,t){return new Promise((r,o)=>{if(t?.aborted){o(t.reason instanceof A?t.reason:new A(N.RequestTimeout,String(t.reason)));return}let n=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(n),o(t?.reason instanceof A?t.reason:new A(N.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",i,{once:!0})})}function Vy(e){let t=new AbortController,r=()=>t.abort(e?.reason);if(e?.addEventListener("abort",r,{once:!0}),e?.aborted)t.abort(e.reason);return{signal:t.signal,abort:(o)=>t.abort(o),dispose:()=>e?.removeEventListener("abort",r)}}async function Jy(e){let{config:t,method:r,originalParams:o,requestOptions:n,hooks:i,signal:s}=e,a=e.flowStartedAt??Date.now(),l=e.firstPayload,u=0;while(!0){if(u+=1,u>t.maxRounds)throw new A(N.InputRequiredRoundsExceeded,Fy(r,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:l.inputRequests,...l.requestState!==void 0&&{requestState:l.requestState}}});n.onprogress?.({progress:u,message:`Fulfilling input required by '${r}' (round ${u})`});let d=Object.entries(l.inputRequests??{}),m;if(d.length>0){let b=Vy(s);try{let y=await Promise.all(d.map(async([v,L])=>{try{return[v,await i.dispatchInputRequest(v,L,b.signal)]}catch(H){throw b.abort(H),H}}));m=Object.fromEntries(y)}finally{b.dispose()}}else await Hy(Zy,s);let f={...n.timeout!==void 0&&{timeout:n.timeout}};if(n.maxTotalTimeout!==void 0){let b=Date.now()-a,y=n.maxTotalTimeout-b;if(y<=0)throw new A(N.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:b});f.maxTotalTimeout=y}let g=await i.retry(Dy(o,m,l.requestState),f);if(pg(g)){l={inputRequests:g.inputRequests??{},...g.requestState!==void 0&&{requestState:g.requestState}};continue}return g}}var By=["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"],Wy={IdJagTokenExchangeResponseSchema:Ii,OAuthClientInformationFullSchema:Xo,OAuthClientInformationSchema:Ni,OAuthClientMetadataSchema:Oi,OAuthClientRegistrationErrorSchema:gc,OAuthErrorResponseSchema:Yo,OAuthMetadataSchema:Br,OAuthProtectedResourceMetadataSchema:Wo,OAuthTokenRevocationRequestSchema:Sc,OAuthTokensSchema:Go,OpenIdProviderDiscoveryMetadataSchema:Ko,OpenIdProviderMetadataSchema:Ci},yg={},vg={};function zg(e,t){let r=e.slice(0,-6);yg[r]=t,vg[r]=(o)=>t.safeParse(o).success}for(let e of By)zg(e,py[e]);for(let[e,t]of Object.entries(Wy))zg(e,t);var Ky=Object.freeze(yg),wg=Object.freeze(vg);function Gy(e){switch(e){case"initialize":case"notifications/initialized":return Ht(void 0);case"server/discover":return Ht(xc);default:return}}var Tc=60000,Yy=[Mt,vo,Or,zo],Xy=["inputResponses","requestState"];function Lf(e,t){let r=e.params;if(!ji(r))return{message:e,lifted:{}};let o=r._meta,n=ji(o)?Yy.filter((l)=>(l in o)):[],i=t==="request"?Xy.filter((l)=>(l in r)):[];if(n.length===0&&i.length===0)return{message:e,lifted:{}};let s={},a={...r};if(n.length>0&&ji(o)){let l={},u={...o};for(let d of n)l[d]=o[d],delete u[d];if(s.envelope=l,Object.keys(u).length>0)a._meta=u;else delete a._meta}for(let l of i){if(l==="inputResponses")s.inputResponses=a[l];if(l==="requestState")s.requestState=a[l];delete a[l]}return{message:{...e,params:a},lifted:s}}function Uf(e,t){let r=e.validateResult(t,void 0);if(!r.ok&&r.reason==="not-in-era")return;return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let n=e.validateResult(t,o);if(n.ok)return{value:n.value};return{issues:[{message:n.reason==="invalid"?n.message:`not-in-era: ${t}`}]}}}}}function Eu(e){return()=>e}var Qy=Eu(void 0),ev,Ec=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{ev=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Ja,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){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new A(N.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){if(e.params.requestId===void 0)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,o,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:n,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new A(N.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=(n)=>{r?.(n),this._onerror(n)};let o=this._transport?.onmessage;this._transport.onmessage=(n,i)=>{if(o?.(n,i),en(n)||tn(n))this._onresponse(n);else if(Gr(n))this._onrequest(n,i);else if(dg(n))this._onnotification(n,i);else this._onerror(Error(`Unknown message type: ${JSON.stringify(n)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new A(N.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(r);for(let o of t.values())o.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=Lf(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let s=Of(t.classification);if(s!==o.era){this._onerror(Error(`Era mismatch on inbound notification '${r.method}': classified as ${s} but this instance serves ${o.era}`));return}}if(lu(r.method)&&!o.hasNotificationMethod(r.method))return;let n=this._notificationHandlers.get(r.method),i=this.fallbackNotificationHandler;if(n===void 0&&i===void 0)return;Promise.resolve().then(()=>n===void 0?i(r):n(r,o)).catch((s)=>this._onerror(Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e,t){let{message:r,lifted:o}=Lf(e,"request"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let i=this._transport,s=(y,v,L)=>{let H={jsonrpc:"2.0",id:r.id,error:{code:y,message:v,...L!==void 0&&{data:L}}};i?.send(H).catch((x)=>this._onerror(Error(`Failed to send an error response: ${x}`)))};if(t?.classification!==void 0){let y=Of(t.classification);if(y!==n.era){this._onerror(Error(`Era mismatch on inbound request '${r.method}': classified as ${y} but this instance serves ${n.era}`));let v=t.classification.revision??y;s(W.UnsupportedProtocolVersion,`Unsupported protocol version: ${v}`,{supported:this._supportedProtocolVersions,requested:v});return}}if(cu(r.method)&&!n.hasRequestMethod(r.method)&&!(Nf(r.method)&&this._customSchemaRequestMethods.has(r.method))){s(W.MethodNotFound,"Method not found");return}let a=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(a===void 0){s(W.MethodNotFound,"Method not found");return}let l=n.checkInboundEnvelope(o);if(l!==void 0){s(W.InvalidParams,l);return}let u=(y,v)=>this._notificationViaCodec(this._resolveOutboundCodec(y.method),y,{...v,relatedRequestId:r.id}),d=(y,v,L)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(y.method),y,v,{...L,relatedRequestId:r.id}),m=new AbortController;this._requestHandlerAbortControllers.set(r.id,m);let f=o.inputResponses===void 0?void 0:tv(o.inputResponses),g={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:o.requestState===void 0?Qy:Eu(o.requestState),signal:m.signal,send:(y,v,L)=>{let H=this._resolveOutboundCodec(y.method);if(this._assertOutboundRequestInEra(H,y.method),hu(v))return d(y,v,L);let x=Uf(H,y.method);if(x===void 0)throw TypeError(`'${y.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return d(y,x,v)},notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},b=this.buildContext(g,t);Promise.resolve().then(()=>a(r,b)).then(async(y)=>{if(m.signal.aborted)return;let v;try{v=n.encodeResult(r.method,y,this._outboundServerInfo())}catch(H){this._onerror(Error(`Failed to encode result for ${r.method}: ${H}`)),s(W.InternalError,"Internal error");return}let L={result:v,jsonrpc:"2.0",id:r.id};await i?.send(L)},async(y)=>{if(m.signal.aborted)return;let v=Number.isSafeInteger(y.code)?y.code:W.InternalError,L={jsonrpc:"2.0",id:r.id,error:{code:n.encodeErrorCode(v),message:y.message??"Internal error",...y.data!==void 0&&{data:y.data}}};await i?.send(L)}).catch((y)=>this._onerror(Error(`Failed to send response: ${y}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(r.id)===m)this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,o=Number(t),n=this._progressHandlers.get(o);if(!n){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(a){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(a);return}n(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),en(e))r(e);else r(re.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let o=this._resolveOutboundCodec(e.method);if(hu(t)){if(!Nf(e.method))this._assertOutboundRequestInEra(o,e.method);return this._requestWithSchemaViaCodec(o,e,t,r)}this._assertOutboundRequestInEra(o,e.method);let n=Uf(o,e.method);if(n===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(o,e,n,t)}_negotiatedWireCodec(){return Ht(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=Gy(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(cu(t)&&!e.hasRequestMethod(t))throw new A(N.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,r)}_requestWithSchemaViaCodec(e,t,r,o){let{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s,headers:a}=o??{},l=Date.now(),u,d;return new Promise((m,f)=>{let g=(w)=>{f(w)};if(!this._transport){g(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(w){g(w);return}if(o?.signal?.aborted){let w=o.signal.reason;throw w instanceof A?w:new A(N.RequestTimeout,String(w))}let b=e.era===xc&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,y=this._requestMessageId++;d=y;let v={...t,jsonrpc:"2.0",id:y};if(o?.onprogress)this._progressHandlers.set(y,o.onprogress),v.params={...t.params,_meta:{...t.params?._meta,progressToken:y}};let L=this._envelopeOutbound(v),H=!1,x=(w)=>{if(H)return;if(this._progressHandlers.delete(y),b===void 0){if(t.method!=="initialize")this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:y,reason:String(w)}}),{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s}).catch((D)=>this._onerror(Error(`Failed to send cancellation: ${D}`)))}else b.abort();f(w instanceof A?w:new A(N.RequestTimeout,String(w)))};this._responseHandlers.set(y,(w)=>{if(o?.signal?.aborted)return;if(H=!0,w instanceof Error)return f(w);let D;try{D=e.decodeResult(t.method,w.result)}catch(Y){return f(Y instanceof Error?Y:Error(String(Y)))}if(D.kind==="invalid")return f(D.error);if(D.kind==="input_required"){if(o?.allowInputRequired===!0)return m(sv(D));let Y={codec:e,request:t,resultSchema:r,options:o,flowStartedAt:l,retry:(ue,$e)=>this._requestWithSchemaViaCodec(e,ue===void 0?{method:t.method}:{method:t.method,params:ue},r,$e)};return m(this._resolveNonCompleteResult(D,Y))}let X=D.result;uu(r,X).then((Y)=>{if(Y.success)m(Y.data);else f(new A(N.InvalidResult,`Invalid result for ${t.method}: ${Y.error}`))},f)}),u=()=>x(o?.signal?.reason),o?.signal?.addEventListener("abort",u,{once:!0});let Z=o?.timeout??Tc,R=()=>x(new A(N.RequestTimeout,"Request timed out",{timeout:Z}));this._setupTimeout(y,Z,o?.maxTotalTimeout,R,o?.resetTimeoutOnProgress??!1),this._transport.send(L,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:s,headers:a,requestSignal:b?.signal}).catch((w)=>{this._progressHandlers.delete(y),f(w)})}).finally(()=>{if(u)o?.signal?.removeEventListener("abort",u);if(d!==void 0)this._responseHandlers.delete(d),this._cleanupTimeout(d)})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new A(N.NotConnected,"Not connected");if(lu(t.method)&&!e.hasNotificationMethod(t.method))throw new A(N.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);let o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&r?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;this._transport?.send(o,r).catch((n)=>this._onerror(n))});return}await this._transport.send(o,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let o;if(typeof t==="function"){if(!cu(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=(n,i)=>{let s=this._negotiatedWireCodec(),a=s.validateRequest(e,n);if(!a.ok&&a.reason==="not-in-era")a=s.validateInputRequest(e,n);if(!a.ok){if(a.reason==="not-in-era")throw new re(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(a.message)}return Promise.resolve(t(a.value,i))}}else if(r)o=async(n,i)=>{let s=await uu(t.params,{...n.params});if(!s.success)throw new re(W.InvalidParams,`Invalid params for ${e}: ${s.error}`);return r(s.data,i)};else throw TypeError("setRequestHandler: handler is required");if(typeof t==="function")this._customSchemaRequestMethods.delete(e);else this._customSchemaRequestMethods.add(e);this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t==="function"){if(!lu(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,n)=>{let i=n.validateNotification(e,o);if(!i.ok){if(i.reason==="not-in-era")throw new re(W.InternalError,`No wire schema for ${e} in the resolved era`);throw Error(i.message)}return Promise.resolve(t(i.value))});return}if(!r)throw TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async(o)=>{let n=await uu(t.params,{...o.params});if(!n.success)throw new re(W.InvalidParams,`Invalid params for notification ${e}: ${n.error}`);await r(n.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function ji(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Rg(e,t){let r={...e};for(let o in t){let n=o,i=t[n];if(i===void 0)continue;let s=r[n];r[n]=ji(s)&&ji(i)?{...s,...i}:i}return r}function wc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function tv(e){let t={},r=[];if(!wc(e))return{accepted:t,droppedKeys:r};for(let[o,n]of Object.entries(e)){if(!wc(n)||"method"in n||"result"in n){r.push(o);continue}t[o]=n}return{accepted:t,droppedKeys:r}}function Zf(e){throw new A(N.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function rv(e,t,r,o,n){return{sessionId:n,mcpReq:{id:e,method:t,_meta:r?._meta,requestState:Eu(void 0),signal:o,send:()=>Zf("send"),notify:()=>Zf("notify")}}}async function ov(e,t,r,o,n){if(!wc(o)||typeof o.method!=="string")throw new A(N.InvalidResult,`Invalid input request '${r}': each inputRequests entry must be an embedded request object with a method`,{key:r});let i=o.method;if(!t.hasInputRequestMethod(i))throw new A(N.InvalidResult,`Invalid input request '${r}': '${i}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:r,method:i});let s=e.getRequestHandler(i);if(s===void 0)throw new A(N.CapabilityNotSupported,`Cannot fulfil input request '${r}': no handler is registered for '${i}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:r,method:i});let a=wc(o.params)?o.params:void 0;return await s({jsonrpc:"2.0",id:r,method:i,...a!==void 0&&{params:a}},e.buildContext(rv(r,i,a,n,e.sessionId)))}function nv(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function xg(e,t,r,o){let{codec:n,request:i,options:s,flowStartedAt:a}=o,l={inputRequests:r.inputRequests,...r.requestState!==void 0&&{requestState:r.requestState}},u={dispatchInputRequest:(d,m,f)=>ov(e,n,d,m,f),retry:(d,m)=>o.retry(d,nv(s,m))};return Jy({config:t,method:i.method,originalParams:i.params,firstPayload:l,flowStartedAt:a,signal:s?.signal,requestOptions:{...s?.timeout!==void 0&&{timeout:s.timeout},...s?.maxTotalTimeout!==void 0&&{maxTotalTimeout:s.maxTotalTimeout},...s?.onprogress!==void 0&&{onprogress:s.onprogress}},hooks:u})}function sv(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}/*!
|
|
66
66
|
* content-type
|
|
67
67
|
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
68
68
|
* MIT Licensed
|
|
69
|
-
*/var Jy=nd((e)=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=n;function n(a){if(!a)throw TypeError("argument string is required");var l=typeof a==="object"?i(a):a;if(typeof l!=="string")throw TypeError("argument string is required to be a string");var u=l.indexOf(";"),d=u!==-1?l.slice(0,u).trim():l.trim();if(!o.test(d))throw TypeError("invalid media type");var m=new s(d.toLowerCase());if(u!==-1){var f,S,b;t.lastIndex=u;while(S=t.exec(l)){if(S.index!==u)throw TypeError("invalid parameter format");if(u+=S[0].length,f=S[1].toLowerCase(),b=S[2],b.charCodeAt(0)===34){if(b=b.slice(1,-1),b.indexOf("\\")!==-1)b=b.replace(r,"$1")}m.parameters[f]=b}if(u!==l.length)throw TypeError("invalid parameter format")}return m}function i(a){var l;if(typeof a.getHeader==="function")l=a.getHeader("content-type");else if(typeof a.headers==="object")l=a.headers&&a.headers["content-type"];if(typeof l!=="string")throw TypeError("content-type header is missing from object");return l}function s(a){this.parameters=Object.create(null),this.type=a}}),By=id(Jy(),1);function fg(e){if(!e)return;try{return By.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();if(t===""||e.slice(t.length).includes(","))return;return t}}function Cf(e){if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Array.isArray(e))return Object.fromEntries(e);return{...e}}function gg(e=fetch,t){if(!t)return e;return async(r,o)=>e(r,{...t,...o,headers:o?.headers?{...Cf(t.headers),...Cf(o.headers)}:t.headers})}var Wy=new Set([301,302,303,307,308]),Ky=5;function Gy(e,t){if(e.protocol===t.protocol&&e.host===t.host)return!0;return e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}function Sg(e,t){let r=Wy.has(t.status)?t.headers?.get("location"):void 0;if(!r)return;try{return new URL(r,e)}catch{return}}var _g=new WeakSet;function bg(e){let t=(r,o)=>e(r,o);return _g.add(t),t}function Ni(e){if(_g.has(e))return e;return async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let o=(r?.method??"GET").toUpperCase(),n=t;for(let i=0;;i++){let s=await e(n,{...r,redirect:"manual"}),a=Sg(n,s);if(!a||i===Ky)return s;let l=new URL(n),u=o==="GET"||s.status===307||s.status===308,d=!(a.username||a.password)||a.username===l.username&&a.password===l.password;if(!u||!d||!Gy(l,a))return s;await s.text?.().catch(()=>{}),n=a}}}function yg(e,t){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";let r=Sg(t.url||e,t);if(!r)return;if(r.username=r.password=r.search=r.hash="",r.protocol==="http:"&&new URL(t.url||e).protocol==="https:")return r.protocol="https:",`Redirect from https to plain http not followed; try ${r.href} as the endpoint`;return`Redirect to ${r.href} not followed; use that URL as the endpoint if it is the intended server`}function qi(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let o=e.length;if(o!==t.length)return!1;for(let n=0;n<o;n++)if(!qi(e[n],t[n]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)return!1;for(let i of o)if(!qi(e[i],t[i]))return!1;return!0}return e===t}function it(e){return encodeURI(Yy(e))}function Yy(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var Xy={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Qy={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},ev={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},tv=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 Hr(e,t=Object.create(null),r=tv,o=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let s=new URL(i,r.href);if(s.hash.length>1)t[s.href]=e;else if(s.hash="",o==="")r=s;else Hr(e,t,r)}}else if(e!==!0&&e!==!1)return t;let n=r.href+(o?"#"+o:"");if(t[n]!==void 0)throw Error(`Duplicate schema URI "${n}".`);if(t[n]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:n});if(e.$ref&&e.__absolute_ref__===void 0){let i=new URL(e.$ref,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=new URL(e.$recursiveRef,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=new URL("#"+e.$anchor,r.href);t[i.href]=e}for(let i in e){if(ev[i])continue;let s=`${o}/${it(i)}`,a=e[i];if(Array.isArray(a)){if(Xy[i]){let l=a.length;for(let u=0;u<l;u++)Hr(a[u],t,r,`${s}/${u}`)}}else if(Qy[i])for(let l in a)Hr(a[l],t,r,`${s}/${it(l)}`);else Hr(a,t,r,s)}return t}var rv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ov=[0,31,28,31,30,31,30,31,31,30,31,30,31],nv=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,sv=/^(?=.{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,iv=/^(?:[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,av=/^(?:(?:[^\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,cv=/^(?:(?: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,lv=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,uv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,dv=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,pv=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,hv=(e)=>{if(e[0]==='"')return!1;let[t,r,...o]=e.split("@");if(!t||!r||o.length!==0||t.length>64||r.length>253)return!1;if(t[0]==="."||t.endsWith(".")||t.includes(".."))return!1;if(!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))return!1;return r.split(".").every((n)=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(n))},mv=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,fv=/^((([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,gv=(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 zt(e){return e.test.bind(e)}var vg={date:zg,time:wg.bind(void 0,!1),"date-time":bv,duration:gv,uri:zv,"uri-reference":zt(iv),"uri-template":zt(av),url:zt(cv),email:hv,hostname:zt(sv),ipv4:zt(mv),ipv6:zt(fv),regex:Rv,uuid:zt(lv),"json-pointer":zt(uv),"json-pointer-uri-fragment":zt(dv),"relative-json-pointer":zt(pv)};function Sv(e){return e%4===0&&(e%100!==0||e%400===0)}function zg(e){let t=e.match(rv);if(!t)return!1;let r=+t[1],o=+t[2],n=+t[3];return o>=1&&o<=12&&n>=1&&n<=(o==2&&Sv(r)?29:ov[o])}function wg(e,t){let r=t.match(nv);if(!r)return!1;let o=+r[1],n=+r[2],i=+r[3],s=!!r[5];return(o<=23&&n<=59&&i<=59||o==23&&n==59&&i==60)&&(!e||s)}var _v=/t|\s/i;function bv(e){let t=e.split(_v);return t.length==2&&zg(t[0])&&wg(!0,t[1])}var yv=/\/|:/,vv=/^(?:[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 zv(e){return yv.test(e)&&vv.test(e)}var wv=/[^\\]\\Z/;function Rv(e){if(wv.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function xv(e){let t=0,r=e.length,o=0,n;while(o<r)if(t++,n=e.charCodeAt(o++),n>=55296&&n<=56319&&o<r){if(n=e.charCodeAt(o),(n&64512)==56320)o++}return t}function he(e,t,r="2019-09",o=Hr(t),n=!0,i=null,s="#",a="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let u=typeof e,d;switch(u){case"boolean":case"number":case"string":d=u;break;case"object":if(e===null)d="null";else if(Array.isArray(e))d="array";else d="object";break;default:throw Error(`Instances of "${u}" type are not supported.`)}let{$ref:m,$recursiveRef:f,$recursiveAnchor:S,type:b,const:y,enum:v,required:U,not:H,anyOf:x,allOf:Z,oneOf:R,if:w,then:D,else:X,format:Y,properties:le,patternProperties:Ee,additionalProperties:te,unevaluatedProperties:ie,minProperties:ve,maxProperties:ke,propertyNames:ct,dependentRequired:qe,dependentSchemas:We,dependencies:lt,prefixItems:Ze,items:$e,additionalItems:Tt,unevaluatedItems:Et,contains:ut,minContains:Re,maxContains:Ce,minItems:Ie,maxItems:et,uniqueItems:lr,minimum:De,maximum:Fe,exclusiveMinimum:Ae,exclusiveMaximum:Ke,multipleOf:Ge,minLength:dt,maxLength:pt,pattern:Ht,__absolute_ref__:ht,__absolute_recursive_ref__:ur}=t,C=[];if(S===!0&&i===null)i=t;if(f==="#"){let V=i===null?o[ur]:i,q=`${a}/$recursiveRef`,G=he(e,i===null?t:i,r,o,n,V,s,q,l);if(!G.valid)C.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:q,error:"A subschema had errors."},...G.errors)}if(m!==void 0){let V=o[ht||m];if(V===void 0){let I=`Unresolved $ref "${m}".`;if(ht&&ht!==m)I+=` Absolute URI "${ht}".`;throw I+=`
|
|
69
|
+
*/var iv=fd((e)=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=n;function n(a){if(!a)throw TypeError("argument string is required");var l=typeof a==="object"?i(a):a;if(typeof l!=="string")throw TypeError("argument string is required to be a string");var u=l.indexOf(";"),d=u!==-1?l.slice(0,u).trim():l.trim();if(!o.test(d))throw TypeError("invalid media type");var m=new s(d.toLowerCase());if(u!==-1){var f,g,b;t.lastIndex=u;while(g=t.exec(l)){if(g.index!==u)throw TypeError("invalid parameter format");if(u+=g[0].length,f=g[1].toLowerCase(),b=g[2],b.charCodeAt(0)===34){if(b=b.slice(1,-1),b.indexOf("\\")!==-1)b=b.replace(r,"$1")}m.parameters[f]=b}if(u!==l.length)throw TypeError("invalid parameter format")}return m}function i(a){var l;if(typeof a.getHeader==="function")l=a.getHeader("content-type");else if(typeof a.headers==="object")l=a.headers&&a.headers["content-type"];if(typeof l!=="string")throw TypeError("content-type header is missing from object");return l}function s(a){this.parameters=Object.create(null),this.type=a}}),av=Sd(iv(),1);function Pg(e){if(!e)return;try{return av.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();if(t===""||e.slice(t.length).includes(","))return;return t}}function Df(e){if(!e)return{};if(e instanceof Headers)return Object.fromEntries(e.entries());if(Array.isArray(e))return Object.fromEntries(e);return{...e}}function Tg(e=fetch,t){if(!t)return e;return async(r,o)=>e(r,{...t,...o,headers:o?.headers?{...Df(t.headers),...Df(o.headers)}:t.headers})}var cv=new Set([301,302,303,307,308]),lv=5;function uv(e,t){if(e.protocol===t.protocol&&e.host===t.host)return!0;return e.protocol==="http:"&&t.protocol==="https:"&&e.hostname===t.hostname&&!e.port&&!t.port}function Eg(e,t){let r=cv.has(t.status)?t.headers?.get("location"):void 0;if(!r)return;try{return new URL(r,e)}catch{return}}var kg=new WeakSet;function $g(e){let t=(r,o)=>e(r,o);return kg.add(t),t}function Zi(e){if(kg.has(e))return e;return async(t,r)=>{if(r?.redirect==="error"||r?.redirect==="manual")return e(t,r);let o=(r?.method??"GET").toUpperCase(),n=t;for(let i=0;;i++){let s=await e(n,{...r,redirect:"manual"}),a=Eg(n,s);if(!a||i===lv)return s;let l=new URL(n),u=o==="GET"||s.status===307||s.status===308,d=!(a.username||a.password)||a.username===l.username&&a.password===l.password;if(!u||!d||!uv(l,a))return s;await s.text?.().catch(()=>{}),n=a}}}function Cg(e,t){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose where it points";let r=Eg(t.url||e,t);if(!r)return;if(r.username=r.password=r.search=r.hash="",r.protocol==="http:"&&new URL(t.url||e).protocol==="https:")return r.protocol="https:",`Redirect from https to plain http not followed; try ${r.href} as the endpoint`;return`Redirect to ${r.href} not followed; use that URL as the endpoint if it is the intended server`}function Di(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let o=e.length;if(o!==t.length)return!1;for(let n=0;n<o;n++)if(!Di(e[n],t[n]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let o=Object.keys(e),n=Object.keys(t);if(o.length!==n.length)return!1;for(let i of o)if(!Di(e[i],t[i]))return!1;return!0}return e===t}function dt(e){return encodeURI(dv(e))}function dv(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var pv={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},hv={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},mv={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},fv=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 Yr(e,t=Object.create(null),r=fv,o=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let s=new URL(i,r.href);if(s.hash.length>1)t[s.href]=e;else if(s.hash="",o==="")r=s;else Yr(e,t,r)}}else if(e!==!0&&e!==!1)return t;let n=r.href+(o?"#"+o:"");if(t[n]!==void 0)throw Error(`Duplicate schema URI "${n}".`);if(t[n]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:n});if(e.$ref&&e.__absolute_ref__===void 0){let i=new URL(e.$ref,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=new URL(e.$recursiveRef,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=new URL("#"+e.$anchor,r.href);t[i.href]=e}for(let i in e){if(mv[i])continue;let s=`${o}/${dt(i)}`,a=e[i];if(Array.isArray(a)){if(pv[i]){let l=a.length;for(let u=0;u<l;u++)Yr(a[u],t,r,`${s}/${u}`)}}else if(hv[i])for(let l in a)Yr(a[l],t,r,`${s}/${dt(l)}`);else Yr(a,t,r,s)}return t}var gv=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Sv=[0,31,28,31,30,31,30,31,31,30,31,30,31],_v=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,bv=/^(?=.{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,yv=/^(?:[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,vv=/^(?:(?:[^\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,zv=/^(?:(?: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,wv=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Rv=/^(?:\/(?:[^~/]|~0|~1)*)*$/,xv=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Pv=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Tv=(e)=>{if(e[0]==='"')return!1;let[t,r,...o]=e.split("@");if(!t||!r||o.length!==0||t.length>64||r.length>253)return!1;if(t[0]==="."||t.endsWith(".")||t.includes(".."))return!1;if(!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))return!1;return r.split(".").every((n)=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(n))},Ev=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,kv=/^((([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,$v=(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 Et(e){return e.test.bind(e)}var Ig={date:Og,time:Ng.bind(void 0,!1),"date-time":Ov,duration:$v,uri:qv,"uri-reference":Et(yv),"uri-template":Et(vv),url:Et(zv),email:Tv,hostname:Et(bv),ipv4:Et(Ev),ipv6:Et(kv),regex:jv,uuid:Et(wv),"json-pointer":Et(Rv),"json-pointer-uri-fragment":Et(xv),"relative-json-pointer":Et(Pv)};function Cv(e){return e%4===0&&(e%100!==0||e%400===0)}function Og(e){let t=e.match(gv);if(!t)return!1;let r=+t[1],o=+t[2],n=+t[3];return o>=1&&o<=12&&n>=1&&n<=(o==2&&Cv(r)?29:Sv[o])}function Ng(e,t){let r=t.match(_v);if(!r)return!1;let o=+r[1],n=+r[2],i=+r[3],s=!!r[5];return(o<=23&&n<=59&&i<=59||o==23&&n==59&&i==60)&&(!e||s)}var Iv=/t|\s/i;function Ov(e){let t=e.split(Iv);return t.length==2&&Og(t[0])&&Ng(!0,t[1])}var Nv=/\/|:/,Av=/^(?:[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 qv(e){return Nv.test(e)&&Av.test(e)}var Mv=/[^\\]\\Z/;function jv(e){if(Mv.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function Lv(e){let t=0,r=e.length,o=0,n;while(o<r)if(t++,n=e.charCodeAt(o++),n>=55296&&n<=56319&&o<r){if(n=e.charCodeAt(o),(n&64512)==56320)o++}return t}function me(e,t,r="2019-09",o=Yr(t),n=!0,i=null,s="#",a="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let u=typeof e,d;switch(u){case"boolean":case"number":case"string":d=u;break;case"object":if(e===null)d="null";else if(Array.isArray(e))d="array";else d="object";break;default:throw Error(`Instances of "${u}" type are not supported.`)}let{$ref:m,$recursiveRef:f,$recursiveAnchor:g,type:b,const:y,enum:v,required:L,not:H,anyOf:x,allOf:Z,oneOf:R,if:w,then:D,else:X,format:Y,properties:ue,patternProperties:$e,additionalProperties:oe,unevaluatedProperties:ae,minProperties:we,maxProperties:Ce,propertyNames:mt,dependentRequired:Me,dependentSchemas:Ye,dependencies:ft,prefixItems:Fe,items:Ie,additionalItems:It,unevaluatedItems:Ot,contains:gt,minContains:Pe,maxContains:Oe,minItems:Ne,maxItems:st,uniqueItems:gr,minimum:He,maximum:Ve,exclusiveMinimum:je,exclusiveMaximum:Xe,multipleOf:Qe,minLength:St,maxLength:_t,pattern:Yt,__absolute_ref__:bt,__absolute_recursive_ref__:Sr}=t,I=[];if(g===!0&&i===null)i=t;if(f==="#"){let V=i===null?o[Sr]:i,q=`${a}/$recursiveRef`,G=me(e,i===null?t:i,r,o,n,V,s,q,l);if(!G.valid)I.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:q,error:"A subschema had errors."},...G.errors)}if(m!==void 0){let V=o[bt||m];if(V===void 0){let O=`Unresolved $ref "${m}".`;if(bt&&bt!==m)O+=` Absolute URI "${bt}".`;throw O+=`
|
|
70
70
|
Known schemas:
|
|
71
71
|
- ${Object.keys(o).join(`
|
|
72
|
-
- `)}`,Error(I)}let q=`${a}/$ref`,G=he(e,V,r,o,n,i,s,q,l);if(!G.valid)C.push({instanceLocation:s,keyword:"$ref",keywordLocation:q,error:"A subschema had errors."},...G.errors);if(r==="4"||r==="7")return{valid:C.length===0,errors:C}}if(Array.isArray(b)){let V=b.length,q=!1;for(let G=0;G<V;G++)if(d===b[G]||b[G]==="integer"&&d==="number"&&e%1===0&&e===e){q=!0;break}if(!q)C.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b.join('", "')}".`})}else if(b==="integer"){if(d!=="number"||e%1||e!==e)C.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`})}else if(b!==void 0&&d!==b)C.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`});if(y!==void 0){if(d==="object"||d==="array"){if(!qi(e,y))C.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}else if(e!==y)C.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}if(v!==void 0){if(d==="object"||d==="array"){if(!v.some((V)=>qi(e,V)))C.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}else if(!v.some((V)=>e===V))C.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}if(H!==void 0){let V=`${a}/not`;if(he(e,H,r,o,n,i,s,V).valid)C.push({instanceLocation:s,keyword:"not",keywordLocation:V,error:'Instance matched "not" schema.'})}let mt=[];if(x!==void 0){let V=`${a}/anyOf`,q=C.length,G=!1;for(let I=0;I<x.length;I++){let k=x[I],B=Object.create(l),J=he(e,k,r,o,n,S===!0?i:null,s,`${V}/${I}`,B);if(C.push(...J.errors),G=G||J.valid,J.valid)mt.push(B)}if(G)C.length=q;else C.splice(q,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:V,error:"Instance does not match any subschemas."})}if(Z!==void 0){let V=`${a}/allOf`,q=C.length,G=!0;for(let I=0;I<Z.length;I++){let k=Z[I],B=Object.create(l),J=he(e,k,r,o,n,S===!0?i:null,s,`${V}/${I}`,B);if(C.push(...J.errors),G=G&&J.valid,J.valid)mt.push(B)}if(G)C.length=q;else C.splice(q,0,{instanceLocation:s,keyword:"allOf",keywordLocation:V,error:"Instance does not match every subschema."})}if(R!==void 0){let V=`${a}/oneOf`,q=C.length,G=R.filter((I,k)=>{let B=Object.create(l),J=he(e,I,r,o,n,S===!0?i:null,s,`${V}/${k}`,B);if(C.push(...J.errors),J.valid)mt.push(B);return J.valid}).length;if(G===1)C.length=q;else C.splice(q,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:V,error:`Instance does not match exactly one subschema (${G} matches).`})}if(d==="object"||d==="array")Object.assign(l,...mt);if(w!==void 0){let V=`${a}/if`;if(he(e,w,r,o,n,i,s,V,l).valid){if(D!==void 0){let q=he(e,D,r,o,n,i,s,`${a}/then`,l);if(!q.valid)C.push({instanceLocation:s,keyword:"if",keywordLocation:V,error:'Instance does not match "then" schema.'},...q.errors)}}else if(X!==void 0){let q=he(e,X,r,o,n,i,s,`${a}/else`,l);if(!q.valid)C.push({instanceLocation:s,keyword:"if",keywordLocation:V,error:'Instance does not match "else" schema.'},...q.errors)}}if(d==="object"){if(U!==void 0){for(let I of U)if(!(I in e))C.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${I}".`})}let V=Object.keys(e);if(ve!==void 0&&V.length<ve)C.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${ve} properties.`});if(ke!==void 0&&V.length>ke)C.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${ke} properties.`});if(ct!==void 0){let I=`${a}/propertyNames`;for(let k in e){let B=`${s}/${it(k)}`,J=he(k,ct,r,o,n,i,B,I);if(!J.valid)C.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:I,error:`Property name "${k}" does not match schema.`},...J.errors)}}if(qe!==void 0){let I=`${a}/dependantRequired`;for(let k in qe)if(k in e){let B=qe[k];for(let J of B)if(!(J in e))C.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:I,error:`Instance has "${k}" but does not have "${J}".`})}}if(We!==void 0)for(let I in We){let k=`${a}/dependentSchemas`;if(I in e){let B=he(e,We[I],r,o,n,i,s,`${k}/${it(I)}`,l);if(!B.valid)C.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:k,error:`Instance has "${I}" but does not match dependant schema.`},...B.errors)}}if(lt!==void 0){let I=`${a}/dependencies`;for(let k in lt)if(k in e){let B=lt[k];if(Array.isArray(B)){for(let J of B)if(!(J in e))C.push({instanceLocation:s,keyword:"dependencies",keywordLocation:I,error:`Instance has "${k}" but does not have "${J}".`})}else{let J=he(e,B,r,o,n,i,s,`${I}/${it(k)}`);if(!J.valid)C.push({instanceLocation:s,keyword:"dependencies",keywordLocation:I,error:`Instance has "${k}" but does not match dependant schema.`},...J.errors)}}}let q=Object.create(null),G=!1;if(le!==void 0){let I=`${a}/properties`;for(let k in le){if(!(k in e))continue;let B=`${s}/${it(k)}`,J=he(e[k],le[k],r,o,n,i,B,`${I}/${it(k)}`);if(J.valid)l[k]=q[k]=!0;else if(G=n,C.push({instanceLocation:s,keyword:"properties",keywordLocation:I,error:`Property "${k}" does not match schema.`},...J.errors),G)break}}if(!G&&Ee!==void 0){let I=`${a}/patternProperties`;for(let k in Ee){let B=new RegExp(k,"u"),J=Ee[k];for(let ge in e){if(!B.test(ge))continue;let dr=`${s}/${it(ge)}`,ft=he(e[ge],J,r,o,n,i,dr,`${I}/${it(k)}`);if(ft.valid)l[ge]=q[ge]=!0;else G=n,C.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:I,error:`Property "${ge}" matches pattern "${k}" but does not match associated schema.`},...ft.errors)}}}if(!G&&te!==void 0){let I=`${a}/additionalProperties`;for(let k in e){if(q[k])continue;let B=`${s}/${it(k)}`,J=he(e[k],te,r,o,n,i,B,I);if(J.valid)l[k]=!0;else G=n,C.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:I,error:`Property "${k}" does not match additional properties schema.`},...J.errors)}}else if(!G&&ie!==void 0){let I=`${a}/unevaluatedProperties`;for(let k in e)if(!l[k]){let B=`${s}/${it(k)}`,J=he(e[k],ie,r,o,n,i,B,I);if(J.valid)l[k]=!0;else C.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:I,error:`Property "${k}" does not match unevaluated properties schema.`},...J.errors)}}}else if(d==="array"){if(et!==void 0&&e.length>et)C.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${et}).`});if(Ie!==void 0&&e.length<Ie)C.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Ie}).`});let V=e.length,q=0,G=!1;if(Ze!==void 0){let I=`${a}/prefixItems`,k=Math.min(Ze.length,V);for(;q<k;q++){let B=he(e[q],Ze[q],r,o,n,i,`${s}/${q}`,`${I}/${q}`);if(l[q]=!0,!B.valid){if(G=n,C.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:I,error:"Items did not match schema."},...B.errors),G)break}}}if($e!==void 0){let I=`${a}/items`;if(Array.isArray($e)){let k=Math.min($e.length,V);for(;q<k;q++){let B=he(e[q],$e[q],r,o,n,i,`${s}/${q}`,`${I}/${q}`);if(l[q]=!0,!B.valid){if(G=n,C.push({instanceLocation:s,keyword:"items",keywordLocation:I,error:"Items did not match schema."},...B.errors),G)break}}}else for(;q<V;q++){let k=he(e[q],$e,r,o,n,i,`${s}/${q}`,I);if(l[q]=!0,!k.valid){if(G=n,C.push({instanceLocation:s,keyword:"items",keywordLocation:I,error:"Items did not match schema."},...k.errors),G)break}}if(!G&&Tt!==void 0){let k=`${a}/additionalItems`;for(;q<V;q++){let B=he(e[q],Tt,r,o,n,i,`${s}/${q}`,k);if(l[q]=!0,!B.valid)G=n,C.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:k,error:"Items did not match additional items schema."},...B.errors)}}}if(ut!==void 0)if(V===0&&Re===void 0)C.push({instanceLocation:s,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Re!==void 0&&V<Re)C.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${V}) than minContains (${Re}).`});else{let I=`${a}/contains`,k=C.length,B=0;for(let J=0;J<V;J++){let ge=he(e[J],ut,r,o,n,i,`${s}/${J}`,I);if(ge.valid)l[J]=!0,B++;else C.push(...ge.errors)}if(B>=(Re||0))C.length=k;if(Re===void 0&&Ce===void 0&&B===0)C.splice(k,0,{instanceLocation:s,keyword:"contains",keywordLocation:I,error:"Array does not contain item matching schema."});else if(Re!==void 0&&B<Re)C.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Re} items matching schema. Only ${B} items were found.`});else if(Ce!==void 0&&B>Ce)C.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Ce} items matching schema. ${B} items were found.`})}if(!G&&Et!==void 0){let I=`${a}/unevaluatedItems`;for(;q<V;q++){if(l[q])continue;let k=he(e[q],Et,r,o,n,i,`${s}/${q}`,I);if(l[q]=!0,!k.valid)C.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:I,error:"Items did not match unevaluated items schema."},...k.errors)}}if(lr)for(let I=0;I<V;I++){let k=e[I],B=typeof k==="object"&&k!==null;for(let J=0;J<V;J++){if(I===J)continue;let ge=e[J];if(k===ge||B&&typeof ge==="object"&&ge!==null&&qi(k,ge))C.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${I} and ${J}.`}),I=Number.MAX_SAFE_INTEGER,J=Number.MAX_SAFE_INTEGER}}}else if(d==="number"){if(r==="4"){if(De!==void 0&&(Ae===!0&&e<=De||e<De))C.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Ae?"or equal to ":""} ${De}.`});if(Fe!==void 0&&(Ke===!0&&e>=Fe||e>Fe))C.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Ke?"or equal to ":""} ${Fe}.`})}else{if(De!==void 0&&e<De)C.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${De}.`});if(Fe!==void 0&&e>Fe)C.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Fe}.`});if(Ae!==void 0&&e<=Ae)C.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${Ae}.`});if(Ke!==void 0&&e>=Ke)C.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ke}.`})}if(Ge!==void 0){let V=e%Ge;if(Math.abs(0-V)>=0.00000011920929&&Math.abs(Ge-V)>=0.00000011920929)C.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Ge}.`})}}else if(d==="string"){let V=dt===void 0&&pt===void 0?0:xv(e);if(dt!==void 0&&V<dt)C.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${V} < ${dt}).`});if(pt!==void 0&&V>pt)C.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${V} > ${pt}).`});if(Ht!==void 0&&!new RegExp(Ht,"u").test(e))C.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(Y!==void 0&&vg[Y]&&!vg[Y](e))C.push({instanceLocation:s,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${Y}".`})}return{valid:C.length===0,errors:C}}var Pv=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=Hr(e)}validate(e){return he(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){if(t)e={...e,$id:t};Hr(e,this.lookup)}},bu=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=ld(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){let t=new Pv(e,this.draft??this._draftFor(e),this.shortcircuit);return(r)=>{let o=t.validate(r);return o.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:o.errors.map((n)=>`${n.instanceLocation}: ${n.error}`).join("; ")}}}};var Rg=!0;var yu;yu=globalThis.crypto;async function Tv(e){return(await yu).getRandomValues(new Uint8Array(e))}async function Ev(e){let r=Math.pow(2,8)-Math.pow(2,8)%66,o="";while(o.length<e){let n=await Tv(e-o.length);for(let i of n)if(i<r)o+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[i%66]}return o}async function kv(e){return await Ev(e)}async function $v(e){let t=await(await yu).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function vu(e){if(!e)e=43;if(e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await kv(e),r=await $v(t);return{code_verifier:t,code_challenge:r}}class vc extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}var xg=10,Cv=13,Vr=32;function zu(e){}function Eg(e){if(typeof e=="function")throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=zu,onError:r=zu,onRetry:o=zu,onComment:n,maxBufferSize:i}=e,s=[],a=0,l=!0,u,d="",m=0,f,S=!1;function b(R){if(S)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,R.charCodeAt(0)===239&&R.charCodeAt(1)===187&&R.charCodeAt(2)===191&&(R=R.slice(3))),s.length===0){let X=v(R);X!==""&&(s.push(X),a=X.length),y();return}if(R.indexOf(`
|
|
73
|
-
`)===-1&&R.indexOf("\r")===-1){s.push(R),a+=R.length,y();return}s.push(R);let w=s.join("");s.length=0,a=0;let D=v(w);D!==""&&(s.push(D),a=D.length),y()}function y(){i!==void 0&&(a+d.length<=i||(
|
|
72
|
+
- `)}`,Error(O)}let q=`${a}/$ref`,G=me(e,V,r,o,n,i,s,q,l);if(!G.valid)I.push({instanceLocation:s,keyword:"$ref",keywordLocation:q,error:"A subschema had errors."},...G.errors);if(r==="4"||r==="7")return{valid:I.length===0,errors:I}}if(Array.isArray(b)){let V=b.length,q=!1;for(let G=0;G<V;G++)if(d===b[G]||b[G]==="integer"&&d==="number"&&e%1===0&&e===e){q=!0;break}if(!q)I.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b.join('", "')}".`})}else if(b==="integer"){if(d!=="number"||e%1||e!==e)I.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`})}else if(b!==void 0&&d!==b)I.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${d}" is invalid. Expected "${b}".`});if(y!==void 0){if(d==="object"||d==="array"){if(!Di(e,y))I.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}else if(e!==y)I.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})}if(v!==void 0){if(d==="object"||d==="array"){if(!v.some((V)=>Di(e,V)))I.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}else if(!v.some((V)=>e===V))I.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})}if(H!==void 0){let V=`${a}/not`;if(me(e,H,r,o,n,i,s,V).valid)I.push({instanceLocation:s,keyword:"not",keywordLocation:V,error:'Instance matched "not" schema.'})}let yt=[];if(x!==void 0){let V=`${a}/anyOf`,q=I.length,G=!1;for(let O=0;O<x.length;O++){let C=x[O],B=Object.create(l),J=me(e,C,r,o,n,g===!0?i:null,s,`${V}/${O}`,B);if(I.push(...J.errors),G=G||J.valid,J.valid)yt.push(B)}if(G)I.length=q;else I.splice(q,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:V,error:"Instance does not match any subschemas."})}if(Z!==void 0){let V=`${a}/allOf`,q=I.length,G=!0;for(let O=0;O<Z.length;O++){let C=Z[O],B=Object.create(l),J=me(e,C,r,o,n,g===!0?i:null,s,`${V}/${O}`,B);if(I.push(...J.errors),G=G&&J.valid,J.valid)yt.push(B)}if(G)I.length=q;else I.splice(q,0,{instanceLocation:s,keyword:"allOf",keywordLocation:V,error:"Instance does not match every subschema."})}if(R!==void 0){let V=`${a}/oneOf`,q=I.length,G=R.filter((O,C)=>{let B=Object.create(l),J=me(e,O,r,o,n,g===!0?i:null,s,`${V}/${C}`,B);if(I.push(...J.errors),J.valid)yt.push(B);return J.valid}).length;if(G===1)I.length=q;else I.splice(q,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:V,error:`Instance does not match exactly one subschema (${G} matches).`})}if(d==="object"||d==="array")Object.assign(l,...yt);if(w!==void 0){let V=`${a}/if`;if(me(e,w,r,o,n,i,s,V,l).valid){if(D!==void 0){let q=me(e,D,r,o,n,i,s,`${a}/then`,l);if(!q.valid)I.push({instanceLocation:s,keyword:"if",keywordLocation:V,error:'Instance does not match "then" schema.'},...q.errors)}}else if(X!==void 0){let q=me(e,X,r,o,n,i,s,`${a}/else`,l);if(!q.valid)I.push({instanceLocation:s,keyword:"if",keywordLocation:V,error:'Instance does not match "else" schema.'},...q.errors)}}if(d==="object"){if(L!==void 0){for(let O of L)if(!(O in e))I.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${O}".`})}let V=Object.keys(e);if(we!==void 0&&V.length<we)I.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${we} properties.`});if(Ce!==void 0&&V.length>Ce)I.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${Ce} properties.`});if(mt!==void 0){let O=`${a}/propertyNames`;for(let C in e){let B=`${s}/${dt(C)}`,J=me(C,mt,r,o,n,i,B,O);if(!J.valid)I.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:O,error:`Property name "${C}" does not match schema.`},...J.errors)}}if(Me!==void 0){let O=`${a}/dependantRequired`;for(let C in Me)if(C in e){let B=Me[C];for(let J of B)if(!(J in e))I.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:O,error:`Instance has "${C}" but does not have "${J}".`})}}if(Ye!==void 0)for(let O in Ye){let C=`${a}/dependentSchemas`;if(O in e){let B=me(e,Ye[O],r,o,n,i,s,`${C}/${dt(O)}`,l);if(!B.valid)I.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:C,error:`Instance has "${O}" but does not match dependant schema.`},...B.errors)}}if(ft!==void 0){let O=`${a}/dependencies`;for(let C in ft)if(C in e){let B=ft[C];if(Array.isArray(B)){for(let J of B)if(!(J in e))I.push({instanceLocation:s,keyword:"dependencies",keywordLocation:O,error:`Instance has "${C}" but does not have "${J}".`})}else{let J=me(e,B,r,o,n,i,s,`${O}/${dt(C)}`);if(!J.valid)I.push({instanceLocation:s,keyword:"dependencies",keywordLocation:O,error:`Instance has "${C}" but does not match dependant schema.`},...J.errors)}}}let q=Object.create(null),G=!1;if(ue!==void 0){let O=`${a}/properties`;for(let C in ue){if(!(C in e))continue;let B=`${s}/${dt(C)}`,J=me(e[C],ue[C],r,o,n,i,B,`${O}/${dt(C)}`);if(J.valid)l[C]=q[C]=!0;else if(G=n,I.push({instanceLocation:s,keyword:"properties",keywordLocation:O,error:`Property "${C}" does not match schema.`},...J.errors),G)break}}if(!G&&$e!==void 0){let O=`${a}/patternProperties`;for(let C in $e){let B=new RegExp(C,"u"),J=$e[C];for(let _e in e){if(!B.test(_e))continue;let _r=`${s}/${dt(_e)}`,vt=me(e[_e],J,r,o,n,i,_r,`${O}/${dt(C)}`);if(vt.valid)l[_e]=q[_e]=!0;else G=n,I.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:O,error:`Property "${_e}" matches pattern "${C}" but does not match associated schema.`},...vt.errors)}}}if(!G&&oe!==void 0){let O=`${a}/additionalProperties`;for(let C in e){if(q[C])continue;let B=`${s}/${dt(C)}`,J=me(e[C],oe,r,o,n,i,B,O);if(J.valid)l[C]=!0;else G=n,I.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:O,error:`Property "${C}" does not match additional properties schema.`},...J.errors)}}else if(!G&&ae!==void 0){let O=`${a}/unevaluatedProperties`;for(let C in e)if(!l[C]){let B=`${s}/${dt(C)}`,J=me(e[C],ae,r,o,n,i,B,O);if(J.valid)l[C]=!0;else I.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:O,error:`Property "${C}" does not match unevaluated properties schema.`},...J.errors)}}}else if(d==="array"){if(st!==void 0&&e.length>st)I.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${st}).`});if(Ne!==void 0&&e.length<Ne)I.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Ne}).`});let V=e.length,q=0,G=!1;if(Fe!==void 0){let O=`${a}/prefixItems`,C=Math.min(Fe.length,V);for(;q<C;q++){let B=me(e[q],Fe[q],r,o,n,i,`${s}/${q}`,`${O}/${q}`);if(l[q]=!0,!B.valid){if(G=n,I.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:O,error:"Items did not match schema."},...B.errors),G)break}}}if(Ie!==void 0){let O=`${a}/items`;if(Array.isArray(Ie)){let C=Math.min(Ie.length,V);for(;q<C;q++){let B=me(e[q],Ie[q],r,o,n,i,`${s}/${q}`,`${O}/${q}`);if(l[q]=!0,!B.valid){if(G=n,I.push({instanceLocation:s,keyword:"items",keywordLocation:O,error:"Items did not match schema."},...B.errors),G)break}}}else for(;q<V;q++){let C=me(e[q],Ie,r,o,n,i,`${s}/${q}`,O);if(l[q]=!0,!C.valid){if(G=n,I.push({instanceLocation:s,keyword:"items",keywordLocation:O,error:"Items did not match schema."},...C.errors),G)break}}if(!G&&It!==void 0){let C=`${a}/additionalItems`;for(;q<V;q++){let B=me(e[q],It,r,o,n,i,`${s}/${q}`,C);if(l[q]=!0,!B.valid)G=n,I.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:C,error:"Items did not match additional items schema."},...B.errors)}}}if(gt!==void 0)if(V===0&&Pe===void 0)I.push({instanceLocation:s,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Pe!==void 0&&V<Pe)I.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${V}) than minContains (${Pe}).`});else{let O=`${a}/contains`,C=I.length,B=0;for(let J=0;J<V;J++){let _e=me(e[J],gt,r,o,n,i,`${s}/${J}`,O);if(_e.valid)l[J]=!0,B++;else I.push(..._e.errors)}if(B>=(Pe||0))I.length=C;if(Pe===void 0&&Oe===void 0&&B===0)I.splice(C,0,{instanceLocation:s,keyword:"contains",keywordLocation:O,error:"Array does not contain item matching schema."});else if(Pe!==void 0&&B<Pe)I.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Pe} items matching schema. Only ${B} items were found.`});else if(Oe!==void 0&&B>Oe)I.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Oe} items matching schema. ${B} items were found.`})}if(!G&&Ot!==void 0){let O=`${a}/unevaluatedItems`;for(;q<V;q++){if(l[q])continue;let C=me(e[q],Ot,r,o,n,i,`${s}/${q}`,O);if(l[q]=!0,!C.valid)I.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:O,error:"Items did not match unevaluated items schema."},...C.errors)}}if(gr)for(let O=0;O<V;O++){let C=e[O],B=typeof C==="object"&&C!==null;for(let J=0;J<V;J++){if(O===J)continue;let _e=e[J];if(C===_e||B&&typeof _e==="object"&&_e!==null&&Di(C,_e))I.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${O} and ${J}.`}),O=Number.MAX_SAFE_INTEGER,J=Number.MAX_SAFE_INTEGER}}}else if(d==="number"){if(r==="4"){if(He!==void 0&&(je===!0&&e<=He||e<He))I.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${je?"or equal to ":""} ${He}.`});if(Ve!==void 0&&(Xe===!0&&e>=Ve||e>Ve))I.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Xe?"or equal to ":""} ${Ve}.`})}else{if(He!==void 0&&e<He)I.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${He}.`});if(Ve!==void 0&&e>Ve)I.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${Ve}.`});if(je!==void 0&&e<=je)I.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${je}.`});if(Xe!==void 0&&e>=Xe)I.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Xe}.`})}if(Qe!==void 0){let V=e%Qe;if(Math.abs(0-V)>=0.00000011920929&&Math.abs(Qe-V)>=0.00000011920929)I.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Qe}.`})}}else if(d==="string"){let V=St===void 0&&_t===void 0?0:Lv(e);if(St!==void 0&&V<St)I.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${V} < ${St}).`});if(_t!==void 0&&V>_t)I.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${V} > ${_t}).`});if(Yt!==void 0&&!new RegExp(Yt,"u").test(e))I.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(Y!==void 0&&Ig[Y]&&!Ig[Y](e))I.push({instanceLocation:s,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${Y}".`})}return{valid:I.length===0,errors:I}}var Uv=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=Yr(e)}validate(e){return me(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){if(t)e={...e,$id:t};Yr(e,this.lookup)}},ku=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=yd(e,"pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.");return t==="draft-7"?"7":t}getValidator(e){let t=new Uv(e,this.draft??this._draftFor(e),this.shortcircuit);return(r)=>{let o=t.validate(r);return o.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:o.errors.map((n)=>`${n.instanceLocation}: ${n.error}`).join("; ")}}}};var Ag=!0;var $u;$u=globalThis.crypto;async function Zv(e){return(await $u).getRandomValues(new Uint8Array(e))}async function Dv(e){let r=Math.pow(2,8)-Math.pow(2,8)%66,o="";while(o.length<e){let n=await Zv(e-o.length);for(let i of n)if(i<r)o+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[i%66]}return o}async function Fv(e){return await Dv(e)}async function Hv(e){let t=await(await $u).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Cu(e){if(!e)e=43;if(e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Fv(e),r=await Hv(t);return{code_verifier:t,code_challenge:r}}class kc extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}var qg=10,Vv=13,Xr=32;function Iu(e){}function Lg(e){if(typeof e=="function")throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Iu,onError:r=Iu,onRetry:o=Iu,onComment:n,maxBufferSize:i}=e,s=[],a=0,l=!0,u,d="",m=0,f,g=!1;function b(R){if(g)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,R.charCodeAt(0)===239&&R.charCodeAt(1)===187&&R.charCodeAt(2)===191&&(R=R.slice(3))),s.length===0){let X=v(R);X!==""&&(s.push(X),a=X.length),y();return}if(R.indexOf(`
|
|
73
|
+
`)===-1&&R.indexOf("\r")===-1){s.push(R),a+=R.length,y();return}s.push(R);let w=s.join("");s.length=0,a=0;let D=v(w);D!==""&&(s.push(D),a=D.length),y()}function y(){i!==void 0&&(a+d.length<=i||(g=!0,s.length=0,a=0,u=void 0,d="",m=0,f=void 0,r(new kc(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function v(R){let w=0;if(R.indexOf("\r")===-1){let D=R.indexOf(`
|
|
74
74
|
`,w);for(;D!==-1;){if(w===D){m>0&&t({id:u,event:f,data:d}),u=void 0,d="",m=0,f=void 0,w=D+1,D=R.indexOf(`
|
|
75
|
-
`,w);continue}let X=R.charCodeAt(w);if(
|
|
76
|
-
`,w);continue}d=m===0?
|
|
77
|
-
${
|
|
75
|
+
`,w);continue}let X=R.charCodeAt(w);if(Mg(R,w,X)){let Y=R.charCodeAt(w+5)===Xr?w+6:w+5,ue=R.slice(Y,D);if(m===0&&R.charCodeAt(D+1)===qg){t({id:u,event:f,data:ue}),u=void 0,d="",f=void 0,w=D+2,D=R.indexOf(`
|
|
76
|
+
`,w);continue}d=m===0?ue:`${d}
|
|
77
|
+
${ue}`,m++}else jg(R,w,X)?f=R.slice(R.charCodeAt(w+6)===Xr?w+7:w+6,D)||void 0:L(R,w,D);w=D+1,D=R.indexOf(`
|
|
78
78
|
`,w)}return R.slice(w)}for(;w<R.length;){let D=R.indexOf("\r",w),X=R.indexOf(`
|
|
79
|
-
`,w),Y=-1;if(D!==-1&&X!==-1?Y=D<X?D:X:D!==-1?D===R.length-1?Y=-1:Y=D:X!==-1&&(Y=X),Y===-1)break;
|
|
80
|
-
${
|
|
81
|
-
${w}`,m++;break;case"id":w.includes("\x00")||(u=w);break;case"retry":/^\d+$/.test(w)?o(parseInt(w,10)):r(new vc(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:D}));break;default:r(new vc(`Unknown field "${R.length>20?`${R.slice(0,20)}…`:R}"`,{type:"unknown-field",field:R,value:w,line:D}));break}}function x(){m>0&&t({id:u,event:f,data:d}),u=void 0,d="",m=0,f=void 0}function Z(R={}){if(R.consume&&s.length>0){let w=s.join("");U(w,0,w.length)}l=!0,u=void 0,d="",m=0,f=void 0,s.length=0,a=0,S=!1}return{feed:b,reset:Z}}function Pg(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Tg(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}class wu extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:o}={}){let n;super({start(i){n=Eg({onEvent:(s)=>{i.enqueue(s)},onError(s){typeof e=="function"&&e(s),(e==="terminate"||s.type==="max-buffer-size-exceeded")&&i.error(s)},onRetry:t,onComment:r,maxBufferSize:o})},transform(i){n.feed(i)}})}}var Mi=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e){super(e);this.name=new.target.name,Zr(this,new.target)}},$u=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 §3.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`);this.kind=e,this.expected=t,this.received=r}},Iv=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`);this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},Zg=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`);this.tokenEndpoint=e}},Rc=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`);this.recordedIssuer=e,this.currentIssuer=t}},kg=class extends Mi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`);this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function Cu(e,t,r){if(!e)return;if(typeof e.issuer!=="string"){if(r?.canPersistStamp!==!1)console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field.");return e.issuer===void 0?e:{...e,issuer:void 0}}return Dg(e.issuer,t)?e:void 0}function Dg(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function Ov(e){if(e==null)return!1;let t=e;return typeof t.tokens==="function"&&typeof t.clientInformation==="function"}async function Nv(e,t,r){let{resourceMetadataUrl:o,scope:n}=Ai(t.response);if(await Iu(e,{serverUrl:t.serverUrl,resourceMetadataUrl:o,scope:n,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new wt}function qv(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async(r)=>Nv(e,r,t)}}var wt=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e){super(e??"Unauthorized");this.name="UnauthorizedError",Zr(this,new.target)}};function Nu(e){return e?.authorization_response_iss_parameter_supported===!0}function qu({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t===void 0)return;if(e===void 0){if(r)throw new $u("authorization_response",t,void 0);return}if(e!==t)throw new $u("authorization_response",t,e)}function Ru(...e){let t=new Set;for(let r of e){if(!r)continue;for(let o of r.split(/\s+/))if(o)t.add(o)}return t.size>0?[...t].join(" "):void 0}function Av(e,t){if(!e)return!1;let r=new Set((t??"").split(/\s+/).filter(Boolean));for(let o of e.split(/\s+/))if(o&&!r.has(o))return!0;return!1}async function Mv(e,t,r,o,n){if(typeof e==="string")return{authorizationCode:e,iss:t};let i=e.get("iss")??void 0,s=e.get("code");if(s)return{authorizationCode:s,iss:i};let a=(await r.discoveryState?.())?.authorizationServerMetadata;if(!a)try{a=(await Bg(o,n)).authorizationServerMetadata}catch{a=void 0}if(!a)throw new wt("Authorization callback failed and the issuer could not be verified");qu({iss:i,expectedIssuer:a.issuer,issParameterSupported:Nu(a)});let l=e.get("error");if(l)throw new Dr(l,e.get("error_description")??l,e.get("error_uri")??void 0);throw new wt("Authorization callback contained neither `code` nor `error`")}function jv(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var xu="code",Pu="S256";function Lv(e,t){let r=e.client_secret!==void 0;if("token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&jv(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method)))return e.token_endpoint_auth_method;if(t.length===0)return r?"client_secret_basic":"none";if(r&&t.includes("client_secret_basic"))return"client_secret_basic";if(r&&t.includes("client_secret_post"))return"client_secret_post";if(t.includes("none"))return"none";return r?"client_secret_post":"none"}function Uv(e,t,r,o){let{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":Zv(n,i,r);return;case"client_secret_post":Dv(n,i,o);return;case"none":Fv(n,o);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Zv(e,t,r){if(!t)throw Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}function Dv(e,t,r){if(r.set("client_id",e),t)r.set("client_secret",t)}function Fv(e,t){t.set("client_id",e)}function Fg(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function Hv(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!Fg(t.hostname))throw new Zg(t.href);return t}function Vv(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:")return"native";if(Fg(r.hostname))return"native"}return"web"}function Jv(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??Vv(t.redirect_uris)}}async function $g(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Ho.parse(JSON.parse(r));return Dr.fromResponse(o)}catch(o){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Dr(Ut.ServerError,n)}}function Cg(e,t,r){let o=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} — ${o}. Cause: ${JSON.stringify(t.message)}`)}async function Iu(e,t){try{return await Tu(e,t)}catch(r){if(r instanceof Dr){if(r.code===Ut.InvalidClient||r.code===Ut.UnauthorizedClient)return Cg(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Tu(e,t);else if(r.code===Ut.InvalidGrant||r.code===Ut.InvalidDpopProof)return Cg(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await Tu(e,t)}throw r}}function Bv(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:n}=e,i=t||r?.scopes_supported?.join(" ")||n.scope;if(i&&o?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&n.grant_types?.includes("refresh_token"))i=`${i} offline_access`;return i}async function Tu(e,{serverUrl:t,authorizationCode:r,iss:o,scope:n,resourceMetadataUrl:i,fetchFn:s,skipIssuerMetadataValidation:a,forceReauthorization:l}){let u=Jv(e),d=await e.discoveryState?.(),m,f,S,b,y=i;if(!y&&d?.resourceMetadataUrl)y=new URL(d.resourceMetadataUrl);if(d?.authorizationServerUrl){if(f=d.authorizationServerUrl,m=d.resourceMetadata,S=d.authorizationServerMetadata??await Jg(f,{fetchFn:s,skipIssuerValidation:a}),!m)try{m=await Hg(t,{resourceMetadataUrl:y},s)}catch(te){if(te instanceof TypeError)throw te}if(S!==d.authorizationServerMetadata||m!==d.resourceMetadata)await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:S})}else{let te=await Bg(t,{resourceMetadataUrl:y,fetchFn:s,skipIssuerMetadataValidation:a});f=te.authorizationServerUrl,S=te.authorizationServerMetadata,m=te.resourceMetadata,b={authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:S}}let v=S?.issuer??String(f),U={issuer:v};if(await e.saveAuthorizationServerUrl?.(v),r!==void 0){let te=d?.authorizationServerMetadata?.issuer??d?.authorizationServerUrl;if(te===void 0){if(e.saveDiscoveryState!==void 0)throw new Rc("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",v);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.")}else if(!Dg(te,v))throw new Rc(te,v)}if(b)await e.saveDiscoveryState?.(b);let H=await Kv(t,e,m),x=H&&m&&!e.validateResourceURL?m.resource:H;if(x)await e.saveResourceUrl?.(Au(x));let Z=Bv({requestedScope:n,resourceMetadata:m,authServerMetadata:S,clientMetadata:e.clientMetadata}),R=await Promise.resolve(e.clientInformation(U)),w=Cu(R,v,{canPersistStamp:e.saveClientInformation!==void 0});if(w===void 0&&R?.issuer&&e.saveClientInformation===void 0)throw new Rc(R.issuer,v);if(w&&w.issuer===void 0)w={...w,issuer:v},await e.saveClientInformation?.(w,U);if(!w){if(r!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let te=S?.client_id_metadata_document_supported===!0,ie=e.clientMetadataUrl;if(ie&&!Wv(ie))throw new Dr(Ut.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ie}`);if(te&&ie)w={client_id:ie,issuer:v},await e.saveClientInformation?.(w,U);else{if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");w={...await sz(f,{metadata:S,clientMetadata:u,scope:Z,fetchFn:s}),issuer:v},await e.saveClientInformation(w,U)}}let D=!e.redirectUrl;if(r!==void 0||D){if(r!==void 0)qu({iss:o,expectedIssuer:S?.issuer,issParameterSupported:Nu(S)});let te=await nz(e,f,{metadata:S,resource:x,authorizationCode:r,iss:o,scope:Z,fetchFn:s});return await e.saveTokens({...te,issuer:v},U),"AUTHORIZED"}let X=Cu(await e.tokens(U),v);if(X&&X.issuer===void 0)X={...X,issuer:v},await e.saveTokens(X,U);if(X?.refresh_token&&!l){let te;try{te=await oz(f,{metadata:S,clientInformation:w,refreshToken:X.refresh_token,resource:x,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:s})}catch(ie){if(ie instanceof Zg)throw ie;if(!(ie instanceof Dr)||ie.code===Ut.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(ie instanceof Error?ie.message:String(ie))}`);else throw ie}if(te)return await e.saveTokens({...te,issuer:v},U),"AUTHORIZED"}let Y=e.state?await e.state():void 0,{authorizationUrl:le,codeVerifier:Ee}=await tz(f,{metadata:S,clientInformation:w,state:Y,redirectUrl:e.redirectUrl,scope:Z,resource:x});return await e.saveCodeVerifier(Ee),await e.redirectToAuthorization(le),"REDIRECT"}function Wv(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Kv(e,t,r){let o=If(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(!r)return;if(!Of({requestedResource:o,configuredResource:r.resource}))throw Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}var Gv=new Set(["bearer","dpop"]);function Ai(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!Gv.has(r.toLowerCase())||!o)return{};let n=zc(e,"resource_metadata")||void 0,i;if(n)try{i=new URL(n)}catch{}let s=zc(e,"scope")||void 0,a=zc(e,"error")||void 0,l=zc(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:s,error:a,errorDescription:l}}function zc(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),n=r.match(o);if(n){let i=n[1]||n[2];if(i)return i}return null}async function Hg(e,t,r=fetch){let o=await Qv(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.text?.().catch(()=>{}),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.text?.().catch(()=>{}),Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Zo.parse(await o.json())}async function Vg(e,t,r=fetch){let o=Ni(r);try{return await o(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!Rg)throw n;if(t)try{return await o(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}function Yv(e,t="",r={}){if(t.endsWith("/"))t=t.slice(0,-1);return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Ig(e,t,r=fetch){return await Vg(e,{"MCP-Protocol-Version":t},r)}function Xv(e,t){if(!e)return!0;if(t==="/")return!1;return!e.ok&&e.status<500||e.status===502}async function Qv(e,t,r,o){let n=new URL(e),i=o?.protocolVersion??ho,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let l=Yv(t,n.pathname);s=new URL(l,o?.metadataServerUrl??n),s.search=n.search}let a=await Ig(s,i,r);if(!o?.metadataUrl&&Xv(a,n.pathname))a=await Ig(new URL(`/.well-known/${t}`,n),i,r);return a}function ez(e){let t=typeof e==="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;if(n.endsWith("/"))n=n.slice(0,-1);return o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"},{url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function Jg(e,{fetchFn:t=fetch,protocolVersion:r=ho,skipIssuerValidation:o=!1}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},i=ez(e);for(let{url:s,type:a}of i){let l=await Vg(s,n,t);if(!l)continue;if(!l.ok){if(await l.text?.().catch(()=>{}),l.status<500||l.status===502)continue;throw Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}let u=a==="oauth"?Ur.parse(await l.json()):Do.parse(await l.json());if(!o){let d=typeof e==="string"?e:e.href;if(!(u.issuer===d||d.endsWith("/")&&u.issuer===d.slice(0,-1)))throw new $u("metadata",d,u.issuer)}return u}}async function Bg(e,t){let r,o;try{if(r=await Hg(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0)o=r.authorization_servers[0]}catch(i){if(i instanceof TypeError)throw i}if(!o)o=String(new URL("/",e));let n=await Jg(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function Au(e){return typeof e==="string"?e:e.href}async function tz(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:i,resource:s}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(xu))throw Error(`Incompatible auth server: does not support response type ${xu}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Pu))throw Error(`Incompatible auth server: does not support code challenge method ${Pu}`)}else a=new URL("/authorize",e);let l=await vu(),{code_verifier:u,code_challenge:d}=l;if(a.searchParams.set("response_type",xu),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Pu),a.searchParams.set("redirect_uri",String(o)),i)a.searchParams.set("state",i);if(n)a.searchParams.set("scope",n);if(n?.split(" ").includes("offline_access"))a.searchParams.append("prompt","consent");if(s)a.searchParams.set("resource",Au(s));return{authorizationUrl:a,codeVerifier:u}}function rz(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function Wg(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:i,dpop:s,fetchFn:a}){let l=Hv(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i)r.set("resource",Au(i));if(!n&&o)Uv(Lv(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let d=async()=>{let S=new Headers(u);if(n)await n(S,r,l,t);if(s)S.set("DPoP",await s.buildProof({htm:"POST",htu:l}));return Ni(a??fetch)(l,{method:"POST",headers:S,body:r})},m=await d();if(s&&m.status===400){if((await m.clone().json().catch(()=>{}))?.error===Ut.UseDpopNonce)s.observeNonce(m,l),m=await d()}if(s?.observeNonce(m,l),!m.ok)throw await $g(m);let f=await m.json();try{return Fo.parse(iu(f))}catch(S){if(typeof f==="object"&&f!==null&&"error"in f)throw await $g(JSON.stringify(f));throw S}}async function oz(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:i,dpop:s,fetchFn:a}){return{refresh_token:o,...await Wg(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:i,resource:n,dpop:s,fetchFn:a})}}async function nz(e,t,{metadata:r,resource:o,authorizationCode:n,iss:i,scope:s,fetchFn:a}={}){if(n!==void 0)qu({iss:i,expectedIssuer:r?.issuer,issParameterSupported:Nu(r)});let l=r?.issuer??String(t),u=async()=>{let S=await e.clientInformation({issuer:l}),b=Cu(S,l,{canPersistStamp:!1});if(S&&b===void 0)throw new Rc(String(S.issuer),l);return b},d=await u(),m=s??e.clientMetadata.scope,f;if(e.prepareTokenRequest)f=await e.prepareTokenRequest(m);if(!f){if(!n)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");f=rz(n,await e.codeVerifier(),e.redirectUrl)}return d??=await u(),Wg(t,{metadata:r,tokenRequestParams:f,clientInformation:d,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:a})}async function sz(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:n}){let i;if(t){if(!t.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let s={...r,...o===void 0?{}:{scope:o}},a=await Ni(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok)throw new Iv({status:a.status,body:await a.text(),submittedMetadata:s});return Vo.parse(iu(await a.json()))}var wc=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),iz=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(Eu(e))}set(e,t){let r=Eu(e),o=wc.has(e.method),n=!this._entries.has(r);if(!o&&n&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let s of this._entries.keys())if(!wc.has(s.slice(0,s.indexOf("\x00")))){this._entries.delete(s),this._cappedSize--;break}}let i=++this._stamp;if(this._entries.set(r,{...t,stamp:i}),n&&!o)this._cappedSize++;return i}delete(e){if(this._entries.delete(Eu(e))&&!wc.has(e.method))this._cappedSize--}evict(e){let t=`${e}\x00`,r=wc.has(e);for(let o of this._entries.keys())if(o.startsWith(t)){if(this._entries.delete(o),!r)this._cappedSize--}}clear(){this._entries.clear(),this._cappedSize=0}};function Eu(e){return`${e.method}\x00${JSON.stringify([e.partition??"",e.params??""])}`}function ku(e,t){return t===void 0?e:`${e}\x00${t}`}var az=86400000,cz=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,r=()=>{},o="",n=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=r,this._cachePartition=o,this._now=n}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){let r={method:e,params:t??""},o=this._partitionFor("private"),n=await this._store.get({...r,partition:o});if(n!==void 0)return n;let i=this._partitionFor("public");if(i===o)return;let s=await this._store.get({...r,partition:i});return s?.scope==="public"?s:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){let r=this._partitionFor("private"),o=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:r})}catch(n){this._reportError(n)}if(o!==r)try{await this._store.delete({method:e,params:t,partition:o})}catch(n){this._reportError(n)}}async evictKey(e,t){let r=ku(e,t),o=this._evictionGeneration.get(r);if(o!==void 0)this._evictionGeneration.set(r,o+1);await this._deleteBoth(e,t)}captureGeneration(e,t){let r=ku(e,t),o=this._evictionGeneration.get(r)??0;return this._evictionGeneration.set(r,o),o}async write(e,t,r,o){if((this._evictionGeneration.get(ku(e,o?.params))??0)!==r)return;let n=o?.params??"",i=this._partitionFor("private"),s=this._partitionFor("public"),a=(o?.scope??"private")==="public"?s:i;try{await this._store.set({method:e,params:n,partition:a},{value:lz(t),expiresAt:o?.expiresAt,scope:o?.scope})}catch(l){this._reportError(l)}if(s!==i)try{await this._store.delete({method:e,params:n,partition:a===i?s:i})}catch(l){this._reportError(l)}}async read(e,t){let r=await this._probe(e,t);if(r?.expiresAt===void 0||!(r.expiresAt>this.now()))return;try{let o=JSON.parse(r.value);if(typeof o!=="object"||o===null||Array.isArray(o))throw TypeError("cached document is not an object");return{value:o}}catch(o){this._reportError(o),await this._deleteBoth(e,t??"");return}}resetForReconnect(){if(!this._isUserSupplied)this._store.clear();this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){let t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let r=this._decodeListTools(t),o=new Map;if(r!==void 0)for(let n of r.tools)o.set(n.name,n);this._toolIndex={stamp:t.stamp,byName:o}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let r=await this._probe("tools/list");if(r===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==r.stamp){let o=this._decodeListTools(r)??{tools:[]},n=new Map;for(let i of o.tools){let s=t(i);if(s!==void 0)n.set(i.name,s)}this._toolOutputValidatorIndex={stamp:r.stamp,byName:n}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every((r)=>r!==null&&typeof r==="object"))throw TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};function lz(e){let t;try{t=JSON.stringify(e)}catch(r){throw TypeError(`cache value is not JSON-serializable: ${r instanceof Error?r.message:String(r)}`)}if(typeof t!=="string")throw TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}var Kg=Symbol.for("mcp.authSeamEscape");function Xe(e){if(typeof e==="object"&&e!==null||typeof e==="function")try{Object.defineProperty(e,Kg,{value:!0,configurable:!0})}catch{}return e}function uz(e){return(typeof e==="object"&&e!==null||typeof e==="function")&&e[Kg]===!0}var dz=-32022,pz=new Set([-32001,-32020,-32021]);function hz(e,t){switch(e.kind){case"result":return mz(e.result,t);case"rpc-error":return Gg(e,t);case"http-error":return fz(e,t);case"network-error":return Og(e.error,t);case"unusable-reply":return{kind:"error",error:new N(O.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${Yg(e.error)})`,{cause:e.error},{cause:e.error})};case"auth-required":return{kind:"error",error:e.error};case"closed":if(t.transportKind==="stdio")return{kind:"legacy"};return Og(Error("Connection closed during the version negotiation probe"),t);case"timeout":if(t.transportKind==="stdio")return{kind:"legacy"};return{kind:"error",error:new N(O.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function mz(e,t){let r=Lt(Sc).validateResult("server/discover",e);if(!r.ok)return{kind:"legacy"};let o=r.value.supportedVersions,n=t.clientModernVersions.find((i)=>o.includes(i));if(n!==void 0)return{kind:"modern",version:n,discover:r.value};if(t.fallbackAvailable)return{kind:"legacy"};return{kind:"error",error:new gc({supported:[...o],requested:t.requestedVersion})}}function Gg(e,t){let{code:r,message:o,data:n}=e;if(r===dz){let i=Sz(n);if(i===void 0)return{kind:"legacy"};let s=new gc({supported:i,requested:_z(n)??t.requestedVersion},o),a=Oi(i),l=t.clientModernVersions.find((u)=>a.includes(u));if(l!==void 0)return{kind:"corrective",version:l,error:s};if(a.length>0)return{kind:"error",error:s};return t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:s}}if(pz.has(r))return{kind:"legacy"};return{kind:"legacy"}}function fz(e,t){if(e.status===401||e.status===403){let o=e.status===403;return{kind:"error",error:new vt(o?O.ClientHttpForbidden:O.ClientHttpAuthentication,`Version negotiation failed: ${o?"the server denied access (HTTP 403)":"the server requires authorization (HTTP 401)"}`,{status:e.status,statusText:e.statusText,text:e.body})}}if(e.status>=500)return{kind:"error",error:new vt(O.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let r=bz(e.body);if(r!==void 0)return Gg(r,t);return{kind:"legacy"}}function Og(e,t){if(t.environment==="browser"&&gz(e))return{kind:"legacy"};return{kind:"error",error:new N(O.EraNegotiationFailed,`Version negotiation probe failed: ${Yg(e)}`,{cause:e},{cause:e})}}function gz(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function Yg(e){return e instanceof Error?e.message:String(e)}function Sz(e){if(typeof e!=="object"||e===null)return;let t=e.supported;if(!Array.isArray(t)||t.length===0||!t.every((r)=>typeof r==="string"))return;return t}function _z(e){if(typeof e!=="object"||e===null)return;let t=e.requested;return typeof t==="string"?t:void 0}function bz(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=="object"||t===null)return;let r=t.error;if(typeof r!=="object"||r===null)return;let{code:o,message:n,data:i}=r;if(typeof o!=="number")return;return{code:o,message:typeof n==="string"?n:"",data:i}}var yz="legacy";function vz(e,t){let r=e?.mode??yz;if(r==="legacy")return{kind:"legacy"};let o=e?.probe??{};if(typeof r==="object"){if(!Zt(r.pin))throw TypeError(`versionNegotiation: { pin: '${r.pin}' } is not a modern protocol revision — pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:r.pin,probe:o}}let n=t?Oi(t):[];return{kind:"auto",modernVersions:n.length>0?n:[...au],fallbackAvailable:t?cu(t).length>0:!0,probe:o}}function Ng(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function qg(e){return"stderr"in e&&"pid"in e?"stdio":"http"}var zz=class e{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(t){this._transport=t,this._savedOnMessage=t.onmessage,this._savedOnError=t.onerror,this._savedOnClose=t.onclose}static async open(t){let r=new e(t);t.onmessage=(o)=>{let n=r._pending;if(n!==void 0&&(Bo(o)||Wo(o))&&o.id===n.id){if(r._pending=void 0,Bo(o))n.resolve({kind:"response",result:o.result});else n.resolve({kind:"response",error:o.error});return}},t.onerror=(o)=>{r._savedOnError?.(o)},t.onclose=()=>{let o=r._pending;if(o!==void 0)r._pending=void 0,o.resolve({kind:"closed"});r._closeDelivered=!0,r._savedOnClose?.()};try{await t.start()}catch(o){throw r.detach(),o}return r}async exchange(t,r){let o=`server-discover-probe-${++this._probeCounter}`;return new Promise((n)=>{let i=!1,s=(l)=>{if(i)return;if(i=!0,clearTimeout(a),this._pending?.id===o)this._pending=void 0;n(l)},a=setTimeout(()=>s({kind:"timeout"}),r);this._pending={id:o,resolve:s},this._transport.send(t(o)).catch((l)=>s({kind:"send-error",error:l}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let t=this._savedOnClose,r=this._transport,o=!1,n=()=>{if(!o){o=!0;return}t()};r.onclose=n,Ou.set(r,()=>{if(r.onclose===n)r.onclose=t})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let t=this._transport,r=t.start,o=!0;t.start=async function(){if(o){o=!1,t.start=r;return}return r.call(t)}}},Ou=new WeakMap;function Ag(e){let t=Ou.get(e);Ou.delete(e),t?.()}function wz(e,t,r,o){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:Lt(t).outboundEnvelope({protocolVersion:t,clientInfo:r,clientCapabilities:o})}}}function Rz(e){if(e instanceof N&&e.code===O.ClientHttpUnexpectedContent)return!0;return e instanceof Error&&e.name==="SyntaxError"}function xz(e,t){switch(e.kind){case"response":return e.error===void 0?{kind:"result",result:e.result}:{kind:"rpc-error",...e.error};case"send-error":{let r=e.error;if(uz(r)||r instanceof wt||r instanceof Error&&r.name==="UnauthorizedError")return{kind:"auth-required",error:r};if(r instanceof vt){let o=r.data?.text;return{kind:"http-error",status:r.data.status,body:typeof o==="string"?o:void 0,statusText:r.data.statusText}}if(Rz(r))return{kind:"unusable-reply",error:r};return{kind:"network-error",error:r}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function Xg(e,t){let r=e.probe.timeoutMs??t.defaultTimeoutMs,o=Math.max(0,e.probe.maxRetries??0),n=e.kind==="pin"?[e.version]:e.modernVersions,i=e.kind==="auto"&&e.fallbackAvailable,s=await zz.open(t.transport),a=async()=>{let u=n[0],d=!1,m=o;for(;;){let f=await s.exchange((y)=>wz(y,u,t.clientInfo,t.capabilities),r);if(f.kind==="timeout"&&m>0){m--;continue}let S=xz(f,r),b=hz(S,{clientModernVersions:n,requestedVersion:u,fallbackAvailable:i,environment:t.environment,transportKind:t.transportKind});switch(b.kind){case"modern":return{era:"modern",version:b.version,discover:b.discover};case"corrective":if(d)throw b.error;d=!0,u=b.version;continue;case"legacy":{let y=S.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new N(O.EraNegotiationFailed,y===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${y} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new N(O.EraNegotiationFailed,y===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${y} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(y!==void 0&&t.disposableProbe!==!0)throw new N(O.EraNegotiationFailed,`Version negotiation failed: ${y} (this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw b.error}}},l;try{l=await a()}catch(u){throw s.detach(),u}return s.release(),l}function Pz(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;let r=e._serverParams;return typeof r==="object"&&r!==null&&typeof r.command==="string"?r:void 0}async function Tz(e,t,r,o){let i=new t.constructor({...r,stderr:"ignore"}),s=t.close,a=!1,l,u=new Promise((m,f)=>{l=()=>f(Mg())});t.close=async function(){return a=!0,l?.(),s.call(t)};let d;try{let m=Xg(e,{...o,transport:i,transportKind:"stdio",disposableProbe:!0});m.catch(()=>{}),d=await Promise.race([m,u])}finally{await Ez(i),t.close=s}if(a)throw Mg();return d}function Mg(){return new N(O.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function Ez(e){try{let t=e._dispose;await(typeof t==="function"?t.call(e):e.close())}catch{}}function jg(e){let t=e._meta?.[Ot];return pg.Implementation(t)?t:void 0}function xc(e,t){if(!e||t===null||typeof t!=="object")return;if(e.type==="object"&&e.properties&&typeof e.properties==="object"){let r=t,o=e.properties;for(let n of Object.keys(o)){let i=o[n];if(r[n]===void 0&&Object.prototype.hasOwnProperty.call(i,"default"))r[n]=i.default;if(r[n]!==void 0)xc(i,r[n])}}if(Array.isArray(e.anyOf)){for(let r of e.anyOf)if(typeof r!=="boolean")xc(r,t)}if(Array.isArray(e.oneOf)){for(let r of e.oneOf)if(typeof r!=="boolean")xc(r,t)}}function kz(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}function $z(e){if(typeof e==="object"&&e!==null){if(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e))return e;if(e.kind==="modern"&&rr.safeParse(e.discover).success)return e}throw new N(O.EraNegotiationFailed,"connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }")}var Lg={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},Cz=64,Qg=class extends yc{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new N(O.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t);if(this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new bu,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=cg(t?.inputRequired),this._cache=new cz(t?.responseCacheStore??new iz,t?.responseCacheStore!==void 0,(r)=>this._reportStoreError(r),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??Cz,t?.listChanged)this._listChangedConfig=t.listChanged}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&Zt(this._negotiatedProtocolVersion)&&Fr(e))return"drop"}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){if(!this._inputRequiredDriverConfig.autoFulfill)return Promise.reject(new N(O.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance — pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:t.request.method}));return mg({getRequestHandler:(r)=>this._getRequestHandler(r),buildContext:(r)=>this.buildContext(r,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t)}_setupListChangedHandlers(e){if(e.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools);if(e.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts);if(e.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources","notifications/resources/list_changed",e.resources,async()=>(await this.listResources(void 0,{cacheMode:"refresh"})).resources)}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=hg(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){if(e==="elicitation/create")return async(r,o)=>{let n=Lt(this._negotiatedProtocolVersion),i=n.validateRequest("elicitation/create",r);if(!i.ok&&i.reason==="not-in-era")i=n.validateInputRequest("elicitation/create",r);if(!i.ok)throw new ee(i.reason==="not-in-era"?W.InternalError:W.InvalidParams,i.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${i.message}`);let{params:s}=i.value;s.mode=s.mode??"form";let{supportsFormMode:a,supportsUrlMode:l}=kz(this._capabilities.elicitation);if(s.mode==="form"&&!a)throw new ee(W.InvalidParams,"Client does not support form-mode elicitation requests");if(s.mode==="url"&&!l)throw new ee(W.InvalidParams,"Client does not support URL-mode elicitation requests");let u=await t(r,o),d=n.validateResult("elicitation/create",u);if(!d.ok&&d.reason==="not-in-era")d=n.validateInputResponse("elicitation/create",u);if(!d.ok)throw new ee(d.reason==="not-in-era"?W.InternalError:W.InvalidParams,d.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${d.message}`);let m=d.value,f=s.mode==="form"?s.requestedSchema:void 0;if(s.mode==="form"&&m.action==="accept"&&m.content&&f&&this._capabilities.elicitation?.form?.applyDefaults)try{xc(f,m.content)}catch{}return m};if(e==="sampling/createMessage")return async(r,o)=>{let n=Lt(this._negotiatedProtocolVersion),i=n.validateRequest("sampling/createMessage",r);if(!i.ok&&i.reason==="not-in-era")i=n.validateInputRequest("sampling/createMessage",r);if(!i.ok)throw new ee(i.reason==="not-in-era"?W.InternalError:W.InvalidParams,i.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${i.message}`);let{params:s}=i.value,a=await t(r,o),l=Boolean(s.tools||s.toolChoice),u=n.samplingResultVariant(l,a);if(!u.ok&&u.reason==="not-in-era")u=n.validateInputResponse("sampling/createMessage",a);if(!u.ok)throw new ee(u.reason==="not-in-era"?W.InternalError:W.InvalidParams,u.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${u.message}`);return u.value};return t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new N(O.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,$z(t.prior),t);let r=vz(this._versionNegotiation,this._supportedProtocolVersionsOption);if(r.kind!=="legacy")return this._connectNegotiated(e,r,t);return this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let r=this._negotiatedProtocolVersion;if(r!==void 0)e.setProtocolVersion?.(r);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let r=cu(this._supportedProtocolVersions);try{let o=r[0];if(o===void 0)throw new N(O.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let n=await this.request({method:"initialize",params:{protocolVersion:o,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!r.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);if(this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion)e.setProtocolVersion(n.protocolVersion);if(this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=n.protocolVersion,this._listChangedConfig)this._setupListChangedHandlers(this._listChangedConfig)}catch(o){throw this.close(),o}}async _connectNegotiated(e,t,r){if(e.sessionId!==void 0){await super.connect(e);let n=this._negotiatedProtocolVersion;if(n!==void 0&&e.setProtocolVersion)e.setProtocolVersion(n);return}this._resetConnectionState();let o;try{let n=qg(e),i={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:Ng(),defaultTimeoutMs:r?.timeout??bc},s=n==="stdio"?Pz(e):void 0;o=s===void 0?await Xg(t,{...i,transport:e,transportKind:n}):await Tz(t,e,s,i)}catch(n){throw await e.close().catch(()=>{}),Ag(e),n}if(Ag(e),await super.connect(e),o.era==="legacy"){await this._legacyHandshake(e,r);return}if(this._serverCapabilities=o.discover.capabilities,this._serverVersion=jg(o.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.discover.instructions,this._discoverResult=o.discover,this._negotiatedProtocolVersion=o.version,e.setProtocolVersion)e.setProtocolVersion(o.version);if(this._listChangedConfig){let n=this._listChangedConfig,i=this._serverCapabilities,s={...n.tools&&i?.tools?.listChanged&&{tools:n.tools},...n.prompts&&i?.prompts?.listChanged&&{prompts:n.prompts},...n.resources&&i?.resources?.listChanged&&{resources:n.resources}},a=!0;try{this._setupListChangedHandlers(s)}catch(u){a=!1,this.onerror?.(u instanceof Error?u:Error(String(u)))}let l=a?{...s.tools&&{toolsListChanged:!0},...s.prompts&&{promptsListChanged:!0},...s.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(l).length>0){let u=new AbortController,d=()=>u.abort(r?.signal?.reason);if(r?.signal?.aborted)d();r?.signal?.addEventListener("abort",d);try{this._autoOpenedSubscription=await this.listen(l,{timeout:r?.timeout,signal:u.signal})}catch(m){if(r?.signal?.aborted)throw await this.close().catch(()=>{}),m;this.onerror?.(m instanceof Error?m:Error(String(m)))}finally{r?.signal?.removeEventListener("abort",d)}}}}async _connectFromPrior(e,t,r){if(t.kind==="legacy")return this._connectPlainLegacy(e,r);let o=t.discover;this._resetConnectionState();let n=this._supportedProtocolVersionsOption,i=(n&&Oi(n).length>0?Oi(n):au).find((s)=>o.supportedVersions.includes(s));if(i===void 0)throw new N(O.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(e),this._discoverResult=o,this._serverCapabilities=o.capabilities,this._serverVersion=jg(o),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.instructions,this._negotiatedProtocolVersion=i,e.setProtocolVersion?.(i),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(s){this.onerror?.(s instanceof Error?s:Error(String(s)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;if(t!==void 0)return`${t.name}@${t.version}`;return e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return Zt(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new N(O.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new N(O.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new N(O.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new N(O.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new N(O.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new N(O.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new N(O.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new N(O.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new N(O.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new N(O.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){let t=await this._requestWithSchema({method:"server/discover"},rr,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:"completion/complete",params:e},t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:"prompts/list",params:e},t);let r=await this._serveFromCache("prompts/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("prompts/list",e,t,(o)=>o.prompts)}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(e?.cursor!==void 0)return this.request({method:"resources/list",params:e},t);let r=await this._serveFromCache("resources/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("resources/list",e,t,(o)=>o.resources)}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:"resources/templates/list",params:e},t);let r=await this._serveFromCache("resources/templates/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("resources/templates/list",e,t,(o)=>o.resourceTemplates)}async _listAllPages(e,t,r,o,n){let i=r?.cacheMode==="bypass",s=this._cache.captureGeneration(e),a=await this.request({method:e,...t&&{params:{...t}}},r),l=a.nextCursor,u=a,d=1;while(l!==void 0){if(this._listMaxPages!==0&&d>=this._listMaxPages)throw new N(O.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});let m=await this.request({method:e,params:{...t,cursor:l}},r);if(m.nextCursor===l&&JSON.stringify(o(m))===JSON.stringify(o(u)))break;o(a).push(...o(m)),u=m,l=m.nextCursor,d++}if(delete a.nextCursor,n?.(a),i)return a;return await this._cache.write(e,a,s,this._freshness(a)),a}_freshness(e,t){let r=e,o=typeof r.ttlMs==="number"?r.ttlMs:this._defaultCacheTtlMs,n=r.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,o),az),scope:n,params:t}}async _serveFromCache(e,t,r){if(r?.cacheMode==="bypass"||r?.cacheMode==="refresh")return;let o=await this._cache.read(e,t).catch((n)=>void this._reportStoreError(n));if(o!==void 0){if(r?.signal?.aborted){let n=r.signal.reason;throw n instanceof N?n:new N(O.RequestTimeout,String(n))}return o.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}_compileOutputValidator(e){if(!e.outputSchema)return;try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){let r=t??await this._cache.toolDefinition(e);return r===void 0?void 0:fu(r.inputSchema)}async readResource(e,t){let r=await this._serveFromCache("resources/read",e.uri,t);if(r!==void 0)return r;let o=this._cache.captureGeneration("resources/read",e.uri),n=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){let i=this._freshness(n,e.uri);if(i.expiresAt>this._cache.now())await this._cache.write("resources/read",n,o,i);else if(t?.cacheMode==="refresh")await this._cache.evictKey("resources/read",e.uri)}return n}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},t)}async listen(e,t){if(this.transport===void 0)throw new N(O.NotConnected,"Not connected");let r=this._negotiatedProtocolVersion;if(r===void 0||!Zt(r))throw new N(O.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${r??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:r});if(t?.signal?.aborted){let x=t.signal.reason;throw x instanceof N?x:new N(O.RequestTimeout,String(x))}let o=new AbortController,n=`listen:${this._nextListenId++}`,i="opening",s,a,l,u,d=new Promise((x,Z)=>{l=x,u=Z}),m,f=new Promise((x)=>{m=x}),S=(x)=>{if(i==="closed")return;let Z=i==="opening";if(s!==void 0)clearTimeout(s),s=void 0;if("ack"in x){i="open",l(x.ack);return}if(i="closed",a!==void 0)t?.signal?.removeEventListener("abort",a);if(this._listenState.delete(n),o.abort(),m(x.cause),Z)u(x.error??new N(O.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},b=async()=>{o.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:n}}).catch(()=>{})},y=async()=>{if(i==="closed")return;S({cause:"local"}),await b()};this._listenState.set(n,{settle:S});let v=t?.timeout??bc;if(s=setTimeout(()=>{S({cause:"remote",error:new N(O.RequestTimeout,"subscriptions/listen ack timed out",{timeout:v})}),b().catch(()=>{})},v),t?.signal){let x=t.signal;a=()=>{if(i==="closed")return;let Z=x.reason;S({cause:"local",error:Z instanceof Error?Z:Error(String(Z??"Aborted"))}),b().catch(()=>{})},x.addEventListener("abort",a,{once:!0})}let U={jsonrpc:"2.0",id:n,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}},H=(x)=>{S({cause:"remote",error:x instanceof Error?x:Error(String(x))})};try{this.transport.send(U,{requestSignal:o.signal,onRequestStreamEnd:()=>S({cause:"remote",error:Error("subscriptions/listen: stream ended")})}).catch(H)}catch(x){H(x)}return{honoredFilter:await d,close:y,closed:f}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let r=Object.hasOwn(Lg,e.method)?Lg[e.method]:void 0;if(e.method==="notifications/resources/updated"){let o=e.params?.uri;if(typeof o==="string")this._cache.evictKey("resources/read",o)}else if(r!==void 0)for(let o of r)this._cache.evict(o);if(e.method==="notifications/subscriptions/acknowledged"){let o=e.params?._meta?.[Wn],n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){let i=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);n.settle({ack:i.ok?i.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){let o=e.params?.requestId,n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){n.settle({cause:"remote",error:Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,r=typeof t==="string"?this._listenState.get(t):void 0;if(r!==void 0){if(Wo(e))r.settle({cause:"remote",error:ee.fromError(e.error.code,e.error.message,e.error.data)});else r.settle({cause:"graceful",error:new N(O.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new N(O.ConnectionClosed,"Connection closed");for(let t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let r=this.getProtocolEra()==="modern"&&Ng()!=="browser",o=async()=>{if(!r)return t;let l;try{l=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(d){this._reportStoreError(d)}if(!l?.valid||l.declarations.length===0)return t;let u=sg(l.declarations,e.arguments);return Object.keys(u).length===0?t:{...t,headers:{...t?.headers,...u}}},n=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,(l)=>this._compileOutputValidator(l)).catch((l)=>void this._reportStoreError(l)):this._compileOutputValidator(t.toolDefinition),i=()=>{if(n===void 0||n.ok)return;let l=n.compileError,u=(l instanceof Error?l.message:String(l)).slice(0,200);throw new ee(W.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${u}`)};i();let s;try{s=await this.request({method:"tools/call",params:e},await o())}catch(l){let u=l instanceof ee&&l.code===Jo;if(!r||!u||t?.toolDefinition!==void 0)throw l;let d={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,d).catch((m)=>this._reportStoreError(m)),n=await this._cache.outputValidator(e.name,(m)=>this._compileOutputValidator(m)).catch((m)=>void this._reportStoreError(m)),i(),s=await this.request({method:"tools/call",params:e},await o())}let a=n!==void 0&&n.ok?n.validator:void 0;if(a){if(s.structuredContent===void 0&&!s.isError)throw new ee(W.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent!==void 0&&!s.isError)try{let l=a(s.structuredContent);if(!l.valid)throw new ee(W.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)}catch(l){if(l instanceof ee)throw l;throw new ee(W.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)}}return s}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){let o=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(o),o}let r=await this._serveFromCache("tools/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("tools/list",e,t,(o)=>o.tools,(o)=>this._excludeInvalidXMcpHeaderTools(o))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||qg(this.transport)==="stdio")return;let t=e.tools.filter((r)=>{let o=fu(r.inputSchema);if(!o.valid)return console.warn(`[mcp-sdk] excluding tool '${r.name}' from tools/list: invalid x-mcp-header declaration — ${o.reason}`),!1;return!0});if(t.length!==e.tools.length)e.tools=t}_setupListChangedHandler(e,t,r,o){let n=_c(Hs,r);if(!n.success)throw Error(`Invalid ${e} listChanged options: ${n.error.message}`);if(typeof r.onChanged!=="function")throw TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:s}=n.data,{onChanged:a}=r,l=async()=>{if(!i){a(null,null);return}try{a(null,await o())}catch(d){a(d instanceof Error?d:Error(String(d)),null)}},u=()=>{if(s){let d=this._listChangedDebounceTimers.get(e);if(d)clearTimeout(d);let m=setTimeout(l,s);this._listChangedDebounceTimers.set(e,m)}else l()};this.setNotificationHandler(t,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function Iz(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function Oz(e){if(e.status!==401)return!1;let t=e.headers.get("www-authenticate")??"";return Iz(t)&&/use_dpop_nonce/i.test(t)}var Nz=(e,t)=>(r)=>{let o=typeof e==="function"?e:()=>e;return async(n,i)=>{let s=(i?.method??"GET").toUpperCase(),a=new URL(n.toString()),l=await o();if(!l)return r(n,i);let u=async()=>{let m=await t();if(!m)return r(n,i);let f=new Headers(i?.headers),S=await l.buildProof({htm:s,htu:a,accessToken:m});return f.set("Authorization",`DPoP ${m}`),f.set("DPoP",S),r(n,{...i,headers:f})},d=await u();if(Oz(d)&&d.headers.has("dpop-nonce"))l.observeNonce(d,a),await d.text?.().catch(()=>{}),d=await u();return l.observeNonce(d,a),d}},qz=(e)=>Nz(async()=>{try{return await e.dpop?.()}catch(t){throw Xe(t)}},async()=>{let t;try{t=await e.tokens()}catch(r){throw Xe(r)}return t?.token_type?.toLowerCase()==="dpop"?t.access_token:void 0});var vP=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Be(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Be(this,e)}constructor(e,t,r){super(`SSE error: ${t}`);this.code=e,this.event=r,Zr(this,new.target)}};var Az=1,Mz={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2},jz=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function Ug(e,t){if(typeof AbortSignal.any==="function")return AbortSignal.any([e,t]);let r=new AbortController;if(e.aborted)return r.abort(e.reason),r.signal;if(t.aborted)return r.abort(t.reason),r.signal;let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",i)};function n(){o(),r.abort(e.reason)}function i(){o(),r.abort(t.reason)}return e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",i,{once:!0}),r.signal}var eS=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){if(this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,Ov(t?.authProvider)){if(this._oauthProvider=t.authProvider,this._authProvider=qv(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop)this._fetch=qz(t.authProvider)(t.fetch??fetch)}else this._authProvider=t?.authProvider;if(this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=gg(t?.fetch,t?.requestInit),this._redirectPolicy==="follow")this._fetchWithInit=bg(this._fetchWithInit);this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??Mz,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??Az)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(r){throw Xe(r)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new kg({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new kg({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new vt(O.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});if(e.resourceMetadataUrl)this._resourceMetadataUrl=e.resourceMetadataUrl;let r=await this._oauthProvider.tokens(),o=Ru(this._scope,r?.scope,e.scope);this._scope=o;let n=Av(o,r?.scope);return Iu(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:o,forceReauthorization:n,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return this._redirectPolicy==="follow"?e:Ni(e)}_unfollowedRedirect(e,t){let r=this._redirectPolicy==="follow"?void 0:yg(e,t);return r&&`${r} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let e=new Headers(this._requestInit?.headers||void 0),t;try{t=await this._authProvider?.token()}catch(r){throw Xe(r)}if(t)e.set("Authorization",`Bearer ${t}`);if(this._sessionId)e.set("mcp-session-id",this._sessionId);if(this._protocolVersion)e.set("mcp-protocol-version",this._protocolVersion);return e}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!Fr(t))return;let r=t.params?._meta?.[It];if(typeof r!=="string")return;e.set("mcp-protocol-version",r),e.set("mcp-method",t.method);let o=ig(t.method,t.params);if(o?.value!==void 0)e.set("mcp-name",gu(o.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Fr(e))return!1;let t=e.params?._meta?.[It];return typeof t==="string"&&Zt(t)}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:o,requestSignal:n}=e,i=()=>this._abortController?.signal.aborted===!0||n?.aborted===!0;try{let s=await this._commonHeaders(),a=[...s.get("accept")?.split(",").map((m)=>m.trim().toLowerCase())??[],"text/event-stream"];if(s.set("accept",[...new Set(a)].join(", ")),o)s.set("last-event-id",o);let l=this._abortController?.signal,u=n!==void 0&&l!==void 0?Ug(l,n):n??l,d=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:s,signal:u});if(!d.ok){if(d.status===401&&this._authProvider){if(d.headers.has("www-authenticate")){let{resourceMetadataUrl:f,scope:S}=Ai(d);this._resourceMetadataUrl=f,this._scope=Ru(this._scope,S)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:d,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(f){throw Xe(f)}return await d.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r)}if(await d.text?.().catch(()=>{}),t)throw Xe(new vt(O.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:d.statusText}));throw Xe(new wt)}if(d.status===403){let{resourceMetadataUrl:f,scope:S,error:b,errorDescription:y}=Ai(d);if(b==="insufficient_scope"){let v=await d.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:S,resourceMetadataUrl:f,errorDescription:y,statusText:d.statusText,text:v},r)!=="AUTHORIZED")throw Xe(new wt);return this._startOrAuthSse(e,t,r+1)}}if(await d.text?.().catch(()=>{}),d.status===405){e.onRequestStreamEnd?.();return}let m=this._unfollowedRedirect(this._url,d)??d.statusText;throw new vt(O.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${m}`,{status:d.status,statusText:d.statusText})}this._handleSseStream(d.body,e,!0)}catch(s){if(!i())this.onerror?.(s);throw s}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(Error(`Maximum reconnection attempts (${r}) exceeded.`)),e.onRequestStreamEnd?.();return}let o=this._getNextReconnectionDelay(t),n=()=>{if(this._cancelReconnection=void 0,this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this._startOrAuthSse(e).catch((i)=>{if(this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this.onerror?.(Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`));try{this._scheduleReconnection(e,t+1)}catch(s){this.onerror?.(s instanceof Error?s:Error(String(s)))}})};if(this._reconnectionScheduler){let i=this._reconnectionScheduler(n,o,t);this._cancelReconnection=typeof i==="function"?i:void 0}else{let i=setTimeout(n,o);this._cancelReconnection=()=>clearTimeout(i)}}_handleSseStream(e,t,r){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:o,replayMessageId:n,requestSignal:i,onRequestStreamEnd:s}=t,a=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0,l,u=!1,d=!1;(async()=>{try{let f=e.pipeThrough(new TextDecoderStream).pipeThrough(new wu({onRetry:(S)=>{this._serverRetryMs=S}})).getReader();while(!0){let{value:S,done:b}=await f.read();if(b)break;if(S.id)l=S.id,u=!0,o?.(S.id);if(!S.data)continue;if(!S.event||S.event==="message")try{let y=st.parse(JSON.parse(S.data));if(Bo(y)||Wo(y)){if(d=!0,n!==void 0)y.id=n}this.onmessage?.(y)}catch(y){this.onerror?.(y)}}if((r||u)&&!d&&this._abortController&&!a())this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:i,onRequestStreamEnd:s},0);else if(!a())s?.()}catch(f){if(a())return;if(this.onerror?.(Error(`SSE stream disconnected: ${f}`)),(r||u)&&!d&&this._abortController&&!a())try{this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:i,onRequestStreamEnd:s},0)}catch(S){this.onerror?.(Error(`Failed to reconnect: ${S instanceof Error?S.message:String(S)}`)),s?.()}else s?.()}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new wt("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:o}=await Mv(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await Iu(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:o,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new wt("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,r,o=0){try{let{resumptionToken:n,onresumptiontoken:i}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Fr(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch((v)=>this.onerror?.(v));return}let s=await this._commonHeaders();this._applyBodyDerivedHeaders(s,e);let a=Array.isArray(e)?e.some((v)=>mu(v)):mu(e);if(a)s.delete("mcp-session-id");if(t?.headers!==void 0)for(let[v,U]of Object.entries(t.headers)){if(jz.has(v.toLowerCase()))continue;s.set(v,U)}s.set("content-type","application/json");let l=[...s.get("accept")?.split(",").map((v)=>v.trim().toLowerCase())??[],"application/json","text/event-stream"];s.set("accept",[...new Set(l)].join(", "));let u=this._abortController?.signal,d=t?.requestSignal!==void 0&&u!==void 0?Ug(u,t.requestSignal):t?.requestSignal??u,m={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:d},f=await this._redirects(this._fetch??fetch)(this._url,m);if(a&&f.ok)this._sessionId=f.headers.get("mcp-session-id")||void 0;if(!f.ok){if(f.status===401&&this._authProvider){if(f.headers.has("www-authenticate")){let{resourceMetadataUrl:H,scope:x}=Ai(f);this._resourceMetadataUrl=H,this._scope=Ru(this._scope,x)}if(this._authProvider.onUnauthorized&&!r){try{await this._authProvider.onUnauthorized({response:f,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(H){throw Xe(H)}return await f.text?.().catch(()=>{}),this._send(e,t,!0,o)}if(await f.text?.().catch(()=>{}),r)throw Xe(new vt(O.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:f.statusText}));throw Xe(new wt)}let v=await f.text?.().catch(()=>null);if(f.status===403){let{resourceMetadataUrl:H,scope:x,error:Z,errorDescription:R}=Ai(f);if(Z==="insufficient_scope"){if(await this._stepUpAuthorize({scope:x,resourceMetadataUrl:H,errorDescription:R,statusText:f.statusText,text:v},o)!=="AUTHORIZED")throw Xe(new wt);return this._send(e,t,r,o+1)}}if(f.status===400&&typeof v==="string"&&this._isModernEnvelopedRequest(e))try{let H=st.parse(JSON.parse(v)),x=(Array.isArray(e)?e:[e]).filter((Z)=>Fr(Z));if(Wo(H)&&x.some((Z)=>Z.id===H.id)){this.onmessage?.(H);return}}catch{}let U=this._unfollowedRedirect(this._url,f)??v;throw new vt(O.ClientHttpNotImplemented,`Error POSTing to endpoint: ${U}`,{status:f.status,statusText:f.statusText,text:v})}if(f.status===202){if(await f.text?.().catch(()=>{}),rg(e))this._startOrAuthSse({resumptionToken:void 0}).catch((v)=>this.onerror?.(v));return}let S=(Array.isArray(e)?e:[e]).some((v)=>("method"in v)&&("id"in v)&&v.id!==void 0),b=f.headers.get("content-type"),y=fg(b);if(S)if(y==="text/event-stream")this._handleSseStream(f.body,{onresumptiontoken:i,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(y==="application/json"){let v=await f.json(),U=Array.isArray(v)?v.map((H)=>st.parse(H)):[st.parse(v)];for(let H of U)this.onmessage?.(H)}else throw await f.text?.().catch(()=>{}),new N(O.ClientHttpUnexpectedContent,`Unexpected content type: ${b}`,{contentType:b});else await f.text?.().catch(()=>{})}catch(n){if(t?.requestSignal?.aborted!==!0)this.onerror?.(n);throw n}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await this._redirects(this._fetch??fetch)(this._url,t);if(await r.text?.().catch(()=>{}),!r.ok&&r.status!==405)throw new vt(O.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,r)??r.statusText}`,{status:r.status,statusText:r.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};class iS{_eventSlots=new Map;setHandler(e,t){let r=this._ensureEventSlot(e);if(r.onHandler&&t)console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`);r.onHandler=t}getHandler(e){return this._eventSlots.get(e)?.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let r=this._eventSlots.get(e);if(!r)return;let o=r.listeners.indexOf(t);if(o!==-1)r.listeners.splice(o,1)}dispatch(e,t){let r=this._eventSlots.get(e);if(!r)return;r.onHandler?.(t);for(let o of[...r.listeners])o(t)}_ensureEventSlot(e){let t=this._eventSlots.get(e);if(!t)t={listeners:[]},this._eventSlots.set(e,t);return t}}class aS{_methods=new Set;claim(e,t){if(this._methods.has(e))throw Error(`Handler for "${e}" already registered (via ${t}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._methods.add(e)}replace(e){this._methods.add(e)}release(e){this._methods.delete(e)}has(e){return this._methods.has(e)}}var tS=new Set;function rS(e,t){let[r,o]=t,n=r?.shape;if(typeof n?.method?.value!=="string")return;let i=n.method.value,s=e==="request"?"setRequestHandler":"setNotificationHandler";if(!tS.has(s))tS.add(s),console.warn(`[ext-apps] ${s}(Schema, handler) is deprecated; use ${s}("${i}", { params: Schema.shape.params }, handler).`);let a=o;return[i,{params:n.params},e==="request"?(l,u)=>a({method:i,params:l},Lz(u)):(l)=>a({method:i,params:l})]}function Lz(e){return{signal:e.mcpReq.signal,requestId:e.mcpReq.id,sessionId:e.sessionId,_meta:e.mcpReq._meta,sendRequest:e.mcpReq.send,sendNotification:e.mcpReq.notify,authInfo:e.http?.authInfo}}var cS="2026-01-26";var Uz="ui/notifications/tool-input-partial";var Zz=T([h("light"),h("dark")]).describe("Color theme preference for the host environment."),ji=T([h("inline"),h("fullscreen"),h("pip")]).describe("Display mode for UI presentation."),Dz=T([h("--color-background-primary"),h("--color-background-secondary"),h("--color-background-tertiary"),h("--color-background-inverse"),h("--color-background-ghost"),h("--color-background-info"),h("--color-background-danger"),h("--color-background-success"),h("--color-background-warning"),h("--color-background-disabled"),h("--color-text-primary"),h("--color-text-secondary"),h("--color-text-tertiary"),h("--color-text-inverse"),h("--color-text-ghost"),h("--color-text-info"),h("--color-text-danger"),h("--color-text-success"),h("--color-text-warning"),h("--color-text-disabled"),h("--color-border-primary"),h("--color-border-secondary"),h("--color-border-tertiary"),h("--color-border-inverse"),h("--color-border-ghost"),h("--color-border-info"),h("--color-border-danger"),h("--color-border-success"),h("--color-border-warning"),h("--color-border-disabled"),h("--color-ring-primary"),h("--color-ring-secondary"),h("--color-ring-inverse"),h("--color-ring-info"),h("--color-ring-danger"),h("--color-ring-success"),h("--color-ring-warning"),h("--font-sans"),h("--font-mono"),h("--font-weight-normal"),h("--font-weight-medium"),h("--font-weight-semibold"),h("--font-weight-bold"),h("--font-text-xs-size"),h("--font-text-sm-size"),h("--font-text-md-size"),h("--font-text-lg-size"),h("--font-heading-xs-size"),h("--font-heading-sm-size"),h("--font-heading-md-size"),h("--font-heading-lg-size"),h("--font-heading-xl-size"),h("--font-heading-2xl-size"),h("--font-heading-3xl-size"),h("--font-text-xs-line-height"),h("--font-text-sm-line-height"),h("--font-text-md-line-height"),h("--font-text-lg-line-height"),h("--font-heading-xs-line-height"),h("--font-heading-sm-line-height"),h("--font-heading-md-line-height"),h("--font-heading-lg-line-height"),h("--font-heading-xl-line-height"),h("--font-heading-2xl-line-height"),h("--font-heading-3xl-line-height"),h("--border-radius-xs"),h("--border-radius-sm"),h("--border-radius-md"),h("--border-radius-lg"),h("--border-radius-xl"),h("--border-radius-full"),h("--border-width-regular"),h("--shadow-hairline"),h("--shadow-sm"),h("--shadow-md"),h("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),Fz=P(Dz.describe(`Style variables for theming MCP apps.
|
|
79
|
+
`,w),Y=-1;if(D!==-1&&X!==-1?Y=D<X?D:X:D!==-1?D===R.length-1?Y=-1:Y=D:X!==-1&&(Y=X),Y===-1)break;L(R,w,Y),w=Y+1,R.charCodeAt(w-1)===Vv&&R.charCodeAt(w)===qg&&w++}return R.slice(w)}function L(R,w,D){if(w===D){x();return}let X=R.charCodeAt(w);if(Mg(R,w,X)){let we=R.charCodeAt(w+5)===Xr?w+6:w+5,Ce=R.slice(we,D);d=m===0?Ce:`${d}
|
|
80
|
+
${Ce}`,m++;return}if(jg(R,w,X)){f=R.slice(R.charCodeAt(w+6)===Xr?w+7:w+6,D)||void 0;return}if(X===105&&R.charCodeAt(w+1)===100&&R.charCodeAt(w+2)===58){let we=R.slice(R.charCodeAt(w+3)===Xr?w+4:w+3,D);we.includes("\x00")||(u=we);return}if(X===58){if(n){let we=R.slice(w,D);n(we.slice(R.charCodeAt(w+1)===Xr?2:1))}return}let Y=R.slice(w,D),ue=Y.indexOf(":");if(ue===-1){H(Y,"",Y);return}let $e=Y.slice(0,ue),oe=Y.charCodeAt(ue+1)===Xr?2:1,ae=Y.slice(ue+oe);H($e,ae,Y)}function H(R,w,D){switch(R){case"event":f=w||void 0;break;case"data":d=m===0?w:`${d}
|
|
81
|
+
${w}`,m++;break;case"id":w.includes("\x00")||(u=w);break;case"retry":/^\d+$/.test(w)?o(parseInt(w,10)):r(new kc(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:D}));break;default:r(new kc(`Unknown field "${R.length>20?`${R.slice(0,20)}…`:R}"`,{type:"unknown-field",field:R,value:w,line:D}));break}}function x(){m>0&&t({id:u,event:f,data:d}),u=void 0,d="",m=0,f=void 0}function Z(R={}){if(R.consume&&s.length>0){let w=s.join("");L(w,0,w.length)}l=!0,u=void 0,d="",m=0,f=void 0,s.length=0,a=0,g=!1}return{feed:b,reset:Z}}function Mg(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function jg(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}class Ou extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:o}={}){let n;super({start(i){n=Lg({onEvent:(s)=>{i.enqueue(s)},onError(s){typeof e=="function"&&e(s),(e==="terminate"||s.type==="max-buffer-size-exceeded")&&i.error(s)},onRetry:t,onComment:r,maxBufferSize:o})},transform(i){n.feed(i)}})}}var Hi=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Ke(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ke(this,e)}constructor(e){super(e);this.name=new.target.name,Wr(this,new.target)}},Uu=class extends Hi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 §3.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`);this.kind=e,this.expected=t,this.received=r}},Jv=class extends Hi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`);this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},Xg=class extends Hi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`);this.tokenEndpoint=e}},Ic=class extends Hi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`);this.recordedIssuer=e,this.currentIssuer=t}},Ug=class extends Hi{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`);this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function Zu(e,t,r){if(!e)return;if(typeof e.issuer!=="string"){if(r?.canPersistStamp!==!1)console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field.");return e.issuer===void 0?e:{...e,issuer:void 0}}return Qg(e.issuer,t)?e:void 0}function Qg(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function Bv(e){if(e==null)return!1;let t=e;return typeof t.tokens==="function"&&typeof t.clientInformation==="function"}async function Wv(e,t,r){let{resourceMetadataUrl:o,scope:n}=Fi(t.response);if(await Du(e,{serverUrl:t.serverUrl,resourceMetadataUrl:o,scope:n,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new kt}function Kv(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async(r)=>Wv(e,r,t)}}var kt=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Ke(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ke(this,e)}constructor(e){super(e??"Unauthorized");this.name="UnauthorizedError",Wr(this,new.target)}};function Hu(e){return e?.authorization_response_iss_parameter_supported===!0}function Vu({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t===void 0)return;if(e===void 0){if(r)throw new Uu("authorization_response",t,void 0);return}if(e!==t)throw new Uu("authorization_response",t,e)}function Nu(...e){let t=new Set;for(let r of e){if(!r)continue;for(let o of r.split(/\s+/))if(o)t.add(o)}return t.size>0?[...t].join(" "):void 0}function Gv(e,t){if(!e)return!1;let r=new Set((t??"").split(/\s+/).filter(Boolean));for(let o of e.split(/\s+/))if(o&&!r.has(o))return!0;return!1}async function Yv(e,t,r,o,n){if(typeof e==="string")return{authorizationCode:e,iss:t};let i=e.get("iss")??void 0,s=e.get("code");if(s)return{authorizationCode:s,iss:i};let a=(await r.discoveryState?.())?.authorizationServerMetadata;if(!a)try{a=(await nS(o,n)).authorizationServerMetadata}catch{a=void 0}if(!a)throw new kt("Authorization callback failed and the issuer could not be verified");Vu({iss:i,expectedIssuer:a.issuer,issParameterSupported:Hu(a)});let l=e.get("error");if(l)throw new Kr(l,e.get("error_description")??l,e.get("error_uri")??void 0);throw new kt("Authorization callback contained neither `code` nor `error`")}function Xv(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var Au="code",qu="S256";function Qv(e,t){let r=e.client_secret!==void 0;if("token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Xv(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method)))return e.token_endpoint_auth_method;if(t.length===0)return r?"client_secret_basic":"none";if(r&&t.includes("client_secret_basic"))return"client_secret_basic";if(r&&t.includes("client_secret_post"))return"client_secret_post";if(t.includes("none"))return"none";return r?"client_secret_post":"none"}function ez(e,t,r,o){let{client_id:n,client_secret:i}=t;switch(e){case"client_secret_basic":tz(n,i,r);return;case"client_secret_post":rz(n,i,o);return;case"none":oz(n,o);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function tz(e,t,r){if(!t)throw Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}function rz(e,t,r){if(r.set("client_id",e),t)r.set("client_secret",t)}function oz(e,t){t.set("client_id",e)}function eS(e){return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function nz(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!eS(t.hostname))throw new Xg(t.href);return t}function sz(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:")return"native";if(eS(r.hostname))return"native"}return"web"}function iz(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??sz(t.redirect_uris)}}async function Zg(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Yo.parse(JSON.parse(r));return Kr.fromResponse(o)}catch(o){let n=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Kr(Vt.ServerError,n)}}function Dg(e,t,r){let o=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${r} (provider implements no invalidateCredentials())`:`invalidating the stored ${r} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} — ${o}. Cause: ${JSON.stringify(t.message)}`)}async function Du(e,t){try{return await Mu(e,t)}catch(r){if(r instanceof Kr){if(r.code===Vt.InvalidClient||r.code===Vt.UnauthorizedClient)return Dg(e,r,"client credentials and tokens"),await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await Mu(e,t);else if(r.code===Vt.InvalidGrant||r.code===Vt.InvalidDpopProof)return Dg(e,r,"tokens"),await e.invalidateCredentials?.("tokens"),await Mu(e,t)}throw r}}function az(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:o,clientMetadata:n}=e,i=t||r?.scopes_supported?.join(" ")||n.scope;if(i&&o?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&n.grant_types?.includes("refresh_token"))i=`${i} offline_access`;return i}async function Mu(e,{serverUrl:t,authorizationCode:r,iss:o,scope:n,resourceMetadataUrl:i,fetchFn:s,skipIssuerMetadataValidation:a,forceReauthorization:l}){let u=iz(e),d=await e.discoveryState?.(),m,f,g,b,y=i;if(!y&&d?.resourceMetadataUrl)y=new URL(d.resourceMetadataUrl);if(d?.authorizationServerUrl){if(f=d.authorizationServerUrl,m=d.resourceMetadata,g=d.authorizationServerMetadata??await oS(f,{fetchFn:s,skipIssuerValidation:a}),!m)try{m=await tS(t,{resourceMetadataUrl:y},s)}catch(oe){if(oe instanceof TypeError)throw oe}if(g!==d.authorizationServerMetadata||m!==d.resourceMetadata)await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:g})}else{let oe=await nS(t,{resourceMetadataUrl:y,fetchFn:s,skipIssuerMetadataValidation:a});f=oe.authorizationServerUrl,g=oe.authorizationServerMetadata,m=oe.resourceMetadata,b={authorizationServerUrl:String(f),resourceMetadataUrl:y?.toString(),resourceMetadata:m,authorizationServerMetadata:g}}let v=g?.issuer??String(f),L={issuer:v};if(await e.saveAuthorizationServerUrl?.(v),r!==void 0){let oe=d?.authorizationServerMetadata?.issuer??d?.authorizationServerUrl;if(oe===void 0){if(e.saveDiscoveryState!==void 0)throw new Ic("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",v);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.")}else if(!Qg(oe,v))throw new Ic(oe,v)}if(b)await e.saveDiscoveryState?.(b);let H=await lz(t,e,m),x=H&&m&&!e.validateResourceURL?m.resource:H;if(x)await e.saveResourceUrl?.(Ju(x));let Z=az({requestedScope:n,resourceMetadata:m,authServerMetadata:g,clientMetadata:e.clientMetadata}),R=await Promise.resolve(e.clientInformation(L)),w=Zu(R,v,{canPersistStamp:e.saveClientInformation!==void 0});if(w===void 0&&R?.issuer&&e.saveClientInformation===void 0)throw new Ic(R.issuer,v);if(w&&w.issuer===void 0)w={...w,issuer:v},await e.saveClientInformation?.(w,L);if(!w){if(r!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");let oe=g?.client_id_metadata_document_supported===!0,ae=e.clientMetadataUrl;if(ae&&!cz(ae))throw new Kr(Vt.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ae}`);if(oe&&ae)w={client_id:ae,issuer:v},await e.saveClientInformation?.(w,L);else{if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");w={...await bz(f,{metadata:g,clientMetadata:u,scope:Z,fetchFn:s}),issuer:v},await e.saveClientInformation(w,L)}}let D=!e.redirectUrl;if(r!==void 0||D){if(r!==void 0)Vu({iss:o,expectedIssuer:g?.issuer,issParameterSupported:Hu(g)});let oe=await _z(e,f,{metadata:g,resource:x,authorizationCode:r,iss:o,scope:Z,fetchFn:s});return await e.saveTokens({...oe,issuer:v},L),"AUTHORIZED"}let X=Zu(await e.tokens(L),v);if(X&&X.issuer===void 0)X={...X,issuer:v},await e.saveTokens(X,L);if(X?.refresh_token&&!l){let oe;try{oe=await Sz(f,{metadata:g,clientInformation:w,refreshToken:X.refresh_token,resource:x,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:s})}catch(ae){if(ae instanceof Xg)throw ae;if(!(ae instanceof Kr)||ae.code===Vt.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(ae instanceof Error?ae.message:String(ae))}`);else throw ae}if(oe)return await e.saveTokens({...oe,issuer:v},L),"AUTHORIZED"}let Y=e.state?await e.state():void 0,{authorizationUrl:ue,codeVerifier:$e}=await fz(f,{metadata:g,clientInformation:w,state:Y,redirectUrl:e.redirectUrl,scope:Z,resource:x});return await e.saveCodeVerifier($e),await e.redirectToAuthorization(ue),"REDIRECT"}function cz(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function lz(e,t,r){let o=Ff(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(!r)return;if(!Hf({requestedResource:o,configuredResource:r.resource}))throw Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}var uz=new Set(["bearer","dpop"]);function Fi(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(!r||!uz.has(r.toLowerCase())||!o)return{};let n=$c(e,"resource_metadata")||void 0,i;if(n)try{i=new URL(n)}catch{}let s=$c(e,"scope")||void 0,a=$c(e,"error")||void 0,l=$c(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:s,error:a,errorDescription:l}}function $c(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),n=r.match(o);if(n){let i=n[1]||n[2];if(i)return i}return null}async function tS(e,t,r=fetch){let o=await hz(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.text?.().catch(()=>{}),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.text?.().catch(()=>{}),Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Wo.parse(await o.json())}async function rS(e,t,r=fetch){let o=Zi(r);try{return await o(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!Ag)throw n;if(t)try{return await o(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}return}}function dz(e,t="",r={}){if(t.endsWith("/"))t=t.slice(0,-1);return r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Fg(e,t,r=fetch){return await rS(e,{"MCP-Protocol-Version":t},r)}function pz(e,t){if(!e)return!0;if(t==="/")return!1;return!e.ok&&e.status<500||e.status===502}async function hz(e,t,r,o){let n=new URL(e),i=o?.protocolVersion??yo,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let l=dz(t,n.pathname);s=new URL(l,o?.metadataServerUrl??n),s.search=n.search}let a=await Fg(s,i,r);if(!o?.metadataUrl&&pz(a,n.pathname))a=await Fg(new URL(`/.well-known/${t}`,n),i,r);return a}function mz(e){let t=typeof e==="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let n=t.pathname;if(n.endsWith("/"))n=n.slice(0,-1);return o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"},{url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function oS(e,{fetchFn:t=fetch,protocolVersion:r=yo,skipIssuerValidation:o=!1}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},i=mz(e);for(let{url:s,type:a}of i){let l=await rS(s,n,t);if(!l)continue;if(!l.ok){if(await l.text?.().catch(()=>{}),l.status<500||l.status===502)continue;throw Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}let u=a==="oauth"?Br.parse(await l.json()):Ko.parse(await l.json());if(!o){let d=typeof e==="string"?e:e.href;if(!(u.issuer===d||d.endsWith("/")&&u.issuer===d.slice(0,-1)))throw new Uu("metadata",d,u.issuer)}return u}}async function nS(e,t){let r,o;try{if(r=await tS(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0)o=r.authorization_servers[0]}catch(i){if(i instanceof TypeError)throw i}if(!o)o=String(new URL("/",e));let n=await oS(o,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function Ju(e){return typeof e==="string"?e:e.href}async function fz(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:n,state:i,resource:s}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Au))throw Error(`Incompatible auth server: does not support response type ${Au}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(qu))throw Error(`Incompatible auth server: does not support code challenge method ${qu}`)}else a=new URL("/authorize",e);let l=await Cu(),{code_verifier:u,code_challenge:d}=l;if(a.searchParams.set("response_type",Au),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",qu),a.searchParams.set("redirect_uri",String(o)),i)a.searchParams.set("state",i);if(n)a.searchParams.set("scope",n);if(n?.split(" ").includes("offline_access"))a.searchParams.append("prompt","consent");if(s)a.searchParams.set("resource",Ju(s));return{authorizationUrl:a,codeVerifier:u}}function gz(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function sS(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:i,dpop:s,fetchFn:a}){let l=nz(t?.token_endpoint??new URL("/token",e)),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i)r.set("resource",Ju(i));if(!n&&o)ez(Qv(o,t?.token_endpoint_auth_methods_supported??[]),o,u,r);let d=async()=>{let g=new Headers(u);if(n)await n(g,r,l,t);if(s)g.set("DPoP",await s.buildProof({htm:"POST",htu:l}));return Zi(a??fetch)(l,{method:"POST",headers:g,body:r})},m=await d();if(s&&m.status===400){if((await m.clone().json().catch(()=>{}))?.error===Vt.UseDpopNonce)s.observeNonce(m,l),m=await d()}if(s?.observeNonce(m,l),!m.ok)throw await Zg(m);let f=await m.json();try{return Go.parse(gu(f))}catch(g){if(typeof f==="object"&&f!==null&&"error"in f)throw await Zg(JSON.stringify(f));throw g}}async function Sz(e,{metadata:t,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:i,dpop:s,fetchFn:a}){return{refresh_token:o,...await sS(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),clientInformation:r,addClientAuthentication:i,resource:n,dpop:s,fetchFn:a})}}async function _z(e,t,{metadata:r,resource:o,authorizationCode:n,iss:i,scope:s,fetchFn:a}={}){if(n!==void 0)Vu({iss:i,expectedIssuer:r?.issuer,issParameterSupported:Hu(r)});let l=r?.issuer??String(t),u=async()=>{let g=await e.clientInformation({issuer:l}),b=Zu(g,l,{canPersistStamp:!1});if(g&&b===void 0)throw new Ic(String(g.issuer),l);return b},d=await u(),m=s??e.clientMetadata.scope,f;if(e.prepareTokenRequest)f=await e.prepareTokenRequest(m);if(!f){if(!n)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");f=gz(n,await e.codeVerifier(),e.redirectUrl)}return d??=await u(),sS(t,{metadata:r,tokenRequestParams:f,clientInformation:d,addClientAuthentication:e.addClientAuthentication,resource:o,dpop:await e.dpop?.(),fetchFn:a})}async function bz(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:n}){let i;if(t){if(!t.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let s={...r,...o===void 0?{}:{scope:o}},a=await Zi(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok)throw new Jv({status:a.status,body:await a.text(),submittedMetadata:s});return Xo.parse(gu(await a.json()))}var Cc=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),yz=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(ju(e))}set(e,t){let r=ju(e),o=Cc.has(e.method),n=!this._entries.has(r);if(!o&&n&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let s of this._entries.keys())if(!Cc.has(s.slice(0,s.indexOf("\x00")))){this._entries.delete(s),this._cappedSize--;break}}let i=++this._stamp;if(this._entries.set(r,{...t,stamp:i}),n&&!o)this._cappedSize++;return i}delete(e){if(this._entries.delete(ju(e))&&!Cc.has(e.method))this._cappedSize--}evict(e){let t=`${e}\x00`,r=Cc.has(e);for(let o of this._entries.keys())if(o.startsWith(t)){if(this._entries.delete(o),!r)this._cappedSize--}}clear(){this._entries.clear(),this._cappedSize=0}};function ju(e){return`${e.method}\x00${JSON.stringify([e.partition??"",e.params??""])}`}function Lu(e,t){return t===void 0?e:`${e}\x00${t}`}var vz=86400000,zz=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,r=()=>{},o="",n=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=r,this._cachePartition=o,this._now=n}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){let r={method:e,params:t??""},o=this._partitionFor("private"),n=await this._store.get({...r,partition:o});if(n!==void 0)return n;let i=this._partitionFor("public");if(i===o)return;let s=await this._store.get({...r,partition:i});return s?.scope==="public"?s:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){let r=this._partitionFor("private"),o=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:r})}catch(n){this._reportError(n)}if(o!==r)try{await this._store.delete({method:e,params:t,partition:o})}catch(n){this._reportError(n)}}async evictKey(e,t){let r=Lu(e,t),o=this._evictionGeneration.get(r);if(o!==void 0)this._evictionGeneration.set(r,o+1);await this._deleteBoth(e,t)}captureGeneration(e,t){let r=Lu(e,t),o=this._evictionGeneration.get(r)??0;return this._evictionGeneration.set(r,o),o}async write(e,t,r,o){if((this._evictionGeneration.get(Lu(e,o?.params))??0)!==r)return;let n=o?.params??"",i=this._partitionFor("private"),s=this._partitionFor("public"),a=(o?.scope??"private")==="public"?s:i;try{await this._store.set({method:e,params:n,partition:a},{value:wz(t),expiresAt:o?.expiresAt,scope:o?.scope})}catch(l){this._reportError(l)}if(s!==i)try{await this._store.delete({method:e,params:n,partition:a===i?s:i})}catch(l){this._reportError(l)}}async read(e,t){let r=await this._probe(e,t);if(r?.expiresAt===void 0||!(r.expiresAt>this.now()))return;try{let o=JSON.parse(r.value);if(typeof o!=="object"||o===null||Array.isArray(o))throw TypeError("cached document is not an object");return{value:o}}catch(o){this._reportError(o),await this._deleteBoth(e,t??"");return}}resetForReconnect(){if(!this._isUserSupplied)this._store.clear();this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){let t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let r=this._decodeListTools(t),o=new Map;if(r!==void 0)for(let n of r.tools)o.set(n.name,n);this._toolIndex={stamp:t.stamp,byName:o}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let r=await this._probe("tools/list");if(r===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==r.stamp){let o=this._decodeListTools(r)??{tools:[]},n=new Map;for(let i of o.tools){let s=t(i);if(s!==void 0)n.set(i.name,s)}this._toolOutputValidatorIndex={stamp:r.stamp,byName:n}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every((r)=>r!==null&&typeof r==="object"))throw TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};function wz(e){let t;try{t=JSON.stringify(e)}catch(r){throw TypeError(`cache value is not JSON-serializable: ${r instanceof Error?r.message:String(r)}`)}if(typeof t!=="string")throw TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}var iS=Symbol.for("mcp.authSeamEscape");function tt(e){if(typeof e==="object"&&e!==null||typeof e==="function")try{Object.defineProperty(e,iS,{value:!0,configurable:!0})}catch{}return e}function Rz(e){return(typeof e==="object"&&e!==null||typeof e==="function")&&e[iS]===!0}var xz=-32022,Pz=new Set([-32001,-32020,-32021]);function Tz(e,t){switch(e.kind){case"result":return Ez(e.result,t);case"rpc-error":return aS(e,t);case"http-error":return kz(e,t);case"network-error":return Hg(e.error,t);case"unusable-reply":return{kind:"error",error:new A(N.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${cS(e.error)})`,{cause:e.error},{cause:e.error})};case"auth-required":return{kind:"error",error:e.error};case"closed":if(t.transportKind==="stdio")return{kind:"legacy"};return Hg(Error("Connection closed during the version negotiation probe"),t);case"timeout":if(t.transportKind==="stdio")return{kind:"legacy"};return{kind:"error",error:new A(N.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function Ez(e,t){let r=Ht(xc).validateResult("server/discover",e);if(!r.ok)return{kind:"legacy"};let o=r.value.supportedVersions,n=t.clientModernVersions.find((i)=>o.includes(i));if(n!==void 0)return{kind:"modern",version:n,discover:r.value};if(t.fallbackAvailable)return{kind:"legacy"};return{kind:"error",error:new Rc({supported:[...o],requested:t.requestedVersion})}}function aS(e,t){let{code:r,message:o,data:n}=e;if(r===xz){let i=Cz(n);if(i===void 0)return{kind:"legacy"};let s=new Rc({supported:i,requested:Iz(n)??t.requestedVersion},o),a=Ui(i),l=t.clientModernVersions.find((u)=>a.includes(u));if(l!==void 0)return{kind:"corrective",version:l,error:s};if(a.length>0)return{kind:"error",error:s};return t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:s}}if(Pz.has(r))return{kind:"legacy"};return{kind:"legacy"}}function kz(e,t){if(e.status===401||e.status===403){let o=e.status===403;return{kind:"error",error:new Tt(o?N.ClientHttpForbidden:N.ClientHttpAuthentication,`Version negotiation failed: ${o?"the server denied access (HTTP 403)":"the server requires authorization (HTTP 401)"}`,{status:e.status,statusText:e.statusText,text:e.body})}}if(e.status>=500)return{kind:"error",error:new Tt(N.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let r=Oz(e.body);if(r!==void 0)return aS(r,t);return{kind:"legacy"}}function Hg(e,t){if(t.environment==="browser"&&$z(e))return{kind:"legacy"};return{kind:"error",error:new A(N.EraNegotiationFailed,`Version negotiation probe failed: ${cS(e)}`,{cause:e},{cause:e})}}function $z(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function cS(e){return e instanceof Error?e.message:String(e)}function Cz(e){if(typeof e!=="object"||e===null)return;let t=e.supported;if(!Array.isArray(t)||t.length===0||!t.every((r)=>typeof r==="string"))return;return t}function Iz(e){if(typeof e!=="object"||e===null)return;let t=e.requested;return typeof t==="string"?t:void 0}function Oz(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=="object"||t===null)return;let r=t.error;if(typeof r!=="object"||r===null)return;let{code:o,message:n,data:i}=r;if(typeof o!=="number")return;return{code:o,message:typeof n==="string"?n:"",data:i}}var Nz="legacy";function Az(e,t){let r=e?.mode??Nz;if(r==="legacy")return{kind:"legacy"};let o=e?.probe??{};if(typeof r==="object"){if(!Jt(r.pin))throw TypeError(`versionNegotiation: { pin: '${r.pin}' } is not a modern protocol revision — pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:r.pin,probe:o}}let n=t?Ui(t):[];return{kind:"auto",modernVersions:n.length>0?n:[...Su],fallbackAvailable:t?_u(t).length>0:!0,probe:o}}function Vg(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function Jg(e){return"stderr"in e&&"pid"in e?"stdio":"http"}var qz=class e{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(t){this._transport=t,this._savedOnMessage=t.onmessage,this._savedOnError=t.onerror,this._savedOnClose=t.onclose}static async open(t){let r=new e(t);t.onmessage=(o)=>{let n=r._pending;if(n!==void 0&&(en(o)||tn(o))&&o.id===n.id){if(r._pending=void 0,en(o))n.resolve({kind:"response",result:o.result});else n.resolve({kind:"response",error:o.error});return}},t.onerror=(o)=>{r._savedOnError?.(o)},t.onclose=()=>{let o=r._pending;if(o!==void 0)r._pending=void 0,o.resolve({kind:"closed"});r._closeDelivered=!0,r._savedOnClose?.()};try{await t.start()}catch(o){throw r.detach(),o}return r}async exchange(t,r){let o=`server-discover-probe-${++this._probeCounter}`;return new Promise((n)=>{let i=!1,s=(l)=>{if(i)return;if(i=!0,clearTimeout(a),this._pending?.id===o)this._pending=void 0;n(l)},a=setTimeout(()=>s({kind:"timeout"}),r);this._pending={id:o,resolve:s},this._transport.send(t(o)).catch((l)=>s({kind:"send-error",error:l}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let t=this._savedOnClose,r=this._transport,o=!1,n=()=>{if(!o){o=!0;return}t()};r.onclose=n,Fu.set(r,()=>{if(r.onclose===n)r.onclose=t})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let t=this._transport,r=t.start,o=!0;t.start=async function(){if(o){o=!1,t.start=r;return}return r.call(t)}}},Fu=new WeakMap;function Bg(e){let t=Fu.get(e);Fu.delete(e),t?.()}function Mz(e,t,r,o){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:Ht(t).outboundEnvelope({protocolVersion:t,clientInfo:r,clientCapabilities:o})}}}function jz(e){if(e instanceof A&&e.code===N.ClientHttpUnexpectedContent)return!0;return e instanceof Error&&e.name==="SyntaxError"}function Lz(e,t){switch(e.kind){case"response":return e.error===void 0?{kind:"result",result:e.result}:{kind:"rpc-error",...e.error};case"send-error":{let r=e.error;if(Rz(r)||r instanceof kt||r instanceof Error&&r.name==="UnauthorizedError")return{kind:"auth-required",error:r};if(r instanceof Tt){let o=r.data?.text;return{kind:"http-error",status:r.data.status,body:typeof o==="string"?o:void 0,statusText:r.data.statusText}}if(jz(r))return{kind:"unusable-reply",error:r};return{kind:"network-error",error:r}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function lS(e,t){let r=e.probe.timeoutMs??t.defaultTimeoutMs,o=Math.max(0,e.probe.maxRetries??0),n=e.kind==="pin"?[e.version]:e.modernVersions,i=e.kind==="auto"&&e.fallbackAvailable,s=await qz.open(t.transport),a=async()=>{let u=n[0],d=!1,m=o;for(;;){let f=await s.exchange((y)=>Mz(y,u,t.clientInfo,t.capabilities),r);if(f.kind==="timeout"&&m>0){m--;continue}let g=Lz(f,r),b=Tz(g,{clientModernVersions:n,requestedVersion:u,fallbackAvailable:i,environment:t.environment,transportKind:t.transportKind});switch(b.kind){case"modern":return{era:"modern",version:b.version,discover:b.discover};case"corrective":if(d)throw b.error;d=!0,u=b.version;continue;case"legacy":{let y=g.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new A(N.EraNegotiationFailed,y===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${y} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new A(N.EraNegotiationFailed,y===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${y} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(y!==void 0&&t.disposableProbe!==!0)throw new A(N.EraNegotiationFailed,`Version negotiation failed: ${y} (this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw b.error}}},l;try{l=await a()}catch(u){throw s.detach(),u}return s.release(),l}function Uz(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;let r=e._serverParams;return typeof r==="object"&&r!==null&&typeof r.command==="string"?r:void 0}async function Zz(e,t,r,o){let i=new t.constructor({...r,stderr:"ignore"}),s=t.close,a=!1,l,u=new Promise((m,f)=>{l=()=>f(Wg())});t.close=async function(){return a=!0,l?.(),s.call(t)};let d;try{let m=lS(e,{...o,transport:i,transportKind:"stdio",disposableProbe:!0});m.catch(()=>{}),d=await Promise.race([m,u])}finally{await Dz(i),t.close=s}if(a)throw Wg();return d}function Wg(){return new A(N.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function Dz(e){try{let t=e._dispose;await(typeof t==="function"?t.call(e):e.close())}catch{}}function Kg(e){let t=e._meta?.[jt];return wg.Implementation(t)?t:void 0}function Oc(e,t){if(!e||t===null||typeof t!=="object")return;if(e.type==="object"&&e.properties&&typeof e.properties==="object"){let r=t,o=e.properties;for(let n of Object.keys(o)){let i=o[n];if(r[n]===void 0&&Object.prototype.hasOwnProperty.call(i,"default"))r[n]=i.default;if(r[n]!==void 0)Oc(i,r[n])}}if(Array.isArray(e.anyOf)){for(let r of e.anyOf)if(typeof r!=="boolean")Oc(r,t)}if(Array.isArray(e.oneOf)){for(let r of e.oneOf)if(typeof r!=="boolean")Oc(r,t)}}function Fz(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}function Hz(e){if(typeof e==="object"&&e!==null){if(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e))return e;if(e.kind==="modern"&&lr.safeParse(e.discover).success)return e}throw new A(N.EraNegotiationFailed,"connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }")}var Gg={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},Vz=64,uS=class extends Ec{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new A(N.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t);if(this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new ku,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=bg(t?.inputRequired),this._cache=new zz(t?.responseCacheStore??new yz,t?.responseCacheStore!==void 0,(r)=>this._reportStoreError(r),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??Vz,t?.listChanged)this._listChangedConfig=t.listChanged}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&Jt(this._negotiatedProtocolVersion)&&Gr(e))return"drop"}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){if(!this._inputRequiredDriverConfig.autoFulfill)return Promise.reject(new A(N.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance — pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:t.request.method}));return xg({getRequestHandler:(r)=>this._getRequestHandler(r),buildContext:(r)=>this.buildContext(r,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t)}_setupListChangedHandlers(e){if(e.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools);if(e.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts);if(e.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources","notifications/resources/list_changed",e.resources,async()=>(await this.listResources(void 0,{cacheMode:"refresh"})).resources)}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=Rg(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){if(e==="elicitation/create")return async(r,o)=>{let n=Ht(this._negotiatedProtocolVersion),i=n.validateRequest("elicitation/create",r);if(!i.ok&&i.reason==="not-in-era")i=n.validateInputRequest("elicitation/create",r);if(!i.ok)throw new re(i.reason==="not-in-era"?W.InternalError:W.InvalidParams,i.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${i.message}`);let{params:s}=i.value;s.mode=s.mode??"form";let{supportsFormMode:a,supportsUrlMode:l}=Fz(this._capabilities.elicitation);if(s.mode==="form"&&!a)throw new re(W.InvalidParams,"Client does not support form-mode elicitation requests");if(s.mode==="url"&&!l)throw new re(W.InvalidParams,"Client does not support URL-mode elicitation requests");let u=await t(r,o),d=n.validateResult("elicitation/create",u);if(!d.ok&&d.reason==="not-in-era")d=n.validateInputResponse("elicitation/create",u);if(!d.ok)throw new re(d.reason==="not-in-era"?W.InternalError:W.InvalidParams,d.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${d.message}`);let m=d.value,f=s.mode==="form"?s.requestedSchema:void 0;if(s.mode==="form"&&m.action==="accept"&&m.content&&f&&this._capabilities.elicitation?.form?.applyDefaults)try{Oc(f,m.content)}catch{}return m};if(e==="sampling/createMessage")return async(r,o)=>{let n=Ht(this._negotiatedProtocolVersion),i=n.validateRequest("sampling/createMessage",r);if(!i.ok&&i.reason==="not-in-era")i=n.validateInputRequest("sampling/createMessage",r);if(!i.ok)throw new re(i.reason==="not-in-era"?W.InternalError:W.InvalidParams,i.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${i.message}`);let{params:s}=i.value,a=await t(r,o),l=Boolean(s.tools||s.toolChoice),u=n.samplingResultVariant(l,a);if(!u.ok&&u.reason==="not-in-era")u=n.validateInputResponse("sampling/createMessage",a);if(!u.ok)throw new re(u.reason==="not-in-era"?W.InternalError:W.InvalidParams,u.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${u.message}`);return u.value};return t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new A(N.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,Hz(t.prior),t);let r=Az(this._versionNegotiation,this._supportedProtocolVersionsOption);if(r.kind!=="legacy")return this._connectNegotiated(e,r,t);return this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let r=this._negotiatedProtocolVersion;if(r!==void 0)e.setProtocolVersion?.(r);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let r=_u(this._supportedProtocolVersions);try{let o=r[0];if(o===void 0)throw new A(N.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let n=await this.request({method:"initialize",params:{protocolVersion:o,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!r.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);if(this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion)e.setProtocolVersion(n.protocolVersion);if(this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=n.protocolVersion,this._listChangedConfig)this._setupListChangedHandlers(this._listChangedConfig)}catch(o){throw this.close(),o}}async _connectNegotiated(e,t,r){if(e.sessionId!==void 0){await super.connect(e);let n=this._negotiatedProtocolVersion;if(n!==void 0&&e.setProtocolVersion)e.setProtocolVersion(n);return}this._resetConnectionState();let o;try{let n=Jg(e),i={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:Vg(),defaultTimeoutMs:r?.timeout??Tc},s=n==="stdio"?Uz(e):void 0;o=s===void 0?await lS(t,{...i,transport:e,transportKind:n}):await Zz(t,e,s,i)}catch(n){throw await e.close().catch(()=>{}),Bg(e),n}if(Bg(e),await super.connect(e),o.era==="legacy"){await this._legacyHandshake(e,r);return}if(this._serverCapabilities=o.discover.capabilities,this._serverVersion=Kg(o.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.discover.instructions,this._discoverResult=o.discover,this._negotiatedProtocolVersion=o.version,e.setProtocolVersion)e.setProtocolVersion(o.version);if(this._listChangedConfig){let n=this._listChangedConfig,i=this._serverCapabilities,s={...n.tools&&i?.tools?.listChanged&&{tools:n.tools},...n.prompts&&i?.prompts?.listChanged&&{prompts:n.prompts},...n.resources&&i?.resources?.listChanged&&{resources:n.resources}},a=!0;try{this._setupListChangedHandlers(s)}catch(u){a=!1,this.onerror?.(u instanceof Error?u:Error(String(u)))}let l=a?{...s.tools&&{toolsListChanged:!0},...s.prompts&&{promptsListChanged:!0},...s.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(l).length>0){let u=new AbortController,d=()=>u.abort(r?.signal?.reason);if(r?.signal?.aborted)d();r?.signal?.addEventListener("abort",d);try{this._autoOpenedSubscription=await this.listen(l,{timeout:r?.timeout,signal:u.signal})}catch(m){if(r?.signal?.aborted)throw await this.close().catch(()=>{}),m;this.onerror?.(m instanceof Error?m:Error(String(m)))}finally{r?.signal?.removeEventListener("abort",d)}}}}async _connectFromPrior(e,t,r){if(t.kind==="legacy")return this._connectPlainLegacy(e,r);let o=t.discover;this._resetConnectionState();let n=this._supportedProtocolVersionsOption,i=(n&&Ui(n).length>0?Ui(n):Su).find((s)=>o.supportedVersions.includes(s));if(i===void 0)throw new A(N.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(e),this._discoverResult=o,this._serverCapabilities=o.capabilities,this._serverVersion=Kg(o),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=o.instructions,this._negotiatedProtocolVersion=i,e.setProtocolVersion?.(i),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(s){this.onerror?.(s instanceof Error?s:Error(String(s)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;if(t!==void 0)return`${t.name}@${t.version}`;return e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e===void 0)return;return Jt(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new A(N.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new A(N.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new A(N.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new A(N.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new A(N.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new A(N.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new A(N.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new A(N.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new A(N.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new A(N.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){let t=await this._requestWithSchema({method:"server/discover"},lr,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:"completion/complete",params:e},t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:"prompts/list",params:e},t);let r=await this._serveFromCache("prompts/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("prompts/list",e,t,(o)=>o.prompts)}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(e?.cursor!==void 0)return this.request({method:"resources/list",params:e},t);let r=await this._serveFromCache("resources/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("resources/list",e,t,(o)=>o.resources)}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:"resources/templates/list",params:e},t);let r=await this._serveFromCache("resources/templates/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("resources/templates/list",e,t,(o)=>o.resourceTemplates)}async _listAllPages(e,t,r,o,n){let i=r?.cacheMode==="bypass",s=this._cache.captureGeneration(e),a=await this.request({method:e,...t&&{params:{...t}}},r),l=a.nextCursor,u=a,d=1;while(l!==void 0){if(this._listMaxPages!==0&&d>=this._listMaxPages)throw new A(N.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});let m=await this.request({method:e,params:{...t,cursor:l}},r);if(m.nextCursor===l&&JSON.stringify(o(m))===JSON.stringify(o(u)))break;o(a).push(...o(m)),u=m,l=m.nextCursor,d++}if(delete a.nextCursor,n?.(a),i)return a;return await this._cache.write(e,a,s,this._freshness(a)),a}_freshness(e,t){let r=e,o=typeof r.ttlMs==="number"?r.ttlMs:this._defaultCacheTtlMs,n=r.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,o),vz),scope:n,params:t}}async _serveFromCache(e,t,r){if(r?.cacheMode==="bypass"||r?.cacheMode==="refresh")return;let o=await this._cache.read(e,t).catch((n)=>void this._reportStoreError(n));if(o!==void 0){if(r?.signal?.aborted){let n=r.signal.reason;throw n instanceof A?n:new A(N.RequestTimeout,String(n))}return o.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}_compileOutputValidator(e){if(!e.outputSchema)return;try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){let r=t??await this._cache.toolDefinition(e);return r===void 0?void 0:xu(r.inputSchema)}async readResource(e,t){let r=await this._serveFromCache("resources/read",e.uri,t);if(r!==void 0)return r;let o=this._cache.captureGeneration("resources/read",e.uri),n=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){let i=this._freshness(n,e.uri);if(i.expiresAt>this._cache.now())await this._cache.write("resources/read",n,o,i);else if(t?.cacheMode==="refresh")await this._cache.evictKey("resources/read",e.uri)}return n}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},t)}async listen(e,t){if(this.transport===void 0)throw new A(N.NotConnected,"Not connected");let r=this._negotiatedProtocolVersion;if(r===void 0||!Jt(r))throw new A(N.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${r??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:r});if(t?.signal?.aborted){let x=t.signal.reason;throw x instanceof A?x:new A(N.RequestTimeout,String(x))}let o=new AbortController,n=`listen:${this._nextListenId++}`,i="opening",s,a,l,u,d=new Promise((x,Z)=>{l=x,u=Z}),m,f=new Promise((x)=>{m=x}),g=(x)=>{if(i==="closed")return;let Z=i==="opening";if(s!==void 0)clearTimeout(s),s=void 0;if("ack"in x){i="open",l(x.ack);return}if(i="closed",a!==void 0)t?.signal?.removeEventListener("abort",a);if(this._listenState.delete(n),o.abort(),m(x.cause),Z)u(x.error??new A(N.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},b=async()=>{o.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:n}}).catch(()=>{})},y=async()=>{if(i==="closed")return;g({cause:"local"}),await b()};this._listenState.set(n,{settle:g});let v=t?.timeout??Tc;if(s=setTimeout(()=>{g({cause:"remote",error:new A(N.RequestTimeout,"subscriptions/listen ack timed out",{timeout:v})}),b().catch(()=>{})},v),t?.signal){let x=t.signal;a=()=>{if(i==="closed")return;let Z=x.reason;g({cause:"local",error:Z instanceof Error?Z:Error(String(Z??"Aborted"))}),b().catch(()=>{})},x.addEventListener("abort",a,{once:!0})}let L={jsonrpc:"2.0",id:n,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}},H=(x)=>{g({cause:"remote",error:x instanceof Error?x:Error(String(x))})};try{this.transport.send(L,{requestSignal:o.signal,onRequestStreamEnd:()=>g({cause:"remote",error:Error("subscriptions/listen: stream ended")})}).catch(H)}catch(x){H(x)}return{honoredFilter:await d,close:y,closed:f}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let r=Object.hasOwn(Gg,e.method)?Gg[e.method]:void 0;if(e.method==="notifications/resources/updated"){let o=e.params?.uri;if(typeof o==="string")this._cache.evictKey("resources/read",o)}else if(r!==void 0)for(let o of r)this._cache.evict(o);if(e.method==="notifications/subscriptions/acknowledged"){let o=e.params?._meta?.[ts],n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){let i=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);n.settle({ack:i.ok?i.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){let o=e.params?.requestId,n=typeof o==="string"?this._listenState.get(o):void 0;if(n!==void 0){n.settle({cause:"remote",error:Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,r=typeof t==="string"?this._listenState.get(t):void 0;if(r!==void 0){if(tn(e))r.settle({cause:"remote",error:re.fromError(e.error.code,e.error.message,e.error.data)});else r.settle({cause:"graceful",error:new A(N.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new A(N.ConnectionClosed,"Connection closed");for(let t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let r=this.getProtocolEra()==="modern"&&Vg()!=="browser",o=async()=>{if(!r)return t;let l;try{l=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(d){this._reportStoreError(d)}if(!l?.valid||l.declarations.length===0)return t;let u=gg(l.declarations,e.arguments);return Object.keys(u).length===0?t:{...t,headers:{...t?.headers,...u}}},n=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,(l)=>this._compileOutputValidator(l)).catch((l)=>void this._reportStoreError(l)):this._compileOutputValidator(t.toolDefinition),i=()=>{if(n===void 0||n.ok)return;let l=n.compileError,u=(l instanceof Error?l.message:String(l)).slice(0,200);throw new re(W.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${u}`)};i();let s;try{s=await this.request({method:"tools/call",params:e},await o())}catch(l){let u=l instanceof re&&l.code===Qo;if(!r||!u||t?.toolDefinition!==void 0)throw l;let d={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,d).catch((m)=>this._reportStoreError(m)),n=await this._cache.outputValidator(e.name,(m)=>this._compileOutputValidator(m)).catch((m)=>void this._reportStoreError(m)),i(),s=await this.request({method:"tools/call",params:e},await o())}let a=n!==void 0&&n.ok?n.validator:void 0;if(a){if(s.structuredContent===void 0&&!s.isError)throw new re(W.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent!==void 0&&!s.isError)try{let l=a(s.structuredContent);if(!l.valid)throw new re(W.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)}catch(l){if(l instanceof re)throw l;throw new re(W.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)}}return s}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){let o=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(o),o}let r=await this._serveFromCache("tools/list",void 0,t);if(r!==void 0)return r;return this._listAllPages("tools/list",e,t,(o)=>o.tools,(o)=>this._excludeInvalidXMcpHeaderTools(o))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||Jg(this.transport)==="stdio")return;let t=e.tools.filter((r)=>{let o=xu(r.inputSchema);if(!o.valid)return console.warn(`[mcp-sdk] excluding tool '${r.name}' from tools/list: invalid x-mcp-header declaration — ${o.reason}`),!1;return!0});if(t.length!==e.tools.length)e.tools=t}_setupListChangedHandler(e,t,r,o){let n=Pc(Ys,r);if(!n.success)throw Error(`Invalid ${e} listChanged options: ${n.error.message}`);if(typeof r.onChanged!=="function")throw TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:s}=n.data,{onChanged:a}=r,l=async()=>{if(!i){a(null,null);return}try{a(null,await o())}catch(d){a(d instanceof Error?d:Error(String(d)),null)}},u=()=>{if(s){let d=this._listChangedDebounceTimers.get(e);if(d)clearTimeout(d);let m=setTimeout(l,s);this._listChangedDebounceTimers.set(e,m)}else l()};this.setNotificationHandler(t,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function Jz(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function Bz(e){if(e.status!==401)return!1;let t=e.headers.get("www-authenticate")??"";return Jz(t)&&/use_dpop_nonce/i.test(t)}var Wz=(e,t)=>(r)=>{let o=typeof e==="function"?e:()=>e;return async(n,i)=>{let s=(i?.method??"GET").toUpperCase(),a=new URL(n.toString()),l=await o();if(!l)return r(n,i);let u=async()=>{let m=await t();if(!m)return r(n,i);let f=new Headers(i?.headers),g=await l.buildProof({htm:s,htu:a,accessToken:m});return f.set("Authorization",`DPoP ${m}`),f.set("DPoP",g),r(n,{...i,headers:f})},d=await u();if(Bz(d)&&d.headers.has("dpop-nonce"))l.observeNonce(d,a),await d.text?.().catch(()=>{}),d=await u();return l.observeNonce(d,a),d}},Kz=(e)=>Wz(async()=>{try{return await e.dpop?.()}catch(t){throw tt(t)}},async()=>{let t;try{t=await e.tokens()}catch(r){throw tt(r)}return t?.token_type?.toLowerCase()==="dpop"?t.access_token:void 0});var FP=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Ke(this,e)}static isInstance(e){if(typeof this!=="function")throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ke(this,e)}constructor(e,t,r){super(`SSE error: ${t}`);this.code=e,this.event=r,Wr(this,new.target)}};var Gz=1,Yz={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2},Xz=new Set(["authorization","dpop","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);function Yg(e,t){if(typeof AbortSignal.any==="function")return AbortSignal.any([e,t]);let r=new AbortController;if(e.aborted)return r.abort(e.reason),r.signal;if(t.aborted)return r.abort(t.reason),r.signal;let o=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",i)};function n(){o(),r.abort(e.reason)}function i(){o(),r.abort(t.reason)}return e.addEventListener("abort",n,{once:!0}),t.addEventListener("abort",i,{once:!0}),r.signal}var dS=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){if(this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,Bv(t?.authProvider)){if(this._oauthProvider=t.authProvider,this._authProvider=Kv(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop)this._fetch=Kz(t.authProvider)(t.fetch??fetch)}else this._authProvider=t?.authProvider;if(this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=Tg(t?.fetch,t?.requestInit),this._redirectPolicy==="follow")this._fetchWithInit=$g(this._fetchWithInit);this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??Yz,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??Gz)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(r){throw tt(r)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope==="throw")throw new Ug({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new Ug({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new Tt(N.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});if(e.resourceMetadataUrl)this._resourceMetadataUrl=e.resourceMetadataUrl;let r=await this._oauthProvider.tokens(),o=Nu(this._scope,r?.scope,e.scope);this._scope=o;let n=Gv(o,r?.scope);return Du(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:o,forceReauthorization:n,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return this._redirectPolicy==="follow"?e:Zi(e)}_unfollowedRedirect(e,t){let r=this._redirectPolicy==="follow"?void 0:Cg(e,t);return r&&`${r} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let e=new Headers(this._requestInit?.headers||void 0),t;try{t=await this._authProvider?.token()}catch(r){throw tt(r)}if(t)e.set("Authorization",`Bearer ${t}`);if(this._sessionId)e.set("mcp-session-id",this._sessionId);if(this._protocolVersion)e.set("mcp-protocol-version",this._protocolVersion);return e}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!Gr(t))return;let r=t.params?._meta?.[Mt];if(typeof r!=="string")return;e.set("mcp-protocol-version",r),e.set("mcp-method",t.method);let o=Sg(t.method,t.params);if(o?.value!==void 0)e.set("mcp-name",Pu(o.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Gr(e))return!1;let t=e.params?._meta?.[Mt];return typeof t==="string"&&Jt(t)}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:o,requestSignal:n}=e,i=()=>this._abortController?.signal.aborted===!0||n?.aborted===!0;try{let s=await this._commonHeaders(),a=[...s.get("accept")?.split(",").map((m)=>m.trim().toLowerCase())??[],"text/event-stream"];if(s.set("accept",[...new Set(a)].join(", ")),o)s.set("last-event-id",o);let l=this._abortController?.signal,u=n!==void 0&&l!==void 0?Yg(l,n):n??l,d=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:s,signal:u});if(!d.ok){if(d.status===401&&this._authProvider){if(d.headers.has("www-authenticate")){let{resourceMetadataUrl:f,scope:g}=Fi(d);this._resourceMetadataUrl=f,this._scope=Nu(this._scope,g)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:d,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(f){throw tt(f)}return await d.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r)}if(await d.text?.().catch(()=>{}),t)throw tt(new Tt(N.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:d.statusText}));throw tt(new kt)}if(d.status===403){let{resourceMetadataUrl:f,scope:g,error:b,errorDescription:y}=Fi(d);if(b==="insufficient_scope"){let v=await d.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:g,resourceMetadataUrl:f,errorDescription:y,statusText:d.statusText,text:v},r)!=="AUTHORIZED")throw tt(new kt);return this._startOrAuthSse(e,t,r+1)}}if(await d.text?.().catch(()=>{}),d.status===405){e.onRequestStreamEnd?.();return}let m=this._unfollowedRedirect(this._url,d)??d.statusText;throw new Tt(N.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${m}`,{status:d.status,statusText:d.statusText})}this._handleSseStream(d.body,e,!0)}catch(s){if(!i())this.onerror?.(s);throw s}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),o)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(Error(`Maximum reconnection attempts (${r}) exceeded.`)),e.onRequestStreamEnd?.();return}let o=this._getNextReconnectionDelay(t),n=()=>{if(this._cancelReconnection=void 0,this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this._startOrAuthSse(e).catch((i)=>{if(this._abortController?.signal.aborted||e.requestSignal?.aborted)return;this.onerror?.(Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`));try{this._scheduleReconnection(e,t+1)}catch(s){this.onerror?.(s instanceof Error?s:Error(String(s)))}})};if(this._reconnectionScheduler){let i=this._reconnectionScheduler(n,o,t);this._cancelReconnection=typeof i==="function"?i:void 0}else{let i=setTimeout(n,o);this._cancelReconnection=()=>clearTimeout(i)}}_handleSseStream(e,t,r){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:o,replayMessageId:n,requestSignal:i,onRequestStreamEnd:s}=t,a=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0,l,u=!1,d=!1;(async()=>{try{let f=e.pipeThrough(new TextDecoderStream).pipeThrough(new Ou({onRetry:(g)=>{this._serverRetryMs=g}})).getReader();while(!0){let{value:g,done:b}=await f.read();if(b)break;if(g.id)l=g.id,u=!0,o?.(g.id);if(!g.data)continue;if(!g.event||g.event==="message")try{let y=ut.parse(JSON.parse(g.data));if(en(y)||tn(y)){if(d=!0,n!==void 0)y.id=n}this.onmessage?.(y)}catch(y){this.onerror?.(y)}}if((r||u)&&!d&&this._abortController&&!a())this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:i,onRequestStreamEnd:s},0);else if(!a())s?.()}catch(f){if(a())return;if(this.onerror?.(Error(`SSE stream disconnected: ${f}`)),(r||u)&&!d&&this._abortController&&!a())try{this._scheduleReconnection({resumptionToken:l,onresumptiontoken:o,replayMessageId:n,requestSignal:i,onRequestStreamEnd:s},0)}catch(g){this.onerror?.(Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`)),s?.()}else s?.()}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new kt("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:o}=await Yv(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await Du(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:o,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new kt("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,r,o=0){try{let{resumptionToken:n,onresumptiontoken:i}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Gr(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch((v)=>this.onerror?.(v));return}let s=await this._commonHeaders();this._applyBodyDerivedHeaders(s,e);let a=Array.isArray(e)?e.some((v)=>Ru(v)):Ru(e);if(a)s.delete("mcp-session-id");if(t?.headers!==void 0)for(let[v,L]of Object.entries(t.headers)){if(Xz.has(v.toLowerCase()))continue;s.set(v,L)}s.set("content-type","application/json");let l=[...s.get("accept")?.split(",").map((v)=>v.trim().toLowerCase())??[],"application/json","text/event-stream"];s.set("accept",[...new Set(l)].join(", "));let u=this._abortController?.signal,d=t?.requestSignal!==void 0&&u!==void 0?Yg(u,t.requestSignal):t?.requestSignal??u,m={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:d},f=await this._redirects(this._fetch??fetch)(this._url,m);if(a&&f.ok)this._sessionId=f.headers.get("mcp-session-id")||void 0;if(!f.ok){if(f.status===401&&this._authProvider){if(f.headers.has("www-authenticate")){let{resourceMetadataUrl:H,scope:x}=Fi(f);this._resourceMetadataUrl=H,this._scope=Nu(this._scope,x)}if(this._authProvider.onUnauthorized&&!r){try{await this._authProvider.onUnauthorized({response:f,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(H){throw tt(H)}return await f.text?.().catch(()=>{}),this._send(e,t,!0,o)}if(await f.text?.().catch(()=>{}),r)throw tt(new Tt(N.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:f.statusText}));throw tt(new kt)}let v=await f.text?.().catch(()=>null);if(f.status===403){let{resourceMetadataUrl:H,scope:x,error:Z,errorDescription:R}=Fi(f);if(Z==="insufficient_scope"){if(await this._stepUpAuthorize({scope:x,resourceMetadataUrl:H,errorDescription:R,statusText:f.statusText,text:v},o)!=="AUTHORIZED")throw tt(new kt);return this._send(e,t,r,o+1)}}if(f.status===400&&typeof v==="string"&&this._isModernEnvelopedRequest(e))try{let H=ut.parse(JSON.parse(v)),x=(Array.isArray(e)?e:[e]).filter((Z)=>Gr(Z));if(tn(H)&&x.some((Z)=>Z.id===H.id)){this.onmessage?.(H);return}}catch{}let L=this._unfollowedRedirect(this._url,f)??v;throw new Tt(N.ClientHttpNotImplemented,`Error POSTing to endpoint: ${L}`,{status:f.status,statusText:f.statusText,text:v})}if(f.status===202){if(await f.text?.().catch(()=>{}),hg(e))this._startOrAuthSse({resumptionToken:void 0}).catch((v)=>this.onerror?.(v));return}let g=(Array.isArray(e)?e:[e]).some((v)=>("method"in v)&&("id"in v)&&v.id!==void 0),b=f.headers.get("content-type"),y=Pg(b);if(g)if(y==="text/event-stream")this._handleSseStream(f.body,{onresumptiontoken:i,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(y==="application/json"){let v=await f.json(),L=Array.isArray(v)?v.map((H)=>ut.parse(H)):[ut.parse(v)];for(let H of L)this.onmessage?.(H)}else throw await f.text?.().catch(()=>{}),new A(N.ClientHttpUnexpectedContent,`Unexpected content type: ${b}`,{contentType:b});else await f.text?.().catch(()=>{})}catch(n){if(t?.requestSignal?.aborted!==!0)this.onerror?.(n);throw n}}get sessionId(){return this._sessionId}async terminateSession(){if(!this._sessionId)return;try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await this._redirects(this._fetch??fetch)(this._url,t);if(await r.text?.().catch(()=>{}),!r.ok&&r.status!==405)throw new Tt(N.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,r)??r.statusText}`,{status:r.status,statusText:r.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};class SS{_eventSlots=new Map;setHandler(e,t){let r=this._ensureEventSlot(e);if(r.onHandler&&t)console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`);r.onHandler=t}getHandler(e){return this._eventSlots.get(e)?.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let r=this._eventSlots.get(e);if(!r)return;let o=r.listeners.indexOf(t);if(o!==-1)r.listeners.splice(o,1)}dispatch(e,t){let r=this._eventSlots.get(e);if(!r)return;r.onHandler?.(t);for(let o of[...r.listeners])o(t)}_ensureEventSlot(e){let t=this._eventSlots.get(e);if(!t)t={listeners:[]},this._eventSlots.set(e,t);return t}}class _S{_methods=new Set;claim(e,t){if(this._methods.has(e))throw Error(`Handler for "${e}" already registered (via ${t}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._methods.add(e)}replace(e){this._methods.add(e)}release(e){this._methods.delete(e)}has(e){return this._methods.has(e)}}var pS=new Set;function hS(e,t){let[r,o]=t,n=r?.shape;if(typeof n?.method?.value!=="string")return;let i=n.method.value,s=e==="request"?"setRequestHandler":"setNotificationHandler";if(!pS.has(s))pS.add(s),console.warn(`[ext-apps] ${s}(Schema, handler) is deprecated; use ${s}("${i}", { params: Schema.shape.params }, handler).`);let a=o;return[i,{params:n.params},e==="request"?(l,u)=>a({method:i,params:l},Qz(u)):(l)=>a({method:i,params:l})]}function Qz(e){return{signal:e.mcpReq.signal,requestId:e.mcpReq.id,sessionId:e.sessionId,_meta:e.mcpReq._meta,sendRequest:e.mcpReq.send,sendNotification:e.mcpReq.notify,authInfo:e.http?.authInfo}}var bS="2026-01-26";var ew="ui/notifications/tool-input-partial";var tw=T([h("light"),h("dark")]).describe("Color theme preference for the host environment."),Vi=T([h("inline"),h("fullscreen"),h("pip")]).describe("Display mode for UI presentation."),rw=T([h("--color-background-primary"),h("--color-background-secondary"),h("--color-background-tertiary"),h("--color-background-inverse"),h("--color-background-ghost"),h("--color-background-info"),h("--color-background-danger"),h("--color-background-success"),h("--color-background-warning"),h("--color-background-disabled"),h("--color-text-primary"),h("--color-text-secondary"),h("--color-text-tertiary"),h("--color-text-inverse"),h("--color-text-ghost"),h("--color-text-info"),h("--color-text-danger"),h("--color-text-success"),h("--color-text-warning"),h("--color-text-disabled"),h("--color-border-primary"),h("--color-border-secondary"),h("--color-border-tertiary"),h("--color-border-inverse"),h("--color-border-ghost"),h("--color-border-info"),h("--color-border-danger"),h("--color-border-success"),h("--color-border-warning"),h("--color-border-disabled"),h("--color-ring-primary"),h("--color-ring-secondary"),h("--color-ring-inverse"),h("--color-ring-info"),h("--color-ring-danger"),h("--color-ring-success"),h("--color-ring-warning"),h("--font-sans"),h("--font-mono"),h("--font-weight-normal"),h("--font-weight-medium"),h("--font-weight-semibold"),h("--font-weight-bold"),h("--font-text-xs-size"),h("--font-text-sm-size"),h("--font-text-md-size"),h("--font-text-lg-size"),h("--font-heading-xs-size"),h("--font-heading-sm-size"),h("--font-heading-md-size"),h("--font-heading-lg-size"),h("--font-heading-xl-size"),h("--font-heading-2xl-size"),h("--font-heading-3xl-size"),h("--font-text-xs-line-height"),h("--font-text-sm-line-height"),h("--font-text-md-line-height"),h("--font-text-lg-line-height"),h("--font-heading-xs-line-height"),h("--font-heading-sm-line-height"),h("--font-heading-md-line-height"),h("--font-heading-lg-line-height"),h("--font-heading-xl-line-height"),h("--font-heading-2xl-line-height"),h("--font-heading-3xl-line-height"),h("--border-radius-xs"),h("--border-radius-sm"),h("--border-radius-md"),h("--border-radius-lg"),h("--border-radius-xl"),h("--border-radius-full"),h("--border-width-regular"),h("--shadow-hairline"),h("--shadow-sm"),h("--shadow-md"),h("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."),ow=P(rw.describe(`Style variables for theming MCP apps.
|
|
82
82
|
|
|
83
83
|
Individual style keys are optional - hosts may provide any subset of these values.
|
|
84
84
|
Values are strings containing CSS values (colors, sizes, font stacks, etc.).
|
|
85
85
|
|
|
86
86
|
Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
|
|
87
|
-
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),T([c(),
|
|
87
|
+
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),T([c(),ou()]).describe(`Style variables for theming MCP apps.
|
|
88
88
|
|
|
89
89
|
Individual style keys are optional - hosts may provide any subset of these values.
|
|
90
90
|
Values are strings containing CSS values (colors, sizes, font stacks, etc.).
|
|
@@ -96,10 +96,10 @@ Individual style keys are optional - hosts may provide any subset of these value
|
|
|
96
96
|
Values are strings containing CSS values (colors, sizes, font stacks, etc.).
|
|
97
97
|
|
|
98
98
|
Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Record<K, string>>\`
|
|
99
|
-
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),
|
|
99
|
+
for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),nw=p({method:h("ui/open-link"),params:p({url:c().describe("URL to open in the host's browser")})}),sw=p({isError:E().optional().describe("True if the host failed to open the URL (e.g., due to security policy).")}).passthrough(),iw=p({isError:E().optional().describe("True if the download failed (e.g., user cancelled or host denied).")}).passthrough(),aw=p({isError:E().optional().describe("True if the host rejected or failed to deliver the message.")}).passthrough(),cw=p({method:h("ui/notifications/sandbox-proxy-ready"),params:p({})}),Bu=p({connectDomains:S(c()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).
|
|
100
100
|
|
|
101
101
|
- Maps to CSP \`connect-src\` directive
|
|
102
|
-
- Empty or omitted → no network connections (secure default)`),resourceDomains:
|
|
102
|
+
- Empty or omitted → no network connections (secure default)`),resourceDomains:S(c()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:S(c()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:S(c()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),Wu=p({camera:p({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."),microphone:p({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."),geolocation:p({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."),clipboardWrite:p({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.")}),lw=p({method:h("ui/notifications/size-changed"),params:p({width:z().optional().describe("New width in pixels."),height:z().optional().describe("New height in pixels.")})}),lT=p({method:h("ui/notifications/tool-input"),params:p({arguments:P(c(),M().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.")})}),uT=p({method:h("ui/notifications/tool-input-partial"),params:p({arguments:P(c(),M().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).")})}),dT=p({method:h("ui/notifications/tool-cancelled"),params:p({reason:c().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").')})}),uw=p({fonts:c().optional()}),dw=p({variables:ow.optional().describe("CSS variables for theming the app."),css:uw.optional().describe("CSS blocks that apps can inject.")}),pT=p({method:h("ui/resource-teardown"),params:p({})}),pw=P(c(),M()),mS=p({text:p({}).optional().describe("Host supports text content blocks."),image:p({}).optional().describe("Host supports image content blocks."),audio:p({}).optional().describe("Host supports audio content blocks."),resource:p({}).optional().describe("Host supports resource content blocks."),resourceLink:p({}).optional().describe("Host supports resource link content blocks."),structuredContent:p({}).optional().describe("Host supports structured content.")}),hw=p({method:h("ui/notifications/request-teardown"),params:p({}).optional()}),mw=p({experimental:P(c(),P(c(),Va()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),openLinks:p({}).optional().describe("Host supports opening external URLs."),downloadFile:p({}).optional().describe("Host supports file downloads via ui/download-file."),serverTools:p({listChanged:E().optional().describe("Host supports tools/list_changed notifications.")}).optional().describe("Host can proxy tool calls to the MCP server."),serverResources:p({listChanged:E().optional().describe("Host supports resources/list_changed notifications.")}).optional().describe("Host can proxy resource reads to the MCP server."),logging:p({}).optional().describe("Host accepts log messages."),sandbox:p({permissions:Wu.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."),csp:Bu.optional().describe("CSP domains approved by the host.")}).optional().describe("Sandbox configuration applied by the host."),updateModelContext:mS.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."),message:mS.optional().describe("Host supports receiving content messages (ui/message) from the view."),sampling:p({tools:p({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),fw=p({experimental:P(c(),P(c(),Va()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."),tools:p({listChanged:E().optional().describe("App supports tools/list_changed notifications.")}).optional().describe("App exposes MCP-style tools that the host can call."),availableDisplayModes:S(Vi).optional().describe("Display modes the app supports.")}),gw=p({method:h("ui/notifications/initialized"),params:p({}).optional()}),hT=p({csp:Bu.optional().describe("Content Security Policy configuration for UI resources."),permissions:Wu.optional().describe("Sandbox permissions requested by the UI resource."),domain:c().optional().describe(`Dedicated origin for view sandbox.
|
|
103
103
|
|
|
104
104
|
Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists.
|
|
105
105
|
|
|
@@ -113,13 +113,13 @@ Boolean requesting whether a visible border and background is provided by the ho
|
|
|
113
113
|
|
|
114
114
|
- \`true\`: request visible border + background
|
|
115
115
|
- \`false\`: request no visible border + background
|
|
116
|
-
- omitted: host decides border`)}),
|
|
116
|
+
- omitted: host decides border`)}),fS=p({method:h("ui/request-display-mode"),params:p({mode:Vi.describe("The display mode being requested.")})}),gS=p({mode:Vi.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),Sw=T([h("model"),h("app")]).describe("Tool visibility scope - who can access the tool."),mT=p({resourceUri:c().optional(),visibility:S(Sw).optional().describe(`Who can access this tool. Default: ["model", "app"]
|
|
117
117
|
- "model": Tool visible to and callable by the agent
|
|
118
|
-
- "app": Tool callable by the app from this server only`),csp:
|
|
119
|
-
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:c().optional().describe("User's language and region preference in BCP 47 format."),timeZone:c().optional().describe("User's timezone in IANA format."),userAgent:c().optional().describe("Host application identifier."),platform:T([h("web"),h("desktop"),h("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p({touch:E().optional().describe("Whether the device supports touch input."),hover:E().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p({top:z().describe("Top safe area inset in pixels."),right:z().describe("Right safe area inset in pixels."),bottom:z().describe("Bottom safe area inset in pixels."),left:z().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),GP=p({method:h("ui/notifications/host-context-changed"),params:lS.describe("Partial context update containing only changed fields.")}),iw=p({method:h("ui/update-model-context"),params:p({content:g(yt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:P(c(),A().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),aw=p({method:h("ui/initialize"),params:p({appInfo:_t.describe("App identification (name and version)."),appCapabilities:tw.describe("Features and capabilities this app provides."),protocolVersion:c().describe("Protocol version this app supports.")})}),cw=p({protocolVersion:c().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:_t.describe("Host application identification and version."),hostCapabilities:ew.describe("Features and capabilities provided by the host."),hostContext:lS.describe("Rich context about the host environment.")}).passthrough();class Li{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=(r)=>{if(t&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let o=st.safeParse(r.data);if(o.success)console.debug("Parsed message",o.data),this.onmessage?.(o.data);else if(r.data?.jsonrpc!=="2.0")console.debug("Ignoring non-JSON-RPC message",o.error.message,r);else console.error("Failed to parse message",o.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+o.error.message))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,t){if(e.method!==Uz)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var lw=[cS];class Ui extends yc{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new iS;_methods=new aS;setRequestHandler=(...e)=>{let[t,...r]=rS("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...r)};setNotificationHandler=(...e)=>{let[t,...r]=rS("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...r)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_wrapHandler(e,t){let r=super._wrapHandler(e,t);if(e==="ui/initialize"||e==="ping")return r;return async(o,n)=>{if(!this._initializedReceived)console.warn(`[ext-apps] AppBridge received '${e}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`);return r(o,n)}}eventSchemas={sizechange:Kz,sandboxready:Wz,initialized:rw,requestteardown:Qz,loggingmessage:Ar};setEventHandler(e,t){this._ensureEventSlot(e),this._events.setHandler(e,t)}getEventHandler(e){return this._events.getHandler(e)}addEventListener(e,t){this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);let r=(o)=>{if(e==="initialized")this._initializedReceived=!0;this._events.dispatch(e,o)};if(e==="loggingmessage")this.setNotificationHandler("notifications/message",(o)=>{r(o.params)});else this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(o)=>r(o));this._registeredEvents.add(e)}warnIfRequestHandlerReplaced(e,t,r){if(t&&r)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t,r,o){super(o);this._client=e,this._hostInfo=t,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=o?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:aw.shape.params,result:cw},(n)=>this._onAppsInitialize(n)),this.replaceRequestHandler("ping",(n,i)=>(this.onping?.(n.params,i),{})),this.replaceRequestHandler("ui/request-display-mode",{params:nS.shape.params,result:sS},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(e){return e}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(e){this.setEventHandler("sizechange",e)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(e){this.setEventHandler("sandboxready",e)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(e){this.setEventHandler("initialized",e)}_onmessage;get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,e),this._onmessage=e,this.replaceRequestHandler("ui/message",{params:sw.shape.params,result:Bz},async(t,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(t,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler("ui/open-link",{params:Hz.shape.params,result:Vz},async(t,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(t,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler("ui/download-file",{params:nw.shape.params,result:Jz},async(t,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(t,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(e){this.setEventHandler("requestteardown",e)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler("ui/request-display-mode",{params:nS.shape.params,result:sS},async(t,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(t,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(e){this.setEventHandler("loggingmessage",e)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler("ui/update-model-context",{params:iw.shape.params,result:tr},async(t,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(t,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",async(t,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(e){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,e),this._oncreatesamplingmessage=e,this.replaceRequestHandler("sampling/createMessage",async(t,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(t.params,r)})}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler("resources/list",async(t,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(t.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler("resources/templates/list",async(t,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(t.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler("resources/read",async(t,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(t.params,r)})}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler("prompts/list",async(t,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(t.params,r)})}sendPromptListChanged(e={}){return this.notification({method:"notifications/prompts/list_changed",params:e})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(e){let t=e.protocolVersion;if(this._appInfo!==void 0)console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values.");return this._appCapabilities=e.appCapabilities,this._appInfo=e.appInfo,{protocolVersion:lw.includes(t)?t:cS,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},r=!1;for(let o of Object.keys(e)){let n=this._hostContext[o],i=e[o];if(uw(n,i))continue;t[o]=i,r=!0}if(r)this._hostContext=e,this.sendHostContextChange(t)}sendHostContextChange(e){return this.notification({method:"ui/notifications/host-context-changed",params:e})}sendToolInput(e){return this.notification({method:"ui/notifications/tool-input",params:e})}sendToolInputPartial(e){return this.notification({method:"ui/notifications/tool-input-partial",params:e})}sendToolResult(e){return this.notification({method:"ui/notifications/tool-result",params:e})}sendToolCancelled(e){return this.notification({method:"ui/notifications/tool-cancelled",params:e})}sendSandboxResourceReady(e){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:e})}teardownResource(e,t){return this.request({method:"ui/resource-teardown",params:e},Xz,t)}sendResourceTeardown=this.teardownResource;callTool(e,t){return this.request({method:"tools/call",params:e},t)}listTools(e,t){return this.request({method:"tools/list",params:e},t)}async connect(e){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let t=this._client.getServerCapabilities();if(!t)throw Error("Client server capabilities not available");if(t.tools){if(this.oncalltool=async(r,o)=>this._client.request({method:"tools/call",params:r},{signal:o.mcpReq.signal}),t.tools.listChanged)this._client.setNotificationHandler("notifications/tools/list_changed",(r)=>this.sendToolListChanged(r.params))}if(t.resources){if(this.onlistresources=async(r,o)=>this._client.request({method:"resources/list",params:r},{signal:o.mcpReq.signal}),this.onlistresourcetemplates=async(r,o)=>this._client.request({method:"resources/templates/list",params:r},{signal:o.mcpReq.signal}),this.onreadresource=async(r,o)=>this._client.request({method:"resources/read",params:r},{signal:o.mcpReq.signal}),t.resources.listChanged)this._client.setNotificationHandler("notifications/resources/list_changed",(r)=>this.sendResourceListChanged(r.params))}if(t.prompts){if(this.onlistprompts=async(r,o)=>this._client.request({method:"prompts/list",params:r},{signal:o.mcpReq.signal}),t.prompts.listChanged)this._client.setNotificationHandler("notifications/prompts/list_changed",(r)=>this.sendPromptListChanged(r.params))}}return super.connect(e)}}function uw(e,t){return JSON.stringify(e)===JSON.stringify(t)}var uS=[200,800],dw=(e)=>e?.name==="TypeError"&&/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.)$/.test(e.message);function pw(e,t){return new Promise((r,o)=>{t?.throwIfAborted();let i=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),s=()=>{clearTimeout(i),t.removeEventListener("abort",s),o(t.reason)};t?.addEventListener("abort",s,{once:!0})})}function dS(e,{signal:t,onDiagnostic:r,wait:o=pw}={}){return async(n)=>{for(let i=1;;i++){t?.throwIfAborted();try{let s=await e(n);if(t?.throwIfAborted(),i>1)r?.({state:"recovered",uri:n.uri,attempt:i});return s}catch(s){if(t?.throwIfAborted(),!dw(s))throw s;if(i>uS.length)throw r?.({state:"exhausted",uri:n.uri,attempt:i,message:s.message}),Object.assign(Error(`MCP resource transport failed for ${n.uri} after ${i} attempts: ${s.message}. Inspect the host connection and browser network diagnostics; this resource-loading error does not establish a component assertion failure.`,{cause:s}),{code:"ADS_RESOURCE_TRANSPORT"});let a=uS[i-1];r?.({state:"retry",uri:n.uri,attempt:i,nextAttempt:i+1,delayMs:a,message:s.message}),await o(a,t)}}}}function pS(e){let t=[],r=new Map;for(let o of e){if(!o.group){t.push(o);continue}if(!r.has(o.group))r.set(o.group,[]);r.get(o.group).push(o)}return[...t.length?[{label:null,entries:t}]:[],...[...r].sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>({label:o,entries:n}))]}async function mS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:i,callTool:s,context:a,onError:l,onState:u}){let d={slot:e,title:t,sandboxUrl:r,resourceUri:o,readResource:i,callTool:s,context:a,onError:l,onState:u},m=n,f,S,b,y=!1;function v(){if(y||b)return;u?.({state:"loading"}),b=Promise.resolve().then(async()=>{if(await S,await f?.close(),y)return;S=hS({...d,result:m,onReopen:v});try{f=await S}finally{S=void 0}}).catch((U)=>{if(!y)l(U)}).finally(()=>{b=void 0})}S=hS({...d,result:m,onReopen:v});try{f=await S}finally{S=void 0}return{async updateResult(U){if(m=U,await b,!y)await f.updateResult(m)},refreshContext(){if(!y&&!b)f.refreshContext()},async close(){y=!0,await b,await f?.close()}}}async function hS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:i,callTool:s,context:a,onError:l,onState:u,onReopen:d}){let m=!1,S=(await i({uri:o})).contents.find((x)=>x.mimeType==="text/html;profile=mcp-app"&&typeof x.text==="string");if(!S)throw Error("Comparison preview App is unavailable.");let b=document.createElement("iframe");b.title=t,b.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),b.src=r,e.append(b);let y=new Ui(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:a(b)});y.onreadresource=i,y.oncalltool=s,y.onerror=(x)=>{if(!m)l(x)},y.onloggingmessage=(x)=>{if(m||x.logger!=="ads-preview")return;if(x.data?.code==="ADS_PREVIEW_REOPEN"){d();return}if(u?.(x.data),x.data?.state==="error")l(Error(x.data.message))};let v,U=new Promise((x,Z)=>{v=setTimeout(()=>Z(Error("Comparison App initialization timed out.")),15000),y.oninitialized=()=>{clearTimeout(v),x()}});y.onsandboxready=()=>y.sendSandboxResourceReady({html:S.text,csp:S._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});let H=new ResizeObserver(()=>y.setHostContext(a(b)));try{await Promise.all([y.connect(new Li(b.contentWindow,b.contentWindow)),U]),H.observe(b),await y.sendToolInput({arguments:{}}),await y.sendToolResult(n)}catch(x){throw H.disconnect(),b.remove(),await y.close(),x}finally{clearTimeout(v)}return{updateResult:(x)=>y.sendToolResult(x),refreshContext:()=>y.setHostContext(a(b)),async close(){m=!0,H.disconnect();try{await y.teardownResource({},{timeout:500})}catch{}await y.close(),b.remove()}}}function Lu(e,t){return t===e||t.startsWith(e+"/")||t.startsWith(e+".")}function fS(e,t,r,o=new Map){let n=new Map(r.map(({id:l,title:u,revision:d,state:m,preview:f})=>[l,{id:l,title:u,revision:d,state:m,...f?{preview:f}:{}}])),i=new Map(e.map((l)=>[l.id,{...l,drafts:(l.drafts??[]).flatMap((u)=>n.has(u.id)?[n.get(u.id)]:[])}]));for(let l of t){let u=i.get(l.id);i.set(l.id,{...u,...l,kind:"tokens",drafts:u?.drafts??[]})}let s=(l,u)=>l==="tokens"&&u.kind==="tokens"||(u.unit?u.unit===l:Lu(l,u.id)),a=(l,u)=>{if(!l.drafts.some((d)=>d.id===u.id))l.drafts.push(n.get(u.id))};for(let l of r){let u=o.get(l.id);for(let d of u?.scenarios??[]){if(!l.units.some((f)=>s(f,d)))continue;let m=i.get(d.id);if(!m)m={...d,draftOnly:!0,drafts:[]},i.set(d.id,m);a(m,l)}}for(let l of r)for(let u of l.units){let d=u.split("/")[0];if(!["brand","tokens","components","patterns","composition"].includes(d))continue;let m=[...i.values()].filter((f)=>s(u,f));if(m.length)for(let f of m)a(f,l);else i.set(u,{id:u,unit:u,title:u.split("/").at(-1),kind:d,draftOnly:!0,pendingDraftScenario:!0,drafts:[n.get(l.id)]})}return{scenarios:[...i.values()],categories:[...i.values()].filter((l)=>l.kind==="tokens")}}function gS(e,t,r){let o=e.drafts?.find((l)=>l.id===r)??e.drafts?.[0],n=o&&(t?.drafts?.find((l)=>l.id===o.id)??o.preview),i=o?n?.scenarios?.find((l)=>l.id===e.id)??n:t?.previews?.find((l)=>l.id===e.id)??e.build,s=i?.state==="error"?"error":i?.state==="checking"||i?.live?"checking":i?.building||["queued","building"].includes(i?.state)?"building":i?.current?"ready":i?.stale?"stale":"unreported",a={error:pa(i),checking:"Preview compiled; checking changes",building:"Preview build in progress",ready:"Preview build complete",stale:"Previous preview; current source not built",unreported:"Preview not built"};return{state:s,label:`${o?"Draft · ":""}${a[s]}${o&&s==="ready"?" · unaccepted":""}`}}var SS={unreported:'<circle cx="8" cy="8" r="3"/>',building:'<circle cx="8" cy="8" r="5" stroke-dasharray="22 10"/>',checking:'<circle cx="8" cy="8" r="5" stroke-dasharray="3 3"/><path d="m6 8 1.5 1.5L10 6"/>',ready:'<circle cx="8" cy="8" r="5"/><path d="m5.5 8 1.7 1.7 3.3-3.4"/>',stale:'<circle cx="8" cy="8" r="5" stroke-dasharray="2 3"/>',error:'<circle cx="8" cy="8" r="5"/><path d="M8 5.5v3M8 10.5h.01"/>'};var L=(e)=>document.getElementById(e),at=new URLSearchParams(location.search),_S=at.get("scenario")??at.get("category"),hw=["brand","tokens","components","patterns","composition"],Yo=[],_e,kc=at.get("draft"),Bu=[],vS=[],Wu=new Map,en=at.get("split")==="1",Du,tn=[],Dt=0,Ic;async function Oc(){let e=tn;tn=[],await Promise.allSettled(e.map((t)=>t.close()))}var Qe=document.createElement("button");Qe.id="split-view";Qe.setAttribute("aria-label","Split view");Qe.setAttribute("aria-pressed","false");Qe.disabled=!0;Qe.title="Select a draft with an accepted version to compare";Qe.innerHTML='<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1" y="2" width="14" height="12" rx="1"/><path d="M8 2v12"/></svg>';L("viewport").before(Qe);var se="brand",Le={},bS=new Map,Pc=!0,Ku=[],Nc=[],qc=[],Go,Ji,me,Ue,Ko,Fi,Xo,Fu,Zi,Rt=0,Qo=at.get("capture")!=="1"&&at.get("viewport")==="phone",ar=at.get("capture")==="1"&&at.get("theme")==="dark"?"dark":"light";if(at.get("capture")==="1")document.documentElement.dataset.capture="true";document.documentElement.dataset.theme=ar;var Uu,zS=!0,Tc=!1,$c,Hu,Ac=!1,Hi=!1,Jr,ir,Zu=0,Di,Wr=new AbortController,xt=new Qg({name:"ads-showcase",version:"1.0.0"},{versionNegotiation:{mode:"auto"},capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}),wS=(e,t={},r={})=>xt.callTool({name:e,arguments:t},{signal:Wr.signal,...r}),Cc=dS((e)=>xt.readResource(e,{signal:Wr.signal}),{signal:Wr.signal,onDiagnostic:(e)=>{if(e.state==="retry")document.documentElement.dataset.adsResourceRetries=String(Number(document.documentElement.dataset.adsResourceRetries??0)+1);console.warn("ADS resource transport",e)}}),RS=async(e)=>JSON.parse((await Cc({uri:e})).contents.find((t)=>typeof t.text==="string").text);function xS(e){let t=qc.find((r)=>r.name===e.name);if(!t||!(t._meta?.ui?.visibility??["model","app"]).includes("app"))throw Error("This tool is not callable from an App.");return xt.callTool(e)}function Se(e,t=!1,r=t?"error":e?"checking":"ready"){let o=e||"Preview is up to date.";if(L("preview-error").hidden=!t,L("preview-error-message").textContent=t?o.split(`
|
|
120
|
-
`)[0]:"",
|
|
121
|
-
`)[0]}`),
|
|
122
|
-
`)}function
|
|
123
|
-
The retained preview is not verified against the current source.`:""}`,!0)}async function
|
|
124
|
-
`),!0)}},s.onerror=
|
|
125
|
-
${
|
|
118
|
+
- "app": Tool callable by the app from this server only`),csp:nu().optional(),permissions:nu().optional()}),fT=p({mimeTypes:S(c()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),_w=p({method:h("ui/download-file"),params:p({contents:S(T([Zr,Dr])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),bw=p({method:h("ui/message"),params:p({role:h("user").describe('Message role, currently only "user" is supported.'),content:S(Pt).describe("Message content blocks (text, image, etc.).")})}),gT=p({method:h("ui/notifications/sandbox-resource-ready"),params:p({html:c().describe("HTML content to load into the inner iframe."),sandbox:c().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:Bu.optional().describe("CSP configuration from resource metadata."),permissions:Wu.optional().describe("Sandbox permissions from resource metadata.")})}),ST=p({method:h("ui/notifications/tool-result"),params:dr.describe("Standard MCP tool execution result.")}),yS=p({toolInfo:p({id:lt.optional().describe("JSON-RPC id of the tools/call request."),tool:ur.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:tw.optional().describe("Current color theme preference."),styles:dw.optional().describe("Style configuration for theming the app."),displayMode:Vi.optional().describe("How the UI is currently displayed."),availableDisplayModes:S(Vi).optional().describe("Display modes the host supports."),containerDimensions:T([p({height:z().describe("Fixed container height in pixels.")}),p({maxHeight:T([z(),ou()]).optional().describe("Maximum container height in pixels.")})]).and(T([p({width:z().describe("Fixed container width in pixels.")}),p({maxWidth:T([z(),ou()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
|
|
119
|
+
container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:c().optional().describe("User's language and region preference in BCP 47 format."),timeZone:c().optional().describe("User's timezone in IANA format."),userAgent:c().optional().describe("Host application identifier."),platform:T([h("web"),h("desktop"),h("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:p({touch:E().optional().describe("Whether the device supports touch input."),hover:E().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:p({top:z().describe("Top safe area inset in pixels."),right:z().describe("Right safe area inset in pixels."),bottom:z().describe("Bottom safe area inset in pixels."),left:z().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),_T=p({method:h("ui/notifications/host-context-changed"),params:yS.describe("Partial context update containing only changed fields.")}),yw=p({method:h("ui/update-model-context"),params:p({content:S(Pt).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:P(c(),M().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),vw=p({method:h("ui/initialize"),params:p({appInfo:Rt.describe("App identification (name and version)."),appCapabilities:fw.describe("Features and capabilities this app provides."),protocolVersion:c().describe("Protocol version this app supports.")})}),zw=p({protocolVersion:c().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:Rt.describe("Host application identification and version."),hostCapabilities:mw.describe("Features and capabilities provided by the host."),hostContext:yS.describe("Rich context about the host environment.")}).passthrough();class Ji{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=(r)=>{if(t&&r.source!==this.eventSource){console.debug("Ignoring message from unknown source",r);return}let o=ut.safeParse(r.data);if(o.success)console.debug("Parsed message",o.data),this.onmessage?.(o.data);else if(r.data?.jsonrpc!=="2.0")console.debug("Ignoring non-JSON-RPC message",o.error.message,r);else console.error("Failed to parse message",o.error.message,r),this.onerror?.(Error("Invalid JSON-RPC message received: "+o.error.message))}}async start(){window.addEventListener("message",this.messageListener)}async send(e,t){if(e.method!==ew)console.debug("Sending message",e);this.eventTarget.postMessage(e,"*")}async close(){window.removeEventListener("message",this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion}var ww=[bS];class Bi extends Ec{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new SS;_methods=new _S;setRequestHandler=(...e)=>{let[t,...r]=hS("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...r)};setNotificationHandler=(...e)=>{let[t,...r]=hS("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...r)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_wrapHandler(e,t){let r=super._wrapHandler(e,t);if(e==="ui/initialize"||e==="ping")return r;return async(o,n)=>{if(!this._initializedReceived)console.warn(`[ext-apps] AppBridge received '${e}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`);return r(o,n)}}eventSchemas={sizechange:lw,sandboxready:cw,initialized:gw,requestteardown:hw,loggingmessage:Fr};setEventHandler(e,t){this._ensureEventSlot(e),this._events.setHandler(e,t)}getEventHandler(e){return this._events.getHandler(e)}addEventListener(e,t){this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);let r=(o)=>{if(e==="initialized")this._initializedReceived=!0;this._events.dispatch(e,o)};if(e==="loggingmessage")this.setNotificationHandler("notifications/message",(o)=>{r(o.params)});else this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(o)=>r(o));this._registeredEvents.add(e)}warnIfRequestHandlerReplaced(e,t,r){if(t&&r)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t,r,o){super(o);this._client=e,this._hostInfo=t,this._hostCapabilities=r,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),this._ensureEventSlot("initialized"),this._hostContext=o?.hostContext||{},this.replaceRequestHandler("ui/initialize",{params:vw.shape.params,result:zw},(n)=>this._onAppsInitialize(n)),this.replaceRequestHandler("ping",(n,i)=>(this.onping?.(n.params,i),{})),this.replaceRequestHandler("ui/request-display-mode",{params:fS.shape.params,result:gS},()=>({mode:this._hostContext.displayMode??"inline"}))}buildContext(e){return e}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler("sizechange")}set onsizechange(e){this.setEventHandler("sizechange",e)}get onsandboxready(){return this.getEventHandler("sandboxready")}set onsandboxready(e){this.setEventHandler("sandboxready",e)}get oninitialized(){return this.getEventHandler("initialized")}set oninitialized(e){this.setEventHandler("initialized",e)}_onmessage;get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced("onmessage",this._onmessage,e),this._onmessage=e,this.replaceRequestHandler("ui/message",{params:bw.shape.params,result:aw},async(t,r)=>{if(!this._onmessage)throw Error("No onmessage handler set");return this._onmessage(t,r)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced("onopenlink",this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler("ui/open-link",{params:nw.shape.params,result:sw},async(t,r)=>{if(!this._onopenlink)throw Error("No onopenlink handler set");return this._onopenlink(t,r)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced("ondownloadfile",this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler("ui/download-file",{params:_w.shape.params,result:iw},async(t,r)=>{if(!this._ondownloadfile)throw Error("No ondownloadfile handler set");return this._ondownloadfile(t,r)})}get onrequestteardown(){return this.getEventHandler("requestteardown")}set onrequestteardown(e){this.setEventHandler("requestteardown",e)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced("onrequestdisplaymode",this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler("ui/request-display-mode",{params:fS.shape.params,result:gS},async(t,r)=>{if(!this._onrequestdisplaymode)throw Error("No onrequestdisplaymode handler set");return this._onrequestdisplaymode(t,r)})}get onloggingmessage(){return this.getEventHandler("loggingmessage")}set onloggingmessage(e){this.setEventHandler("loggingmessage",e)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced("onupdatemodelcontext",this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler("ui/update-model-context",{params:yw.shape.params,result:cr},async(t,r)=>{if(!this._onupdatemodelcontext)throw Error("No onupdatemodelcontext handler set");return this._onupdatemodelcontext(t,r)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",async(t,r)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,r)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(e){this.warnIfRequestHandlerReplaced("oncreatesamplingmessage",this._oncreatesamplingmessage,e),this._oncreatesamplingmessage=e,this.replaceRequestHandler("sampling/createMessage",async(t,r)=>{if(!this._oncreatesamplingmessage)throw Error("No oncreatesamplingmessage handler set");return this._oncreatesamplingmessage(t.params,r)})}sendToolListChanged(e={}){return this.notification({method:"notifications/tools/list_changed",params:e})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced("onlistresources",this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler("resources/list",async(t,r)=>{if(!this._onlistresources)throw Error("No onlistresources handler set");return this._onlistresources(t.params,r)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced("onlistresourcetemplates",this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler("resources/templates/list",async(t,r)=>{if(!this._onlistresourcetemplates)throw Error("No onlistresourcetemplates handler set");return this._onlistresourcetemplates(t.params,r)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced("onreadresource",this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler("resources/read",async(t,r)=>{if(!this._onreadresource)throw Error("No onreadresource handler set");return this._onreadresource(t.params,r)})}sendResourceListChanged(e={}){return this.notification({method:"notifications/resources/list_changed",params:e})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced("onlistprompts",this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler("prompts/list",async(t,r)=>{if(!this._onlistprompts)throw Error("No onlistprompts handler set");return this._onlistprompts(t.params,r)})}sendPromptListChanged(e={}){return this.notification({method:"notifications/prompts/list_changed",params:e})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(e){let t=e.protocolVersion;if(this._appInfo!==void 0)console.warn("[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values.");return this._appCapabilities=e.appCapabilities,this._appInfo=e.appInfo,{protocolVersion:ww.includes(t)?t:bS,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},r=!1;for(let o of Object.keys(e)){let n=this._hostContext[o],i=e[o];if(Rw(n,i))continue;t[o]=i,r=!0}if(r)this._hostContext=e,this.sendHostContextChange(t)}sendHostContextChange(e){return this.notification({method:"ui/notifications/host-context-changed",params:e})}sendToolInput(e){return this.notification({method:"ui/notifications/tool-input",params:e})}sendToolInputPartial(e){return this.notification({method:"ui/notifications/tool-input-partial",params:e})}sendToolResult(e){return this.notification({method:"ui/notifications/tool-result",params:e})}sendToolCancelled(e){return this.notification({method:"ui/notifications/tool-cancelled",params:e})}sendSandboxResourceReady(e){return this.notification({method:"ui/notifications/sandbox-resource-ready",params:e})}teardownResource(e,t){return this.request({method:"ui/resource-teardown",params:e},pw,t)}sendResourceTeardown=this.teardownResource;callTool(e,t){return this.request({method:"tools/call",params:e},t)}listTools(e,t){return this.request({method:"tools/list",params:e},t)}async connect(e){if(this.transport)throw Error("AppBridge is already connected. Call close() before connecting again.");if(this._initializedReceived=!1,this._client){let t=this._client.getServerCapabilities();if(!t)throw Error("Client server capabilities not available");if(t.tools){if(this.oncalltool=async(r,o)=>this._client.request({method:"tools/call",params:r},{signal:o.mcpReq.signal}),t.tools.listChanged)this._client.setNotificationHandler("notifications/tools/list_changed",(r)=>this.sendToolListChanged(r.params))}if(t.resources){if(this.onlistresources=async(r,o)=>this._client.request({method:"resources/list",params:r},{signal:o.mcpReq.signal}),this.onlistresourcetemplates=async(r,o)=>this._client.request({method:"resources/templates/list",params:r},{signal:o.mcpReq.signal}),this.onreadresource=async(r,o)=>this._client.request({method:"resources/read",params:r},{signal:o.mcpReq.signal}),t.resources.listChanged)this._client.setNotificationHandler("notifications/resources/list_changed",(r)=>this.sendResourceListChanged(r.params))}if(t.prompts){if(this.onlistprompts=async(r,o)=>this._client.request({method:"prompts/list",params:r},{signal:o.mcpReq.signal}),t.prompts.listChanged)this._client.setNotificationHandler("notifications/prompts/list_changed",(r)=>this.sendPromptListChanged(r.params))}}return super.connect(e)}}function Rw(e,t){return JSON.stringify(e)===JSON.stringify(t)}var vS=[200,800],xw=(e)=>e?.name==="TypeError"&&/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.)$/.test(e.message);function Pw(e,t){return new Promise((r,o)=>{t?.throwIfAborted();let i=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),s=()=>{clearTimeout(i),t.removeEventListener("abort",s),o(t.reason)};t?.addEventListener("abort",s,{once:!0})})}function zS(e,{signal:t,onDiagnostic:r,wait:o=Pw}={}){return async(n)=>{for(let i=1;;i++){t?.throwIfAborted();try{let s=await e(n);if(t?.throwIfAborted(),i>1)r?.({state:"recovered",uri:n.uri,attempt:i});return s}catch(s){if(t?.throwIfAborted(),!xw(s))throw s;if(i>vS.length)throw r?.({state:"exhausted",uri:n.uri,attempt:i,message:s.message}),Object.assign(Error(`MCP resource transport failed for ${n.uri} after ${i} attempts: ${s.message}. Inspect the host connection and browser network diagnostics; this resource-loading error does not establish a component assertion failure.`,{cause:s}),{code:"ADS_RESOURCE_TRANSPORT"});let a=vS[i-1];r?.({state:"retry",uri:n.uri,attempt:i,nextAttempt:i+1,delayMs:a,message:s.message}),await o(a,t)}}}}function wS(e){let t=[],r=new Map;for(let o of e){if(!o.group){t.push(o);continue}if(!r.has(o.group))r.set(o.group,[]);r.get(o.group).push(o)}return[...t.length?[{label:null,entries:t}]:[],...[...r].sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>({label:o,entries:n}))]}async function xS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:i,callTool:s,context:a,onError:l,onState:u}){let d={slot:e,title:t,sandboxUrl:r,resourceUri:o,readResource:i,callTool:s,context:a,onError:l,onState:u},m=n,f,g,b,y=!1;function v(){if(y||b)return;u?.({state:"loading"}),b=Promise.resolve().then(async()=>{if(await g,await f?.close(),y)return;g=RS({...d,result:m,onReopen:v});try{f=await g}finally{g=void 0}}).catch((L)=>{if(!y)l(L)}).finally(()=>{b=void 0})}g=RS({...d,result:m,onReopen:v});try{f=await g}finally{g=void 0}return{async updateResult(L){if(m=L,await b,!y)await f.updateResult(m)},refreshContext(){if(!y&&!b)f.refreshContext()},async close(){y=!0,await b,await f?.close()}}}async function RS({slot:e,title:t,sandboxUrl:r,resourceUri:o,result:n,readResource:i,callTool:s,context:a,onError:l,onState:u,onReopen:d}){let m=!1,g=(await i({uri:o})).contents.find((x)=>x.mimeType==="text/html;profile=mcp-app"&&typeof x.text==="string");if(!g)throw Error("Comparison preview App is unavailable.");let b=document.createElement("iframe");b.title=t,b.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),b.src=r,e.append(b);let y=new Bi(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:a(b)});y.onreadresource=i,y.oncalltool=s,y.onerror=(x)=>{if(!m)l(x)},y.onloggingmessage=(x)=>{if(m||x.logger!=="ads-preview")return;if(x.data?.code==="ADS_PREVIEW_REOPEN"){d();return}if(u?.(x.data),x.data?.state==="error")l(Error(x.data.message))};let v,L=new Promise((x,Z)=>{v=setTimeout(()=>Z(Error("Comparison App initialization timed out.")),15000),y.oninitialized=()=>{clearTimeout(v),x()}});y.onsandboxready=()=>y.sendSandboxResourceReady({html:g.text,csp:g._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});let H=new ResizeObserver(()=>y.setHostContext(a(b)));try{await Promise.all([y.connect(new Ji(b.contentWindow,b.contentWindow)),L]),H.observe(b),await y.sendToolInput({arguments:{}}),await y.sendToolResult(n)}catch(x){throw H.disconnect(),b.remove(),await y.close(),x}finally{clearTimeout(v)}return{updateResult:(x)=>y.sendToolResult(x),refreshContext:()=>y.setHostContext(a(b)),async close(){m=!0,H.disconnect();try{await y.teardownResource({},{timeout:500})}catch{}await y.close(),b.remove()}}}function Ku(e,t){return t===e||t.startsWith(e+"/")||t.startsWith(e+".")}function PS(e,t,r,o=new Map){let n=new Map(r.map(({id:l,title:u,revision:d,state:m,preview:f})=>[l,{id:l,title:u,revision:d,state:m,...f?{preview:f}:{}}])),i=new Map(e.map((l)=>[l.id,{...l,drafts:(l.drafts??[]).flatMap((u)=>n.has(u.id)?[n.get(u.id)]:[])}]));for(let l of t){let u=i.get(l.id);i.set(l.id,{...u,...l,kind:"tokens",drafts:u?.drafts??[]})}let s=(l,u)=>l==="tokens"&&u.kind==="tokens"||(u.unit?u.unit===l:Ku(l,u.id)),a=(l,u)=>{if(!l.drafts.some((d)=>d.id===u.id))l.drafts.push(n.get(u.id))};for(let l of r){let u=o.get(l.id);for(let d of u?.scenarios??[]){if(!l.units.some((f)=>s(f,d)))continue;let m=i.get(d.id);if(!m)m={...d,draftOnly:!0,drafts:[]},i.set(d.id,m);a(m,l)}}for(let l of r)for(let u of l.units){let d=u.split("/")[0];if(!["brand","tokens","components","patterns","composition"].includes(d))continue;let m=[...i.values()].filter((f)=>s(u,f));if(m.length)for(let f of m)a(f,l);else i.set(u,{id:u,unit:u,title:u.split("/").at(-1),kind:d,draftOnly:!0,pendingDraftScenario:!0,drafts:[n.get(l.id)]})}return{scenarios:[...i.values()],categories:[...i.values()].filter((l)=>l.kind==="tokens")}}function TS(e,t,r){let o=e.drafts?.find((l)=>l.id===r)??e.drafts?.[0],n=o&&(t?.drafts?.find((l)=>l.id===o.id)??o.preview),i=o?n?.scenarios?.find((l)=>l.id===e.id)??n:t?.previews?.find((l)=>l.id===e.id)??e.build,s=i?.state==="error"?"error":i?.state==="checking"||i?.live?"checking":i?.building||["queued","building"].includes(i?.state)?"building":i?.current?"ready":i?.stale?"stale":"unreported",a={error:ya(i),checking:"Preview compiled; checking changes",building:"Preview build in progress",ready:"Preview build complete",stale:"Previous preview; current source not built",unreported:"Preview not built"};return{state:s,label:`${o?"Draft · ":""}${a[s]}${o&&s==="ready"?" · unaccepted":""}`}}var ES={unreported:'<circle cx="8" cy="8" r="3"/>',building:'<circle cx="8" cy="8" r="5" stroke-dasharray="22 10"/>',checking:'<circle cx="8" cy="8" r="5" stroke-dasharray="3 3"/><path d="m6 8 1.5 1.5L10 6"/>',ready:'<circle cx="8" cy="8" r="5"/><path d="m5.5 8 1.7 1.7 3.3-3.4"/>',stale:'<circle cx="8" cy="8" r="5" stroke-dasharray="2 3"/>',error:'<circle cx="8" cy="8" r="5"/><path d="M8 5.5v3M8 10.5h.01"/>'};var Nc="ads://project/icons";function Q(e,t={},...r){let o=Object.assign(document.createElement(e),t);return o.append(...r.filter((n)=>n!==null&&n!==void 0&&n!==!1)),o}var Tw={fill:"black",stroke:"none","stroke-width":"1","stroke-linecap":"butt","stroke-linejoin":"miter","stroke-miterlimit":"4","stroke-dasharray":"none","fill-opacity":"1","stroke-opacity":"1","fill-rule":"nonzero"};function Ew(e){let t=new DOMParser().parseFromString(e,"image/svg+xml").documentElement;if(t.namespaceURI!=="http://www.w3.org/2000/svg"||t.localName!=="svg")return null;for(let o of t.querySelectorAll("*"))if(["script","foreignObject","iframe","image","a","animate","set","animateTransform","animateMotion"].includes(o.localName)||o.namespaceURI!=="http://www.w3.org/2000/svg")o.remove();for(let o of[t,...t.querySelectorAll("*")])for(let n of Array.from(o.attributes))if(/^on/i.test(n.name)||/href$/i.test(n.name)&&!n.value.trim().startsWith("#"))o.removeAttribute(n.name);let r=document.importNode(t,!0);for(let o of["width","height","class"])r.removeAttribute(o);for(let[o,n]of Object.entries(Tw))if(!r.style.getPropertyValue(o))r.style.setProperty(o,r.getAttribute(o)??n);return r.setAttribute("aria-hidden","true"),r.setAttribute("focusable","false"),r}function Gu(e,t,r){let o=Q("span",{className:"icons-glyph"});o.style.width=o.style.height=`${t}px`;let n=Ew(e.svg);if(n)o.append(n);if(r)o.setAttribute("role","img"),o.setAttribute("aria-label",r),o.title=r;else o.setAttribute("aria-hidden","true");return o}function kw(e){let t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("class","icons-grid"),t.setAttribute("aria-hidden","true"),t.setAttribute("viewBox",`${e.x} ${e.y} ${e.width} ${e.height}`),t.setAttribute("preserveAspectRatio","xMidYMid meet");let r=Math.max(1,Math.ceil(Math.max(e.width,e.height)/48)),o=(n,i,s,a,l)=>{let u=document.createElementNS("http://www.w3.org/2000/svg","line");for(let[d,m]of Object.entries({x1:n,y1:i,x2:s,y2:a}))u.setAttribute(d,m);if(l)u.setAttribute("class","mid");t.append(u)};for(let n=0;n<=e.width;n+=r)o(e.x+n,e.y,e.x+n,e.y+e.height,n*2===e.width);for(let n=0;n<=e.height;n+=r)o(e.x,e.y+n,e.x+e.width,e.y+n,n*2===e.height);if(e.width%2&&r===1)o(e.x+e.width/2,e.y,e.x+e.width/2,e.y+e.height,!0);if(e.height%2&&r===1)o(e.x,e.y+e.height/2,e.x+e.width,e.y+e.height/2,!0);return t}var Yu=(e,t)=>`${e} ${t}${e===1?"":"s"}`;function $w(e){let t=e.filter((r)=>r.severity==="error").length;return t===e.length?Yu(t,"error"):Yu(e.length,"issue")}function kS(e){return Q("p",{className:"icons-finding",title:e.file??""},Q("strong",{textContent:e.rule})," ",e.message)}function Cw(e,t){let r=Q("article",{className:"icons-card"});if(r.dataset.glyph=e.name,e.findings.length)r.dataset.findings=String(e.findings.length);let o=Q("div",{className:"icons-card-head"},Q("h3",{textContent:e.name}),e.findings.length?Q("span",{className:"icons-badge",textContent:$w(e.findings)}):null),n=Q("div",{className:"icons-mag"});if(e.grid)n.append(kw(e.grid));n.append(Gu(e,96));let i=Q("div",{className:"icons-sizes"},...t.map((s)=>Q("span",{className:"icons-size"},Gu(e,s.px),Q("small",{textContent:String(s.px),title:s.token}))));return r.append(...[o,e.aliases.length?Q("p",{className:"icons-alias",textContent:`alias: ${e.aliases.join(", ")}`}):null,n,i,...e.findings.map(kS)].filter(Boolean)),r.setAttribute("aria-label",e.name),r}function Iw(e){let t=Q("figure",{className:"icons-logo"});if(t.dataset.logo=e.name,e.tooLarge)return t.append(Q("figcaption",{textContent:`${e.name} (over 1 MB; not shown)`})),t;let r=Q("span",{className:"icons-logo-muted",title:`${e.name}, muted`});return r.setAttribute("aria-hidden","true"),r.style.maskImage=r.style.webkitMaskImage=`url("${e.src}")`,t.append(Q("img",{src:e.src,alt:e.name,title:e.file}),r,Q("figcaption",{textContent:e.name})),t}var Ow=(e,t)=>!t||[e.name,...e.aliases].some((r)=>r.toLowerCase().includes(t));function $S(e,t){let r=e.querySelector(":scope > .icons-view"),o=r?.querySelector("input[type=search]")?.value??"",n=r?.scrollTop??0;if(r=Q("div",{className:"icons-view"}),r.setAttribute("role","region"),r.setAttribute("aria-label","Icons"),!t?.configured)return r.append(Q("h1",{textContent:"Icons"}),Q("p",{className:"icons-summary",textContent:"The project configures no glyph set (assets.glyphs)."})),e.replaceChildren(r),r;let i=t.mixed?"mixed grids":t.grid?`${/^(?:8|11|18)(?!\d)|^8/.test(String(t.grid.width))?"an":"a"} ${t.grid.width}×${t.grid.height} grid`:"no viewBox",s=`${t.source} · ${Yu(t.glyphs.length,"glyph")} on ${i} · ${t.aliasCount} ${t.aliasCount===1?"alias":"aliases"}`,a=Q("input",{type:"search",placeholder:"Search name or alias",value:o});a.setAttribute("aria-label","Search glyphs by name or alias");let l=Q("div",{className:"icons-set"});l.setAttribute("role","list"),l.setAttribute("aria-label","The set");let u=Q("div",{className:"icons-cards"}),d=Q("p",{className:"icons-empty",hidden:!0}),m=t.textSize;r.append(Q("div",{className:"icons-head"},Q("div",{},Q("h1",{textContent:"Icons"}),Q("p",{className:"icons-summary",textContent:s})),a),...t.findings.map(kS),Q("h2",{},"The set ",Q("small",{textContent:m?`every glyph at ${m.px} px, the size used beside text`:"every glyph"})),l,Q("h2",{},"Glyphs ",Q("small",{textContent:t.sizes.length?"each on its grid, at every icon size":"each on its grid"})),d,u);for(let g of t.glyphs){let b=Q("span",{className:"icons-set-item"},Gu(g,m?.px??18,g.name));b.dataset.glyph=g.name,b.setAttribute("role","listitem"),l.append(b),u.append(Cw(g,t.sizes))}if(t.logos)r.append(Q("h2",{},"Other products' logos ",Q("small",{textContent:`${t.logos.source} · in color and muted`})),t.logos.files.length?Q("div",{className:"icons-logos"},...t.logos.files.map(Iw)):Q("p",{className:"icons-summary",textContent:"No images yet."}));let f=()=>{let g=a.value.trim().toLowerCase(),b=0;t.glyphs.forEach((y,v)=>{let L=Ow(y,g);l.children[v].hidden=u.children[v].hidden=!L,b+=L}),d.hidden=b>0,d.textContent=`No glyph matches “${a.value.trim()}”.`};if(a.addEventListener("input",f),f(),e.replaceChildren(r),r.scrollTop=n,o&&document.activeElement===document.body)a.focus();return r}var k=(e)=>document.getElementById(e),De=new URLSearchParams(location.search),CS=De.get("scenario")??De.get("category"),Nw=["brand","tokens","icons","components","patterns","composition"],Mc=!1,sn=[],be,jc=De.get("draft"),nd=[],NS=[],sd=new Map,ln=De.get("split")==="1",ed,fr=[],$t=0,Fc;async function Qi(){let e=fr;fr=[],await Promise.allSettled(e.map((t)=>t.close()))}var nt=document.createElement("button");nt.id="split-view";nt.setAttribute("aria-label","Split view");nt.setAttribute("aria-pressed","false");nt.disabled=!0;nt.title="Select a draft with an accepted version to compare";nt.innerHTML='<svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1" y="2" width="14" height="12" rx="1"/><path d="M8 2v12"/></svg>';k("viewport").before(nt);var te="brand",Ze={},IS=new Map,Wi=!0,id=[],Hc=[],Vc=[],rt,ea,fe,ye,rn,Gi,an,Lc,on,Ge=0,cn=De.get("capture")!=="1"&&De.get("viewport")==="phone",ot=[{name:"light",scheme:"light"},{name:"dark",scheme:"dark"}],Kt=De.get("capture")==="1"&&De.get("theme")||"light";if(De.get("capture")==="1")document.documentElement.dataset.capture="true";var td=()=>ot.find((e)=>e.name===Kt)?.scheme??"light";function AS(){document.documentElement.dataset.theme=td();let e=ot[(ot.findIndex((r)=>r.name===Kt)+1)%ot.length],t=ot.length>1?`Use ${e.name} theme`:`Theme: ${Kt}`;k("theme").setAttribute("aria-label",t),k("theme").title=t,k("theme").disabled=ot.length<2,k("theme").querySelector("svg").innerHTML=td()==="dark"?'<circle cx="8" cy="8" r="3"/><path d="M8 1v1M8 14v1M1 8h1M14 8h1M3 3l1 1M12 12l1 1M3 13l1-1M12 4l1-1"/>':'<path d="M13.5 9a5.5 5.5 0 0 1-6.5-6.5A5.5 5.5 0 1 0 13.5 9Z"/>'}document.documentElement.dataset.theme="light";var Qr=[],pt=De.get("capture")==="1"&&De.get("brand")||null;function qS(){let e=k("brand-select");if(e.hidden=!Qr.length,e.options.length!==Qr.length||Qr.some((t,r)=>e.options[r].value!==t.name))e.replaceChildren(...Qr.map((t)=>Object.assign(document.createElement("option"),{value:t.name,textContent:t.name})));if(pt)e.value=pt,e.title=`Brand: ${pt}`}var Xu,MS=!0,Ac=!1,Uc,rd,Jc=!1,Yi=!1,hr,Bt,Qu=0,Ki,eo=new AbortController,Ct=new uS({name:"ads-showcase",version:"1.0.0"},{versionNegotiation:{mode:"auto"},capabilities:{extensions:{"io.modelcontextprotocol/ui":{mimeTypes:["text/html;profile=mcp-app"]}}}}),jS=(e,t={},r={})=>Ct.callTool({name:e,arguments:t},{signal:eo.signal,...r}),Zc=zS((e)=>Ct.readResource(e,{signal:eo.signal}),{signal:eo.signal,onDiagnostic:(e)=>{if(e.state==="retry")document.documentElement.dataset.adsResourceRetries=String(Number(document.documentElement.dataset.adsResourceRetries??0)+1);console.warn("ADS resource transport",e)}}),ad=async(e)=>JSON.parse((await Zc({uri:e})).contents.find((t)=>typeof t.text==="string").text);function LS(e){let t=Vc.find((r)=>r.name===e.name);if(!t||!(t._meta?.ui?.visibility??["model","app"]).includes("app"))throw Error("This tool is not callable from an App.");return Ct.callTool(e)}function Se(e,t=!1,r=t?"error":e?"checking":"ready"){let o=e||"Preview is up to date.";if(k("preview-error").hidden=!t,k("preview-error-message").textContent=t?o.split(`
|
|
120
|
+
`)[0]:"",k("preview-error-message").title=t?o:"",k("status").textContent=o,k("status").dataset.error=String(t),!t)for(let n of["errorCategory","errorCode","resourceUri"])delete k("status").dataset[n];if(t)k("status").removeAttribute("role");else k("status").setAttribute("role","status");k("preview-status").dataset.phase=r,k("preview-status").title=o,k("preview-status").setAttribute("aria-label",`Preview status: ${o.split(`
|
|
121
|
+
`)[0]}`),US()}function US(){let e=ea?.warmup,t=e?`Background views: ${e.completed}/${e.total} compiled${e.failed?`; ${e.failed} failed`:""}.`:"";k("warmup-status").hidden=!e,k("warmup-status").textContent=t,k("preview-status").dataset.warmup=e?.state??"disabled",k("preview-status").title=[k("status").textContent,t].filter(Boolean).join(`
|
|
122
|
+
`)}function ZS(){Se(fe?"Updating preview…":"Opening preview…",!1,"reloading")}function un(){return ta().find((e)=>e.id===Ze[te])}function dn(e=un()){let t=sn.find((r)=>r.id===jc&&sd.get(r.id)?.scenario===e?.id);return e?.drafts?.find((r)=>r.id===jc)??t??e?.drafts?.[0]}function cd(){return Boolean(dn()&&(un()?.draftOnly||ln))}function Xi(){return`${te}:${Ze[te]}${cd()?`:draft:${dn().id}`:""}`}function qc(e=fe){return e?.key===Xi()}function DS(e=ea){if(cd()){let t=e?.drafts?.find((r)=>r.id===dn()?.id);return t?.scenarios?.find((r)=>r.id===Ze[te])??t}return e?.previews?.find((t)=>t.id===Ze[te])}var FS=(e)=>JSON.stringify(e&&[e.session,e.revision,e.current,e.live]);function HS(){({scenarios:Hc,categories:id}=PS(nd,NS,sn,sd))}function Aw(e){sd.set(e.structuredContent.id,e.structuredContent),HS()}async function od(e,t,r=eo.signal){let o=(rt?.previewWatch?.buildTimeoutMs??30000)+15000;try{return await jS(e,t,{signal:AbortSignal.any([eo.signal,r]),timeout:o})}catch(n){if(n.code!=="REQUEST_TIMEOUT")throw n;throw Object.assign(Error(`The preview request timed out after ${Math.ceil(o/1000)} seconds. No preview result was received. Retry the preview.`,{cause:n}),{code:"ADS_PREVIEW_REQUEST_TIMEOUT",category:"transport"})}}async function ld(e,t,r){let o=un()?.id===t&&un().pendingDraftScenario||e.units?.includes(t)&&!nd.some((i)=>i.id===t),n=await od("ads_show_draft",{id:e.id,...!o&&t?{scenario:t}:{}},r);if(n.isError)throw Error(n.content?.find((i)=>i.type==="text")?.text??"Draft preview failed.");if(o){let i=n.structuredContent.scenarios.find((s)=>t==="tokens"?s.kind==="tokens":s.unit?s.unit===t:Ku(t,s.id));if(!i)throw Error("Draft owner has no scenario yet. Add an independently mountable scenario before previewing it.");if(i.id!==n.structuredContent.scenario)n=await od("ads_show_draft",{id:e.id,scenario:i.id},r);if(n.isError)throw Error(n.content?.find((s)=>s.type==="text")?.text??"Draft preview failed.")}return Aw(n),n}function Wt(e=!1){if(e)on=fe?.key;an=void 0,k("loader").hidden=!0,k("preview").setAttribute("aria-busy","false")}function OS(e){let t=new URL(location.href);for(let n of["scenario","category","draft","split","section"])t.searchParams.delete(n);if(te==="icons")return t.searchParams.set("section","icons"),t.pathname+t.search+t.hash;if(e)t.searchParams.set("scenario",e);let r=ta().find((n)=>n.id===e),o=dn(r);if(o&&(r.draftOnly||ln)){if(t.searchParams.set("draft",o.id),!r.draftOnly)t.searchParams.set("split","1")}return t.pathname+t.search+t.hash}function ta(){return te==="tokens"?id:te==="icons"?[]:Hc.filter((e)=>e.kind===te)}function VS(e,t){let{state:r,label:o}=TS(t,ea,jc),n=e.querySelector(".entry-preview");if(!n)n=document.createElement("span"),n.className="entry-preview",n.setAttribute("aria-hidden","true"),e.append(n);n.dataset.state=r,n.title=o,n.innerHTML=`<svg viewBox="0 0 16 16">${ES[r]}</svg>`,e.dataset.buildState=r,e.setAttribute("aria-description",o)}var nn=!1;function to(){return{theme:td(),adsTheme:Kt,...pt?{adsBrand:pt}:{},gridOverlay:nn,displayMode:"inline",containerDimensions:{width:k("frame-slot").clientWidth,height:k("frame-slot").clientHeight}}}function ra(){let e=Hc.some((n)=>n.kind==="brand");if(k("sections").querySelector('[data-section="brand"]').hidden=!e,te==="brand"&&!e)te="tokens";if(k("sections").querySelector('[data-section="icons"]').hidden=!rt?.icons,te==="icons"&&!rt?.icons)te="tokens";document.body.dataset.activeSection=te;let t=ta();if(!t.some((n)=>n.id===Ze[te]))Ze[te]=t[0]?.id??null;history.replaceState(null,"",OS(Ze[te]));let r=k("sidebar").scrollTop;k("entries").setAttribute("aria-label",te[0].toUpperCase()+te.slice(1));let o=(n)=>{let i=document.createElement("a");if(i.textContent=n.title,n.drafts?.length){let s=document.createElement("span");s.className="draft-badge",s.textContent=n.drafts.length>1?`Drafts ${n.drafts.length}`:"Draft",s.title=n.draftOnly?"Draft only; no accepted version yet":"Draft available; use Split view to compare",i.append(" ",s)}if(i.href=OS(n.id),i.dataset.scenario=n.id,VS(i,n),n.id===Ze[te])i.setAttribute("aria-current","page");return i.addEventListener("click",(s)=>{if(s.button||s.metaKey||s.ctrlKey||s.shiftKey||s.altKey)return;s.preventDefault(),Ze[te]=n.id,ra(),Gt().catch(ht)}),i};k("entries").replaceChildren(...wS(t).flatMap((n)=>{if(!n.label)return n.entries.map(o);let i=`${te}:${n.label}`,s=document.createElement("details");s.className="entry-group",s.open=IS.get(i)??!0;let a=document.createElement("summary");a.textContent=n.label;let l=document.createElement("div");return l.setAttribute("role","group"),l.setAttribute("aria-label",n.label),l.append(...n.entries.map(o)),s.append(a,l),s.addEventListener("toggle",()=>{if(s.isConnected)IS.set(i,s.open)}),[s]})),k("sidebar").scrollTop=r;for(let n of k("sections").querySelectorAll("button"))if(n.dataset.section===te)n.setAttribute("aria-current","page");else n.removeAttribute("aria-current");Dc()}function ht(e){if(!Jc&&!Yi)Wt(),k("status").dataset.errorCategory=e.category??(e.code==="ADS_RESOURCE_TRANSPORT"?"transport":"runner"),k("status").dataset.errorCode=e.code??"ADS_HOST_STARTUP",Se(`${e.message}${fe?`
|
|
123
|
+
The retained preview is not verified against the current source.`:""}`,!0)}async function mr(e){if(!e)return;try{await e.teardownResource({},{timeout:500})}catch{}await e.close()}function JS(){if(Jc||Yi)return;Yi=!0,eo.abort(),++Ge,clearTimeout(Uc),Wt(),Se("MCP disconnected. The retained preview is stale. Refresh the page after restarting ADS.",!0);let e=ye;ye=void 0,mr(e),++$t,Qi()}async function ud(){let e=await ad("ads://project/explorer");if(rt=e.status,ea=rt.build,Vc=e.tools,rt.themes?.length){if(ot=rt.themes,!ot.some((i)=>i.name===Kt))Kt=ot[0].name;AS(),ye?.setHostContext(to())}Qr=rt.brands??[],pt=Qr.some((i)=>i.name===pt)?pt:Qr[0]?.name??null,qS(),ye?.setHostContext(to()),NS=e.categories,nd=e.scenarios,sn=e.drafts,k("title").textContent=(rt.drafts?.previewOnly?"Draft · ":"")+rt.project.showcase.title,k("title").title=rt.projectRoot,HS();let t=Wi?CS:Ze[te],r=Wi&&sn.find((i)=>i.id===jc),o=fe?.draft&&sn.find((i)=>i.id===fe.draftId);if(r||o&&be&&(o.revision!==be.revision||be.discovery?.state==="pending")){let i=await ld(r||o,r?CS:be.scenario);if(r)t=i.structuredContent.scenario;if(fe?.draft&&o){be=i.structuredContent,Fc=i;for(let s of fr)if(s.side==="draft")await s.updateResult(i)}}let n=Hc.find((i)=>i.id===t);if(n&&Nw.includes(n.kind))te=n.kind,Ze[te]=n.id;else if(Wi&&id.some((i)=>i.id===t))te="tokens",Ze.tokens=t;else if(Wi&&De.get("section")==="icons"&&rt.icons)te="icons";Wi=!1,ra()}function Gt({force:e=!1}={}){if(Yi)return Promise.resolve();if(te==="icons")return Mw(e);if(Mc=!1,k("frame-slot").querySelector(":scope > .icons-view"))k("frame-slot").replaceChildren();let t=Ze[te],r=Xi();if(rn?.key===r)return rn.promise;if(!e&&Gi?.key===r)return Promise.resolve();if(!e&&!rn&&fe?.key===r)return Promise.resolve();Gi=void 0;let o={key:r};return rn=o,o.promise=qw(t,r,te==="tokens").finally(()=>{if(rn===o)rn=void 0}),o.promise}async function qw(e,t,r){Lc?.abort();let o=Lc=new AbortController,n=++Ge;an=!0,k("loader").hidden=t===on,k("preview").setAttribute("aria-busy","true");try{if(++$t,await Qi(),n!==Ge)return;if(cd()){await mr(ye),ye=void 0,hr=void 0,Bt=void 0;let u=dn(),d=await ld(u,e,o.signal);if(n!==Ge)return;if(be=d.structuredContent,Fc=d,un()?.pendingDraftScenario||!ta().some((m)=>m.id===e))Ze[te]=be.scenario;fe={key:Xi(),id:be.scenario,draftId:u.id,generation:n,draft:!0},Dc(),await Uw(),ra(),Wt(!0),Se("Draft preview only. Acceptance checks have not run.",!1,"ready");return}if(be=void 0,Dc(),!e&&!r){if(await mr(ye),n!==Ge)return;ye=void 0,fe=void 0,on=void 0,hr=void 0,Bt=void 0,k("frame-slot").replaceChildren(),Wt(),Se("No scenarios discovered. Colocate an independently mountable scenario and fixture with the public implementation.");return}let i=Vc.find((u)=>u.name===(r?"ads_show_tokens":"ads_show_scenario"));if(!i?._meta?.ui?.resourceUri)throw Error("The server did not expose a preview App tool.");let s=r?e?{category:e}:{}:{id:e};if(i.inputSchema?.properties?.waitFor)s.waitFor=De.get("capture")==="1"||De.get("waitFor")==="verified"?"verified":"compiled";ZS();let a=await od(i.name,s,o.signal);if(n!==Ge)return;if(a.isError)throw Object.assign(Error(a.content?.find((u)=>u.type==="text")?.text??"Preview build failed."),a.structuredContent?.failure);fe={key:t,id:e,generation:n,token:r&&!a.structuredContent?.scenario,build:a.structuredContent?.build,manifestRevision:a.structuredContent?.manifestRevision};let l=await jw(i._meta.ui.resourceUri);if(n!==Ge)return;if(hr==="ui://ads/preview"&&!fe.manifestRevision)throw Error("The resource preview has no manifest revision.");if(on!==t)on=void 0;if(await l.sendToolInput({arguments:s}),await l.sendToolResult(a),n===Ge&&!a.structuredContent?.manifestUri)Wt(!0),Se("")}catch(i){if(n===Ge)Gi={key:Xi(),build:FS(DS())},ht(i)}}async function Mw(e){if(Mc&&!e&&k("frame-slot").querySelector(":scope > .icons-view"))return;Lc?.abort();let t=++Ge;if(!k("frame-slot").querySelector(":scope > .icons-view")){k("loader").hidden=!1,++$t,await Qi();let r=ye;ye=void 0,fe=void 0,on=void 0,hr=void 0,Bt=void 0,be=void 0,await mr(r)}try{let r=await ad(Nc);if(t!==Ge||te!=="icons")return;$S(k("frame-slot"),r),Mc=!0,Wt(),Se(""),Dc()}catch(r){if(t===Ge)ht(r)}}async function jw(e){if(hr===e&&Bt)return Bt;let t=++Qu,r=ye;ye=void 0,hr=e,Bt=(async()=>{await mr(r);let o=await Zc({uri:e});if(t!==Qu||Jc||Yi)throw Error("Preview opening was superseded.");let n=o.contents.find((u)=>u.mimeType==="text/html;profile=mcp-app"&&typeof u.text==="string");if(!n)throw Error("The preview resource contains no MCP App.");let i=document.createElement("iframe");i.title="Design-system preview",i.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),i.src=Ki,k("frame-slot").replaceChildren(i);let s=new Bi(null,{name:"ADS showcase",version:"1.0.0"},{serverResources:{},serverTools:{},logging:{}},{hostContext:to()});ye=s,s.onreadresource=(u)=>Zc(u),s.oncalltool=LS,s.onloggingmessage=(u)=>{if(s!==ye||u.logger!=="ads-preview"||fe?.generation!==Ge||!qc()||u.data?.id!==fe?.id)return;let d=u.data.revision===fe.manifestRevision||u.data.selectionRevision===fe.manifestRevision;if(u.data.state==="ready"&&d)fe.manifestRevision=u.data.revision,Wt(!0),Se("");else if(u.data.state==="checking"&&(!an||d))Wt(!0),Se("Checking changes…");else if(u.data.state==="loading")Se("Updating preview…",!1,"reloading");else if(u.data.state==="reverting")Se("Restoring the last verified preview…",!1,"reverting");else if(u.data.code==="ADS_PREVIEW_REOPEN")ye=void 0,hr=void 0,Bt=void 0,ZS(),mr(s).then(()=>Gt({force:!0})).catch(ht);else if(u.data.state==="error"){if(Wt(),k("status").dataset.errorCategory=u.data.category??"build",k("status").dataset.errorCode=u.data.code??"ADS_PREVIEW_BUILD",u.data.resourceUri)k("status").dataset.resourceUri=u.data.resourceUri;else delete k("status").dataset.resourceUri;Se([u.data.message,u.data.code,u.data.resourceUri].filter(Boolean).join(`
|
|
124
|
+
`),!0)}},s.onerror=ht;let a,l=new Promise((u,d)=>{a=setTimeout(()=>d(Error("MCP App initialization timed out.")),15000),s.oninitialized=()=>{clearTimeout(a),u()}});s.onsandboxready=()=>s.sendSandboxResourceReady({html:n.text,csp:n._meta?.ui?.csp,sandbox:"allow-scripts allow-forms"});try{await Promise.all([s.connect(new Ji(i.contentWindow,i.contentWindow)),l])}catch(u){throw await mr(s),u}finally{clearTimeout(a)}return s})();try{return await Bt}catch(o){if(t===Qu)hr=void 0,Bt=void 0;throw o}}async function Lw(){let e=fe,t=await ad("ads://project/build");ea=t,US();for(let o of k("entries").querySelectorAll("a[data-scenario]")){let n=ta().find((i)=>i.id===o.dataset.scenario);if(n)VS(o,n)}if(Gi?.key===Xi()){let o=DS(t);if(o&&(o.current||o.live)&&FS(o)!==Gi.build)await Gt({force:!0});return}if(!e||e.token||an||!qc(e))return;if(e.draft){let o=t.drafts?.find((s)=>s.id===e.draftId),n=o?.scenarios?.find((s)=>s.id===be?.scenario)??o,i=n&&JSON.stringify([o?.session,n.revision,n.live?.revision,n.current]);if(n&&(n.current||n.live)&&e.buildSignature!==i){e.buildSignature=i;let s=sn.find((a)=>a.id===e.draftId);if(s){let a=await ld(s,be.scenario);if(fe!==e||an||!qc(e))return;be=a.structuredContent,Fc=a;for(let l of fr)if(l.side==="draft")await l.updateResult(a)}}if(n?.state==="error")Se("Draft preview build failed. Showing the previous preview.",!0);else if(n?.building)Se(n.live||n.state==="checking"?"Draft preview compiled; checking changes…":"Building draft preview… Showing the previous preview.",!1,n.live||n.state==="checking"?"checking":"compiling");else if(n?.current&&ed?.state==="ready")Se("Draft preview ready · unaccepted.");return}if(fe!==e||an||!qc(e))return;let r=t.previews.find((o)=>o.id===e.id);if(!r){Se("The selected scenario is no longer registered.",!0);return}if(["idle","building"].includes(r.state)&&e.build?.current&&r.session===e.build.session&&r.revision<=e.build.revision)return;if(r.state==="error"){Se(`${ya(r)}. Showing an earlier view.
|
|
125
|
+
${md(r.diagnostics)}`,!0);return}if(["idle","building"].includes(r.state)){Se(r.live?"Checking changes…":"Compiling changes… The current view is the previous preview.",!1,r.live?"checking":"compiling");return}if(r.current&&(r.revision!==e.build?.revision||r.session!==e.build?.session))await Gt({force:!0})}function oa(e=!1,t=!1){if(Ac||=e,t&&fe?.token)fe.key="invalidated";if(clearTimeout(Uc),MS)return;Uc=setTimeout(()=>{if(Xu){oa(e,t);return}Xu=(async()=>{if(Ac)Ac=!1,await ud();await Gt(),await Lw()})().catch(ht).finally(()=>{Xu=void 0})},150)}async function Uw(){if(!be)return;let e=be,t=Fc;ed=void 0;let r=++$t;if(await Qi(),r!==$t)return;let o=ln&&e.acceptedExists;nt.setAttribute("aria-pressed",String(o));let n=document.createElement("div");n.className="draft-comparison",n.dataset.split=String(o);for(let i of o?["accepted","draft"]:["draft"]){let s=document.createElement("section");s.className="draft-version";let a=document.createElement("h2");a.dataset.version=i,a.textContent=i==="accepted"?"Accepted":"Draft · unaccepted";let l=document.createElement("div");l.className="draft-stage",l.dataset.version=i,s.append(a,l),n.append(s)}k("frame-slot").replaceChildren(n),await Promise.all([...n.querySelectorAll(".draft-stage")].map(async(i)=>{let s=i.dataset.version,a=s==="draft"?t:await jS("ads_show_scenario",{id:e.scenario,waitFor:"compiled"});if(a.isError)throw Error(a.content?.find((d)=>d.type==="text")?.text??"Comparison build failed.");if(r!==$t)return;let l=Vc.find((d)=>d.name===(s==="draft"?"ads_show_draft":"ads_show_scenario")),u=await xS({slot:i,title:s==="draft"?"Draft version":"Accepted version",sandboxUrl:Ki,resourceUri:l._meta.ui.resourceUri,result:a,readResource:Zc,callTool:LS,context:(d)=>({theme:Kt,...pt?{adsBrand:pt}:{},gridOverlay:nn,displayMode:"inline",containerDimensions:{width:d.clientWidth,height:d.clientHeight}}),onError:(d)=>{if(r===$t)ht(d)},onState:(d)=>{if(r!==$t||s!=="draft")return;if(ed=d,d.state==="ready")Se("Draft preview ready · unaccepted.");else if(d.state==="checking")Se("Draft preview compiled; checking changes…",!1,"checking");else if(["loading","reverting"].includes(d.state))Se("Updating draft preview…",!1,"reloading")}});if(r!==$t)await u.close();else fr.push({...u,side:s})}))}function Dc(){let e=un(),t=Boolean(dn(e))&&!e?.draftOnly;nt.disabled=!t,nt.title=e?.draftOnly?"No accepted version yet":t?"Compare accepted and draft versions":"No draft for this entry",nt.setAttribute("aria-pressed",String(t&&ln));let r=document.querySelector('.draft-version h2[data-version="draft"]');if(r&&be){let o={draft:"unaccepted",checking:"checking acceptance",failed:"acceptance failed",conflict:"source conflict",interrupted:"acceptance interrupted","dependency-error":"dependency needs attention"};r.textContent=`Draft · ${o[be.state]??be.state}`,r.title=be.dependencies?.length?`Draft dependencies: ${be.dependencies.join(", ")}`:""}}nt.addEventListener("click",()=>{ln=!ln,ra(),Gt().catch(ht)});for(let e of k("sections").querySelectorAll("button"))e.addEventListener("click",()=>{te=e.dataset.section,ra(),Gt().catch(ht)});var dd=window.matchMedia("(max-width: 760px)");function BS(e){document.body.classList.toggle("collapsed",e),k("pane-toggle").setAttribute("aria-expanded",String(!e)),k("pane-toggle").setAttribute("aria-label",e?"Show navigation pane":"Hide navigation pane"),k("pane-toggle").title=e?"Show navigation pane":"Hide navigation pane",k("pane-toggle").querySelector("path").setAttribute("d",e?"M6 4l4 4-4 4":"M10 4l-4 4 4 4")}var pd=()=>BS(k("header").hidden||dd.matches);pd();dd.addEventListener("change",pd);k("pane-toggle").addEventListener("click",()=>BS(!document.body.classList.contains("collapsed")));function WS(){document.documentElement.dataset.viewport=cn?"phone":"auto",k("viewport").setAttribute("aria-pressed",String(cn)),k("viewport").title=cn?"Use available preview width":"Preview at phone width (390 px)"}WS();k("viewport").addEventListener("click",()=>{cn=!cn,WS();let e=new URL(location.href);if(cn)e.searchParams.set("viewport","phone");else e.searchParams.delete("viewport");history.replaceState(null,"",e.pathname+e.search+e.hash)});k("theme").addEventListener("click",()=>{Kt=ot[(ot.findIndex((e)=>e.name===Kt)+1)%ot.length].name,AS(),ye?.setHostContext(to())});k("theme").addEventListener("click",()=>{for(let e of fr)e.refreshContext()});k("brand-select").addEventListener("change",()=>{pt=k("brand-select").value,qS(),ye?.setHostContext(to());for(let e of fr)e.refreshContext()});k("grid-overlay").addEventListener("click",()=>{nn=!nn,k("grid-overlay").setAttribute("aria-pressed",String(nn)),k("grid-overlay").setAttribute("aria-label",nn?"Hide grid overlay":"Show grid overlay"),k("grid-overlay").title=k("grid-overlay").getAttribute("aria-label"),ye?.setHostContext(to());for(let e of fr)e.refreshContext()});k("minimize").addEventListener("click",()=>{k("header").hidden=!0,document.body.classList.add("collapsed")});var KS=new ResizeObserver(()=>ye?.setHostContext(to()));KS.observe(k("frame-slot"));k("retry-preview").addEventListener("click",()=>{(async()=>{await ud(),await Gt({force:!0})})().catch(ht)});window.addEventListener("pagehide",()=>{Jc=!0,Lc?.abort(),eo.abort(),clearTimeout(Uc),KS.disconnect(),dd.removeEventListener("change",pd),mr(ye),++$t,Qi(),rd?.close(),Ct.close()},{once:!0});Ct.onclose=JS;Ct.setNotificationHandler("notifications/resources/list_changed",()=>oa(!0));Ct.setNotificationHandler("notifications/tools/list_changed",()=>oa(!0));Ct.setNotificationHandler("notifications/resources/updated",({params:e})=>{if(e.uri===Nc)Mc=!1;oa(e.uri==="ads://project/explorer",e.uri==="ads://project/tokens")});try{if(Ki=(await fetch("/host.json").then((e)=>e.json())).sandboxUrl,!Ki||new URL(Ki).origin===location.origin)throw Error("The separate-origin MCP App sandbox is unavailable.");if(await Ct.connect(new dS(new URL("/mcp",location.href))),rd=await Ct.listen({resourcesListChanged:!0,toolsListChanged:!0,resourceSubscriptions:["ads://project/build","ads://project/tokens","ads://project/explorer",Nc]}),rd.closed.then((e)=>{if(e!=="local")JS()}),await ud(),MS=!1,await Gt(),Ac)oa()}catch(e){ht(e)}
|