@whoz-oss/coday-server 1.2.2 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/server.js +1 -1
package/package.json
CHANGED
package/server.js
CHANGED
|
@@ -1425,7 +1425,7 @@ Summary:
|
|
|
1425
1425
|
|
|
1426
1426
|
`)}h.write("payload.value = newResult;"),h.write("return payload;");let b=h.compile();return(x,E)=>b(p,x,E)},s,a=ug,o=!by.jitless,u=o&&cae.value,f=e.catchall,d;t._zod.parse=(p,h)=>{d??(d=n.value);let m=p.value;return a(m)?o&&u&&h?.async===!1&&h.jitless!==!0?(s||(s=i(e.shape)),p=s(p,h),f?n$e([],m,p,h,d,t):p):r(p,h):(p.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),p)}});function bje(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let i=t.filter(s=>!O0(s));return i.length===1?(e.value=i[0].value,i[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(a=>Qu(a,n,hc())))}),e)}var Eae=He("$ZodUnion",(t,e)=>{ni.init(t,e),On(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),On(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),On(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),On(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(i=>i._zod.pattern);return new RegExp(`^(${n.map(i=>_E(i.source)).join("|")})$`)}});let r=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(n,i)=>{if(r)return r(n,i);let s=!1,a=[];for(let o of e.options){let c=o._zod.run({value:n.value,issues:[]},i);if(c instanceof Promise)a.push(c),s=!0;else{if(c.issues.length===0)return c;a.push(c)}}return s?Promise.all(a).then(o=>bje(o,n,t,i)):bje(a,n,t,i)}});var s$e=He("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Eae.init(t,e);let r=t._zod.parse;On(t._zod,"propValues",()=>{let i={};for(let s of e.options){let a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[o,c]of Object.entries(a)){i[o]||(i[o]=new Set);for(let u of c)i[o].add(u)}}return i});let n=wy(()=>{let i=e.options,s=new Map;for(let a of i){let o=a._zod.propValues?.[e.discriminator];if(!o||o.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(let c of o){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,a)}}return s});t._zod.parse=(i,s)=>{let a=i.value;if(!ug(a))return i.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),i;let o=n.value.get(a?.[e.discriminator]);return o?o._zod.run(i,s):e.unionFallback||s.direction==="backward"?r(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(n.value.keys()),input:a,path:[e.discriminator],inst:t}),i)}}),a$e=He("$ZodIntersection",(t,e)=>{ni.init(t,e),t._zod.parse=(r,n)=>{let i=r.value,s=e.left._zod.run({value:i,issues:[]},n),a=e.right._zod.run({value:i,issues:[]},n);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([c,u])=>xje(r,c,u)):xje(r,s,a)}});function _ae(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(P0(t)&&P0(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),i={...t,...e};for(let s of n){let a=_ae(t[s],e[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};i[s]=a.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let i=t[n],s=e[n],a=_ae(i,s);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function xje(t,e,r){let n=new Map,i;for(let o of e.issues)if(o.code==="unrecognized_keys"){i??(i=o);for(let c of o.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else t.issues.push(o);for(let o of r.issues)if(o.code==="unrecognized_keys")for(let c of o.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else t.issues.push(o);let s=[...n].filter(([,o])=>o.l&&o.r).map(([o])=>o);if(s.length&&i&&t.issues.push({...i,keys:s}),O0(t))return t;let a=_ae(e.value,r.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return t.value=a.data,t}var o$e=He("$ZodRecord",(t,e)=>{ni.init(t,e),t._zod.parse=(r,n)=>{let i=r.value;if(!P0(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),r;let s=[],a=e.keyType._zod.values;if(a){r.value={};let o=new Set;for(let u of a)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){o.add(typeof u=="number"?u.toString():u);let f=e.keyType._zod.run({value:u,issues:[]},n);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(f.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(h=>Qu(h,n,hc())),input:u,path:[u],inst:t});continue}let d=f.value,p=e.valueType._zod.run({value:i[u],issues:[]},n);p instanceof Promise?s.push(p.then(h=>{h.issues.length&&r.issues.push(...Xp(u,h.issues)),r.value[d]=h.value})):(p.issues.length&&r.issues.push(...Xp(u,p.issues)),r.value[d]=p.value)}let c;for(let u in i)o.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:c})}else{r.value={};for(let o of Reflect.ownKeys(i)){if(o==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let c=e.keyType._zod.run({value:o,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof o=="string"&&bae.test(o)&&c.issues.length){let d=e.keyType._zod.run({value:Number(o),issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){e.mode==="loose"?r.value[o]=i[o]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>Qu(d,n,hc())),input:o,path:[o],inst:t});continue}let f=e.valueType._zod.run({value:i[o],issues:[]},n);f instanceof Promise?s.push(f.then(d=>{d.issues.length&&r.issues.push(...Xp(o,d.issues)),r.value[c.value]=d.value})):(f.issues.length&&r.issues.push(...Xp(o,f.issues)),r.value[c.value]=f.value)}}return s.length?Promise.all(s).then(()=>r):r}});var c$e=He("$ZodEnum",(t,e)=>{ni.init(t,e);let r=xE(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(i=>uae.has(typeof i)).map(i=>typeof i=="string"?Zp(i):i.toString()).join("|")})$`),t._zod.parse=(i,s)=>{let a=i.value;return n.has(a)||i.issues.push({code:"invalid_value",values:r,input:a,inst:t}),i}}),u$e=He("$ZodLiteral",(t,e)=>{if(ni.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Zp(n):n?Zp(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,i)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}});var l$e=He("$ZodTransform",(t,e)=>{ni.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new yy(t.constructor.name);let i=e.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(a=>(r.value=a,r.fallback=!0,r));if(i instanceof Promise)throw new bd;return r.value=i,r.fallback=!0,r}});function wje(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Aae=He("$ZodOptional",(t,e)=>{ni.init(t,e),t._zod.optin="optional",t._zod.optout="optional",On(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),On(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${_E(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){let i=r.value,s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(a=>wje(a,i)):wje(s,i)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),f$e=He("$ZodExactOptional",(t,e)=>{Aae.init(t,e),On(t._zod,"values",()=>e.innerType._zod.values),On(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),d$e=He("$ZodNullable",(t,e)=>{ni.init(t,e),On(t._zod,"optin",()=>e.innerType._zod.optin),On(t._zod,"optout",()=>e.innerType._zod.optout),On(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${_E(r.source)}|null)$`):void 0}),On(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),p$e=He("$ZodDefault",(t,e)=>{ni.init(t,e),t._zod.optin="optional",On(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);if(r.value===void 0)return r.value=e.defaultValue,r;let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>_je(s,e)):_je(i,e)}});function _je(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var h$e=He("$ZodPrefault",(t,e)=>{ni.init(t,e),t._zod.optin="optional",On(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),m$e=He("$ZodNonOptional",(t,e)=>{ni.init(t,e),On(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>Sje(s,t)):Sje(i,t)}});function Sje(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var g$e=He("$ZodCatch",(t,e)=>{ni.init(t,e),t._zod.optin="optional",On(t._zod,"optout",()=>e.innerType._zod.optout),On(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(a=>Qu(a,n,hc()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(s=>Qu(s,n,hc()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var Cae=He("$ZodPipe",(t,e)=>{ni.init(t,e),On(t._zod,"values",()=>e.in._zod.values),On(t._zod,"optin",()=>e.in._zod.optin),On(t._zod,"optout",()=>e.out._zod.optout),On(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=e.out._zod.run(r,n);return s instanceof Promise?s.then(a=>iL(a,e.in,n)):iL(s,e.in,n)}let i=e.in._zod.run(r,n);return i instanceof Promise?i.then(s=>iL(s,e.out,n)):iL(i,e.out,n)}});function iL(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},r)}var v$e=He("$ZodPreprocess",(t,e)=>{Cae.init(t,e)}),y$e=He("$ZodReadonly",(t,e)=>{ni.init(t,e),On(t._zod,"propValues",()=>e.innerType._zod.propValues),On(t._zod,"values",()=>e.innerType._zod.values),On(t._zod,"optin",()=>e.innerType?._zod?.optin),On(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(Eje):Eje(i)}});function Eje(t){return t.value=Object.freeze(t.value),t}var b$e=He("$ZodCustom",(t,e)=>{ka.init(t,e),ni.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,i=e.fn(n);if(i instanceof Promise)return i.then(s=>Aje(s,r,n,t));Aje(i,r,n,t)}});function Aje(t,e,r,n){if(!t){let i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),e.issues.push(_y(i))}}var zrr=()=>{let t={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 e(i){return t[i]??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"},n={nan:"NaN"};return i=>{switch(i.code){case"invalid_type":{let s=n[i.expected]??i.expected,a=pae(i.input),o=n[a]??a;return`Invalid input: expected ${s}, received ${o}`}case"invalid_value":return i.values.length===1?`Invalid input: expected ${YM(i.values[0])}`:`Invalid option: expected one of ${JM(i.values,"|")}`;case"too_big":{let s=i.inclusive?"<=":"<",a=e(i.origin);return a?`Too big: expected ${i.origin??"value"} to have ${s}${i.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${s}${i.maximum.toString()}`}case"too_small":{let s=i.inclusive?">=":">",a=e(i.origin);return a?`Too small: expected ${i.origin} to have ${s}${i.minimum.toString()} ${a.unit}`:`Too small: expected ${i.origin} to be ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${JM(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return i.options&&Array.isArray(i.options)&&i.options.length>0?`Invalid discriminator value. Expected ${i.options.map(a=>`'${a}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};function x$e(){return{localeError:zrr()}}var w$e,Urr=Symbol("ZodOutput"),Hrr=Symbol("ZodInput"),kae=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];return this._map.set(e,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let i={...n,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function _$e(){return new kae}(w$e=globalThis).__zod_globalRegistry??(w$e.__zod_globalRegistry=_$e());var R0=globalThis.__zod_globalRegistry;function S$e(t,e){return new t({type:"string",...Gt(e)})}function E$e(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Gt(e)})}function Tae(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Gt(e)})}function A$e(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Gt(e)})}function C$e(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Gt(e)})}function k$e(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Gt(e)})}function T$e(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Gt(e)})}function Pae(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Gt(e)})}function P$e(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Gt(e)})}function O$e(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Gt(e)})}function R$e(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Gt(e)})}function I$e(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Gt(e)})}function D$e(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Gt(e)})}function F$e(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Gt(e)})}function N$e(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Gt(e)})}function j$e(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Gt(e)})}function $$e(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Gt(e)})}function M$e(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Gt(e)})}function L$e(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Gt(e)})}function q$e(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Gt(e)})}function B$e(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Gt(e)})}function z$e(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Gt(e)})}function U$e(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Gt(e)})}function H$e(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Gt(e)})}function W$e(t,e){return new t({type:"string",format:"date",check:"string_format",...Gt(e)})}function V$e(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Gt(e)})}function G$e(t,e){return new t({type:"string",format:"duration",check:"string_format",...Gt(e)})}function K$e(t,e){return new t({type:"number",checks:[],...Gt(e)})}function J$e(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Gt(e)})}function Z$e(t,e){return new t({type:"boolean",...Gt(e)})}function X$e(t){return new t({type:"any"})}function Y$e(t){return new t({type:"unknown"})}function Q$e(t,e){return new t({type:"never",...Gt(e)})}function oL(t,e){return new xae({check:"less_than",...Gt(e),value:t,inclusive:!1})}function PE(t,e){return new xae({check:"less_than",...Gt(e),value:t,inclusive:!0})}function cL(t,e){return new wae({check:"greater_than",...Gt(e),value:t,inclusive:!1})}function OE(t,e){return new wae({check:"greater_than",...Gt(e),value:t,inclusive:!0})}function uL(t,e){return new ije({check:"multiple_of",...Gt(e),value:t})}function lL(t,e){return new aje({check:"max_length",...Gt(e),maximum:t})}function Sy(t,e){return new oje({check:"min_length",...Gt(e),minimum:t})}function fL(t,e){return new cje({check:"length_equals",...Gt(e),length:t})}function Oae(t,e){return new uje({check:"string_format",format:"regex",...Gt(e),pattern:t})}function Rae(t){return new lje({check:"string_format",format:"lowercase",...Gt(t)})}function Iae(t){return new fje({check:"string_format",format:"uppercase",...Gt(t)})}function Dae(t,e){return new dje({check:"string_format",format:"includes",...Gt(e),includes:t})}function Fae(t,e){return new pje({check:"string_format",format:"starts_with",...Gt(e),prefix:t})}function Nae(t,e){return new hje({check:"string_format",format:"ends_with",...Gt(e),suffix:t})}function I0(t){return new mje({check:"overwrite",tx:t})}function jae(t){return I0(e=>e.normalize(t))}function $ae(){return I0(t=>t.trim())}function Mae(){return I0(t=>t.toLowerCase())}function Lae(){return I0(t=>t.toUpperCase())}function qae(){return I0(t=>oae(t))}function eMe(t,e,r){return new t({type:"array",element:e,...Gt(r)})}function tMe(t,e,r){let n=Gt(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function rMe(t,e,r){return new t({type:"custom",check:"custom",fn:e,...Gt(r)})}function nMe(t,e){let r=Wrr(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(_y(i,n.value,r._zod.def));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(_y(s))}},t(n.value,n)),e);return r}function Wrr(t,e){let r=new ka({check:"custom",...Gt(e)});return r._zod.check=t,r}function Bae(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??R0,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function ss(t,e,r={path:[],schemaPath:[]}){var n;let i=t._zod.def,s=e.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,a);let o=t._zod.toJSONSchema?.();if(o)a.schema=o;else{let f={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,a.schema,f);else{let p=a.schema,h=e.processors[i.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);h(t,e,p,f)}let d=t._zod.parent;d&&(a.ref||(a.ref=d),ss(d,e,f),e.seen.get(d).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(a.schema,c),e.io==="input"&&Do(t)&&(delete a.schema.examples,delete a.schema.default),e.io==="input"&&"_prefault"in a.schema&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,e.seen.get(t).schema}function zae(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let a of t.seen.entries()){let o=t.metadataRegistry.get(a[0])?.id;if(o){let c=n.get(o);if(c&&c!==a[0])throw new Error(`Duplicate schema id "${o}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(o,a[0])}}let i=a=>{let o=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let d=t.external.registry.get(a[0])?.id,p=t.external.uri??(m=>m);if(d)return{ref:p(d)};let h=a[1].defId??a[1].schema.id??`schema${t.counter++}`;return a[1].defId=h,{defId:h,ref:`${p("__shared")}#/${o}/${h}`}}if(a[1]===r)return{ref:"#"};let u=`#/${o}/`,f=a[1].schema.id??`__schema${t.counter++}`;return{defId:f,ref:u+f}},s=a=>{if(a[1].schema.$ref)return;let o=a[1],{ref:c,defId:u}=i(a);o.def={...o.schema},u&&(o.defId=u);let f=o.schema;for(let d in f)delete f[d];f.$ref=c};if(t.cycles==="throw")for(let a of t.seen.entries()){let o=a[1];if(o.cycle)throw new Error(`Cycle detected: #/${o.cycle?.join("/")}/<root>
|
|
1427
1427
|
|
|
1428
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of t.seen.entries()){let o=a[1];if(e===a[0]){s(a);continue}if(t.external){let u=t.external.registry.get(a[0])?.id;if(e!==a[0]&&u){s(a);continue}}if(t.metadataRegistry.get(a[0])?.id){s(a);continue}if(o.cycle){s(a);continue}if(o.count>1&&t.reused==="ref"){s(a);continue}}}function Uae(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=o=>{let c=t.seen.get(o);if(c.ref===null)return;let u=c.def??c.schema,f={...u},d=c.ref;if(c.ref=null,d){n(d);let h=t.seen.get(d),m=h.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Object.assign(u,m),Object.assign(u,f),o._zod.parent===d)for(let v in u)v==="$ref"||v==="allOf"||v in f||delete u[v];if(m.$ref&&h.def)for(let v in u)v==="$ref"||v==="allOf"||v in h.def&&JSON.stringify(u[v])===JSON.stringify(h.def[v])&&delete u[v]}let p=o._zod.parent;if(p&&p!==d){n(p);let h=t.seen.get(p);if(h?.schema.$ref&&(u.$ref=h.schema.$ref,h.def))for(let m in u)m==="$ref"||m==="allOf"||m in h.def&&JSON.stringify(u[m])===JSON.stringify(h.def[m])&&delete u[m]}t.override({zodSchema:o,jsonSchema:u,path:c.path??[]})};for(let o of[...t.seen.entries()].reverse())n(o[0]);let i={};if(t.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let o=t.external.registry.get(e)?.id;if(!o)throw new Error("Schema is missing an `id` property");i.$id=t.external.uri(o)}Object.assign(i,r.def??r.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&i.id===s&&delete i.id;let a=t.external?.defs??{};for(let o of t.seen.entries()){let c=o[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,a[c.defId]=c.def)}t.external||Object.keys(a).length>0&&(t.target==="draft-2020-12"?i.$defs=a:i.definitions=a);try{let o=JSON.parse(JSON.stringify(i));return Object.defineProperty(o,"~standard",{value:{...e["~standard"],jsonSchema:{input:RE(e,"input",t.processors),output:RE(e,"output",t.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function Do(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Do(n.element,r);if(n.type==="set")return Do(n.valueType,r);if(n.type==="lazy")return Do(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Do(n.innerType,r);if(n.type==="intersection")return Do(n.left,r)||Do(n.right,r);if(n.type==="record"||n.type==="map")return Do(n.keyType,r)||Do(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Do(n.in,r)||Do(n.out,r);if(n.type==="object"){for(let i in n.shape)if(Do(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(Do(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(Do(i,r))return!0;return!!(n.rest&&Do(n.rest,r))}return!1}var iMe=(t,e={})=>r=>{let n=Bae({...r,processors:e});return ss(t,n),zae(n,t),Uae(n,t)},RE=(t,e,r={})=>n=>{let{libraryOptions:i,target:s}=n??{},a=Bae({...i??{},target:s,io:e,processors:r});return ss(t,a),zae(a,t),Uae(a,t)};var Vrr={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},sMe=(t,e,r,n)=>{let i=r;i.type="string";let{minimum:s,maximum:a,format:o,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(i.minLength=s),typeof a=="number"&&(i.maxLength=a),o&&(i.format=Vrr[o]??o,i.format===""&&delete i.format,o==="time"&&delete i.format),u&&(i.contentEncoding=u),c&&c.size>0){let f=[...c];f.length===1?i.pattern=f[0].source:f.length>1&&(i.allOf=[...f.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},aMe=(t,e,r,n)=>{let i=r,{minimum:s,maximum:a,format:o,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:f}=t._zod.bag;typeof o=="string"&&o.includes("int")?i.type="integer":i.type="number";let d=typeof f=="number"&&f>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),h=e.target==="draft-04"||e.target==="openapi-3.0";d?h?(i.minimum=f,i.exclusiveMinimum=!0):i.exclusiveMinimum=f:typeof s=="number"&&(i.minimum=s),p?h?(i.maximum=u,i.exclusiveMaximum=!0):i.exclusiveMaximum=u:typeof a=="number"&&(i.maximum=a),typeof c=="number"&&(i.multipleOf=c)},oMe=(t,e,r,n)=>{r.type="boolean"};var cMe=(t,e,r,n)=>{r.not={}},uMe=(t,e,r,n)=>{},lMe=(t,e,r,n)=>{};var fMe=(t,e,r,n)=>{let i=t._zod.def,s=xE(i.entries);s.every(a=>typeof a=="number")&&(r.type="number"),s.every(a=>typeof a=="string")&&(r.type="string"),r.enum=s},dMe=(t,e,r,n)=>{let i=t._zod.def,s=[];for(let a of i.values)if(a===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(a))}else s.push(a);if(s.length!==0)if(s.length===1){let a=s[0];r.type=a===null?"null":typeof a,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[a]:r.const=a}else s.every(a=>typeof a=="number")&&(r.type="number"),s.every(a=>typeof a=="string")&&(r.type="string"),s.every(a=>typeof a=="boolean")&&(r.type="boolean"),s.every(a=>a===null)&&(r.type="null"),r.enum=s};var pMe=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var hMe=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var mMe=(t,e,r,n)=>{let i=r,s=t._zod.def,{minimum:a,maximum:o}=t._zod.bag;typeof a=="number"&&(i.minItems=a),typeof o=="number"&&(i.maxItems=o),i.type="array",i.items=ss(s.element,e,{...n,path:[...n.path,"items"]})},gMe=(t,e,r,n)=>{let i=r,s=t._zod.def;i.type="object",i.properties={};let a=s.shape;for(let u in a)i.properties[u]=ss(a[u],e,{...n,path:[...n.path,"properties",u]});let o=new Set(Object.keys(a)),c=new Set([...o].filter(u=>{let f=s.shape[u]._zod;return e.io==="input"?f.optin===void 0:f.optout===void 0}));c.size>0&&(i.required=Array.from(c)),s.catchall?._zod.def.type==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=ss(s.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},vMe=(t,e,r,n)=>{let i=t._zod.def,s=i.inclusive===!1,a=i.options.map((o,c)=>ss(o,e,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=a:r.anyOf=a},yMe=(t,e,r,n)=>{let i=t._zod.def,s=ss(i.left,e,{...n,path:[...n.path,"allOf",0]}),a=ss(i.right,e,{...n,path:[...n.path,"allOf",1]}),o=u=>"allOf"in u&&Object.keys(u).length===1,c=[...o(s)?s.allOf:[s],...o(a)?a.allOf:[a]];r.allOf=c};var bMe=(t,e,r,n)=>{let i=r,s=t._zod.def;i.type="object";let a=s.keyType,c=a._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let f=ss(s.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(let d of c)i.patternProperties[d.source]=f}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=ss(s.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=ss(s.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=a._zod.values;if(u){let f=[...u].filter(d=>typeof d=="string"||typeof d=="number");f.length>0&&(i.required=f)}},xMe=(t,e,r,n)=>{let i=t._zod.def,s=ss(i.innerType,e,n),a=e.seen.get(t);e.target==="openapi-3.0"?(a.ref=i.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},wMe=(t,e,r,n)=>{let i=t._zod.def;ss(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType},_Me=(t,e,r,n)=>{let i=t._zod.def;ss(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},SMe=(t,e,r,n)=>{let i=t._zod.def;ss(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},EMe=(t,e,r,n)=>{let i=t._zod.def;ss(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType;let a;try{a=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=a},AMe=(t,e,r,n)=>{let i=t._zod.def,s=i.in._zod.traits.has("$ZodTransform"),a=e.io==="input"?s?i.out:i.in:i.out;ss(a,e,n);let o=e.seen.get(t);o.ref=a},CMe=(t,e,r,n)=>{let i=t._zod.def;ss(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType,r.readOnly=!0};var Hae=(t,e,r,n)=>{let i=t._zod.def;ss(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType};var enr=He("ZodISODateTime",(t,e)=>{$je.init(t,e),mi.init(t,e)});function kMe(t){return H$e(enr,t)}var tnr=He("ZodISODate",(t,e)=>{Mje.init(t,e),mi.init(t,e)});function TMe(t){return W$e(tnr,t)}var rnr=He("ZodISOTime",(t,e)=>{Lje.init(t,e),mi.init(t,e)});function PMe(t){return V$e(rnr,t)}var nnr=He("ZodISODuration",(t,e)=>{qje.init(t,e),mi.init(t,e)});function OMe(t){return G$e(nnr,t)}var snr=(t,e)=>{QM.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>gae(t,r)},flatten:{value:r=>mae(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,xy,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,xy,2)}},isEmpty:{get(){return t.issues.length===0}}})};var lu=He("ZodError",snr,{Parent:Error});var IMe=eL(lu),DMe=tL(lu),FMe=EE(lu),NMe=CE(lu),jMe=_Ne(lu),$Me=SNe(lu),MMe=ENe(lu),LMe=ANe(lu),qMe=CNe(lu),BMe=kNe(lu),zMe=TNe(lu),UMe=PNe(lu);var HMe=new WeakMap;function DE(t,e,r){let n=Object.getPrototypeOf(t),i=HMe.get(n);if(i||(i=new Set,HMe.set(n,i)),!i.has(e)){i.add(e);for(let s in r){let a=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let o=a.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:o}),o},set(o){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:o})}})}}}var gi=He("ZodType",(t,e)=>(ni.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:RE(t,"input"),output:RE(t,"output")}}),t.toJSONSchema=iMe(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>IMe(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>FMe(t,r,n),t.parseAsync=async(r,n)=>DMe(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>NMe(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>jMe(t,r,n),t.decode=(r,n)=>$Me(t,r,n),t.encodeAsync=async(r,n)=>MMe(t,r,n),t.decodeAsync=async(r,n)=>LMe(t,r,n),t.safeEncode=(r,n)=>qMe(t,r,n),t.safeDecode=(r,n)=>BMe(t,r,n),t.safeEncodeAsync=async(r,n)=>zMe(t,r,n),t.safeDecodeAsync=async(r,n)=>UMe(t,r,n),DE(t,"ZodType",{check(...r){let n=this.def;return this.clone(Vr.mergeDefs(n,{checks:[...n.checks??[],...r.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return Yu(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(Knr(r,n))},superRefine(r,n){return this.check(Jnr(r,n))},overwrite(r){return this.check(I0(r))},optional(){return Ar(this)},exactOptional(){return jnr(this)},nullable(){return KMe(this)},nullish(){return Ar(KMe(this))},nonoptional(r){return znr(this,r)},array(){return pt(this)},or(r){return Ti([this,r])},and(r){return pL(this,r)},transform(r){return JMe(this,iLe(r))},default(r){return Lnr(this,r)},prefault(r){return Bnr(this,r)},catch(r){return Hnr(this,r)},pipe(r){return JMe(this,r)},readonly(){return Gnr(this)},describe(r){let n=this.clone();return R0.add(n,{description:r}),n},meta(...r){if(r.length===0)return R0.get(this);let n=this.clone();return R0.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return R0.get(t)?.description},configurable:!0}),t)),ZMe=He("_ZodString",(t,e)=>{aL.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(n,i,s)=>sMe(t,n,i,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,DE(t,"_ZodString",{regex(...n){return this.check(Oae(...n))},includes(...n){return this.check(Dae(...n))},startsWith(...n){return this.check(Fae(...n))},endsWith(...n){return this.check(Nae(...n))},min(...n){return this.check(Sy(...n))},max(...n){return this.check(lL(...n))},length(...n){return this.check(fL(...n))},nonempty(...n){return this.check(Sy(1,...n))},lowercase(n){return this.check(Rae(n))},uppercase(n){return this.check(Iae(n))},trim(){return this.check($ae())},normalize(...n){return this.check(jae(...n))},toLowerCase(){return this.check(Mae())},toUpperCase(){return this.check(Lae())},slugify(){return this.check(qae())}})}),onr=He("ZodString",(t,e)=>{aL.init(t,e),ZMe.init(t,e),t.email=r=>t.check(E$e(cnr,r)),t.url=r=>t.check(Pae(XMe,r)),t.jwt=r=>t.check(U$e(Snr,r)),t.emoji=r=>t.check(P$e(unr,r)),t.guid=r=>t.check(Tae(WMe,r)),t.uuid=r=>t.check(A$e(dL,r)),t.uuidv4=r=>t.check(C$e(dL,r)),t.uuidv6=r=>t.check(k$e(dL,r)),t.uuidv7=r=>t.check(T$e(dL,r)),t.nanoid=r=>t.check(O$e(lnr,r)),t.guid=r=>t.check(Tae(WMe,r)),t.cuid=r=>t.check(R$e(fnr,r)),t.cuid2=r=>t.check(I$e(dnr,r)),t.ulid=r=>t.check(D$e(pnr,r)),t.base64=r=>t.check(q$e(xnr,r)),t.base64url=r=>t.check(B$e(wnr,r)),t.xid=r=>t.check(F$e(hnr,r)),t.ksuid=r=>t.check(N$e(mnr,r)),t.ipv4=r=>t.check(j$e(gnr,r)),t.ipv6=r=>t.check($$e(vnr,r)),t.cidrv4=r=>t.check(M$e(ynr,r)),t.cidrv6=r=>t.check(L$e(bnr,r)),t.e164=r=>t.check(z$e(_nr,r)),t.datetime=r=>t.check(kMe(r)),t.date=r=>t.check(TMe(r)),t.time=r=>t.check(PMe(r)),t.duration=r=>t.check(OMe(r))});function _e(t){return S$e(onr,t)}var mi=He("ZodStringFormat",(t,e)=>{ii.init(t,e),ZMe.init(t,e)}),cnr=He("ZodEmail",(t,e)=>{Tje.init(t,e),mi.init(t,e)});var WMe=He("ZodGUID",(t,e)=>{Cje.init(t,e),mi.init(t,e)});var dL=He("ZodUUID",(t,e)=>{kje.init(t,e),mi.init(t,e)});var XMe=He("ZodURL",(t,e)=>{Pje.init(t,e),mi.init(t,e)});function YMe(t){return Pae(XMe,t)}var unr=He("ZodEmoji",(t,e)=>{Oje.init(t,e),mi.init(t,e)});var lnr=He("ZodNanoID",(t,e)=>{Rje.init(t,e),mi.init(t,e)});var fnr=He("ZodCUID",(t,e)=>{Ije.init(t,e),mi.init(t,e)});var dnr=He("ZodCUID2",(t,e)=>{Dje.init(t,e),mi.init(t,e)});var pnr=He("ZodULID",(t,e)=>{Fje.init(t,e),mi.init(t,e)});var hnr=He("ZodXID",(t,e)=>{Nje.init(t,e),mi.init(t,e)});var mnr=He("ZodKSUID",(t,e)=>{jje.init(t,e),mi.init(t,e)});var gnr=He("ZodIPv4",(t,e)=>{Bje.init(t,e),mi.init(t,e)});var vnr=He("ZodIPv6",(t,e)=>{zje.init(t,e),mi.init(t,e)});var ynr=He("ZodCIDRv4",(t,e)=>{Uje.init(t,e),mi.init(t,e)});var bnr=He("ZodCIDRv6",(t,e)=>{Hje.init(t,e),mi.init(t,e)});var xnr=He("ZodBase64",(t,e)=>{Vje.init(t,e),mi.init(t,e)});var wnr=He("ZodBase64URL",(t,e)=>{Gje.init(t,e),mi.init(t,e)});var _nr=He("ZodE164",(t,e)=>{Kje.init(t,e),mi.init(t,e)});var Snr=He("ZodJWT",(t,e)=>{Jje.init(t,e),mi.init(t,e)});var QMe=He("ZodNumber",(t,e)=>{Sae.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(n,i,s)=>aMe(t,n,i,s),DE(t,"ZodNumber",{gt(n,i){return this.check(cL(n,i))},gte(n,i){return this.check(OE(n,i))},min(n,i){return this.check(OE(n,i))},lt(n,i){return this.check(oL(n,i))},lte(n,i){return this.check(PE(n,i))},max(n,i){return this.check(PE(n,i))},int(n){return this.check(VMe(n))},safe(n){return this.check(VMe(n))},positive(n){return this.check(cL(0,n))},nonnegative(n){return this.check(OE(0,n))},negative(n){return this.check(oL(0,n))},nonpositive(n){return this.check(PE(0,n))},multipleOf(n,i){return this.check(uL(n,i))},step(n,i){return this.check(uL(n,i))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function Yn(t){return K$e(QMe,t)}var Enr=He("ZodNumberFormat",(t,e)=>{Zje.init(t,e),QMe.init(t,e)});function VMe(t){return J$e(Enr,t)}var Anr=He("ZodBoolean",(t,e)=>{Xje.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>oMe(t,r,n,i)});function Qn(t){return Z$e(Anr,t)}var Cnr=He("ZodAny",(t,e)=>{Yje.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>uMe(t,r,n,i)});function eLe(){return X$e(Cnr)}var knr=He("ZodUnknown",(t,e)=>{Qje.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lMe(t,r,n,i)});function zi(){return Y$e(knr)}var Tnr=He("ZodNever",(t,e)=>{e$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>cMe(t,r,n,i)});function Pnr(t){return Q$e(Tnr,t)}var Onr=He("ZodArray",(t,e)=>{t$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>mMe(t,r,n,i),t.element=e.element,DE(t,"ZodArray",{min(r,n){return this.check(Sy(r,n))},nonempty(r){return this.check(Sy(1,r))},max(r,n){return this.check(lL(r,n))},length(r,n){return this.check(fL(r,n))},unwrap(){return this.element}})});function pt(t,e){return eMe(Onr,t,e)}var tLe=He("ZodObject",(t,e)=>{i$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>gMe(t,r,n,i),Vr.defineLazy(t,"shape",()=>e.shape),DE(t,"ZodObject",{keyof(){return el(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:zi()})},loose(){return this.clone({...this._zod.def,catchall:zi()})},strict(){return this.clone({...this._zod.def,catchall:Pnr()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return Vr.extend(this,r)},safeExtend(r){return Vr.safeExtend(this,r)},merge(r){return Vr.merge(this,r)},pick(r){return Vr.pick(this,r)},omit(r){return Vr.omit(this,r)},partial(...r){return Vr.partial(sLe,this,r[0])},required(...r){return Vr.required(aLe,this,r[0])}})});function vt(t,e){let r={type:"object",shape:t??{},...Vr.normalizeParams(e)};return new tLe(r)}function fu(t,e){return new tLe({type:"object",shape:t,catchall:zi(),...Vr.normalizeParams(e)})}var rLe=He("ZodUnion",(t,e)=>{Eae.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>vMe(t,r,n,i),t.options=e.options});function Ti(t,e){return new rLe({type:"union",options:t,...Vr.normalizeParams(e)})}var Rnr=He("ZodDiscriminatedUnion",(t,e)=>{rLe.init(t,e),s$e.init(t,e)});function nLe(t,e,r){return new Rnr({type:"union",options:e,discriminator:t,...Vr.normalizeParams(r)})}var Inr=He("ZodIntersection",(t,e)=>{a$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>yMe(t,r,n,i)});function pL(t,e){return new Inr({type:"intersection",left:t,right:e})}var GMe=He("ZodRecord",(t,e)=>{o$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>bMe(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function Ui(t,e,r){return!e||!e._zod?new GMe({type:"record",keyType:_e(),valueType:t,...Vr.normalizeParams(e)}):new GMe({type:"record",keyType:t,valueType:e,...Vr.normalizeParams(r)})}var Wae=He("ZodEnum",(t,e)=>{c$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(n,i,s)=>fMe(t,n,i,s),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let s={};for(let a of n)if(r.has(a))s[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Wae({...e,checks:[],...Vr.normalizeParams(i),entries:s})},t.exclude=(n,i)=>{let s={...e.entries};for(let a of n)if(r.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new Wae({...e,checks:[],...Vr.normalizeParams(i),entries:s})}});function el(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Wae({type:"enum",entries:r,...Vr.normalizeParams(e)})}var Dnr=He("ZodLiteral",(t,e)=>{u$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>dMe(t,r,n,i),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function Mt(t,e){return new Dnr({type:"literal",values:Array.isArray(t)?t:[t],...Vr.normalizeParams(e)})}var Fnr=He("ZodTransform",(t,e)=>{l$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>hMe(t,r,n,i),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new yy(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(Vr.issue(s,r.value,e));else{let a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),r.issues.push(Vr.issue(a))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=i,r.fallback=!0,r)}});function iLe(t){return new Fnr({type:"transform",transform:t})}var sLe=He("ZodOptional",(t,e)=>{Aae.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Hae(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Ar(t){return new sLe({type:"optional",innerType:t})}var Nnr=He("ZodExactOptional",(t,e)=>{f$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Hae(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function jnr(t){return new Nnr({type:"optional",innerType:t})}var $nr=He("ZodNullable",(t,e)=>{d$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>xMe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function KMe(t){return new $nr({type:"nullable",innerType:t})}var Mnr=He("ZodDefault",(t,e)=>{p$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>_Me(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Lnr(t,e){return new Mnr({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Vr.shallowClone(e)}})}var qnr=He("ZodPrefault",(t,e)=>{h$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>SMe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Bnr(t,e){return new qnr({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Vr.shallowClone(e)}})}var aLe=He("ZodNonOptional",(t,e)=>{m$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>wMe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function znr(t,e){return new aLe({type:"nonoptional",innerType:t,...Vr.normalizeParams(e)})}var Unr=He("ZodCatch",(t,e)=>{g$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>EMe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Hnr(t,e){return new Unr({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var oLe=He("ZodPipe",(t,e)=>{Cae.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>AMe(t,r,n,i),t.in=e.in,t.out=e.out});function JMe(t,e){return new oLe({type:"pipe",in:t,out:e})}var Wnr=He("ZodPreprocess",(t,e)=>{oLe.init(t,e),v$e.init(t,e)}),Vnr=He("ZodReadonly",(t,e)=>{y$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>CMe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Gnr(t){return new Vnr({type:"readonly",innerType:t})}var cLe=He("ZodCustom",(t,e)=>{b$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>pMe(t,r,n,i)});function uLe(t,e){return tMe(cLe,t??(()=>!0),e)}function Knr(t,e={}){return rMe(cLe,t,e)}function Jnr(t,e){return nMe(t,e)}function lLe(t,e){return new Wnr({type:"pipe",in:iLe(t),out:e})}var dLe={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 fLe;fLe||(fLe={});hc(x$e());var Ta=YMe().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:dLe.custom,message:"URL must be parseable",fatal:!0}),nae}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),hLe=fu({resource:_e().url(),authorization_servers:pt(Ta).optional(),jwks_uri:_e().url().optional(),scopes_supported:pt(_e()).optional(),bearer_methods_supported:pt(_e()).optional(),resource_signing_alg_values_supported:pt(_e()).optional(),resource_name:_e().optional(),resource_documentation:_e().optional(),resource_policy_uri:_e().url().optional(),resource_tos_uri:_e().url().optional(),tls_client_certificate_bound_access_tokens:Qn().optional(),authorization_details_types_supported:pt(_e()).optional(),dpop_signing_alg_values_supported:pt(_e()).optional(),dpop_bound_access_tokens_required:Qn().optional()}),Vae=fu({issuer:_e(),authorization_endpoint:Ta,token_endpoint:Ta,registration_endpoint:Ta.optional(),scopes_supported:pt(_e()).optional(),response_types_supported:pt(_e()),response_modes_supported:pt(_e()).optional(),grant_types_supported:pt(_e()).optional(),token_endpoint_auth_methods_supported:pt(_e()).optional(),token_endpoint_auth_signing_alg_values_supported:pt(_e()).optional(),service_documentation:Ta.optional(),revocation_endpoint:Ta.optional(),revocation_endpoint_auth_methods_supported:pt(_e()).optional(),revocation_endpoint_auth_signing_alg_values_supported:pt(_e()).optional(),introspection_endpoint:_e().optional(),introspection_endpoint_auth_methods_supported:pt(_e()).optional(),introspection_endpoint_auth_signing_alg_values_supported:pt(_e()).optional(),code_challenge_methods_supported:pt(_e()).optional(),client_id_metadata_document_supported:Qn().optional()}),Xnr=fu({issuer:_e(),authorization_endpoint:Ta,token_endpoint:Ta,userinfo_endpoint:Ta.optional(),jwks_uri:Ta,registration_endpoint:Ta.optional(),scopes_supported:pt(_e()).optional(),response_types_supported:pt(_e()),response_modes_supported:pt(_e()).optional(),grant_types_supported:pt(_e()).optional(),acr_values_supported:pt(_e()).optional(),subject_types_supported:pt(_e()),id_token_signing_alg_values_supported:pt(_e()),id_token_encryption_alg_values_supported:pt(_e()).optional(),id_token_encryption_enc_values_supported:pt(_e()).optional(),userinfo_signing_alg_values_supported:pt(_e()).optional(),userinfo_encryption_alg_values_supported:pt(_e()).optional(),userinfo_encryption_enc_values_supported:pt(_e()).optional(),request_object_signing_alg_values_supported:pt(_e()).optional(),request_object_encryption_alg_values_supported:pt(_e()).optional(),request_object_encryption_enc_values_supported:pt(_e()).optional(),token_endpoint_auth_methods_supported:pt(_e()).optional(),token_endpoint_auth_signing_alg_values_supported:pt(_e()).optional(),display_values_supported:pt(_e()).optional(),claim_types_supported:pt(_e()).optional(),claims_supported:pt(_e()).optional(),service_documentation:_e().optional(),claims_locales_supported:pt(_e()).optional(),ui_locales_supported:pt(_e()).optional(),claims_parameter_supported:Qn().optional(),request_parameter_supported:Qn().optional(),request_uri_parameter_supported:Qn().optional(),require_request_uri_registration:Qn().optional(),op_policy_uri:Ta.optional(),op_tos_uri:Ta.optional(),client_id_metadata_document_supported:Qn().optional()}),mLe=vt({...Xnr.shape,...Vae.pick({code_challenge_methods_supported:!0}).shape}),FE=vt({access_token:_e(),id_token:_e().optional(),token_type:_e(),expires_in:Yn().optional(),scope:_e().optional(),refresh_token:_e().optional()}).strip(),gLe=vt({error:_e(),error_description:_e().optional(),error_uri:_e().optional()}),pLe=Ta.optional().or(Mt("").transform(()=>{})),Ynr=vt({redirect_uris:pt(Ta),token_endpoint_auth_method:_e().optional(),grant_types:pt(_e()).optional(),response_types:pt(_e()).optional(),client_name:_e().optional(),client_uri:Ta.optional(),logo_uri:pLe,scope:_e().optional(),contacts:pt(_e()).optional(),tos_uri:pLe,policy_uri:_e().optional(),jwks_uri:Ta.optional(),jwks:eLe().optional(),software_id:_e().optional(),software_version:_e().optional(),software_statement:_e().optional()}).strip(),Qnr=vt({client_id:_e(),client_secret:_e().optional(),client_id_issued_at:Yn().optional(),client_secret_expires_at:Yn().optional()}).strip(),hL=Ynr.merge(Qnr),j_n=vt({error:_e(),error_description:_e().optional()}).strip(),$_n=vt({token:_e(),token_type_hint:_e().optional()}).strip();var mL=class{constructor(e,r,n,i,s,a,o,c){this.interactor=e;this.userService=r;this.projectName=n;this.mcpId=i;this.redirectUri=s;this.staticClientId=a;this.staticClientSecret=o;this.staticScope=c}_codeVerifier;_discoveryState;finishAuth=null;_pendingAuthPromise;_pendingAuthResolve;_pendingAuthReject;get redirectUrl(){return this.redirectUri}get clientMetadata(){return{redirect_uris:[this.redirectUri],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:`Coday MCP Client (${this.mcpId})`,...this.staticScope!==void 0?{scope:this.staticScope}:{}}}async validateResourceURL(e,r){if(this.staticScope!==void 0){this.interactor.debug(`[MCP OAuth:${this.mcpId}] validateResourceURL: suppressing resource scopes (staticScope='${this.staticScope}')`);return}}async saveDiscoveryState(e){if(this.staticScope!==void 0&&e.resourceMetadata){let n={...e.resourceMetadata,scopes_supported:void 0};this.interactor.debug(`[MCP OAuth:${this.mcpId}] saveDiscoveryState: stripping scopes_supported from resourceMetadata`),this._discoveryState={...e,resourceMetadata:n}}else this._discoveryState=e}async discoveryState(){return this._discoveryState}tokens(){let e=this.loadRaw()?.tokens;if(!e){this.interactor.debug(`[MCP OAuth:${this.mcpId}] no stored tokens found`);return}let r=FE.safeParse(e);if(!r.success){this.interactor.warn(`[MCP OAuth:${this.mcpId}] stored tokens are invalid: ${JSON.stringify(r.error.issues)}`);return}return this.interactor.debug(`[MCP OAuth:${this.mcpId}] tokens loaded (expires_in=${r.data.expires_in})`),r.data}async saveTokens(e){this.ensureStoragePath().tokens=e,this.userService.save(),this.interactor.debug(`[MCP OAuth:${this.mcpId}] tokens saved`)}clientInformation(){if(this.staticClientId)return this.interactor.debug(`[MCP OAuth:${this.mcpId}] using static client credentials (client_id=${this.staticClientId})`),{client_id:this.staticClientId,...this.staticClientSecret?{client_secret:this.staticClientSecret}:{},redirect_uris:[this.redirectUri],token_endpoint_auth_method:this.staticClientSecret?"client_secret_post":"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:`Coday MCP Client (${this.mcpId})`};let e=this.loadRaw(),r=e?.clientInfo;if(!r){this.interactor.debug(`[MCP OAuth:${this.mcpId}] no stored client info found`);return}if(!e?.tokens){this.clearStorage();return}let n=hL.safeParse(r);if(!n.success){this.interactor.warn(`[MCP OAuth:${this.mcpId}] stored client info is invalid: ${JSON.stringify(n.error.issues)}`);return}return this.interactor.debug(`[MCP OAuth:${this.mcpId}] client info loaded (client_id=${n.data.client_id})`),n.data}async saveClientInformation(e){if(this.staticClientId){this.interactor.debug(`[MCP OAuth:${this.mcpId}] skipping saveClientInformation (static credentials in use)`);return}this.ensureStoragePath().clientInfo=e,this.userService.save(),this.interactor.debug(`[MCP OAuth:${this.mcpId}] client info saved (id=${e.client_id})`)}saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error(`[MCP OAuth:${this.mcpId}] no code verifier available`);return this._codeVerifier}setFinishAuth(e){this.interactor.debug(`[MCP OAuth:${this.mcpId}] finishAuth callback registered`),this.finishAuth=e}waitForAuth(){return this._pendingAuthPromise}redirectToAuthorization(e){if(this.interactor.warn(`[MCP OAuth:${this.mcpId}] OAuth authorization required \u2014 opening auth URL`),this.staticScope!==void 0){let r=new URL(e.toString());this.staticScope===""?(r.searchParams.delete("scope"),this.interactor.debug(`[MCP OAuth:${this.mcpId}] stripped scope from authorization URL`)):(r.searchParams.set("scope",this.staticScope),this.interactor.debug(`[MCP OAuth:${this.mcpId}] overrode scope to '${this.staticScope}' in authorization URL`)),e=r}this.interactor.debug(`[MCP OAuth:${this.mcpId}] redirecting to authorization: ${e}`),this._pendingAuthPromise||(this._pendingAuthPromise=new Promise((r,n)=>{this._pendingAuthResolve=r,this._pendingAuthReject=n}),this._pendingAuthPromise.then(()=>{this._pendingAuthPromise=void 0},()=>{this._pendingAuthPromise=void 0})),this.interactor.sendEvent(new Jf({authUrl:e.toString(),state:e.searchParams.get("state")??"",integrationName:this.mcpId}))}async invalidateCredentials(e){this.interactor.warn(`[MCP OAuth:${this.mcpId}] invalidating credentials: ${e}`);let r=this.loadRaw();if(this._pendingAuthReject&&(this._pendingAuthReject(new Error(`[MCP OAuth:${this.mcpId}] credentials invalidated during pending auth flow`)),this._pendingAuthResolve=void 0,this._pendingAuthReject=void 0),!!r)switch(e){case"all":this.clearStorage();break;case"client":delete r.clientInfo,this.userService.save();break;case"tokens":delete r.tokens,this.userService.save();break;case"verifier":this._codeVerifier=void 0;break}}async handleCallback(e){if(e.integrationName!==this.mcpId){this.interactor.debug(`[MCP OAuth:${this.mcpId}] ignoring callback for integration '${e.integrationName}'`);return}if(this.interactor.debug(`[MCP OAuth:${this.mcpId}] handling OAuth callback`),e.error){let r=e.error==="access_denied"?"OAuth authentication denied by user":`OAuth error: ${e.error}${e.errorDescription?" - "+e.errorDescription:""}`;this.interactor.warn(r),this._pendingAuthReject&&(this._pendingAuthReject(new Error(r)),this._pendingAuthResolve=void 0,this._pendingAuthReject=void 0);return}if(!e.code){let r=`[MCP OAuth:${this.mcpId}] callback missing authorization code`;this.interactor.error(r),this._pendingAuthReject&&(this._pendingAuthReject(new Error(r)),this._pendingAuthResolve=void 0,this._pendingAuthReject=void 0);return}if(!this.finishAuth){let r=`[MCP OAuth:${this.mcpId}] no transport registered to receive auth code`;this.interactor.error(r),this._pendingAuthReject&&(this._pendingAuthReject(new Error(r)),this._pendingAuthResolve=void 0,this._pendingAuthReject=void 0);return}this.interactor.debug(`[MCP OAuth:${this.mcpId}] received authorization code, completing auth flow`);try{await this.finishAuth(e.code),this._pendingAuthResolve&&(this._pendingAuthResolve(),this._pendingAuthResolve=void 0,this._pendingAuthReject=void 0)}catch(r){this.interactor.error(`[MCP OAuth:${this.mcpId}] finishAuth failed: ${r.message}`),this._pendingAuthReject&&(this._pendingAuthReject(r),this._pendingAuthResolve=void 0,this._pendingAuthReject=void 0)}}loadRaw(){return this.userService.config.projects?.[this.projectName]?.integration?.[this.mcpId]?.mcpOAuth}ensureStoragePath(){let e=this.userService.config;e.projects||(e.projects={}),e.projects[this.projectName]||(e.projects[this.projectName]={integration:{}});let r=e.projects[this.projectName];r.integration||(r.integration={}),r.integration[this.mcpId]||(r.integration[this.mcpId]={});let n=r.integration[this.mcpId];return n.mcpOAuth||(n.mcpOAuth={}),n.mcpOAuth}clearStorage(){let e=this.userService.config.projects?.[this.projectName];e?.integration?.[this.mcpId]&&(delete e.integration[this.mcpId].mcpOAuth,this.userService.save())}};function Ey(t){return!!t._zod}function lg(t,e){return Ey(t)?AE(t,e):t.safeParse(e)}function gL(t){var e,r;if(!t)return;let n;if(Ey(t)?n=(r=(e=t._zod)===null||e===void 0?void 0:e.def)===null||r===void 0?void 0:r.shape:n=t.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function vLe(t){var e;if(Ey(t)){let a=(e=t._zod)===null||e===void 0?void 0:e.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let i=t.value;if(i!==void 0)return i}var Cy="2025-06-18";var yLe=[Cy,"2025-03-26","2024-11-05","2024-10-07"],yL="2.0",xd=uLe(t=>t!==null&&(typeof t=="object"||typeof t=="function")),bLe=Ti([_e(),Yn().int()]),xLe=_e(),eir=fu({progressToken:bLe.optional()}),tf=fu({_meta:eir.optional()}),mc=vt({method:_e(),params:tf.optional()}),ky=fu({_meta:Ui(_e(),zi()).optional()}),rf=vt({method:_e(),params:ky.optional()}),tl=fu({_meta:Ui(_e(),zi()).optional()}),bL=Ti([_e(),Yn().int()]),wLe=vt({jsonrpc:Mt(yL),id:bL,...mc.shape}).strict(),xL=t=>wLe.safeParse(t).success,_Le=vt({jsonrpc:Mt(yL),...rf.shape}).strict(),SLe=t=>_Le.safeParse(t).success,ELe=vt({jsonrpc:Mt(yL),id:bL,result:tl}).strict(),NE=t=>ELe.safeParse(t).success,na;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(na||(na={}));var ALe=vt({jsonrpc:Mt(yL),id:bL,error:vt({code:Yn().int(),message:_e(),data:Ar(zi())})}).strict(),CLe=t=>ALe.safeParse(t).success,D0=Ti([wLe,_Le,ELe,ALe]),fg=tl.strict(),tir=ky.extend({requestId:bL,reason:_e().optional()}),wL=rf.extend({method:Mt("notifications/cancelled"),params:tir}),rir=vt({src:_e(),mimeType:_e().optional(),sizes:pt(_e()).optional()}),jE=vt({icons:pt(rir).optional()}),Ay=vt({name:_e(),title:_e().optional()}),kLe=Ay.extend({...Ay.shape,...jE.shape,version:_e(),websiteUrl:_e().optional()}),nir=pL(vt({applyDefaults:Qn().optional()}),Ui(_e(),zi())),iir=lLe(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,pL(vt({form:nir.optional(),url:xd.optional()}),Ui(_e(),zi()).optional())),sir=vt({experimental:Ui(_e(),xd).optional(),sampling:vt({context:xd.optional(),tools:xd.optional()}).optional(),elicitation:iir.optional(),roots:vt({listChanged:Qn().optional()}).optional()}),air=tf.extend({protocolVersion:_e(),capabilities:sir,clientInfo:kLe}),oir=mc.extend({method:Mt("initialize"),params:air});var cir=vt({experimental:Ui(_e(),xd).optional(),logging:xd.optional(),completions:xd.optional(),prompts:Ar(vt({listChanged:Ar(Qn())})),resources:vt({subscribe:Qn().optional(),listChanged:Qn().optional()}).optional(),tools:vt({listChanged:Qn().optional()}).optional()}),Kae=tl.extend({protocolVersion:_e(),capabilities:cir,serverInfo:kLe,instructions:_e().optional()}),TLe=rf.extend({method:Mt("notifications/initialized")}),PLe=t=>TLe.safeParse(t).success,_L=mc.extend({method:Mt("ping")}),uir=vt({progress:Yn(),total:Ar(Yn()),message:Ar(_e())}),lir=vt({...ky.shape,...uir.shape,progressToken:bLe}),SL=rf.extend({method:Mt("notifications/progress"),params:lir}),fir=tf.extend({cursor:xLe.optional()}),EL=mc.extend({params:fir.optional()}),AL=tl.extend({nextCursor:Ar(xLe)}),OLe=vt({uri:_e(),mimeType:Ar(_e()),_meta:Ui(_e(),zi()).optional()}),RLe=OLe.extend({text:_e()}),Jae=_e().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),ILe=OLe.extend({blob:Jae}),DLe=vt({...Ay.shape,...jE.shape,uri:_e(),description:Ar(_e()),mimeType:Ar(_e()),_meta:Ar(fu({}))}),dir=vt({...Ay.shape,...jE.shape,uriTemplate:_e(),description:Ar(_e()),mimeType:Ar(_e()),_meta:Ar(fu({}))}),pir=EL.extend({method:Mt("resources/list")}),Zae=AL.extend({resources:pt(DLe)}),hir=EL.extend({method:Mt("resources/templates/list")}),Xae=AL.extend({resourceTemplates:pt(dir)}),Yae=tf.extend({uri:_e()}),mir=Yae,gir=mc.extend({method:Mt("resources/read"),params:mir}),Qae=tl.extend({contents:pt(Ti([RLe,ILe]))}),vir=rf.extend({method:Mt("notifications/resources/list_changed")}),yir=Yae,bir=mc.extend({method:Mt("resources/subscribe"),params:yir}),xir=Yae,wir=mc.extend({method:Mt("resources/unsubscribe"),params:xir}),_ir=ky.extend({uri:_e()}),Sir=rf.extend({method:Mt("notifications/resources/updated"),params:_ir}),Eir=vt({name:_e(),description:Ar(_e()),required:Ar(Qn())}),Air=vt({...Ay.shape,...jE.shape,description:Ar(_e()),arguments:Ar(pt(Eir)),_meta:Ar(fu({}))}),Cir=EL.extend({method:Mt("prompts/list")}),eoe=AL.extend({prompts:pt(Air)}),kir=tf.extend({name:_e(),arguments:Ui(_e(),_e()).optional()}),Tir=mc.extend({method:Mt("prompts/get"),params:kir}),FLe=vt({type:Mt("text"),text:_e(),_meta:Ui(_e(),zi()).optional()}),NLe=vt({type:Mt("image"),data:Jae,mimeType:_e(),_meta:Ui(_e(),zi()).optional()}),jLe=vt({type:Mt("audio"),data:Jae,mimeType:_e(),_meta:Ui(_e(),zi()).optional()}),Pir=vt({type:Mt("tool_use"),name:_e(),id:_e(),input:vt({}).passthrough(),_meta:Ar(vt({}).passthrough())}).passthrough(),Oir=vt({type:Mt("resource"),resource:Ti([RLe,ILe]),_meta:Ui(_e(),zi()).optional()}),Rir=DLe.extend({type:Mt("resource_link")}),toe=Ti([FLe,NLe,jLe,Rir,Oir]),Iir=vt({role:el(["user","assistant"]),content:toe}),roe=tl.extend({description:Ar(_e()),messages:pt(Iir)}),Dir=rf.extend({method:Mt("notifications/prompts/list_changed")}),Fir=vt({title:_e().optional(),readOnlyHint:Qn().optional(),destructiveHint:Qn().optional(),idempotentHint:Qn().optional(),openWorldHint:Qn().optional()}),$Le=vt({...Ay.shape,...jE.shape,description:_e().optional(),inputSchema:vt({type:Mt("object"),properties:Ui(_e(),xd).optional(),required:pt(_e()).optional()}).catchall(zi()),outputSchema:vt({type:Mt("object"),properties:Ui(_e(),xd).optional(),required:pt(_e()).optional()}).catchall(zi()).optional(),annotations:Ar(Fir),_meta:Ui(_e(),zi()).optional()}),Nir=EL.extend({method:Mt("tools/list")}),noe=AL.extend({tools:pt($Le)}),CL=tl.extend({content:pt(toe).default([]),structuredContent:Ui(_e(),zi()).optional(),isError:Ar(Qn())}),sSn=CL.or(tl.extend({toolResult:zi()})),jir=tf.extend({name:_e(),arguments:Ar(Ui(_e(),zi()))}),$ir=mc.extend({method:Mt("tools/call"),params:jir}),Mir=rf.extend({method:Mt("notifications/tools/list_changed")}),MLe=el(["debug","info","notice","warning","error","critical","alert","emergency"]),Lir=tf.extend({level:MLe}),qir=mc.extend({method:Mt("logging/setLevel"),params:Lir}),Bir=ky.extend({level:MLe,logger:_e().optional(),data:zi()}),zir=rf.extend({method:Mt("notifications/message"),params:Bir}),Uir=vt({name:_e().optional()}),Hir=vt({hints:Ar(pt(Uir)),costPriority:Ar(Yn().min(0).max(1)),speedPriority:Ar(Yn().min(0).max(1)),intelligencePriority:Ar(Yn().min(0).max(1))}),Wir=vt({mode:Ar(el(["auto","required","none"]))}),Vir=vt({type:Mt("tool_result"),toolUseId:_e().describe("The unique identifier for the corresponding tool call."),content:pt(toe).default([]),structuredContent:vt({}).passthrough().optional(),isError:Ar(Qn()),_meta:Ar(vt({}).passthrough())}).passthrough(),vL=nLe("type",[FLe,NLe,jLe,Pir,Vir]),Gir=vt({role:el(["user","assistant"]),content:Ti([vL,pt(vL)]),_meta:Ar(vt({}).passthrough())}).passthrough(),Kir=tf.extend({messages:pt(Gir),modelPreferences:Hir.optional(),systemPrompt:_e().optional(),includeContext:el(["none","thisServer","allServers"]).optional(),temperature:Yn().optional(),maxTokens:Yn().int(),stopSequences:pt(_e()).optional(),metadata:xd.optional(),tools:Ar(pt($Le)),toolChoice:Ar(Wir)}),Jir=mc.extend({method:Mt("sampling/createMessage"),params:Kir}),Zir=tl.extend({model:_e(),stopReason:Ar(el(["endTurn","stopSequence","maxTokens","toolUse"]).or(_e())),role:el(["user","assistant"]),content:Ti([vL,pt(vL)])}),Xir=vt({type:Mt("boolean"),title:_e().optional(),description:_e().optional(),default:Qn().optional()}),Yir=vt({type:Mt("string"),title:_e().optional(),description:_e().optional(),minLength:Yn().optional(),maxLength:Yn().optional(),format:el(["email","uri","date","date-time"]).optional(),default:_e().optional()}),Qir=vt({type:el(["number","integer"]),title:_e().optional(),description:_e().optional(),minimum:Yn().optional(),maximum:Yn().optional(),default:Yn().optional()}),esr=vt({type:Mt("string"),title:_e().optional(),description:_e().optional(),enum:pt(_e()),default:_e().optional()}),tsr=vt({type:Mt("string"),title:_e().optional(),description:_e().optional(),oneOf:pt(vt({const:_e(),title:_e()})),default:_e().optional()}),rsr=vt({type:Mt("string"),title:_e().optional(),description:_e().optional(),enum:pt(_e()),enumNames:pt(_e()).optional(),default:_e().optional()}),nsr=Ti([esr,tsr]),isr=vt({type:Mt("array"),title:_e().optional(),description:_e().optional(),minItems:Yn().optional(),maxItems:Yn().optional(),items:vt({type:Mt("string"),enum:pt(_e())}),default:pt(_e()).optional()}),ssr=vt({type:Mt("array"),title:_e().optional(),description:_e().optional(),minItems:Yn().optional(),maxItems:Yn().optional(),items:vt({anyOf:pt(vt({const:_e(),title:_e()}))}),default:pt(_e()).optional()}),asr=Ti([isr,ssr]),osr=Ti([rsr,nsr,asr]),csr=Ti([osr,Xir,Yir,Qir]),usr=tf.extend({mode:Mt("form").optional(),message:_e(),requestedSchema:vt({type:Mt("object"),properties:Ui(_e(),csr),required:pt(_e()).optional()})}),lsr=tf.extend({mode:Mt("url"),message:_e(),elicitationId:_e(),url:_e().url()}),fsr=Ti([usr,lsr]),ioe=mc.extend({method:Mt("elicitation/create"),params:fsr}),dsr=ky.extend({elicitationId:_e()}),psr=rf.extend({method:Mt("notifications/elicitation/complete"),params:dsr}),soe=tl.extend({action:el(["accept","decline","cancel"]),content:Ui(_e(),Ti([_e(),Yn(),Qn(),pt(_e())])).optional()}),hsr=vt({type:Mt("ref/resource"),uri:_e()});var msr=vt({type:Mt("ref/prompt"),name:_e()}),gsr=tf.extend({ref:Ti([msr,hsr]),argument:vt({name:_e(),value:_e()}),context:vt({arguments:Ui(_e(),_e()).optional()}).optional()}),vsr=mc.extend({method:Mt("completion/complete"),params:gsr});var aoe=tl.extend({completion:fu({values:pt(_e()).max(100),total:Ar(Yn().int()),hasMore:Ar(Qn())})}),ysr=vt({uri:_e().startsWith("file://"),name:_e().optional(),_meta:Ui(_e(),zi()).optional()}),bsr=mc.extend({method:Mt("roots/list")}),xsr=tl.extend({roots:pt(ysr)}),wsr=rf.extend({method:Mt("notifications/roots/list_changed")}),aSn=Ti([_L,oir,vsr,qir,Tir,Cir,pir,hir,gir,bir,wir,$ir,Nir]),oSn=Ti([wL,SL,TLe,wsr]),cSn=Ti([fg,Zir,soe,xsr]),uSn=Ti([_L,Jir,ioe,bsr]),lSn=Ti([wL,SL,zir,Sir,vir,Mir,Dir,psr]),fSn=Ti([fg,Kae,aoe,roe,eoe,Zae,Xae,Qae,CL,noe]),Pa=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===na.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new Gae(i.elicitations,r)}return new t(e,r,n)}},Gae=class extends Pa{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(na.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){var e,r;return(r=(e=this.data)===null||e===void 0?void 0:e.elicitations)!==null&&r!==void 0?r:[]}};var _sr=Symbol("Let zodToJsonSchema decide on which parser to use");var USn=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ooe(t){let e=gL(t),r=e?.method;if(!r)throw new Error("Schema is missing a method literal");let n=vLe(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function coe(t,e){let r=lg(t,e);if(!r.success)throw r.error;return r.data}var Tsr=6e4,kL=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(wL,r=>{let n=this._requestHandlerAbortControllers.get(r.params.requestId);n?.abort(r.params.reason)}),this.setNotificationHandler(SL,r=>{this._onprogress(r)}),this.setRequestHandler(_L,r=>({}))}_setupTimeout(e,r,n,i,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:i})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),Pa.fromError(na.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,n,i;this._transport=e;let s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s?.(),this._onclose()};let a=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=c=>{a?.(c),this._onerror(c)};let o=(i=this._transport)===null||i===void 0?void 0:i.onmessage;this._transport.onmessage=(c,u)=>{o?.(c,u),NE(c)||CLe(c)?this._onresponse(c):xL(c)?this._onrequest(c,u):SLe(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=Pa.fromError(na.ConnectionClosed,"Connection closed");for(let i of r.values())i(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,r){var n,i;let s=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,a=this._transport;if(s===void 0){a?.send({jsonrpc:"2.0",id:e.id,error:{code:na.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let c={signal:o.signal,sessionId:a?.sessionId,_meta:(i=e.params)===null||i===void 0?void 0:i._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,f,d)=>this.request(u,f,{...d,relatedRequestId:e.id}),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>s(e,c)).then(u=>{if(!o.signal.aborted)return a?.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var f;if(!o.signal.aborted)return a?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:na.InternalError,message:(f=u.message)!==null&&f!==void 0?f:"Internal error",...u.data!==void 0&&{data:u.data}}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),s=this._progressHandlers.get(i);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(i),o=this._timeoutInfo.get(i);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){a(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),NE(e))n(e);else{let i=Pa.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,n){let{relatedRequestId:i,resumptionToken:s,onresumptiontoken:a}=n??{};return new Promise((o,c)=>{var u,f,d,p,h,m;if(!this._transport){c(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(f=n?.signal)===null||f===void 0||f.throwIfAborted();let g=this._requestMessageId++,v={...e,jsonrpc:"2.0",id:g};n?.onprogress&&(this._progressHandlers.set(g,n.onprogress),v.params={...e.params,_meta:{...((d=e.params)===null||d===void 0?void 0:d._meta)||{},progressToken:g}});let y=E=>{var C;this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),(C=this._transport)===null||C===void 0||C.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(E)}},{relatedRequestId:i,resumptionToken:s,onresumptiontoken:a}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`))),c(E)};this._responseHandlers.set(g,E=>{var C;if(!(!((C=n?.signal)===null||C===void 0)&&C.aborted)){if(E instanceof Error)return c(E);try{let T=lg(r,E.result);T.success?o(T.data):c(T.error)}catch(T){c(T)}}}),(p=n?.signal)===null||p===void 0||p.addEventListener("abort",()=>{var E;y((E=n?.signal)===null||E===void 0?void 0:E.reason)});let b=(h=n?.timeout)!==null&&h!==void 0?h:Tsr,x=()=>y(Pa.fromError(na.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(g,b,n?.maxTotalTimeout,x,(m=n?.resetTimeoutOnProgress)!==null&&m!==void 0?m:!1),this._transport.send(v,{relatedRequestId:i,resumptionToken:s,onresumptiontoken:a}).catch(E=>{this._cleanupTimeout(g),c(E)})})}async notification(e,r){var n,i;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((i=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&i!==void 0?i:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var c;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let u={...e,jsonrpc:"2.0"};(c=this._transport)===null||c===void 0||c.send(u,r).catch(f=>this._onerror(f))});return}let o={...e,jsonrpc:"2.0"};await this._transport.send(o,r)}setRequestHandler(e,r){let n=ooe(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,s)=>{let a=coe(e,i);return Promise.resolve(r(a,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=ooe(e);this._notificationHandlers.set(n,i=>{let s=coe(e,i);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function LLe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function qLe(t,e){let r={...t};for(let n in e){let i=n,s=e[i];if(s===void 0)continue;let a=r[i];LLe(a)&&LLe(s)?r[i]={...a,...s}:r[i]=s}return r}var qze=Ur(Yce(),1),Bze=Ur(Lze(),1);function qfr(){let t=new qze.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Bze.default)(t),t}var lq=class{constructor(e){this._ajv=e??qfr()}getValidator(e){var r;let n="$id"in e&&typeof e.$id=="string"?(r=this._ajv.getSchema(e.$id))!==null&&r!==void 0?r:this._ajv.compile(e):this._ajv.compile(e);return i=>n(i)?{valid:!0,data:i,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};function fq(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let i of Object.keys(n)){let s=n[i];r[i]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[i]=s.default),r[i]!==void 0&&fq(s,r[i])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)fq(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)fq(r,e)}}function Bfr(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var dq=class extends kL{constructor(e,r){var n,i;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._jsonSchemaValidator=(i=r?.jsonSchemaValidator)!==null&&i!==void 0?i:new lq}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=qLe(this._capabilities,e)}setRequestHandler(e,r){var n,i,s;let a=gL(e),o=a?.method;if(!o)throw new Error("Schema is missing a method literal");let c;if(Ey(o)){let f=o,d=(n=f._zod)===null||n===void 0?void 0:n.def;c=(i=d?.value)!==null&&i!==void 0?i:f.value}else{let f=o,d=f._def;c=(s=d?.value)!==null&&s!==void 0?s:f.value}if(typeof c!="string")throw new Error("Schema method literal must be a string");if(c==="elicitation/create"){let f=async(d,p)=>{var h,m,g;let v=lg(ioe,d);if(!v.success){let A=v.error instanceof Error?v.error.message:String(v.error);throw new Pa(na.InvalidParams,`Invalid elicitation request: ${A}`)}let{params:y}=v.data,b=(h=y.mode)!==null&&h!==void 0?h:"form",{supportsFormMode:x,supportsUrlMode:E}=Bfr(this._capabilities.elicitation);if(b==="form"&&!x)throw new Pa(na.InvalidParams,"Client does not support form-mode elicitation requests");if(b==="url"&&!E)throw new Pa(na.InvalidParams,"Client does not support URL-mode elicitation requests");let C=await Promise.resolve(r(d,p)),T=lg(soe,C);if(!T.success){let A=T.error instanceof Error?T.error.message:String(T.error);throw new Pa(na.InvalidParams,`Invalid elicitation result: ${A}`)}let I=T.data,F=b==="form"?y.requestedSchema:void 0;if(b==="form"&&I.action==="accept"&&I.content&&F&&!((g=(m=this._capabilities.elicitation)===null||m===void 0?void 0:m.form)===null||g===void 0)&&g.applyDefaults)try{fq(F,I.content)}catch{}return I};return super.setRequestHandler(e,f)}return super.setRequestHandler(e,r)}assertCapability(e,r){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Cy,capabilities:this._capabilities,clientInfo:this._clientInfo}},Kae,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!yLe.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,n,i,s,a;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`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(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`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 Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},fg,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},aoe,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},fg,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},roe,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},eoe,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Zae,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Xae,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Qae,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},fg,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},fg,r)}async callTool(e,r=CL,n){let i=await this.request({method:"tools/call",params:e},r,n),s=this.getToolOutputValidator(e.name);if(s){if(!i.structuredContent&&!i.isError)throw new Pa(na.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{let a=s(i.structuredContent);if(!a.valid)throw new Pa(na.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof Pa?a:new Pa(na.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return i}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let r of e)if(r.outputSchema){let n=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,n)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},noe,r);return this.cacheToolOutputSchemas(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var RUe=Ur(PUe(),1);import gq from"node:process";import{PassThrough as mdr}from"node:stream";var hq=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
1428
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of t.seen.entries()){let o=a[1];if(e===a[0]){s(a);continue}if(t.external){let u=t.external.registry.get(a[0])?.id;if(e!==a[0]&&u){s(a);continue}}if(t.metadataRegistry.get(a[0])?.id){s(a);continue}if(o.cycle){s(a);continue}if(o.count>1&&t.reused==="ref"){s(a);continue}}}function Uae(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=o=>{let c=t.seen.get(o);if(c.ref===null)return;let u=c.def??c.schema,f={...u},d=c.ref;if(c.ref=null,d){n(d);let h=t.seen.get(d),m=h.schema;if(m.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Object.assign(u,m),Object.assign(u,f),o._zod.parent===d)for(let v in u)v==="$ref"||v==="allOf"||v in f||delete u[v];if(m.$ref&&h.def)for(let v in u)v==="$ref"||v==="allOf"||v in h.def&&JSON.stringify(u[v])===JSON.stringify(h.def[v])&&delete u[v]}let p=o._zod.parent;if(p&&p!==d){n(p);let h=t.seen.get(p);if(h?.schema.$ref&&(u.$ref=h.schema.$ref,h.def))for(let m in u)m==="$ref"||m==="allOf"||m in h.def&&JSON.stringify(u[m])===JSON.stringify(h.def[m])&&delete u[m]}t.override({zodSchema:o,jsonSchema:u,path:c.path??[]})};for(let o of[...t.seen.entries()].reverse())n(o[0]);let i={};if(t.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let o=t.external.registry.get(e)?.id;if(!o)throw new Error("Schema is missing an `id` property");i.$id=t.external.uri(o)}Object.assign(i,r.def??r.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&i.id===s&&delete i.id;let a=t.external?.defs??{};for(let o of t.seen.entries()){let c=o[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,a[c.defId]=c.def)}t.external||Object.keys(a).length>0&&(t.target==="draft-2020-12"?i.$defs=a:i.definitions=a);try{let o=JSON.parse(JSON.stringify(i));return Object.defineProperty(o,"~standard",{value:{...e["~standard"],jsonSchema:{input:RE(e,"input",t.processors),output:RE(e,"output",t.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function Do(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Do(n.element,r);if(n.type==="set")return Do(n.valueType,r);if(n.type==="lazy")return Do(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Do(n.innerType,r);if(n.type==="intersection")return Do(n.left,r)||Do(n.right,r);if(n.type==="record"||n.type==="map")return Do(n.keyType,r)||Do(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Do(n.in,r)||Do(n.out,r);if(n.type==="object"){for(let i in n.shape)if(Do(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(Do(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(Do(i,r))return!0;return!!(n.rest&&Do(n.rest,r))}return!1}var iMe=(t,e={})=>r=>{let n=Bae({...r,processors:e});return ss(t,n),zae(n,t),Uae(n,t)},RE=(t,e,r={})=>n=>{let{libraryOptions:i,target:s}=n??{},a=Bae({...i??{},target:s,io:e,processors:r});return ss(t,a),zae(a,t),Uae(a,t)};var Vrr={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},sMe=(t,e,r,n)=>{let i=r;i.type="string";let{minimum:s,maximum:a,format:o,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(i.minLength=s),typeof a=="number"&&(i.maxLength=a),o&&(i.format=Vrr[o]??o,i.format===""&&delete i.format,o==="time"&&delete i.format),u&&(i.contentEncoding=u),c&&c.size>0){let f=[...c];f.length===1?i.pattern=f[0].source:f.length>1&&(i.allOf=[...f.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},aMe=(t,e,r,n)=>{let i=r,{minimum:s,maximum:a,format:o,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:f}=t._zod.bag;typeof o=="string"&&o.includes("int")?i.type="integer":i.type="number";let d=typeof f=="number"&&f>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),h=e.target==="draft-04"||e.target==="openapi-3.0";d?h?(i.minimum=f,i.exclusiveMinimum=!0):i.exclusiveMinimum=f:typeof s=="number"&&(i.minimum=s),p?h?(i.maximum=u,i.exclusiveMaximum=!0):i.exclusiveMaximum=u:typeof a=="number"&&(i.maximum=a),typeof c=="number"&&(i.multipleOf=c)},oMe=(t,e,r,n)=>{r.type="boolean"};var cMe=(t,e,r,n)=>{r.not={}},uMe=(t,e,r,n)=>{},lMe=(t,e,r,n)=>{};var fMe=(t,e,r,n)=>{let i=t._zod.def,s=xE(i.entries);s.every(a=>typeof a=="number")&&(r.type="number"),s.every(a=>typeof a=="string")&&(r.type="string"),r.enum=s},dMe=(t,e,r,n)=>{let i=t._zod.def,s=[];for(let a of i.values)if(a===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(a))}else s.push(a);if(s.length!==0)if(s.length===1){let a=s[0];r.type=a===null?"null":typeof a,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[a]:r.const=a}else s.every(a=>typeof a=="number")&&(r.type="number"),s.every(a=>typeof a=="string")&&(r.type="string"),s.every(a=>typeof a=="boolean")&&(r.type="boolean"),s.every(a=>a===null)&&(r.type="null"),r.enum=s};var pMe=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var hMe=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var mMe=(t,e,r,n)=>{let i=r,s=t._zod.def,{minimum:a,maximum:o}=t._zod.bag;typeof a=="number"&&(i.minItems=a),typeof o=="number"&&(i.maxItems=o),i.type="array",i.items=ss(s.element,e,{...n,path:[...n.path,"items"]})},gMe=(t,e,r,n)=>{let i=r,s=t._zod.def;i.type="object",i.properties={};let a=s.shape;for(let u in a)i.properties[u]=ss(a[u],e,{...n,path:[...n.path,"properties",u]});let o=new Set(Object.keys(a)),c=new Set([...o].filter(u=>{let f=s.shape[u]._zod;return e.io==="input"?f.optin===void 0:f.optout===void 0}));c.size>0&&(i.required=Array.from(c)),s.catchall?._zod.def.type==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=ss(s.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},vMe=(t,e,r,n)=>{let i=t._zod.def,s=i.inclusive===!1,a=i.options.map((o,c)=>ss(o,e,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=a:r.anyOf=a},yMe=(t,e,r,n)=>{let i=t._zod.def,s=ss(i.left,e,{...n,path:[...n.path,"allOf",0]}),a=ss(i.right,e,{...n,path:[...n.path,"allOf",1]}),o=u=>"allOf"in u&&Object.keys(u).length===1,c=[...o(s)?s.allOf:[s],...o(a)?a.allOf:[a]];r.allOf=c};var bMe=(t,e,r,n)=>{let i=r,s=t._zod.def;i.type="object";let a=s.keyType,c=a._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let f=ss(s.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(let d of c)i.patternProperties[d.source]=f}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=ss(s.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=ss(s.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=a._zod.values;if(u){let f=[...u].filter(d=>typeof d=="string"||typeof d=="number");f.length>0&&(i.required=f)}},xMe=(t,e,r,n)=>{let i=t._zod.def,s=ss(i.innerType,e,n),a=e.seen.get(t);e.target==="openapi-3.0"?(a.ref=i.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},wMe=(t,e,r,n)=>{let i=t._zod.def;ss(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType},_Me=(t,e,r,n)=>{let i=t._zod.def;ss(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},SMe=(t,e,r,n)=>{let i=t._zod.def;ss(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},EMe=(t,e,r,n)=>{let i=t._zod.def;ss(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType;let a;try{a=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=a},AMe=(t,e,r,n)=>{let i=t._zod.def,s=i.in._zod.traits.has("$ZodTransform"),a=e.io==="input"?s?i.out:i.in:i.out;ss(a,e,n);let o=e.seen.get(t);o.ref=a},CMe=(t,e,r,n)=>{let i=t._zod.def;ss(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType,r.readOnly=!0};var Hae=(t,e,r,n)=>{let i=t._zod.def;ss(i.innerType,e,n);let s=e.seen.get(t);s.ref=i.innerType};var enr=He("ZodISODateTime",(t,e)=>{$je.init(t,e),mi.init(t,e)});function kMe(t){return H$e(enr,t)}var tnr=He("ZodISODate",(t,e)=>{Mje.init(t,e),mi.init(t,e)});function TMe(t){return W$e(tnr,t)}var rnr=He("ZodISOTime",(t,e)=>{Lje.init(t,e),mi.init(t,e)});function PMe(t){return V$e(rnr,t)}var nnr=He("ZodISODuration",(t,e)=>{qje.init(t,e),mi.init(t,e)});function OMe(t){return G$e(nnr,t)}var snr=(t,e)=>{QM.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>gae(t,r)},flatten:{value:r=>mae(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,xy,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,xy,2)}},isEmpty:{get(){return t.issues.length===0}}})};var lu=He("ZodError",snr,{Parent:Error});var IMe=eL(lu),DMe=tL(lu),FMe=EE(lu),NMe=CE(lu),jMe=_Ne(lu),$Me=SNe(lu),MMe=ENe(lu),LMe=ANe(lu),qMe=CNe(lu),BMe=kNe(lu),zMe=TNe(lu),UMe=PNe(lu);var HMe=new WeakMap;function DE(t,e,r){let n=Object.getPrototypeOf(t),i=HMe.get(n);if(i||(i=new Set,HMe.set(n,i)),!i.has(e)){i.add(e);for(let s in r){let a=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let o=a.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:o}),o},set(o){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:o})}})}}}var gi=He("ZodType",(t,e)=>(ni.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:RE(t,"input"),output:RE(t,"output")}}),t.toJSONSchema=iMe(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>IMe(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>FMe(t,r,n),t.parseAsync=async(r,n)=>DMe(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>NMe(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>jMe(t,r,n),t.decode=(r,n)=>$Me(t,r,n),t.encodeAsync=async(r,n)=>MMe(t,r,n),t.decodeAsync=async(r,n)=>LMe(t,r,n),t.safeEncode=(r,n)=>qMe(t,r,n),t.safeDecode=(r,n)=>BMe(t,r,n),t.safeEncodeAsync=async(r,n)=>zMe(t,r,n),t.safeDecodeAsync=async(r,n)=>UMe(t,r,n),DE(t,"ZodType",{check(...r){let n=this.def;return this.clone(Vr.mergeDefs(n,{checks:[...n.checks??[],...r.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return Yu(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(Knr(r,n))},superRefine(r,n){return this.check(Jnr(r,n))},overwrite(r){return this.check(I0(r))},optional(){return Ar(this)},exactOptional(){return jnr(this)},nullable(){return KMe(this)},nullish(){return Ar(KMe(this))},nonoptional(r){return znr(this,r)},array(){return pt(this)},or(r){return Ti([this,r])},and(r){return pL(this,r)},transform(r){return JMe(this,iLe(r))},default(r){return Lnr(this,r)},prefault(r){return Bnr(this,r)},catch(r){return Hnr(this,r)},pipe(r){return JMe(this,r)},readonly(){return Gnr(this)},describe(r){let n=this.clone();return R0.add(n,{description:r}),n},meta(...r){if(r.length===0)return R0.get(this);let n=this.clone();return R0.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return R0.get(t)?.description},configurable:!0}),t)),ZMe=He("_ZodString",(t,e)=>{aL.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(n,i,s)=>sMe(t,n,i,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,DE(t,"_ZodString",{regex(...n){return this.check(Oae(...n))},includes(...n){return this.check(Dae(...n))},startsWith(...n){return this.check(Fae(...n))},endsWith(...n){return this.check(Nae(...n))},min(...n){return this.check(Sy(...n))},max(...n){return this.check(lL(...n))},length(...n){return this.check(fL(...n))},nonempty(...n){return this.check(Sy(1,...n))},lowercase(n){return this.check(Rae(n))},uppercase(n){return this.check(Iae(n))},trim(){return this.check($ae())},normalize(...n){return this.check(jae(...n))},toLowerCase(){return this.check(Mae())},toUpperCase(){return this.check(Lae())},slugify(){return this.check(qae())}})}),onr=He("ZodString",(t,e)=>{aL.init(t,e),ZMe.init(t,e),t.email=r=>t.check(E$e(cnr,r)),t.url=r=>t.check(Pae(XMe,r)),t.jwt=r=>t.check(U$e(Snr,r)),t.emoji=r=>t.check(P$e(unr,r)),t.guid=r=>t.check(Tae(WMe,r)),t.uuid=r=>t.check(A$e(dL,r)),t.uuidv4=r=>t.check(C$e(dL,r)),t.uuidv6=r=>t.check(k$e(dL,r)),t.uuidv7=r=>t.check(T$e(dL,r)),t.nanoid=r=>t.check(O$e(lnr,r)),t.guid=r=>t.check(Tae(WMe,r)),t.cuid=r=>t.check(R$e(fnr,r)),t.cuid2=r=>t.check(I$e(dnr,r)),t.ulid=r=>t.check(D$e(pnr,r)),t.base64=r=>t.check(q$e(xnr,r)),t.base64url=r=>t.check(B$e(wnr,r)),t.xid=r=>t.check(F$e(hnr,r)),t.ksuid=r=>t.check(N$e(mnr,r)),t.ipv4=r=>t.check(j$e(gnr,r)),t.ipv6=r=>t.check($$e(vnr,r)),t.cidrv4=r=>t.check(M$e(ynr,r)),t.cidrv6=r=>t.check(L$e(bnr,r)),t.e164=r=>t.check(z$e(_nr,r)),t.datetime=r=>t.check(kMe(r)),t.date=r=>t.check(TMe(r)),t.time=r=>t.check(PMe(r)),t.duration=r=>t.check(OMe(r))});function _e(t){return S$e(onr,t)}var mi=He("ZodStringFormat",(t,e)=>{ii.init(t,e),ZMe.init(t,e)}),cnr=He("ZodEmail",(t,e)=>{Tje.init(t,e),mi.init(t,e)});var WMe=He("ZodGUID",(t,e)=>{Cje.init(t,e),mi.init(t,e)});var dL=He("ZodUUID",(t,e)=>{kje.init(t,e),mi.init(t,e)});var XMe=He("ZodURL",(t,e)=>{Pje.init(t,e),mi.init(t,e)});function YMe(t){return Pae(XMe,t)}var unr=He("ZodEmoji",(t,e)=>{Oje.init(t,e),mi.init(t,e)});var lnr=He("ZodNanoID",(t,e)=>{Rje.init(t,e),mi.init(t,e)});var fnr=He("ZodCUID",(t,e)=>{Ije.init(t,e),mi.init(t,e)});var dnr=He("ZodCUID2",(t,e)=>{Dje.init(t,e),mi.init(t,e)});var pnr=He("ZodULID",(t,e)=>{Fje.init(t,e),mi.init(t,e)});var hnr=He("ZodXID",(t,e)=>{Nje.init(t,e),mi.init(t,e)});var mnr=He("ZodKSUID",(t,e)=>{jje.init(t,e),mi.init(t,e)});var gnr=He("ZodIPv4",(t,e)=>{Bje.init(t,e),mi.init(t,e)});var vnr=He("ZodIPv6",(t,e)=>{zje.init(t,e),mi.init(t,e)});var ynr=He("ZodCIDRv4",(t,e)=>{Uje.init(t,e),mi.init(t,e)});var bnr=He("ZodCIDRv6",(t,e)=>{Hje.init(t,e),mi.init(t,e)});var xnr=He("ZodBase64",(t,e)=>{Vje.init(t,e),mi.init(t,e)});var wnr=He("ZodBase64URL",(t,e)=>{Gje.init(t,e),mi.init(t,e)});var _nr=He("ZodE164",(t,e)=>{Kje.init(t,e),mi.init(t,e)});var Snr=He("ZodJWT",(t,e)=>{Jje.init(t,e),mi.init(t,e)});var QMe=He("ZodNumber",(t,e)=>{Sae.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(n,i,s)=>aMe(t,n,i,s),DE(t,"ZodNumber",{gt(n,i){return this.check(cL(n,i))},gte(n,i){return this.check(OE(n,i))},min(n,i){return this.check(OE(n,i))},lt(n,i){return this.check(oL(n,i))},lte(n,i){return this.check(PE(n,i))},max(n,i){return this.check(PE(n,i))},int(n){return this.check(VMe(n))},safe(n){return this.check(VMe(n))},positive(n){return this.check(cL(0,n))},nonnegative(n){return this.check(OE(0,n))},negative(n){return this.check(oL(0,n))},nonpositive(n){return this.check(PE(0,n))},multipleOf(n,i){return this.check(uL(n,i))},step(n,i){return this.check(uL(n,i))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function Yn(t){return K$e(QMe,t)}var Enr=He("ZodNumberFormat",(t,e)=>{Zje.init(t,e),QMe.init(t,e)});function VMe(t){return J$e(Enr,t)}var Anr=He("ZodBoolean",(t,e)=>{Xje.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>oMe(t,r,n,i)});function Qn(t){return Z$e(Anr,t)}var Cnr=He("ZodAny",(t,e)=>{Yje.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>uMe(t,r,n,i)});function eLe(){return X$e(Cnr)}var knr=He("ZodUnknown",(t,e)=>{Qje.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lMe(t,r,n,i)});function zi(){return Y$e(knr)}var Tnr=He("ZodNever",(t,e)=>{e$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>cMe(t,r,n,i)});function Pnr(t){return Q$e(Tnr,t)}var Onr=He("ZodArray",(t,e)=>{t$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>mMe(t,r,n,i),t.element=e.element,DE(t,"ZodArray",{min(r,n){return this.check(Sy(r,n))},nonempty(r){return this.check(Sy(1,r))},max(r,n){return this.check(lL(r,n))},length(r,n){return this.check(fL(r,n))},unwrap(){return this.element}})});function pt(t,e){return eMe(Onr,t,e)}var tLe=He("ZodObject",(t,e)=>{i$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>gMe(t,r,n,i),Vr.defineLazy(t,"shape",()=>e.shape),DE(t,"ZodObject",{keyof(){return el(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:zi()})},loose(){return this.clone({...this._zod.def,catchall:zi()})},strict(){return this.clone({...this._zod.def,catchall:Pnr()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return Vr.extend(this,r)},safeExtend(r){return Vr.safeExtend(this,r)},merge(r){return Vr.merge(this,r)},pick(r){return Vr.pick(this,r)},omit(r){return Vr.omit(this,r)},partial(...r){return Vr.partial(sLe,this,r[0])},required(...r){return Vr.required(aLe,this,r[0])}})});function vt(t,e){let r={type:"object",shape:t??{},...Vr.normalizeParams(e)};return new tLe(r)}function fu(t,e){return new tLe({type:"object",shape:t,catchall:zi(),...Vr.normalizeParams(e)})}var rLe=He("ZodUnion",(t,e)=>{Eae.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>vMe(t,r,n,i),t.options=e.options});function Ti(t,e){return new rLe({type:"union",options:t,...Vr.normalizeParams(e)})}var Rnr=He("ZodDiscriminatedUnion",(t,e)=>{rLe.init(t,e),s$e.init(t,e)});function nLe(t,e,r){return new Rnr({type:"union",options:e,discriminator:t,...Vr.normalizeParams(r)})}var Inr=He("ZodIntersection",(t,e)=>{a$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>yMe(t,r,n,i)});function pL(t,e){return new Inr({type:"intersection",left:t,right:e})}var GMe=He("ZodRecord",(t,e)=>{o$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>bMe(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function Ui(t,e,r){return!e||!e._zod?new GMe({type:"record",keyType:_e(),valueType:t,...Vr.normalizeParams(e)}):new GMe({type:"record",keyType:t,valueType:e,...Vr.normalizeParams(r)})}var Wae=He("ZodEnum",(t,e)=>{c$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(n,i,s)=>fMe(t,n,i,s),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let s={};for(let a of n)if(r.has(a))s[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Wae({...e,checks:[],...Vr.normalizeParams(i),entries:s})},t.exclude=(n,i)=>{let s={...e.entries};for(let a of n)if(r.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new Wae({...e,checks:[],...Vr.normalizeParams(i),entries:s})}});function el(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Wae({type:"enum",entries:r,...Vr.normalizeParams(e)})}var Dnr=He("ZodLiteral",(t,e)=>{u$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>dMe(t,r,n,i),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function Mt(t,e){return new Dnr({type:"literal",values:Array.isArray(t)?t:[t],...Vr.normalizeParams(e)})}var Fnr=He("ZodTransform",(t,e)=>{l$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>hMe(t,r,n,i),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new yy(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(Vr.issue(s,r.value,e));else{let a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),r.issues.push(Vr.issue(a))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=i,r.fallback=!0,r)}});function iLe(t){return new Fnr({type:"transform",transform:t})}var sLe=He("ZodOptional",(t,e)=>{Aae.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Hae(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Ar(t){return new sLe({type:"optional",innerType:t})}var Nnr=He("ZodExactOptional",(t,e)=>{f$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Hae(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function jnr(t){return new Nnr({type:"optional",innerType:t})}var $nr=He("ZodNullable",(t,e)=>{d$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>xMe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function KMe(t){return new $nr({type:"nullable",innerType:t})}var Mnr=He("ZodDefault",(t,e)=>{p$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>_Me(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Lnr(t,e){return new Mnr({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Vr.shallowClone(e)}})}var qnr=He("ZodPrefault",(t,e)=>{h$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>SMe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Bnr(t,e){return new qnr({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Vr.shallowClone(e)}})}var aLe=He("ZodNonOptional",(t,e)=>{m$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>wMe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function znr(t,e){return new aLe({type:"nonoptional",innerType:t,...Vr.normalizeParams(e)})}var Unr=He("ZodCatch",(t,e)=>{g$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>EMe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Hnr(t,e){return new Unr({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var oLe=He("ZodPipe",(t,e)=>{Cae.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>AMe(t,r,n,i),t.in=e.in,t.out=e.out});function JMe(t,e){return new oLe({type:"pipe",in:t,out:e})}var Wnr=He("ZodPreprocess",(t,e)=>{oLe.init(t,e),v$e.init(t,e)}),Vnr=He("ZodReadonly",(t,e)=>{y$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>CMe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Gnr(t){return new Vnr({type:"readonly",innerType:t})}var cLe=He("ZodCustom",(t,e)=>{b$e.init(t,e),gi.init(t,e),t._zod.processJSONSchema=(r,n,i)=>pMe(t,r,n,i)});function uLe(t,e){return tMe(cLe,t??(()=>!0),e)}function Knr(t,e={}){return rMe(cLe,t,e)}function Jnr(t,e){return nMe(t,e)}function lLe(t,e){return new Wnr({type:"pipe",in:iLe(t),out:e})}var dLe={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 fLe;fLe||(fLe={});hc(x$e());var Ta=YMe().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:dLe.custom,message:"URL must be parseable",fatal:!0}),nae}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),hLe=fu({resource:_e().url(),authorization_servers:pt(Ta).optional(),jwks_uri:_e().url().optional(),scopes_supported:pt(_e()).optional(),bearer_methods_supported:pt(_e()).optional(),resource_signing_alg_values_supported:pt(_e()).optional(),resource_name:_e().optional(),resource_documentation:_e().optional(),resource_policy_uri:_e().url().optional(),resource_tos_uri:_e().url().optional(),tls_client_certificate_bound_access_tokens:Qn().optional(),authorization_details_types_supported:pt(_e()).optional(),dpop_signing_alg_values_supported:pt(_e()).optional(),dpop_bound_access_tokens_required:Qn().optional()}),Vae=fu({issuer:_e(),authorization_endpoint:Ta,token_endpoint:Ta,registration_endpoint:Ta.optional(),scopes_supported:pt(_e()).optional(),response_types_supported:pt(_e()),response_modes_supported:pt(_e()).optional(),grant_types_supported:pt(_e()).optional(),token_endpoint_auth_methods_supported:pt(_e()).optional(),token_endpoint_auth_signing_alg_values_supported:pt(_e()).optional(),service_documentation:Ta.optional(),revocation_endpoint:Ta.optional(),revocation_endpoint_auth_methods_supported:pt(_e()).optional(),revocation_endpoint_auth_signing_alg_values_supported:pt(_e()).optional(),introspection_endpoint:_e().optional(),introspection_endpoint_auth_methods_supported:pt(_e()).optional(),introspection_endpoint_auth_signing_alg_values_supported:pt(_e()).optional(),code_challenge_methods_supported:pt(_e()).optional(),client_id_metadata_document_supported:Qn().optional()}),Xnr=fu({issuer:_e(),authorization_endpoint:Ta,token_endpoint:Ta,userinfo_endpoint:Ta.optional(),jwks_uri:Ta,registration_endpoint:Ta.optional(),scopes_supported:pt(_e()).optional(),response_types_supported:pt(_e()),response_modes_supported:pt(_e()).optional(),grant_types_supported:pt(_e()).optional(),acr_values_supported:pt(_e()).optional(),subject_types_supported:pt(_e()),id_token_signing_alg_values_supported:pt(_e()),id_token_encryption_alg_values_supported:pt(_e()).optional(),id_token_encryption_enc_values_supported:pt(_e()).optional(),userinfo_signing_alg_values_supported:pt(_e()).optional(),userinfo_encryption_alg_values_supported:pt(_e()).optional(),userinfo_encryption_enc_values_supported:pt(_e()).optional(),request_object_signing_alg_values_supported:pt(_e()).optional(),request_object_encryption_alg_values_supported:pt(_e()).optional(),request_object_encryption_enc_values_supported:pt(_e()).optional(),token_endpoint_auth_methods_supported:pt(_e()).optional(),token_endpoint_auth_signing_alg_values_supported:pt(_e()).optional(),display_values_supported:pt(_e()).optional(),claim_types_supported:pt(_e()).optional(),claims_supported:pt(_e()).optional(),service_documentation:_e().optional(),claims_locales_supported:pt(_e()).optional(),ui_locales_supported:pt(_e()).optional(),claims_parameter_supported:Qn().optional(),request_parameter_supported:Qn().optional(),request_uri_parameter_supported:Qn().optional(),require_request_uri_registration:Qn().optional(),op_policy_uri:Ta.optional(),op_tos_uri:Ta.optional(),client_id_metadata_document_supported:Qn().optional()}),mLe=vt({...Xnr.shape,...Vae.pick({code_challenge_methods_supported:!0}).shape}),FE=vt({access_token:_e(),id_token:_e().optional(),token_type:_e(),expires_in:Yn().optional(),scope:_e().optional(),refresh_token:_e().optional()}).strip(),gLe=vt({error:_e(),error_description:_e().optional(),error_uri:_e().optional()}),pLe=Ta.optional().or(Mt("").transform(()=>{})),Ynr=vt({redirect_uris:pt(Ta),token_endpoint_auth_method:_e().optional(),grant_types:pt(_e()).optional(),response_types:pt(_e()).optional(),client_name:_e().optional(),client_uri:Ta.optional(),logo_uri:pLe,scope:_e().optional(),contacts:pt(_e()).optional(),tos_uri:pLe,policy_uri:_e().optional(),jwks_uri:Ta.optional(),jwks:eLe().optional(),software_id:_e().optional(),software_version:_e().optional(),software_statement:_e().optional()}).strip(),Qnr=vt({client_id:_e(),client_secret:_e().optional(),client_id_issued_at:Yn().optional(),client_secret_expires_at:Yn().optional()}).strip(),hL=Ynr.merge(Qnr),j_n=vt({error:_e(),error_description:_e().optional()}).strip(),$_n=vt({token:_e(),token_type_hint:_e().optional()}).strip();var mL=class{constructor(e,r,n,i,s,a,o,c){this.interactor=e;this.userService=r;this.projectName=n;this.mcpId=i;this.redirectUri=s;this.staticClientId=a;this.staticClientSecret=o;this.staticScope=c}_codeVerifier;_discoveryState;finishAuth=null;_pendingAuthPromise;_pendingAuthResolve;_pendingAuthReject;get redirectUrl(){return this.redirectUri}get clientMetadata(){return{redirect_uris:[this.redirectUri],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:`Coday MCP Client (${this.mcpId})`,...this.staticScope!==void 0?{scope:this.staticScope}:{}}}async validateResourceURL(e,r){if(this.staticScope!==void 0){this.interactor.debug(`[MCP OAuth:${this.mcpId}] validateResourceURL: suppressing resource scopes (staticScope='${this.staticScope}')`);return}}async saveDiscoveryState(e){if(this.staticScope!==void 0&&e.resourceMetadata){let n={...e.resourceMetadata,scopes_supported:void 0};this.interactor.debug(`[MCP OAuth:${this.mcpId}] saveDiscoveryState: stripping scopes_supported from resourceMetadata`),this._discoveryState={...e,resourceMetadata:n}}else this._discoveryState=e}async discoveryState(){return this._discoveryState}tokens(){let e=this.loadRaw()?.tokens;if(!e){this.interactor.debug(`[MCP OAuth:${this.mcpId}] no stored tokens found`);return}let r=FE.safeParse(e);if(!r.success){this.interactor.warn(`[MCP OAuth:${this.mcpId}] stored tokens are invalid: ${JSON.stringify(r.error.issues)}`);return}return this.interactor.debug(`[MCP OAuth:${this.mcpId}] tokens loaded (expires_in=${r.data.expires_in})`),r.data}async saveTokens(e){this.ensureStoragePath().tokens=e,this.userService.save(),this.interactor.debug(`[MCP OAuth:${this.mcpId}] tokens saved`)}clientInformation(){if(this.staticClientId)return this.interactor.debug(`[MCP OAuth:${this.mcpId}] using static client credentials (client_id=${this.staticClientId})`),{client_id:this.staticClientId,...this.staticClientSecret?{client_secret:this.staticClientSecret}:{},redirect_uris:[this.redirectUri],token_endpoint_auth_method:this.staticClientSecret?"client_secret_post":"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:`Coday MCP Client (${this.mcpId})`};let e=this.loadRaw(),r=e?.clientInfo;if(!r){this.interactor.debug(`[MCP OAuth:${this.mcpId}] no stored client info found`);return}if(!e?.tokens){if(!(!!this._codeVerifier||!!this._pendingAuthPromise)){this.interactor.debug(`[MCP OAuth:${this.mcpId}] client info found without tokens and no flow in progress \u2014 clearing stale registration`),this.clearStorage();return}this.interactor.debug(`[MCP OAuth:${this.mcpId}] client info found without tokens but OAuth flow in progress \u2014 keeping registration`)}let n=hL.safeParse(r);if(!n.success){this.interactor.warn(`[MCP OAuth:${this.mcpId}] stored client info is invalid: ${JSON.stringify(n.error.issues)}`);return}return this.interactor.debug(`[MCP OAuth:${this.mcpId}] client info loaded (client_id=${n.data.client_id})`),n.data}async saveClientInformation(e){if(this.staticClientId){this.interactor.debug(`[MCP OAuth:${this.mcpId}] skipping saveClientInformation (static credentials in use)`);return}this.ensureStoragePath().clientInfo=e,this.userService.save(),this.interactor.debug(`[MCP OAuth:${this.mcpId}] client info saved (id=${e.client_id})`)}saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this._codeVerifier)throw new Error(`[MCP OAuth:${this.mcpId}] no code verifier available`);return this._codeVerifier}setFinishAuth(e){this.interactor.debug(`[MCP OAuth:${this.mcpId}] finishAuth callback registered`),this.finishAuth=e}waitForAuth(){return this._pendingAuthPromise}redirectToAuthorization(e){if(this.interactor.warn(`[MCP OAuth:${this.mcpId}] OAuth authorization required \u2014 opening auth URL`),this.staticScope!==void 0){let r=new URL(e.toString());this.staticScope===""?(r.searchParams.delete("scope"),this.interactor.debug(`[MCP OAuth:${this.mcpId}] stripped scope from authorization URL`)):(r.searchParams.set("scope",this.staticScope),this.interactor.debug(`[MCP OAuth:${this.mcpId}] overrode scope to '${this.staticScope}' in authorization URL`)),e=r}this.interactor.debug(`[MCP OAuth:${this.mcpId}] redirecting to authorization: ${e}`),this._pendingAuthPromise||(this._pendingAuthPromise=new Promise((r,n)=>{this._pendingAuthResolve=r,this._pendingAuthReject=n}),this._pendingAuthPromise.then(()=>{this._pendingAuthPromise=void 0},()=>{this._pendingAuthPromise=void 0})),this.interactor.sendEvent(new Jf({authUrl:e.toString(),state:e.searchParams.get("state")??"",integrationName:this.mcpId}))}async invalidateCredentials(e){this.interactor.warn(`[MCP OAuth:${this.mcpId}] invalidating credentials: ${e}`);let r=this.loadRaw();if(this._pendingAuthReject&&(this._pendingAuthReject(new Error(`[MCP OAuth:${this.mcpId}] credentials invalidated during pending auth flow`)),this._pendingAuthResolve=void 0,this._pendingAuthReject=void 0),!!r)switch(e){case"all":this.clearStorage();break;case"client":delete r.clientInfo,this.userService.save();break;case"tokens":delete r.tokens,this.userService.save();break;case"verifier":this._codeVerifier=void 0;break}}async handleCallback(e){if(e.integrationName!==this.mcpId){this.interactor.debug(`[MCP OAuth:${this.mcpId}] ignoring callback for integration '${e.integrationName}'`);return}if(this.interactor.debug(`[MCP OAuth:${this.mcpId}] handling OAuth callback`),e.error){let r=e.error==="access_denied"?"OAuth authentication denied by user":`OAuth error: ${e.error}${e.errorDescription?" - "+e.errorDescription:""}`;this.interactor.warn(r),this._pendingAuthReject&&(this._pendingAuthReject(new Error(r)),this._pendingAuthResolve=void 0,this._pendingAuthReject=void 0);return}if(!e.code){let r=`[MCP OAuth:${this.mcpId}] callback missing authorization code`;this.interactor.error(r),this._pendingAuthReject&&(this._pendingAuthReject(new Error(r)),this._pendingAuthResolve=void 0,this._pendingAuthReject=void 0);return}if(!this.finishAuth){let r=`[MCP OAuth:${this.mcpId}] no transport registered to receive auth code`;this.interactor.error(r),this._pendingAuthReject&&(this._pendingAuthReject(new Error(r)),this._pendingAuthResolve=void 0,this._pendingAuthReject=void 0);return}this.interactor.debug(`[MCP OAuth:${this.mcpId}] received authorization code, completing auth flow`);try{await this.finishAuth(e.code),this._pendingAuthResolve&&(this._pendingAuthResolve(),this._pendingAuthResolve=void 0,this._pendingAuthReject=void 0)}catch(r){this.interactor.error(`[MCP OAuth:${this.mcpId}] finishAuth failed: ${r.message}`),this._pendingAuthReject&&(this._pendingAuthReject(r),this._pendingAuthResolve=void 0,this._pendingAuthReject=void 0)}}loadRaw(){return this.userService.config.projects?.[this.projectName]?.integration?.[this.mcpId]?.mcpOAuth}ensureStoragePath(){let e=this.userService.config;e.projects||(e.projects={}),e.projects[this.projectName]||(e.projects[this.projectName]={integration:{}});let r=e.projects[this.projectName];r.integration||(r.integration={}),r.integration[this.mcpId]||(r.integration[this.mcpId]={});let n=r.integration[this.mcpId];return n.mcpOAuth||(n.mcpOAuth={}),n.mcpOAuth}clearStorage(){let e=this.userService.config.projects?.[this.projectName];e?.integration?.[this.mcpId]&&(delete e.integration[this.mcpId].mcpOAuth,this.userService.save())}};function Ey(t){return!!t._zod}function lg(t,e){return Ey(t)?AE(t,e):t.safeParse(e)}function gL(t){var e,r;if(!t)return;let n;if(Ey(t)?n=(r=(e=t._zod)===null||e===void 0?void 0:e.def)===null||r===void 0?void 0:r.shape:n=t.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function vLe(t){var e;if(Ey(t)){let a=(e=t._zod)===null||e===void 0?void 0:e.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let i=t.value;if(i!==void 0)return i}var Cy="2025-06-18";var yLe=[Cy,"2025-03-26","2024-11-05","2024-10-07"],yL="2.0",xd=uLe(t=>t!==null&&(typeof t=="object"||typeof t=="function")),bLe=Ti([_e(),Yn().int()]),xLe=_e(),eir=fu({progressToken:bLe.optional()}),tf=fu({_meta:eir.optional()}),mc=vt({method:_e(),params:tf.optional()}),ky=fu({_meta:Ui(_e(),zi()).optional()}),rf=vt({method:_e(),params:ky.optional()}),tl=fu({_meta:Ui(_e(),zi()).optional()}),bL=Ti([_e(),Yn().int()]),wLe=vt({jsonrpc:Mt(yL),id:bL,...mc.shape}).strict(),xL=t=>wLe.safeParse(t).success,_Le=vt({jsonrpc:Mt(yL),...rf.shape}).strict(),SLe=t=>_Le.safeParse(t).success,ELe=vt({jsonrpc:Mt(yL),id:bL,result:tl}).strict(),NE=t=>ELe.safeParse(t).success,na;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(na||(na={}));var ALe=vt({jsonrpc:Mt(yL),id:bL,error:vt({code:Yn().int(),message:_e(),data:Ar(zi())})}).strict(),CLe=t=>ALe.safeParse(t).success,D0=Ti([wLe,_Le,ELe,ALe]),fg=tl.strict(),tir=ky.extend({requestId:bL,reason:_e().optional()}),wL=rf.extend({method:Mt("notifications/cancelled"),params:tir}),rir=vt({src:_e(),mimeType:_e().optional(),sizes:pt(_e()).optional()}),jE=vt({icons:pt(rir).optional()}),Ay=vt({name:_e(),title:_e().optional()}),kLe=Ay.extend({...Ay.shape,...jE.shape,version:_e(),websiteUrl:_e().optional()}),nir=pL(vt({applyDefaults:Qn().optional()}),Ui(_e(),zi())),iir=lLe(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,pL(vt({form:nir.optional(),url:xd.optional()}),Ui(_e(),zi()).optional())),sir=vt({experimental:Ui(_e(),xd).optional(),sampling:vt({context:xd.optional(),tools:xd.optional()}).optional(),elicitation:iir.optional(),roots:vt({listChanged:Qn().optional()}).optional()}),air=tf.extend({protocolVersion:_e(),capabilities:sir,clientInfo:kLe}),oir=mc.extend({method:Mt("initialize"),params:air});var cir=vt({experimental:Ui(_e(),xd).optional(),logging:xd.optional(),completions:xd.optional(),prompts:Ar(vt({listChanged:Ar(Qn())})),resources:vt({subscribe:Qn().optional(),listChanged:Qn().optional()}).optional(),tools:vt({listChanged:Qn().optional()}).optional()}),Kae=tl.extend({protocolVersion:_e(),capabilities:cir,serverInfo:kLe,instructions:_e().optional()}),TLe=rf.extend({method:Mt("notifications/initialized")}),PLe=t=>TLe.safeParse(t).success,_L=mc.extend({method:Mt("ping")}),uir=vt({progress:Yn(),total:Ar(Yn()),message:Ar(_e())}),lir=vt({...ky.shape,...uir.shape,progressToken:bLe}),SL=rf.extend({method:Mt("notifications/progress"),params:lir}),fir=tf.extend({cursor:xLe.optional()}),EL=mc.extend({params:fir.optional()}),AL=tl.extend({nextCursor:Ar(xLe)}),OLe=vt({uri:_e(),mimeType:Ar(_e()),_meta:Ui(_e(),zi()).optional()}),RLe=OLe.extend({text:_e()}),Jae=_e().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),ILe=OLe.extend({blob:Jae}),DLe=vt({...Ay.shape,...jE.shape,uri:_e(),description:Ar(_e()),mimeType:Ar(_e()),_meta:Ar(fu({}))}),dir=vt({...Ay.shape,...jE.shape,uriTemplate:_e(),description:Ar(_e()),mimeType:Ar(_e()),_meta:Ar(fu({}))}),pir=EL.extend({method:Mt("resources/list")}),Zae=AL.extend({resources:pt(DLe)}),hir=EL.extend({method:Mt("resources/templates/list")}),Xae=AL.extend({resourceTemplates:pt(dir)}),Yae=tf.extend({uri:_e()}),mir=Yae,gir=mc.extend({method:Mt("resources/read"),params:mir}),Qae=tl.extend({contents:pt(Ti([RLe,ILe]))}),vir=rf.extend({method:Mt("notifications/resources/list_changed")}),yir=Yae,bir=mc.extend({method:Mt("resources/subscribe"),params:yir}),xir=Yae,wir=mc.extend({method:Mt("resources/unsubscribe"),params:xir}),_ir=ky.extend({uri:_e()}),Sir=rf.extend({method:Mt("notifications/resources/updated"),params:_ir}),Eir=vt({name:_e(),description:Ar(_e()),required:Ar(Qn())}),Air=vt({...Ay.shape,...jE.shape,description:Ar(_e()),arguments:Ar(pt(Eir)),_meta:Ar(fu({}))}),Cir=EL.extend({method:Mt("prompts/list")}),eoe=AL.extend({prompts:pt(Air)}),kir=tf.extend({name:_e(),arguments:Ui(_e(),_e()).optional()}),Tir=mc.extend({method:Mt("prompts/get"),params:kir}),FLe=vt({type:Mt("text"),text:_e(),_meta:Ui(_e(),zi()).optional()}),NLe=vt({type:Mt("image"),data:Jae,mimeType:_e(),_meta:Ui(_e(),zi()).optional()}),jLe=vt({type:Mt("audio"),data:Jae,mimeType:_e(),_meta:Ui(_e(),zi()).optional()}),Pir=vt({type:Mt("tool_use"),name:_e(),id:_e(),input:vt({}).passthrough(),_meta:Ar(vt({}).passthrough())}).passthrough(),Oir=vt({type:Mt("resource"),resource:Ti([RLe,ILe]),_meta:Ui(_e(),zi()).optional()}),Rir=DLe.extend({type:Mt("resource_link")}),toe=Ti([FLe,NLe,jLe,Rir,Oir]),Iir=vt({role:el(["user","assistant"]),content:toe}),roe=tl.extend({description:Ar(_e()),messages:pt(Iir)}),Dir=rf.extend({method:Mt("notifications/prompts/list_changed")}),Fir=vt({title:_e().optional(),readOnlyHint:Qn().optional(),destructiveHint:Qn().optional(),idempotentHint:Qn().optional(),openWorldHint:Qn().optional()}),$Le=vt({...Ay.shape,...jE.shape,description:_e().optional(),inputSchema:vt({type:Mt("object"),properties:Ui(_e(),xd).optional(),required:pt(_e()).optional()}).catchall(zi()),outputSchema:vt({type:Mt("object"),properties:Ui(_e(),xd).optional(),required:pt(_e()).optional()}).catchall(zi()).optional(),annotations:Ar(Fir),_meta:Ui(_e(),zi()).optional()}),Nir=EL.extend({method:Mt("tools/list")}),noe=AL.extend({tools:pt($Le)}),CL=tl.extend({content:pt(toe).default([]),structuredContent:Ui(_e(),zi()).optional(),isError:Ar(Qn())}),sSn=CL.or(tl.extend({toolResult:zi()})),jir=tf.extend({name:_e(),arguments:Ar(Ui(_e(),zi()))}),$ir=mc.extend({method:Mt("tools/call"),params:jir}),Mir=rf.extend({method:Mt("notifications/tools/list_changed")}),MLe=el(["debug","info","notice","warning","error","critical","alert","emergency"]),Lir=tf.extend({level:MLe}),qir=mc.extend({method:Mt("logging/setLevel"),params:Lir}),Bir=ky.extend({level:MLe,logger:_e().optional(),data:zi()}),zir=rf.extend({method:Mt("notifications/message"),params:Bir}),Uir=vt({name:_e().optional()}),Hir=vt({hints:Ar(pt(Uir)),costPriority:Ar(Yn().min(0).max(1)),speedPriority:Ar(Yn().min(0).max(1)),intelligencePriority:Ar(Yn().min(0).max(1))}),Wir=vt({mode:Ar(el(["auto","required","none"]))}),Vir=vt({type:Mt("tool_result"),toolUseId:_e().describe("The unique identifier for the corresponding tool call."),content:pt(toe).default([]),structuredContent:vt({}).passthrough().optional(),isError:Ar(Qn()),_meta:Ar(vt({}).passthrough())}).passthrough(),vL=nLe("type",[FLe,NLe,jLe,Pir,Vir]),Gir=vt({role:el(["user","assistant"]),content:Ti([vL,pt(vL)]),_meta:Ar(vt({}).passthrough())}).passthrough(),Kir=tf.extend({messages:pt(Gir),modelPreferences:Hir.optional(),systemPrompt:_e().optional(),includeContext:el(["none","thisServer","allServers"]).optional(),temperature:Yn().optional(),maxTokens:Yn().int(),stopSequences:pt(_e()).optional(),metadata:xd.optional(),tools:Ar(pt($Le)),toolChoice:Ar(Wir)}),Jir=mc.extend({method:Mt("sampling/createMessage"),params:Kir}),Zir=tl.extend({model:_e(),stopReason:Ar(el(["endTurn","stopSequence","maxTokens","toolUse"]).or(_e())),role:el(["user","assistant"]),content:Ti([vL,pt(vL)])}),Xir=vt({type:Mt("boolean"),title:_e().optional(),description:_e().optional(),default:Qn().optional()}),Yir=vt({type:Mt("string"),title:_e().optional(),description:_e().optional(),minLength:Yn().optional(),maxLength:Yn().optional(),format:el(["email","uri","date","date-time"]).optional(),default:_e().optional()}),Qir=vt({type:el(["number","integer"]),title:_e().optional(),description:_e().optional(),minimum:Yn().optional(),maximum:Yn().optional(),default:Yn().optional()}),esr=vt({type:Mt("string"),title:_e().optional(),description:_e().optional(),enum:pt(_e()),default:_e().optional()}),tsr=vt({type:Mt("string"),title:_e().optional(),description:_e().optional(),oneOf:pt(vt({const:_e(),title:_e()})),default:_e().optional()}),rsr=vt({type:Mt("string"),title:_e().optional(),description:_e().optional(),enum:pt(_e()),enumNames:pt(_e()).optional(),default:_e().optional()}),nsr=Ti([esr,tsr]),isr=vt({type:Mt("array"),title:_e().optional(),description:_e().optional(),minItems:Yn().optional(),maxItems:Yn().optional(),items:vt({type:Mt("string"),enum:pt(_e())}),default:pt(_e()).optional()}),ssr=vt({type:Mt("array"),title:_e().optional(),description:_e().optional(),minItems:Yn().optional(),maxItems:Yn().optional(),items:vt({anyOf:pt(vt({const:_e(),title:_e()}))}),default:pt(_e()).optional()}),asr=Ti([isr,ssr]),osr=Ti([rsr,nsr,asr]),csr=Ti([osr,Xir,Yir,Qir]),usr=tf.extend({mode:Mt("form").optional(),message:_e(),requestedSchema:vt({type:Mt("object"),properties:Ui(_e(),csr),required:pt(_e()).optional()})}),lsr=tf.extend({mode:Mt("url"),message:_e(),elicitationId:_e(),url:_e().url()}),fsr=Ti([usr,lsr]),ioe=mc.extend({method:Mt("elicitation/create"),params:fsr}),dsr=ky.extend({elicitationId:_e()}),psr=rf.extend({method:Mt("notifications/elicitation/complete"),params:dsr}),soe=tl.extend({action:el(["accept","decline","cancel"]),content:Ui(_e(),Ti([_e(),Yn(),Qn(),pt(_e())])).optional()}),hsr=vt({type:Mt("ref/resource"),uri:_e()});var msr=vt({type:Mt("ref/prompt"),name:_e()}),gsr=tf.extend({ref:Ti([msr,hsr]),argument:vt({name:_e(),value:_e()}),context:vt({arguments:Ui(_e(),_e()).optional()}).optional()}),vsr=mc.extend({method:Mt("completion/complete"),params:gsr});var aoe=tl.extend({completion:fu({values:pt(_e()).max(100),total:Ar(Yn().int()),hasMore:Ar(Qn())})}),ysr=vt({uri:_e().startsWith("file://"),name:_e().optional(),_meta:Ui(_e(),zi()).optional()}),bsr=mc.extend({method:Mt("roots/list")}),xsr=tl.extend({roots:pt(ysr)}),wsr=rf.extend({method:Mt("notifications/roots/list_changed")}),aSn=Ti([_L,oir,vsr,qir,Tir,Cir,pir,hir,gir,bir,wir,$ir,Nir]),oSn=Ti([wL,SL,TLe,wsr]),cSn=Ti([fg,Zir,soe,xsr]),uSn=Ti([_L,Jir,ioe,bsr]),lSn=Ti([wL,SL,zir,Sir,vir,Mir,Dir,psr]),fSn=Ti([fg,Kae,aoe,roe,eoe,Zae,Xae,Qae,CL,noe]),Pa=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===na.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new Gae(i.elicitations,r)}return new t(e,r,n)}},Gae=class extends Pa{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(na.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){var e,r;return(r=(e=this.data)===null||e===void 0?void 0:e.elicitations)!==null&&r!==void 0?r:[]}};var _sr=Symbol("Let zodToJsonSchema decide on which parser to use");var USn=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ooe(t){let e=gL(t),r=e?.method;if(!r)throw new Error("Schema is missing a method literal");let n=vLe(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function coe(t,e){let r=lg(t,e);if(!r.success)throw r.error;return r.data}var Tsr=6e4,kL=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(wL,r=>{let n=this._requestHandlerAbortControllers.get(r.params.requestId);n?.abort(r.params.reason)}),this.setNotificationHandler(SL,r=>{this._onprogress(r)}),this.setRequestHandler(_L,r=>({}))}_setupTimeout(e,r,n,i,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:i})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),Pa.fromError(na.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,n,i;this._transport=e;let s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s?.(),this._onclose()};let a=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=c=>{a?.(c),this._onerror(c)};let o=(i=this._transport)===null||i===void 0?void 0:i.onmessage;this._transport.onmessage=(c,u)=>{o?.(c,u),NE(c)||CLe(c)?this._onresponse(c):xL(c)?this._onrequest(c,u):SLe(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=Pa.fromError(na.ConnectionClosed,"Connection closed");for(let i of r.values())i(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,r){var n,i;let s=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,a=this._transport;if(s===void 0){a?.send({jsonrpc:"2.0",id:e.id,error:{code:na.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let c={signal:o.signal,sessionId:a?.sessionId,_meta:(i=e.params)===null||i===void 0?void 0:i._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,f,d)=>this.request(u,f,{...d,relatedRequestId:e.id}),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>s(e,c)).then(u=>{if(!o.signal.aborted)return a?.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var f;if(!o.signal.aborted)return a?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:na.InternalError,message:(f=u.message)!==null&&f!==void 0?f:"Internal error",...u.data!==void 0&&{data:u.data}}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),s=this._progressHandlers.get(i);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(i),o=this._timeoutInfo.get(i);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){a(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),NE(e))n(e);else{let i=Pa.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,n){let{relatedRequestId:i,resumptionToken:s,onresumptiontoken:a}=n??{};return new Promise((o,c)=>{var u,f,d,p,h,m;if(!this._transport){c(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(f=n?.signal)===null||f===void 0||f.throwIfAborted();let g=this._requestMessageId++,v={...e,jsonrpc:"2.0",id:g};n?.onprogress&&(this._progressHandlers.set(g,n.onprogress),v.params={...e.params,_meta:{...((d=e.params)===null||d===void 0?void 0:d._meta)||{},progressToken:g}});let y=E=>{var C;this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),(C=this._transport)===null||C===void 0||C.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(E)}},{relatedRequestId:i,resumptionToken:s,onresumptiontoken:a}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`))),c(E)};this._responseHandlers.set(g,E=>{var C;if(!(!((C=n?.signal)===null||C===void 0)&&C.aborted)){if(E instanceof Error)return c(E);try{let T=lg(r,E.result);T.success?o(T.data):c(T.error)}catch(T){c(T)}}}),(p=n?.signal)===null||p===void 0||p.addEventListener("abort",()=>{var E;y((E=n?.signal)===null||E===void 0?void 0:E.reason)});let b=(h=n?.timeout)!==null&&h!==void 0?h:Tsr,x=()=>y(Pa.fromError(na.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(g,b,n?.maxTotalTimeout,x,(m=n?.resetTimeoutOnProgress)!==null&&m!==void 0?m:!1),this._transport.send(v,{relatedRequestId:i,resumptionToken:s,onresumptiontoken:a}).catch(E=>{this._cleanupTimeout(g),c(E)})})}async notification(e,r){var n,i;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((i=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&i!==void 0?i:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var c;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let u={...e,jsonrpc:"2.0"};(c=this._transport)===null||c===void 0||c.send(u,r).catch(f=>this._onerror(f))});return}let o={...e,jsonrpc:"2.0"};await this._transport.send(o,r)}setRequestHandler(e,r){let n=ooe(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,s)=>{let a=coe(e,i);return Promise.resolve(r(a,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=ooe(e);this._notificationHandlers.set(n,i=>{let s=coe(e,i);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function LLe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function qLe(t,e){let r={...t};for(let n in e){let i=n,s=e[i];if(s===void 0)continue;let a=r[i];LLe(a)&&LLe(s)?r[i]={...a,...s}:r[i]=s}return r}var qze=Ur(Yce(),1),Bze=Ur(Lze(),1);function qfr(){let t=new qze.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Bze.default)(t),t}var lq=class{constructor(e){this._ajv=e??qfr()}getValidator(e){var r;let n="$id"in e&&typeof e.$id=="string"?(r=this._ajv.getSchema(e.$id))!==null&&r!==void 0?r:this._ajv.compile(e):this._ajv.compile(e);return i=>n(i)?{valid:!0,data:i,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};function fq(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let i of Object.keys(n)){let s=n[i];r[i]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[i]=s.default),r[i]!==void 0&&fq(s,r[i])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)fq(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)fq(r,e)}}function Bfr(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var dq=class extends kL{constructor(e,r){var n,i;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._jsonSchemaValidator=(i=r?.jsonSchemaValidator)!==null&&i!==void 0?i:new lq}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=qLe(this._capabilities,e)}setRequestHandler(e,r){var n,i,s;let a=gL(e),o=a?.method;if(!o)throw new Error("Schema is missing a method literal");let c;if(Ey(o)){let f=o,d=(n=f._zod)===null||n===void 0?void 0:n.def;c=(i=d?.value)!==null&&i!==void 0?i:f.value}else{let f=o,d=f._def;c=(s=d?.value)!==null&&s!==void 0?s:f.value}if(typeof c!="string")throw new Error("Schema method literal must be a string");if(c==="elicitation/create"){let f=async(d,p)=>{var h,m,g;let v=lg(ioe,d);if(!v.success){let A=v.error instanceof Error?v.error.message:String(v.error);throw new Pa(na.InvalidParams,`Invalid elicitation request: ${A}`)}let{params:y}=v.data,b=(h=y.mode)!==null&&h!==void 0?h:"form",{supportsFormMode:x,supportsUrlMode:E}=Bfr(this._capabilities.elicitation);if(b==="form"&&!x)throw new Pa(na.InvalidParams,"Client does not support form-mode elicitation requests");if(b==="url"&&!E)throw new Pa(na.InvalidParams,"Client does not support URL-mode elicitation requests");let C=await Promise.resolve(r(d,p)),T=lg(soe,C);if(!T.success){let A=T.error instanceof Error?T.error.message:String(T.error);throw new Pa(na.InvalidParams,`Invalid elicitation result: ${A}`)}let I=T.data,F=b==="form"?y.requestedSchema:void 0;if(b==="form"&&I.action==="accept"&&I.content&&F&&!((g=(m=this._capabilities.elicitation)===null||m===void 0?void 0:m.form)===null||g===void 0)&&g.applyDefaults)try{fq(F,I.content)}catch{}return I};return super.setRequestHandler(e,f)}return super.setRequestHandler(e,r)}assertCapability(e,r){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Cy,capabilities:this._capabilities,clientInfo:this._clientInfo}},Kae,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!yLe.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,n,i,s,a;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`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(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`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 Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},fg,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},aoe,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},fg,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},roe,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},eoe,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Zae,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Xae,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Qae,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},fg,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},fg,r)}async callTool(e,r=CL,n){let i=await this.request({method:"tools/call",params:e},r,n),s=this.getToolOutputValidator(e.name);if(s){if(!i.structuredContent&&!i.isError)throw new Pa(na.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{let a=s(i.structuredContent);if(!a.valid)throw new Pa(na.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof Pa?a:new Pa(na.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return i}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let r of e)if(r.outputSchema){let n=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,n)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},noe,r);return this.cacheToolOutputSchemas(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var RUe=Ur(PUe(),1);import gq from"node:process";import{PassThrough as mdr}from"node:stream";var hq=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
1429
1429
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),hdr(r)}clear(){this._buffer=void 0}};function hdr(t){return D0.parse(JSON.parse(t))}function OUe(t){return JSON.stringify(t)+`
|
|
1430
1430
|
`}var gdr=gq.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function vdr(){let t={};for(let e of gdr){let r=gq.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var mq=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new hq,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new mdr)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{var n,i,s,a,o;this._process=(0,RUe.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...vdr(),...this._serverParams.env},stdio:["pipe","pipe",(i=this._serverParams.stderr)!==null&&i!==void 0?i:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:gq.platform==="win32"&&ydr(),cwd:this._serverParams.cwd}),this._process.on("error",c=>{var u,f;if(c.name==="AbortError"){(u=this.onclose)===null||u===void 0||u.call(this);return}r(c),(f=this.onerror)===null||f===void 0||f.call(this,c)}),this._process.on("spawn",()=>{e()}),this._process.on("close",c=>{var u;this._process=void 0,(u=this.onclose)===null||u===void 0||u.call(this)}),(s=this._process.stdin)===null||s===void 0||s.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),(a=this._process.stdout)===null||a===void 0||a.on("data",c=>{this._readBuffer.append(c),this.processReadBuffer()}),(o=this._process.stdout)===null||o===void 0||o.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,r;return this._stderrStream?this._stderrStream:(r=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&r!==void 0?r:null}get pid(){var e,r;return(r=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&r!==void 0?r:null}processReadBuffer(){for(var e,r;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(r=this.onerror)===null||r===void 0||r.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(r=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let i=OUe(e);this._process.stdin.write(i)?r():this._process.stdin.once("drain",r)})}};function ydr(){return"type"in gq}function vq(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function yq(t=fetch,e){return e?async(r,n)=>{let i={...e,...n,headers:n?.headers?{...vq(e.headers),...vq(n.headers)}:e.headers};return t(r,i)}:t}var mue;mue=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function bdr(t){return(await mue).getRandomValues(new Uint8Array(t))}async function xdr(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let i=await bdr(t-n.length);for(let s of i)s<r&&(n+=e[s%e.length])}return n}async function wdr(t){return await xdr(t)}async function _dr(t){let e=await(await mue).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function gue(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await wdr(t),r=await _dr(e);return{code_verifier:e,code_challenge:r}}function IUe(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function DUe({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return i.startsWith(s)}var ws=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},hA=class extends ws{};hA.errorCode="invalid_request";var Eg=class extends ws{};Eg.errorCode="invalid_client";var Ag=class extends ws{};Ag.errorCode="invalid_grant";var Cg=class extends ws{};Cg.errorCode="unauthorized_client";var mA=class extends ws{};mA.errorCode="unsupported_grant_type";var gA=class extends ws{};gA.errorCode="invalid_scope";var vA=class extends ws{};vA.errorCode="access_denied";var nh=class extends ws{};nh.errorCode="server_error";var yA=class extends ws{};yA.errorCode="temporarily_unavailable";var bA=class extends ws{};bA.errorCode="unsupported_response_type";var xA=class extends ws{};xA.errorCode="unsupported_token_type";var wA=class extends ws{};wA.errorCode="invalid_token";var _A=class extends ws{};_A.errorCode="method_not_allowed";var SA=class extends ws{};SA.errorCode="too_many_requests";var kg=class extends ws{};kg.errorCode="invalid_client_metadata";var EA=class extends ws{};EA.errorCode="insufficient_scope";var FUe={[hA.errorCode]:hA,[Eg.errorCode]:Eg,[Ag.errorCode]:Ag,[Cg.errorCode]:Cg,[mA.errorCode]:mA,[gA.errorCode]:gA,[vA.errorCode]:vA,[nh.errorCode]:nh,[yA.errorCode]:yA,[bA.errorCode]:bA,[xA.errorCode]:xA,[wA.errorCode]:wA,[_A.errorCode]:_A,[SA.errorCode]:SA,[kg.errorCode]:kg,[EA.errorCode]:EA};var jo=class extends Error{constructor(e){super(e??"Unauthorized")}};function Sdr(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var vue="code",yue="S256";function jUe(t,e){let r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&Sdr(t.token_endpoint_auth_method)&&e.includes(t.token_endpoint_auth_method)?t.token_endpoint_auth_method:r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function $Ue(t,e,r,n){let{client_id:i,client_secret:s}=e;switch(t){case"client_secret_basic":Edr(i,s,r);return;case"client_secret_post":Adr(i,s,n);return;case"none":Cdr(i,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Edr(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function Adr(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function Cdr(t,e){e.set("client_id",t)}async function wue(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=gLe.parse(JSON.parse(r)),{error:i,error_description:s,error_uri:a}=n,o=FUe[i]||nh;return new o(s||"",a)}catch(n){let i=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new nh(i)}}async function ih(t,e){var r,n;try{return await bue(t,e)}catch(i){if(i instanceof Eg||i instanceof Cg)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await bue(t,e);if(i instanceof Ag)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"tokens")),await bue(t,e);throw i}}async function bue(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:i,fetchFn:s}){var a,o;let c,u;try{c=await Pdr(e,{resourceMetadataUrl:i},s),c.authorization_servers&&c.authorization_servers.length>0&&(u=c.authorization_servers[0])}catch{}u||(u=new URL("/",e));let f=await Tdr(e,t,c),d=await Fdr(u,{fetchFn:s}),p=await Promise.resolve(t.clientInformation());if(!p){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let y=d?.client_id_metadata_document_supported===!0,b=t.clientMetadataUrl;if(b&&!kdr(b))throw new kg(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${b}`);if(y&&b)p={client_id:b},await((a=t.saveClientInformation)===null||a===void 0?void 0:a.call(t,p));else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let E=await Mdr(u,{metadata:d,clientMetadata:t.clientMetadata,fetchFn:s});await t.saveClientInformation(E),p=E}}if(r!==void 0){let y=await t.codeVerifier(),b=await jdr(u,{metadata:d,clientInformation:p,authorizationCode:r,codeVerifier:y,redirectUri:t.redirectUrl,resource:f,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(b),"AUTHORIZED"}let h=await t.tokens();if(h?.refresh_token)try{let y=await $dr(u,{metadata:d,clientInformation:p,refreshToken:h.refresh_token,resource:f,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(y),"AUTHORIZED"}catch(y){if(!(!(y instanceof ws)||y instanceof nh))throw y}let m=t.state?await t.state():void 0,{authorizationUrl:g,codeVerifier:v}=await Ndr(u,{metadata:d,clientInformation:p,state:m,redirectUrl:t.redirectUrl,scope:n||((o=c?.scopes_supported)===null||o===void 0?void 0:o.join(" "))||t.clientMetadata.scope,resource:f});return await t.saveCodeVerifier(v),await t.redirectToAuthorization(g),"REDIRECT"}function kdr(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function Tdr(t,e,r){let n=IUe(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!DUe({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Gy(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let i=xue(t,"resource_metadata")||void 0,s;if(i)try{s=new URL(i)}catch{}let a=xue(t,"scope")||void 0,o=xue(t,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:o}}function xue(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),i=r.match(n);return i?i[1]||i[2]:null}async function Pdr(t,e,r=fetch){let n=await Idr(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return hLe.parse(await n.json())}async function _ue(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?_ue(t,void 0,r):void 0;throw n}}function Odr(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function NUe(t,e,r=fetch){return await _ue(t,{"MCP-Protocol-Version":e},r)}function Rdr(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function Idr(t,e,r,n){var i,s;let a=new URL(t),o=(i=n?.protocolVersion)!==null&&i!==void 0?i:Cy,c;if(n?.metadataUrl)c=new URL(n.metadataUrl);else{let f=Odr(e,a.pathname);c=new URL(f,(s=n?.metadataServerUrl)!==null&&s!==void 0?s:a),c.search=a.search}let u=await NUe(c,o,r);if(!n?.metadataUrl&&Rdr(u,a.pathname)){let f=new URL(`/.well-known/${e}`,a);u=await NUe(f,o,r)}return u}function Ddr(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let i=e.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${i}`,e.origin),type:"oidc"}),n.push({url:new URL(`${i}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function Fdr(t,{fetchFn:e=fetch,protocolVersion:r=Cy}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},i=Ddr(t);for(let{url:s,type:a}of i){let o=await _ue(s,n,e);if(o){if(!o.ok){if(o.status>=400&&o.status<500)continue;throw new Error(`HTTP ${o.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return a==="oauth"?Vae.parse(await o.json()):mLe.parse(await o.json())}}}async function Ndr(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:i,state:s,resource:a}){let o;if(e){if(o=new URL(e.authorization_endpoint),!e.response_types_supported.includes(vue))throw new Error(`Incompatible auth server: does not support response type ${vue}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(yue))throw new Error(`Incompatible auth server: does not support code challenge method ${yue}`)}else o=new URL("/authorize",t);let c=await gue(),u=c.code_verifier,f=c.code_challenge;return o.searchParams.set("response_type",vue),o.searchParams.set("client_id",r.client_id),o.searchParams.set("code_challenge",f),o.searchParams.set("code_challenge_method",yue),o.searchParams.set("redirect_uri",String(n)),s&&o.searchParams.set("state",s),i&&o.searchParams.set("scope",i),i?.includes("offline_access")&&o.searchParams.append("prompt","consent"),a&&o.searchParams.set("resource",a.href),{authorizationUrl:o,codeVerifier:u}}async function jdr(t,{metadata:e,clientInformation:r,authorizationCode:n,codeVerifier:i,redirectUri:s,resource:a,addClientAuthentication:o,fetchFn:c}){var u;let f="authorization_code",d=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(f))throw new Error(`Incompatible auth server: does not support grant type ${f}`);let p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:f,code:n,code_verifier:i,redirect_uri:String(s)});if(o)o(p,h,t,e);else{let g=(u=e?.token_endpoint_auth_methods_supported)!==null&&u!==void 0?u:[],v=jUe(r,g);$Ue(v,r,p,h)}a&&h.set("resource",a.href);let m=await(c??fetch)(d,{method:"POST",headers:p,body:h});if(!m.ok)throw await wue(m);return FE.parse(await m.json())}async function $dr(t,{metadata:e,clientInformation:r,refreshToken:n,resource:i,addClientAuthentication:s,fetchFn:a}){var o;let c="refresh_token",u;if(e){if(u=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(c))throw new Error(`Incompatible auth server: does not support grant type ${c}`)}else u=new URL("/token",t);let f=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),d=new URLSearchParams({grant_type:c,refresh_token:n});if(s)s(f,d,t,e);else{let h=(o=e?.token_endpoint_auth_methods_supported)!==null&&o!==void 0?o:[],m=jUe(r,h);$Ue(m,r,f,d)}i&&d.set("resource",i.href);let p=await(a??fetch)(u,{method:"POST",headers:f,body:d});if(!p.ok)throw await wue(p);return FE.parse({refresh_token:n,...await p.json()})}async function Mdr(t,{metadata:e,clientMetadata:r,fetchFn:n}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let s=await(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await wue(s);return hL.parse(await s.json())}var AA=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},MUe=10,Ldr=13,Tg=32;function Sue(t){}function bq(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:e=Sue,onError:r=Sue,onRetry:n=Sue,onComment:i,maxBufferSize:s}=t,a=[],o=0,c=!0,u,f="",d=0,p,h=!1;function m(C){if(h)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,C.charCodeAt(0)===239&&C.charCodeAt(1)===187&&C.charCodeAt(2)===191&&(C=C.slice(3))),a.length===0){let F=v(C);F!==""&&(a.push(F),o=F.length),g();return}if(C.indexOf(`
|
|
1431
1431
|
`)===-1&&C.indexOf("\r")===-1){a.push(C),o+=C.length,g();return}a.push(C);let T=a.join("");a.length=0,o=0;let I=v(T);I!==""&&(a.push(I),o=I.length),g()}function g(){s!==void 0&&(o+f.length<=s||(h=!0,a.length=0,o=0,u=void 0,f="",d=0,p=void 0,r(new AA(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function v(C){let T=0;if(C.indexOf("\r")===-1){let I=C.indexOf(`
|