import{createRequire as e}from"node:module";import t from"node:process";import{PassThrough as n}from"node:stream";var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),u=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var s=o(t),l=0,u=s.length,d;lt[e]).bind(null,d),enumerable:!(r=a(t,d))||r.enumerable});return e},d=(e,t,n)=>(n=e==null?{}:r(s(e)),u(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),f=e(import.meta.url);let p=function(e){return e.InvalidRequest=`invalid_request`,e.InvalidClient=`invalid_client`,e.InvalidGrant=`invalid_grant`,e.UnauthorizedClient=`unauthorized_client`,e.UnsupportedGrantType=`unsupported_grant_type`,e.InvalidScope=`invalid_scope`,e.AccessDenied=`access_denied`,e.ServerError=`server_error`,e.TemporarilyUnavailable=`temporarily_unavailable`,e.UnsupportedResponseType=`unsupported_response_type`,e.UnsupportedTokenType=`unsupported_token_type`,e.InvalidToken=`invalid_token`,e.MethodNotAllowed=`method_not_allowed`,e.TooManyRequests=`too_many_requests`,e.InvalidClientMetadata=`invalid_client_metadata`,e.InsufficientScope=`insufficient_scope`,e.InvalidTarget=`invalid_target`,e}({});var m=class e extends Error{constructor(e,t,n){super(t),this.code=e,this.errorUri=n,this.name=`OAuthError`}toResponseObject(){let e={error:this.code,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}};let h=function(e){return e.NotConnected=`NOT_CONNECTED`,e.AlreadyConnected=`ALREADY_CONNECTED`,e.NotInitialized=`NOT_INITIALIZED`,e.CapabilityNotSupported=`CAPABILITY_NOT_SUPPORTED`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.ConnectionClosed=`CONNECTION_CLOSED`,e.SendFailed=`SEND_FAILED`,e.ClientHttpNotImplemented=`CLIENT_HTTP_NOT_IMPLEMENTED`,e.ClientHttpAuthentication=`CLIENT_HTTP_AUTHENTICATION`,e.ClientHttpForbidden=`CLIENT_HTTP_FORBIDDEN`,e.ClientHttpUnexpectedContent=`CLIENT_HTTP_UNEXPECTED_CONTENT`,e.ClientHttpFailedToOpenStream=`CLIENT_HTTP_FAILED_TO_OPEN_STREAM`,e.ClientHttpFailedToTerminateSession=`CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION`,e}({});var g=class extends Error{constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`SdkError`}};const _=Object.freeze({status:`aborted`});function v(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,`_zod`,{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;en?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var y=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},ee=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};const b={};function x(e){return e&&Object.assign(b,e),b}function te(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function ne(e,t){return typeof t==`bigint`?t.toString():t}function re(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function ie(e){return e==null}function ae(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function oe(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=t.toString(),i=(r.split(`.`)[1]||``).length;if(i===0&&/\d?e-\d?/.test(r)){let e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}let a=n>i?n:i;return Number.parseInt(e.toFixed(a).replace(`.`,``))%Number.parseInt(t.toFixed(a).replace(`.`,``))/10**a}const se=Symbol(`evaluating`);function S(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==se)return r===void 0&&(r=se,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function ce(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function le(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function ue(e){return JSON.stringify(e)}function de(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const fe=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function pe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const me=re(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function he(e){if(pe(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(pe(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function ge(e){return he(e)?{...e}:Array.isArray(e)?[...e]:e}const _e=new Set([`string`,`number`,`symbol`]);function ve(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function ye(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function C(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function be(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const xe={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Se(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return ye(e,le(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return ce(this,`shape`,e),e},checks:[]}))}function Ce(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return ye(e,le(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return ce(this,`shape`,r),r},checks:[]}))}function we(e,t){if(!he(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return ye(e,le(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return ce(this,`shape`,n),n}}))}function Te(e,t){if(!he(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return ye(e,le(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return ce(this,`shape`,n),n}}))}function Ee(e,t){return ye(e,le(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return ce(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function De(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return ye(t,le(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return ce(this,`shape`,i),i},checks:[]}))}function Oe(e,t,n){return ye(t,le(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return ce(this,`shape`,i),i}}))}function ke(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function je(e){return typeof e==`string`?e:e?.message}function Me(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=je(e.inst?._zod.def?.error?.(e))??je(t?.error?.(e))??je(n.customError?.(e))??je(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function Ne(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Pe(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const Fe=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),e.message=JSON.stringify(t,ne,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},Ie=v(`$ZodError`,Fe),Le=v(`$ZodError`,Fe,{Parent:Error});function Re(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function ze(e,t=e=>e.message){let n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`&&i.errors.length)i.errors.map(e=>r({issues:e}));else if(i.code===`invalid_key`)r({issues:i.issues});else if(i.code===`invalid_element`)r({issues:i.issues});else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new y;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>Me(e,a,x())));throw fe(t,i?.callee),t}return o.value},Ve=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>Me(e,a,x())));throw fe(t,i?.callee),t}return o.value},He=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new y;return a.issues.length?{success:!1,error:new(e??Ie)(a.issues.map(e=>Me(e,i,x())))}:{success:!0,data:a.value}},Ue=He(Le),We=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>Me(e,i,x())))}:{success:!0,data:a.value}},Ge=We(Le),Ke=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return Be(e)(t,n,i)},qe=e=>(t,n,r)=>Be(e)(t,n,r),Je=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return Ve(e)(t,n,i)},Ye=e=>async(t,n,r)=>Ve(e)(t,n,r),Xe=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return He(e)(t,n,i)},Ze=e=>(t,n,r)=>He(e)(t,n,r),Qe=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return We(e)(t,n,i)},$e=e=>async(t,n,r)=>We(e)(t,n,r),et=/^[cC][^\s-]{8,}$/,tt=/^[0-9a-z]+$/,nt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,rt=/^[0-9a-vA-V]{20}$/,it=/^[A-Za-z0-9]{27}$/,at=/^[a-zA-Z0-9_-]{21}$/,ot=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,st=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ct=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,lt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function ut(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const dt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ft=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,pt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,mt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ht=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,gt=/^[A-Za-z0-9_-]*$/,_t=/^\+[1-9]\d{6,14}$/,vt=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,yt=RegExp(`^${vt}$`);function bt(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function xt(e){return RegExp(`^${bt(e)}$`)}function St(e){let t=bt({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${vt}T(?:${r})$`)}const Ct=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},wt=/^-?\d+$/,Tt=/^-?\d+(?:\.\d+)?$/,Et=/^(?:true|false)$/i,Dt=/^null$/i,Ot=/^[^A-Z]*$/,kt=/^[^a-z]*$/,w=v(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),At={number:`number`,bigint:`bigint`,object:`date`},jt=v(`$ZodCheckLessThan`,(e,t)=>{w.init(e,t);let n=At[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value{(t.inclusive?r.value<=t.value:r.value{w.init(e,t);let n=At[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Nt=v(`$ZodCheckMultipleOf`,(e,t)=>{w.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):oe(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Pt=v(`$ZodCheckNumberFormat`,(e,t)=>{w.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=xe[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=wt)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}sa&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Ft=v(`$ZodCheckMaxLength`,(e,t)=>{var n;w.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!ie(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum{let r=n.value;if(r.length<=t.maximum)return;let i=Ne(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),It=v(`$ZodCheckMinLength`,(e,t)=>{var n;w.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!ie(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=Ne(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Lt=v(`$ZodCheckLengthEquals`,(e,t)=>{var n;w.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!ie(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=Ne(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Rt=v(`$ZodCheckStringFormat`,(e,t)=>{var n,r;w.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),zt=v(`$ZodCheckRegex`,(e,t)=>{Rt.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Bt=v(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Ot,Rt.init(e,t)}),Vt=v(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=kt,Rt.init(e,t)}),Ht=v(`$ZodCheckIncludes`,(e,t)=>{w.init(e,t);let n=ve(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Ut=v(`$ZodCheckStartsWith`,(e,t)=>{w.init(e,t);let n=RegExp(`^${ve(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Wt=v(`$ZodCheckEndsWith`,(e,t)=>{w.init(e,t);let n=RegExp(`.*${ve(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Gt=v(`$ZodCheckOverwrite`,(e,t)=>{w.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Kt=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(` `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(` `))}};const qt={major:4,minor:3,patch:6},T=v(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=qt;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=ke(e),i;for(let a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new y;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=ke(e,t))});else{if(e.issues.length===t)continue;r||=ke(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(ke(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new y;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new y;return o.then(e=>t(e,r,a))}return t(o,r,a)}}S(e,`~standard`,()=>({validate:t=>{try{let n=Ue(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Ge(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),Jt=v(`$ZodString`,(e,t)=>{T.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ct(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),E=v(`$ZodStringFormat`,(e,t)=>{Rt.init(e,t),Jt.init(e,t)}),Yt=v(`$ZodGUID`,(e,t)=>{t.pattern??=st,E.init(e,t)}),Xt=v(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=ct(e)}else t.pattern??=ct();E.init(e,t)}),Zt=v(`$ZodEmail`,(e,t)=>{t.pattern??=lt,E.init(e,t)}),Qt=v(`$ZodURL`,(e,t)=>{E.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),$t=v(`$ZodEmoji`,(e,t)=>{t.pattern??=ut(),E.init(e,t)}),en=v(`$ZodNanoID`,(e,t)=>{t.pattern??=at,E.init(e,t)}),tn=v(`$ZodCUID`,(e,t)=>{t.pattern??=et,E.init(e,t)}),nn=v(`$ZodCUID2`,(e,t)=>{t.pattern??=tt,E.init(e,t)}),rn=v(`$ZodULID`,(e,t)=>{t.pattern??=nt,E.init(e,t)}),an=v(`$ZodXID`,(e,t)=>{t.pattern??=rt,E.init(e,t)}),on=v(`$ZodKSUID`,(e,t)=>{t.pattern??=it,E.init(e,t)}),sn=v(`$ZodISODateTime`,(e,t)=>{t.pattern??=St(t),E.init(e,t)}),cn=v(`$ZodISODate`,(e,t)=>{t.pattern??=yt,E.init(e,t)}),ln=v(`$ZodISOTime`,(e,t)=>{t.pattern??=xt(t),E.init(e,t)}),un=v(`$ZodISODuration`,(e,t)=>{t.pattern??=ot,E.init(e,t)}),dn=v(`$ZodIPv4`,(e,t)=>{t.pattern??=dt,E.init(e,t),e._zod.bag.format=`ipv4`}),fn=v(`$ZodIPv6`,(e,t)=>{t.pattern??=ft,E.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),pn=v(`$ZodCIDRv4`,(e,t)=>{t.pattern??=pt,E.init(e,t)}),mn=v(`$ZodCIDRv6`,(e,t)=>{t.pattern??=mt,E.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function hn(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const gn=v(`$ZodBase64`,(e,t)=>{t.pattern??=ht,E.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{hn(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function _n(e){if(!gt.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return hn(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const vn=v(`$ZodBase64URL`,(e,t)=>{t.pattern??=gt,E.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{_n(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),yn=v(`$ZodE164`,(e,t)=>{t.pattern??=_t,E.init(e,t)});function bn(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const xn=v(`$ZodJWT`,(e,t)=>{E.init(e,t),e._zod.check=n=>{bn(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Sn=v(`$ZodNumber`,(e,t)=>{T.init(e,t),e._zod.pattern=e._zod.bag.pattern??Tt,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Cn=v(`$ZodNumberFormat`,(e,t)=>{Pt.init(e,t),Sn.init(e,t)}),wn=v(`$ZodBoolean`,(e,t)=>{T.init(e,t),e._zod.pattern=Et,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Tn=v(`$ZodNull`,(e,t)=>{T.init(e,t),e._zod.pattern=Dt,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),En=v(`$ZodAny`,(e,t)=>{T.init(e,t),e._zod.parse=e=>e}),Dn=v(`$ZodUnknown`,(e,t)=>{T.init(e,t),e._zod.parse=e=>e}),On=v(`$ZodNever`,(e,t)=>{T.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function kn(e,t,n){e.issues.length&&t.issues.push(...Ae(n,e.issues)),t.value[n]=e.value}const An=v(`$ZodArray`,(e,t)=>{T.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;ekn(t,n,e))):kn(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function jn(e,t,n,r,i){if(e.issues.length){if(i&&!(n in r))return;t.issues.push(...Ae(n,e.issues))}e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function Mn(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=be(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Nn(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optout===`optional`;for(let i in t){if(s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>jn(e,n,i,t,u))):jn(a,n,i,t,u)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}const Pn=v(`$ZodObject`,(e,t)=>{if(T.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,`shape`,{get:()=>{let n={...e};return Object.defineProperty(t,`shape`,{value:n}),n}})}let n=re(()=>Mn(t));S(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=pe,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optout===`optional`,i=n._zod.run({value:s[e],issues:[]},o);i instanceof Promise?c.push(i.then(n=>jn(n,t,e,s,r))):jn(i,t,e,s,r)}return i?Nn(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Fn=v(`$ZodObjectJIT`,(e,t)=>{Pn.init(e,t);let n=e._zod.parse,r=re(()=>Mn(t)),i=e=>{let t=new Kt([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=ue(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=ue(r),s=e[r]?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),s?t.write(` if (${n}.issues.length) { if (${o} in input) { payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ ...iss, path: iss.path ? [${o}, ...iss.path] : [${o}] }))); } } if (${n}.value === undefined) { if (${o} in input) { newResult[${o}] = undefined; } } else { newResult[${o}] = ${n}.value; } `):t.write(` if (${n}.issues.length) { payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ ...iss, path: iss.path ? [${o}, ...iss.path] : [${o}] }))); } if (${n}.value === undefined) { if (${o} in input) { newResult[${o}] = undefined; } } else { newResult[${o}] = ${n}.value; } `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=pe,s=!b.jitless,c=s&&me.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?Nn([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function In(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!ke(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Me(e,r,x())))}),t)}const Ln=v(`$ZodUnion`,(e,t)=>{T.init(e,t),S(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),S(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),S(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),S(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>ae(e.source)).join(`|`)})$`)}});let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,a)=>{if(n)return r(i,a);let o=!1,s=[];for(let e of t.options){let t=e._zod.run({value:i.value,issues:[]},a);if(t instanceof Promise)s.push(t),o=!0;else{if(t.issues.length===0)return t;s.push(t)}}return o?Promise.all(s).then(t=>In(t,i,e,a)):In(s,i,e,a)}}),Rn=v(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Ln.init(e,t);let n=e._zod.parse;S(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(let r of n)e[t].add(r)}}return e});let r=re(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!pe(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,input:o,path:[t.discriminator],inst:e}),i)}}),zn=v(`$ZodIntersection`,(e,t)=>{T.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Vn(e,t,n)):Vn(e,i,a)}});function Bn(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(he(e)&&he(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Bn(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;re.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),ke(e))return e;let o=Bn(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const Hn=v(`$ZodRecord`,(e,t)=>{T.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!he(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){s.add(typeof e==`number`?e.toString():e);let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...Ae(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...Ae(e,o.issues)),n.value[e]=o.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&Tt.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Me(e,r,x())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Ae(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...Ae(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),Un=v(`$ZodEnum`,(e,t)=>{T.init(e,t);let n=te(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>_e.has(typeof e)).map(e=>typeof e==`string`?ve(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Wn=v(`$ZodLiteral`,(e,t)=>{if(T.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?ve(e):e?ve(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Gn=v(`$ZodTransform`,(e,t)=>{T.init(e,t),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new ee(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new y;return n.value=i,n}});function Kn(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const qn=v(`$ZodOptional`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,S(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),S(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${ae(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>Kn(t,e.value)):Kn(r,e.value)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Jn=v(`$ZodExactOptional`,(e,t)=>{qn.init(e,t),S(e._zod,`values`,()=>t.innerType._zod.values),S(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Yn=v(`$ZodNullable`,(e,t)=>{T.init(e,t),S(e._zod,`optin`,()=>t.innerType._zod.optin),S(e._zod,`optout`,()=>t.innerType._zod.optout),S(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${ae(e.source)}|null)$`):void 0}),S(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Xn=v(`$ZodDefault`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,S(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Zn(e,t)):Zn(r,t)}});function Zn(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Qn=v(`$ZodPrefault`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,S(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),$n=v(`$ZodNonOptional`,(e,t)=>{T.init(e,t),S(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>er(t,e)):er(i,e)}});function er(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}const tr=v(`$ZodCatch`,(e,t)=>{T.init(e,t),S(e._zod,`optin`,()=>t.innerType._zod.optin),S(e._zod,`optout`,()=>t.innerType._zod.optout),S(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Me(e,n,x()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Me(e,n,x()))},input:e.value}),e.issues=[]),e)}}),nr=v(`$ZodPipe`,(e,t)=>{T.init(e,t),S(e._zod,`values`,()=>t.in._zod.values),S(e._zod,`optin`,()=>t.in._zod.optin),S(e._zod,`optout`,()=>t.out._zod.optout),S(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>rr(e,t.in,n)):rr(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>rr(e,t.out,n)):rr(r,t.out,n)}});function rr(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const ir=v(`$ZodReadonly`,(e,t)=>{T.init(e,t),S(e._zod,`propValues`,()=>t.innerType._zod.propValues),S(e._zod,`values`,()=>t.innerType._zod.values),S(e._zod,`optin`,()=>t.innerType?._zod?.optin),S(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(ar):ar(r)}});function ar(e){return e.value=Object.freeze(e.value),e}const or=v(`$ZodLazy`,(e,t)=>{T.init(e,t),S(e._zod,`innerType`,()=>t.getter()),S(e._zod,`pattern`,()=>e._zod.innerType?._zod?.pattern),S(e._zod,`propValues`,()=>e._zod.innerType?._zod?.propValues),S(e._zod,`optin`,()=>e._zod.innerType?._zod?.optin??void 0),S(e._zod,`optout`,()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),sr=v(`$ZodCustom`,(e,t)=>{w.init(e,t),T.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>cr(t,n,r,e));cr(i,n,r,e)}});function cr(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Pe(e))}}var lr,ur=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[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 t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function dr(){return new ur}(lr=globalThis).__zod_globalRegistry??(lr.__zod_globalRegistry=dr());const fr=globalThis.__zod_globalRegistry;function pr(e,t){return new e({type:`string`,...C(t)})}function mr(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...C(t)})}function hr(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...C(t)})}function gr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...C(t)})}function _r(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...C(t)})}function vr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...C(t)})}function yr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...C(t)})}function br(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...C(t)})}function xr(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...C(t)})}function Sr(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...C(t)})}function Cr(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...C(t)})}function wr(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...C(t)})}function Tr(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...C(t)})}function Er(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...C(t)})}function Dr(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...C(t)})}function Or(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...C(t)})}function kr(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...C(t)})}function Ar(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...C(t)})}function jr(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...C(t)})}function Mr(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...C(t)})}function Nr(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...C(t)})}function Pr(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...C(t)})}function Fr(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...C(t)})}function Ir(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...C(t)})}function Lr(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...C(t)})}function Rr(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...C(t)})}function zr(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...C(t)})}function Br(e,t){return new e({type:`number`,checks:[],...C(t)})}function Vr(e,t){return new e({type:`number`,coerce:!0,checks:[],...C(t)})}function Hr(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...C(t)})}function Ur(e,t){return new e({type:`boolean`,...C(t)})}function Wr(e,t){return new e({type:`null`,...C(t)})}function Gr(e){return new e({type:`any`})}function Kr(e){return new e({type:`unknown`})}function qr(e,t){return new e({type:`never`,...C(t)})}function Jr(e,t){return new jt({check:`less_than`,...C(t),value:e,inclusive:!1})}function Yr(e,t){return new jt({check:`less_than`,...C(t),value:e,inclusive:!0})}function Xr(e,t){return new Mt({check:`greater_than`,...C(t),value:e,inclusive:!1})}function Zr(e,t){return new Mt({check:`greater_than`,...C(t),value:e,inclusive:!0})}function Qr(e,t){return new Nt({check:`multiple_of`,...C(t),value:e})}function $r(e,t){return new Ft({check:`max_length`,...C(t),maximum:e})}function ei(e,t){return new It({check:`min_length`,...C(t),minimum:e})}function ti(e,t){return new Lt({check:`length_equals`,...C(t),length:e})}function ni(e,t){return new zt({check:`string_format`,format:`regex`,...C(t),pattern:e})}function ri(e){return new Bt({check:`string_format`,format:`lowercase`,...C(e)})}function ii(e){return new Vt({check:`string_format`,format:`uppercase`,...C(e)})}function ai(e,t){return new Ht({check:`string_format`,format:`includes`,...C(t),includes:e})}function oi(e,t){return new Ut({check:`string_format`,format:`starts_with`,...C(t),prefix:e})}function si(e,t){return new Wt({check:`string_format`,format:`ends_with`,...C(t),suffix:e})}function ci(e){return new Gt({check:`overwrite`,tx:e})}function li(e){return ci(t=>t.normalize(e))}function ui(){return ci(e=>e.trim())}function di(){return ci(e=>e.toLowerCase())}function fi(){return ci(e=>e.toUpperCase())}function pi(){return ci(e=>de(e))}function mi(e,t,n){return new e({type:`array`,element:t,...C(n)})}function hi(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...C(n)})}function gi(e){let t=_i(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(Pe(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push(Pe(r))}},e(n.value,n)));return t}function _i(e,t){let n=new w({check:`custom`,...C(t)});return n._zod.check=e,n}function vi(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??fr,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function D(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,D(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&O(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function yi(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function bi(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&(e.target===`draft-2020-12`?i.$defs=a:i.definitions=a);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:Si(t,`input`,e.processors),output:Si(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function O(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return O(r.element,n);if(r.type===`set`)return O(r.valueType,n);if(r.type===`lazy`)return O(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`)return O(r.innerType,n);if(r.type===`intersection`)return O(r.left,n)||O(r.right,n);if(r.type===`record`||r.type===`map`)return O(r.keyType,n)||O(r.valueType,n);if(r.type===`pipe`)return O(r.in,n)||O(r.out,n);if(r.type===`object`){for(let e in r.shape)if(O(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(O(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(O(e,n))return!0;return!!(r.rest&&O(r.rest,n))}return!1}const xi=(e,t={})=>n=>{let r=vi({...n,processors:t});return D(e,r),yi(r,e),bi(r,e)},Si=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=vi({...i??{},target:a,io:t,processors:n});return D(e,o),yi(o,e),bi(o,e)},Ci={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},wi=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Ci[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Ti=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`,typeof u==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u),typeof a==`number`&&(i.minimum=a,typeof u==`number`&&t.target!==`draft-04`&&(u>=a?delete i.minimum:delete i.exclusiveMinimum)),typeof l==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l),typeof o==`number`&&(i.maximum=o,typeof l==`number`&&t.target!==`draft-04`&&(l<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c==`number`&&(i.multipleOf=c)},Ei=(e,t,n,r)=>{n.type=`boolean`},Di=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Oi=(e,t,n,r)=>{n.not={}},ki=(e,t,n,r)=>{let i=e._zod.def,a=te(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Ai=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},ji=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},Mi=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Ni=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=D(a.element,t,{...r,path:[...r.path,`items`]})},Pi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=D(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=D(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Fi=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>D(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ii=(e,t,n,r)=>{let i=e._zod.def,a=D(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=D(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},Li=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=D(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=D(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=D(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},Ri=(e,t,n,r)=>{let i=e._zod.def,a=D(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},zi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Bi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Vi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Hi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},Ui=(e,t,n,r)=>{let i=e._zod.def,a=t.io===`input`?i.in._zod.def.type===`transform`?i.out:i.in:i.out;D(a,t,r);let o=t.seen.get(e);o.ref=a},Wi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Gi=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ki=(e,t,n,r)=>{let i=e._zod.innerType;D(i,t,r);let a=t.seen.get(e);a.ref=i},qi=v(`ZodISODateTime`,(e,t)=>{sn.init(e,t),j.init(e,t)});function Ji(e){return Ir(qi,e)}const Yi=v(`ZodISODate`,(e,t)=>{cn.init(e,t),j.init(e,t)});function Xi(e){return Lr(Yi,e)}const Zi=v(`ZodISOTime`,(e,t)=>{ln.init(e,t),j.init(e,t)});function Qi(e){return Rr(Zi,e)}const $i=v(`ZodISODuration`,(e,t)=>{un.init(e,t),j.init(e,t)});function ea(e){return zr($i,e)}const ta=(e,t)=>{Ie.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>ze(e,t)},flatten:{value:t=>Re(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,ne,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,ne,2)}},isEmpty:{get(){return e.issues.length===0}}})};v(`ZodError`,ta);const na=v(`ZodError`,ta,{Parent:Error}),ra=Be(na),ia=Ve(na),aa=He(na),oa=We(na),sa=Ke(na),ca=qe(na),la=Je(na),ua=Ye(na),da=Xe(na),fa=Ze(na),pa=Qe(na),ma=$e(na),k=v(`ZodType`,(e,t)=>(T.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Si(e,`input`),output:Si(e,`output`)}}),e.toJSONSchema=xi(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...n)=>e.clone(le(t,{checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>ye(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>ra(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>aa(e,t,n),e.parseAsync=async(t,n)=>ia(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>oa(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>sa(e,t,n),e.decode=(t,n)=>ca(e,t,n),e.encodeAsync=async(t,n)=>la(e,t,n),e.decodeAsync=async(t,n)=>ua(e,t,n),e.safeEncode=(t,n)=>da(e,t,n),e.safeDecode=(t,n)=>fa(e,t,n),e.safeEncodeAsync=async(t,n)=>pa(e,t,n),e.safeDecodeAsync=async(t,n)=>ma(e,t,n),e.refine=(t,n)=>e.check(Oo(t,n)),e.superRefine=t=>e.check(ko(t)),e.overwrite=t=>e.check(ci(t)),e.optional=()=>V(e),e.exactOptional=()=>lo(e),e.nullable=()=>fo(e),e.nullish=()=>V(fo(e)),e.nonoptional=t=>vo(e,t),e.array=()=>F(e),e.or=t=>R([e,t]),e.and=t=>eo(e,t),e.transform=t=>So(e,oo(t)),e.default=t=>mo(e,t),e.prefault=t=>go(e,t),e.catch=t=>bo(e,t),e.pipe=t=>So(e,t),e.readonly=()=>wo(e),e.describe=t=>{let n=e.clone();return fr.add(n,{description:t}),n},Object.defineProperty(e,`description`,{get(){return fr.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return fr.get(e);let n=e.clone();return fr.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),ha=v(`_ZodString`,(e,t)=>{Jt.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(ni(...t)),e.includes=(...t)=>e.check(ai(...t)),e.startsWith=(...t)=>e.check(oi(...t)),e.endsWith=(...t)=>e.check(si(...t)),e.min=(...t)=>e.check(ei(...t)),e.max=(...t)=>e.check($r(...t)),e.length=(...t)=>e.check(ti(...t)),e.nonempty=(...t)=>e.check(ei(1,...t)),e.lowercase=t=>e.check(ri(t)),e.uppercase=t=>e.check(ii(t)),e.trim=()=>e.check(ui()),e.normalize=(...t)=>e.check(li(...t)),e.toLowerCase=()=>e.check(di()),e.toUpperCase=()=>e.check(fi()),e.slugify=()=>e.check(pi())}),ga=v(`ZodString`,(e,t)=>{Jt.init(e,t),ha.init(e,t),e.email=t=>e.check(mr(_a,t)),e.url=t=>e.check(br(ba,t)),e.jwt=t=>e.check(Fr(Ia,t)),e.emoji=t=>e.check(xr(Sa,t)),e.guid=t=>e.check(hr(va,t)),e.uuid=t=>e.check(gr(ya,t)),e.uuidv4=t=>e.check(_r(ya,t)),e.uuidv6=t=>e.check(vr(ya,t)),e.uuidv7=t=>e.check(yr(ya,t)),e.nanoid=t=>e.check(Sr(Ca,t)),e.guid=t=>e.check(hr(va,t)),e.cuid=t=>e.check(Cr(wa,t)),e.cuid2=t=>e.check(wr(Ta,t)),e.ulid=t=>e.check(Tr(Ea,t)),e.base64=t=>e.check(Mr(Na,t)),e.base64url=t=>e.check(Nr(Pa,t)),e.xid=t=>e.check(Er(Da,t)),e.ksuid=t=>e.check(Dr(Oa,t)),e.ipv4=t=>e.check(Or(ka,t)),e.ipv6=t=>e.check(kr(Aa,t)),e.cidrv4=t=>e.check(Ar(ja,t)),e.cidrv6=t=>e.check(jr(Ma,t)),e.e164=t=>e.check(Pr(Fa,t)),e.datetime=t=>e.check(Ji(t)),e.date=t=>e.check(Xi(t)),e.time=t=>e.check(Qi(t)),e.duration=t=>e.check(ea(t))});function A(e){return pr(ga,e)}const j=v(`ZodStringFormat`,(e,t)=>{E.init(e,t),ha.init(e,t)}),_a=v(`ZodEmail`,(e,t)=>{Zt.init(e,t),j.init(e,t)}),va=v(`ZodGUID`,(e,t)=>{Yt.init(e,t),j.init(e,t)}),ya=v(`ZodUUID`,(e,t)=>{Xt.init(e,t),j.init(e,t)}),ba=v(`ZodURL`,(e,t)=>{Qt.init(e,t),j.init(e,t)});function xa(e){return br(ba,e)}const Sa=v(`ZodEmoji`,(e,t)=>{$t.init(e,t),j.init(e,t)}),Ca=v(`ZodNanoID`,(e,t)=>{en.init(e,t),j.init(e,t)}),wa=v(`ZodCUID`,(e,t)=>{tn.init(e,t),j.init(e,t)}),Ta=v(`ZodCUID2`,(e,t)=>{nn.init(e,t),j.init(e,t)}),Ea=v(`ZodULID`,(e,t)=>{rn.init(e,t),j.init(e,t)}),Da=v(`ZodXID`,(e,t)=>{an.init(e,t),j.init(e,t)}),Oa=v(`ZodKSUID`,(e,t)=>{on.init(e,t),j.init(e,t)}),ka=v(`ZodIPv4`,(e,t)=>{dn.init(e,t),j.init(e,t)}),Aa=v(`ZodIPv6`,(e,t)=>{fn.init(e,t),j.init(e,t)}),ja=v(`ZodCIDRv4`,(e,t)=>{pn.init(e,t),j.init(e,t)}),Ma=v(`ZodCIDRv6`,(e,t)=>{mn.init(e,t),j.init(e,t)}),Na=v(`ZodBase64`,(e,t)=>{gn.init(e,t),j.init(e,t)}),Pa=v(`ZodBase64URL`,(e,t)=>{vn.init(e,t),j.init(e,t)}),Fa=v(`ZodE164`,(e,t)=>{yn.init(e,t),j.init(e,t)}),Ia=v(`ZodJWT`,(e,t)=>{xn.init(e,t),j.init(e,t)}),La=v(`ZodNumber`,(e,t)=>{Sn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ti(e,t,n,r),e.gt=(t,n)=>e.check(Xr(t,n)),e.gte=(t,n)=>e.check(Zr(t,n)),e.min=(t,n)=>e.check(Zr(t,n)),e.lt=(t,n)=>e.check(Jr(t,n)),e.lte=(t,n)=>e.check(Yr(t,n)),e.max=(t,n)=>e.check(Yr(t,n)),e.int=t=>e.check(za(t)),e.safe=t=>e.check(za(t)),e.positive=t=>e.check(Xr(0,t)),e.nonnegative=t=>e.check(Zr(0,t)),e.negative=t=>e.check(Jr(0,t)),e.nonpositive=t=>e.check(Yr(0,t)),e.multipleOf=(t,n)=>e.check(Qr(t,n)),e.step=(t,n)=>e.check(Qr(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function M(e){return Br(La,e)}const Ra=v(`ZodNumberFormat`,(e,t)=>{Cn.init(e,t),La.init(e,t)});function za(e){return Hr(Ra,e)}const Ba=v(`ZodBoolean`,(e,t)=>{wn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ei(e,t,n,r)});function N(e){return Ur(Ba,e)}const Va=v(`ZodNull`,(e,t)=>{Tn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Di(e,t,n,r)});function Ha(e){return Wr(Va,e)}const Ua=v(`ZodAny`,(e,t)=>{En.init(e,t),k.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Wa(){return Gr(Ua)}const Ga=v(`ZodUnknown`,(e,t)=>{Dn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function P(){return Kr(Ga)}const Ka=v(`ZodNever`,(e,t)=>{On.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Oi(e,t,n,r)});function qa(e){return qr(Ka,e)}const Ja=v(`ZodArray`,(e,t)=>{An.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ni(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(ei(t,n)),e.nonempty=t=>e.check(ei(1,t)),e.max=(t,n)=>e.check($r(t,n)),e.length=(t,n)=>e.check(ti(t,n)),e.unwrap=()=>e.element});function F(e,t){return mi(Ja,e,t)}const Ya=v(`ZodObject`,(e,t)=>{Fn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pi(e,t,n,r),S(e,`shape`,()=>t.shape),e.keyof=()=>ro(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:P()}),e.loose=()=>e.clone({...e._zod.def,catchall:P()}),e.strict=()=>e.clone({...e._zod.def,catchall:qa()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>we(e,t),e.safeExtend=t=>Te(e,t),e.merge=t=>Ee(e,t),e.pick=t=>Se(e,t),e.omit=t=>Ce(e,t),e.partial=(...t)=>De(so,e,t[0]),e.required=(...t)=>Oe(_o,e,t[0])});function I(e,t){return new Ya({type:`object`,shape:e??{},...C(t)})}function L(e,t){return new Ya({type:`object`,shape:e,catchall:P(),...C(t)})}const Xa=v(`ZodUnion`,(e,t)=>{Ln.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fi(e,t,n,r),e.options=t.options});function R(e,t){return new Xa({type:`union`,options:e,...C(t)})}const Za=v(`ZodDiscriminatedUnion`,(e,t)=>{Xa.init(e,t),Rn.init(e,t)});function Qa(e,t,n){return new Za({type:`union`,options:t,discriminator:e,...C(n)})}const $a=v(`ZodIntersection`,(e,t)=>{zn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ii(e,t,n,r)});function eo(e,t){return new $a({type:`intersection`,left:e,right:t})}const to=v(`ZodRecord`,(e,t)=>{Hn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Li(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function z(e,t,n){return new to({type:`record`,keyType:e,valueType:t,...C(n)})}const no=v(`ZodEnum`,(e,t)=>{Un.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ki(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new no({...t,checks:[],...C(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new no({...t,checks:[],...C(r),entries:i})}});function ro(e,t){return new no({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...C(t)})}const io=v(`ZodLiteral`,(e,t)=>{Wn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ai(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function B(e,t){return new io({type:`literal`,values:Array.isArray(e)?e:[e],...C(t)})}const ao=v(`ZodTransform`,(e,t)=>{Gn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mi(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new ee(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Pe(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Pe(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function oo(e){return new ao({type:`transform`,transform:e})}const so=v(`ZodOptional`,(e,t)=>{qn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function V(e){return new so({type:`optional`,innerType:e})}const co=v(`ZodExactOptional`,(e,t)=>{Jn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function lo(e){return new co({type:`optional`,innerType:e})}const uo=v(`ZodNullable`,(e,t)=>{Yn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ri(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function fo(e){return new uo({type:`nullable`,innerType:e})}const po=v(`ZodDefault`,(e,t)=>{Xn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function mo(e,t){return new po({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ge(t)}})}const ho=v(`ZodPrefault`,(e,t)=>{Qn.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function go(e,t){return new ho({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ge(t)}})}const _o=v(`ZodNonOptional`,(e,t)=>{$n.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function vo(e,t){return new _o({type:`nonoptional`,innerType:e,...C(t)})}const yo=v(`ZodCatch`,(e,t)=>{tr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function bo(e,t){return new yo({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const xo=v(`ZodPipe`,(e,t)=>{nr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ui(e,t,n,r),e.in=t.in,e.out=t.out});function So(e,t){return new xo({type:`pipe`,in:e,out:t})}const Co=v(`ZodReadonly`,(e,t)=>{ir.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wo(e){return new Co({type:`readonly`,innerType:e})}const To=v(`ZodLazy`,(e,t)=>{or.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ki(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Eo(e){return new To({type:`lazy`,getter:e})}const Do=v(`ZodCustom`,(e,t)=>{sr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ji(e,t,n,r)});function Oo(e,t={}){return hi(Do,e,t)}function ko(e){return gi(e)}function Ao(e,t){return So(oo(e),t)}const jo={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 Mo;(function(e){})(Mo||={});function No(e){return Vr(La,e)}const H=xa().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:jo.custom,message:`URL must be parseable`,fatal:!0}),_}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),Po=L({resource:A().url(),authorization_servers:F(H).optional(),jwks_uri:A().url().optional(),scopes_supported:F(A()).optional(),bearer_methods_supported:F(A()).optional(),resource_signing_alg_values_supported:F(A()).optional(),resource_name:A().optional(),resource_documentation:A().optional(),resource_policy_uri:A().url().optional(),resource_tos_uri:A().url().optional(),tls_client_certificate_bound_access_tokens:N().optional(),authorization_details_types_supported:F(A()).optional(),dpop_signing_alg_values_supported:F(A()).optional(),dpop_bound_access_tokens_required:N().optional()}),Fo=L({issuer:A(),authorization_endpoint:H,token_endpoint:H,registration_endpoint:H.optional(),scopes_supported:F(A()).optional(),response_types_supported:F(A()),response_modes_supported:F(A()).optional(),grant_types_supported:F(A()).optional(),token_endpoint_auth_methods_supported:F(A()).optional(),token_endpoint_auth_signing_alg_values_supported:F(A()).optional(),service_documentation:H.optional(),revocation_endpoint:H.optional(),revocation_endpoint_auth_methods_supported:F(A()).optional(),revocation_endpoint_auth_signing_alg_values_supported:F(A()).optional(),introspection_endpoint:A().optional(),introspection_endpoint_auth_methods_supported:F(A()).optional(),introspection_endpoint_auth_signing_alg_values_supported:F(A()).optional(),code_challenge_methods_supported:F(A()).optional(),client_id_metadata_document_supported:N().optional()}),Io=I({...L({issuer:A(),authorization_endpoint:H,token_endpoint:H,userinfo_endpoint:H.optional(),jwks_uri:H,registration_endpoint:H.optional(),scopes_supported:F(A()).optional(),response_types_supported:F(A()),response_modes_supported:F(A()).optional(),grant_types_supported:F(A()).optional(),acr_values_supported:F(A()).optional(),subject_types_supported:F(A()),id_token_signing_alg_values_supported:F(A()),id_token_encryption_alg_values_supported:F(A()).optional(),id_token_encryption_enc_values_supported:F(A()).optional(),userinfo_signing_alg_values_supported:F(A()).optional(),userinfo_encryption_alg_values_supported:F(A()).optional(),userinfo_encryption_enc_values_supported:F(A()).optional(),request_object_signing_alg_values_supported:F(A()).optional(),request_object_encryption_alg_values_supported:F(A()).optional(),request_object_encryption_enc_values_supported:F(A()).optional(),token_endpoint_auth_methods_supported:F(A()).optional(),token_endpoint_auth_signing_alg_values_supported:F(A()).optional(),display_values_supported:F(A()).optional(),claim_types_supported:F(A()).optional(),claims_supported:F(A()).optional(),service_documentation:A().optional(),claims_locales_supported:F(A()).optional(),ui_locales_supported:F(A()).optional(),claims_parameter_supported:N().optional(),request_parameter_supported:N().optional(),request_uri_parameter_supported:N().optional(),require_request_uri_registration:N().optional(),op_policy_uri:H.optional(),op_tos_uri:H.optional(),client_id_metadata_document_supported:N().optional()}).shape,...Fo.pick({code_challenge_methods_supported:!0}).shape}),Lo=I({access_token:A(),id_token:A().optional(),token_type:A(),expires_in:No().optional(),scope:A().optional(),refresh_token:A().optional()}).strip();I({issued_token_type:B(`urn:ietf:params:oauth:token-type:id-jag`),access_token:A(),token_type:A().optional(),expires_in:M().optional(),scope:A().optional()}).strip();const Ro=I({error:A(),error_description:A().optional(),error_uri:A().optional()}),zo=H.optional().or(B(``).transform(()=>void 0)),Bo=I({redirect_uris:F(H),token_endpoint_auth_method:A().optional(),grant_types:F(A()).optional(),response_types:F(A()).optional(),client_name:A().optional(),client_uri:H.optional(),logo_uri:zo,scope:A().optional(),contacts:F(A()).optional(),tos_uri:zo,policy_uri:A().optional(),jwks_uri:H.optional(),jwks:Wa().optional(),software_id:A().optional(),software_version:A().optional(),software_statement:A().optional()}).strip(),Vo=I({client_id:A(),client_secret:A().optional(),client_id_issued_at:M().optional(),client_secret_expires_at:M().optional()}).strip(),Ho=Bo.merge(Vo);I({error:A(),error_description:A().optional()}).strip(),I({token:A(),token_type_hint:A().optional()}).strip();function Uo(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Wo({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length1?`s`:``} required`){super(U.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};const rs=Eo(()=>R([A(),M(),N(),Ha(),z(A(),rs),F(rs)])),G=z(A(),rs),is=R([A(),M().int()]),as=A();L({ttl:M().optional(),pollInterval:M().optional()});const os=I({ttl:M().optional()}),ss=I({taskId:A()}),cs=L({progressToken:is.optional(),[Yo]:ss.optional()}),ls=I({_meta:cs.optional()}),us=ls.extend({task:os.optional()}),K=I({method:A(),params:ls.loose().optional()}),ds=I({_meta:cs.optional()}),fs=I({method:A(),params:ds.loose().optional()}),q=L({_meta:cs.optional()}),ps=R([A(),M().int()]),ms=I({jsonrpc:B(`2.0`),id:ps,...K.shape}).strict(),hs=I({jsonrpc:B(`2.0`),...fs.shape}).strict(),gs=I({jsonrpc:B(`2.0`),id:ps,result:q}).strict(),_s=I({jsonrpc:B(`2.0`),id:ps.optional(),error:I({code:M().int(),message:A(),data:P().optional()})}).strict(),vs=R([ms,hs,gs,_s]);R([gs,_s]);const ys=q.strict(),bs=ds.extend({requestId:ps.optional(),reason:A().optional()}),xs=fs.extend({method:B(`notifications/cancelled`),params:bs}),Ss=I({icons:F(I({src:A(),mimeType:A().optional(),sizes:F(A()).optional(),theme:ro([`light`,`dark`]).optional()})).optional()}),Cs=I({name:A(),title:A().optional()}),ws=Cs.extend({...Cs.shape,...Ss.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),Ts=Ao(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,eo(I({form:eo(I({applyDefaults:N().optional()}),G).optional(),url:G.optional()}),G.optional())),Es=L({list:G.optional(),cancel:G.optional(),requests:L({sampling:L({createMessage:G.optional()}).optional(),elicitation:L({create:G.optional()}).optional()}).optional()}),Ds=L({list:G.optional(),cancel:G.optional(),requests:L({tools:L({call:G.optional()}).optional()}).optional()}),Os=I({experimental:z(A(),G).optional(),sampling:I({context:G.optional(),tools:G.optional()}).optional(),elicitation:Ts.optional(),roots:I({listChanged:N().optional()}).optional(),tasks:Es.optional(),extensions:z(A(),G).optional()}),ks=ls.extend({protocolVersion:A(),capabilities:Os,clientInfo:ws}),As=K.extend({method:B(`initialize`),params:ks}),js=I({experimental:z(A(),G).optional(),logging:G.optional(),completions:G.optional(),prompts:I({listChanged:N().optional()}).optional(),resources:I({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:I({listChanged:N().optional()}).optional(),tasks:Ds.optional(),extensions:z(A(),G).optional()}),Ms=q.extend({protocolVersion:A(),capabilities:js,serverInfo:ws,instructions:A().optional()}),Ns=fs.extend({method:B(`notifications/initialized`),params:ds.optional()}),Ps=K.extend({method:B(`ping`),params:ls.optional()}),Fs=I({progress:M(),total:V(M()),message:V(A())}),Is=I({...ds.shape,...Fs.shape,progressToken:is}),Ls=fs.extend({method:B(`notifications/progress`),params:Is}),Rs=ls.extend({cursor:as.optional()}),zs=K.extend({params:Rs.optional()}),Bs=q.extend({nextCursor:as.optional()}),Vs=ro([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Hs=I({taskId:A(),status:Vs,ttl:R([M(),Ha()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:V(M()),statusMessage:V(A())}),Us=q.extend({task:Hs}),Ws=ds.merge(Hs),Gs=fs.extend({method:B(`notifications/tasks/status`),params:Ws}),Ks=K.extend({method:B(`tasks/get`),params:ls.extend({taskId:A()})}),qs=q.merge(Hs),Js=K.extend({method:B(`tasks/result`),params:ls.extend({taskId:A()})}),Ys=q.loose(),Xs=zs.extend({method:B(`tasks/list`)}),Zs=Bs.extend({tasks:F(Hs)}),Qs=K.extend({method:B(`tasks/cancel`),params:ls.extend({taskId:A()})}),$s=q.merge(Hs),ec=I({uri:A(),mimeType:V(A()),_meta:z(A(),P()).optional()}),tc=ec.extend({text:A()}),nc=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),rc=ec.extend({blob:nc}),ic=ro([`user`,`assistant`]),ac=I({audience:F(ic).optional(),priority:M().min(0).max(1).optional(),lastModified:Ji({offset:!0}).optional()}),oc=I({...Cs.shape,...Ss.shape,uri:A(),description:V(A()),mimeType:V(A()),size:V(M()),annotations:ac.optional(),_meta:V(L({}))}),sc=I({...Cs.shape,...Ss.shape,uriTemplate:A(),description:V(A()),mimeType:V(A()),annotations:ac.optional(),_meta:V(L({}))}),cc=zs.extend({method:B(`resources/list`)}),lc=Bs.extend({resources:F(oc)}),uc=zs.extend({method:B(`resources/templates/list`)}),dc=Bs.extend({resourceTemplates:F(sc)}),fc=ls.extend({uri:A()}),pc=fc,mc=K.extend({method:B(`resources/read`),params:pc}),hc=q.extend({contents:F(R([tc,rc]))}),gc=fs.extend({method:B(`notifications/resources/list_changed`),params:ds.optional()}),_c=fc,vc=K.extend({method:B(`resources/subscribe`),params:_c}),yc=fc,bc=K.extend({method:B(`resources/unsubscribe`),params:yc}),xc=ds.extend({uri:A()}),Sc=fs.extend({method:B(`notifications/resources/updated`),params:xc}),Cc=I({name:A(),description:V(A()),required:V(N())}),wc=I({...Cs.shape,...Ss.shape,description:V(A()),arguments:V(F(Cc)),_meta:V(L({}))}),Tc=zs.extend({method:B(`prompts/list`)}),Ec=Bs.extend({prompts:F(wc)}),Dc=ls.extend({name:A(),arguments:z(A(),A()).optional()}),Oc=K.extend({method:B(`prompts/get`),params:Dc}),kc=I({type:B(`text`),text:A(),annotations:ac.optional(),_meta:z(A(),P()).optional()}),Ac=I({type:B(`image`),data:nc,mimeType:A(),annotations:ac.optional(),_meta:z(A(),P()).optional()}),jc=I({type:B(`image-uri`),uri:A(),mimeType:A().optional(),annotations:ac.optional(),_meta:z(A(),P()).optional()}),Mc=I({type:B(`audio`),data:nc,mimeType:A(),annotations:ac.optional(),_meta:z(A(),P()).optional()}),Nc=I({type:B(`tool_use`),name:A(),id:A(),input:z(A(),P()),_meta:z(A(),P()).optional()}),Pc=I({type:B(`resource`),resource:R([tc,rc]),annotations:ac.optional(),_meta:z(A(),P()).optional()}),Fc=R([kc,Ac,Mc,jc,oc.extend({type:B(`resource_link`)}),Pc]),Ic=I({role:ic,content:Fc}),Lc=q.extend({description:A().optional(),messages:F(Ic)}),Rc=fs.extend({method:B(`notifications/prompts/list_changed`),params:ds.optional()}),zc=I({title:A().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),Bc=I({taskSupport:ro([`required`,`optional`,`forbidden`]).optional()}),Vc=I({...Cs.shape,...Ss.shape,description:A().optional(),inputSchema:I({type:B(`object`),properties:z(A(),rs).optional(),required:F(A()).optional()}).catchall(P()),outputSchema:I({type:B(`object`),properties:z(A(),rs).optional(),required:F(A()).optional()}).catchall(P()).optional(),annotations:zc.optional(),execution:Bc.optional(),_meta:z(A(),P()).optional()}),Hc=zs.extend({method:B(`tools/list`)}),Uc=Bs.extend({tools:F(Vc)}),Wc=q.extend({content:F(Fc).default([]),structuredContent:z(A(),P()).optional(),isError:N().optional()});Wc.or(q.extend({toolResult:P()}));const Gc=us.extend({name:A(),arguments:z(A(),P()).optional()}),Kc=K.extend({method:B(`tools/call`),params:Gc}),qc=fs.extend({method:B(`notifications/tools/list_changed`),params:ds.optional()}),Jc=I({autoRefresh:N().default(!0),debounceMs:M().int().nonnegative().default(300)}),Yc=ro([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Xc=ls.extend({level:Yc}),Zc=K.extend({method:B(`logging/setLevel`),params:Xc}),Qc=ds.extend({level:Yc,logger:A().optional(),data:P()}),$c=fs.extend({method:B(`notifications/message`),params:Qc}),el=I({hints:F(I({name:A().optional()})).optional(),costPriority:M().min(0).max(1).optional(),speedPriority:M().min(0).max(1).optional(),intelligencePriority:M().min(0).max(1).optional()}),tl=I({mode:ro([`auto`,`required`,`none`]).optional()}),nl=I({type:B(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:F(Fc).default([]),structuredContent:I({}).loose().optional(),isError:N().optional(),_meta:z(A(),P()).optional()}),rl=Qa(`type`,[kc,Ac,Mc]),il=Qa(`type`,[kc,Ac,Mc,Nc,nl]),al=I({role:ic,content:R([il,F(il)]),_meta:z(A(),P()).optional()}),ol=us.extend({messages:F(al),modelPreferences:el.optional(),systemPrompt:A().optional(),includeContext:ro([`none`,`thisServer`,`allServers`]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:F(A()).optional(),metadata:G.optional(),tools:F(Vc).optional(),toolChoice:tl.optional()}),sl=K.extend({method:B(`sampling/createMessage`),params:ol}),cl=q.extend({model:A(),stopReason:V(ro([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:ic,content:rl}),ll=q.extend({model:A(),stopReason:V(ro([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:ic,content:R([il,F(il)])}),ul=I({type:B(`boolean`),title:A().optional(),description:A().optional(),default:N().optional()}),dl=I({type:B(`string`),title:A().optional(),description:A().optional(),minLength:M().optional(),maxLength:M().optional(),format:ro([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),fl=I({type:ro([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),pl=I({type:B(`string`),title:A().optional(),description:A().optional(),enum:F(A()),default:A().optional()}),ml=I({type:B(`string`),title:A().optional(),description:A().optional(),oneOf:F(I({const:A(),title:A()})),default:A().optional()}),hl=R([R([I({type:B(`string`),title:A().optional(),description:A().optional(),enum:F(A()),enumNames:F(A()).optional(),default:A().optional()}),R([pl,ml]),R([I({type:B(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({type:B(`string`),enum:F(A())}),default:F(A()).optional()}),I({type:B(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({anyOf:F(I({const:A(),title:A()}))}),default:F(A()).optional()})])]),ul,dl,fl]),gl=R([us.extend({mode:B(`form`).optional(),message:A(),requestedSchema:I({type:B(`object`),properties:z(A(),hl),required:F(A()).optional()}).catchall(P())}),us.extend({mode:B(`url`),message:A(),elicitationId:A(),url:A().url()})]),_l=K.extend({method:B(`elicitation/create`),params:gl}),vl=ds.extend({elicitationId:A()}),yl=fs.extend({method:B(`notifications/elicitation/complete`),params:vl}),bl=q.extend({action:ro([`accept`,`decline`,`cancel`]),content:Ao(e=>e===null?void 0:e,z(A(),R([A(),M(),N(),F(A())])).optional())}),xl=I({type:B(`ref/resource`),uri:A()}),Sl=I({type:B(`ref/prompt`),name:A()}),Cl=ls.extend({ref:R([Sl,xl]),argument:I({name:A(),value:A()}),context:I({arguments:z(A(),A()).optional()}).optional()}),wl=K.extend({method:B(`completion/complete`),params:Cl}),Tl=q.extend({completion:L({values:F(A()).max(100),total:V(M().int()),hasMore:V(N())})}),El=I({uri:A().startsWith(`file://`),name:A().optional(),_meta:z(A(),P()).optional()}),Dl=K.extend({method:B(`roots/list`),params:ls.optional()}),Ol=q.extend({roots:F(El)}),kl=fs.extend({method:B(`notifications/roots/list_changed`),params:ds.optional()}),Al=R([Ps,As,wl,Zc,Oc,Tc,cc,uc,mc,vc,bc,Kc,Hc,Ks,Js,Xs,Qs]),jl=R([xs,Ls,Ns,kl,Gs]);R([ys,cl,ll,bl,Ol,qs,Zs,Us]);const Ml=R([Ps,sl,_l,Dl,Ks,Js,Xs,Qs]),Nl=R([xs,Ls,$c,Sc,gc,qc,Rc,Gs,yl]);R([ys,Ms,Tl,Lc,Ec,lc,dc,hc,Wc,Uc,qs,Zs,Us]);const Pl={ping:ys,initialize:Ms,"completion/complete":Tl,"logging/setLevel":ys,"prompts/get":Lc,"prompts/list":Ec,"resources/list":lc,"resources/templates/list":dc,"resources/read":hc,"resources/subscribe":ys,"resources/unsubscribe":ys,"tools/call":R([Wc,Us]),"tools/list":Uc,"sampling/createMessage":R([ll,Us]),"elicitation/create":R([bl,Us]),"roots/list":Ol,"tasks/get":qs,"tasks/result":q,"tasks/list":Zs,"tasks/cancel":$s};function Fl(e){return Pl[e]}function Il(e){let t={};for(let n of e){let e=n.shape.method.value;t[e]=n}return t}const Ll=Il([...Al.options,...Ml.options]),Rl=Il([...jl.options,...Nl.options]);function zl(e){return Ll[e]}function Bl(e){return Rl[e]}function Vl(e){return vs.parse(e)}const Hl=e=>ms.safeParse(e).success,Ul=e=>hs.safeParse(e).success,Wl=e=>gs.safeParse(e).success,Gl=e=>_s.safeParse(e).success,Kl=e=>us.safeParse(e).success,ql=e=>As.safeParse(e).success,Jl=e=>Ns.safeParse(e).success;function Yl(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Xl(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}function Zl(e,t){return aa(e,t)}function Ql(e){return e===`completed`||e===`failed`||e===`cancelled`}function $l(e){if(!e)return;let{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}=e;return{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}}var eu=class{_taskStore;_taskMessageQueue;_taskProgressTokens=new Map;_requestResolvers=new Map;_options;_host;constructor(e){this._options=e,this._taskStore=e.taskStore,this._taskMessageQueue=e.taskMessageQueue}bind(e){this._host=e,this._taskStore&&(e.registerHandler(`tasks/get`,async(e,t)=>{let n=e.params;return{...await this.handleGetTask(n.taskId,t.sessionId)}}),e.registerHandler(`tasks/result`,async(t,n)=>{let r=t.params;return await this.handleGetTaskPayload(r.taskId,n.sessionId,n.mcpReq.signal,async t=>{await e.sendOnResponseStream(t,n.mcpReq.id)})}),e.registerHandler(`tasks/list`,async(e,t)=>{let n=e.params;return await this.handleListTasks(n?.cursor,t.sessionId)}),e.registerHandler(`tasks/cancel`,async(e,t)=>{let n=e.params;return await this.handleCancelTask(n.taskId,t.sessionId)}))}get _requireHost(){if(!this._host)throw new W(U.InternalError,`TaskManager is not bound to a Protocol host — call bind() first`);return this._host}get taskStore(){return this._taskStore}get _requireTaskStore(){if(!this._taskStore)throw new W(U.InternalError,`TaskStore is not configured`);return this._taskStore}get taskMessageQueue(){return this._taskMessageQueue}async*requestStream(e,t,n){let r=this._requireHost,{task:i}=n??{};if(!i){try{yield{type:`result`,result:await r.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof Error?e:Error(String(e))}}return}let a;try{let i=await r.request(e,Us,n);if(i.task)a=i.task.taskId,yield{type:`taskCreated`,task:i.task};else throw new W(U.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:a},n);if(yield{type:`taskStatus`,task:e},Ql(e.status)){switch(e.status){case`completed`:yield{type:`result`,result:await this.getTaskResult({taskId:a},t,n)};break;case`failed`:yield{type:`error`,error:new W(U.InternalError,`Task ${a} failed`)};break;case`cancelled`:yield{type:`error`,error:new W(U.InternalError,`Task ${a} was cancelled`)};break}return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:a},t,n)};return}let r=e.pollInterval??this._options.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof Error?e:Error(String(e))}}}async getTask(e,t){return this._requireHost.request({method:`tasks/get`,params:e},qs,t)}async getTaskResult(e,t,n){return this._requireHost.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this._requireHost.request({method:`tasks/list`,params:e},Zs,t)}async cancelTask(e,t){return this._requireHost.request({method:`tasks/cancel`,params:e},$s,t)}async handleGetTask(e,t){let n=await this._requireTaskStore.getTask(e,t);if(!n)throw new W(U.InvalidParams,`Failed to retrieve task: Task not found`);return n}async handleGetTaskPayload(e,t,n,r){let i=async()=>{if(this._taskMessageQueue){let n;for(;n=await this._taskMessageQueue.dequeue(e,t);){if(n.type===`response`||n.type===`error`){let e=n.message,t=e.id,r=this._requestResolvers.get(t);if(r)if(this._requestResolvers.delete(t),n.type===`response`)r(e);else{let t=e;r(new W(t.error.code,t.error.message,t.error.data))}else{let e=n.type===`response`?`Response`:`Error`;this._host?.reportError(Error(`${e} handler missing for request ${t}`))}continue}await r(n.message)}}let a=await this._requireTaskStore.getTask(e,t);if(!a)throw new W(U.InvalidParams,`Task not found: ${e}`);if(!Ql(a.status))return await this._waitForTaskUpdate(a.pollInterval,n),await i();let o=await this._requireTaskStore.getTaskResult(e,t);return await this._clearTaskQueue(e),{...o,_meta:{...o._meta,[Yo]:{taskId:e}}}};return await i()}async handleListTasks(e,t){try{let{tasks:n,nextCursor:r}=await this._requireTaskStore.listTasks(e,t);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new W(U.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}async handleCancelTask(e,t){try{let n=await this._requireTaskStore.getTask(e,t);if(!n)throw new W(U.InvalidParams,`Task not found: ${e}`);if(Ql(n.status))throw new W(U.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._requireTaskStore.updateTaskStatus(e,`cancelled`,`Client cancelled task execution.`,t),await this._clearTaskQueue(e);let r=await this._requireTaskStore.getTask(e,t);if(!r)throw new W(U.InvalidParams,`Task not found after cancellation: ${e}`);return{_meta:{},...r}}catch(e){throw e instanceof W?e:new W(U.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}prepareOutboundRequest(e,t,n,r,i){let{task:a,relatedTask:o}=t??{};a&&(e.params={...e.params,task:a}),o&&(e.params={...e.params,_meta:{...e.params?._meta,[Yo]:o}});let s=o?.taskId;return s?(this._requestResolvers.set(n,r),this._enqueueTaskMessage(s,{type:`request`,message:e,timestamp:Date.now()}).catch(e=>{i(e)}),!0):!1}extractInboundTaskContext(e,t){let n=(e.params?._meta)?.[Yo]?.taskId,r=Kl(e.params)?e.params.task:void 0,i;return this._taskStore&&(i={id:n,store:this.createRequestTaskStore(e,t),requestedTtl:r?.ttl}),!n&&!r&&!i?{}:{relatedTaskId:n,taskCreationParams:r,taskContext:i}}wrapSendNotification(e,t){return async n=>{await t(n,{relatedTask:{taskId:e}})}}wrapSendRequest(e,t,n){return async(r,i,a)=>{let o={...a};e&&!o.relatedTask&&(o.relatedTask={taskId:e});let s=o.relatedTask?.taskId??e;return s&&t&&await t.updateTaskStatus(s,`input_required`),await n(r,i,o)}}handleResponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);return n?(this._requestResolvers.delete(t),Wl(e)?n(e):n(new W(e.error.code,e.error.message,e.error.data)),!0):!1}shouldPreserveProgressHandler(e,t){if(Wl(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;if(typeof e.taskId==`string`)return this._taskProgressTokens.set(e.taskId,t),!0}}return!1}async routeNotification(e,t){let n=t?.relatedTask?.taskId;if(!n)return!1;let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta,[Yo]:t.relatedTask}}};return await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()}),!0}async routeResponse(e,t,n){return!e||!this._taskMessageQueue?!1:(await(Gl(t)?this._enqueueTaskMessage(e,{type:`error`,message:t,timestamp:Date.now()},n):this._enqueueTaskMessage(e,{type:`response`,message:t,timestamp:Date.now()},n)),!0)}createRequestTaskStore(e,t){let n=this._requireTaskStore,r=this._host;return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new W(U.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,i,a)=>{await n.storeTaskResult(e,i,a,t);let o=await n.getTask(e,t);if(o){let t=Gs.parse({method:`notifications/tasks/status`,params:o});await r?.notification(t),Ql(o.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,i,a)=>{let o=await n.getTask(e,t);if(!o)throw new W(U.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Ql(o.status))throw new W(U.InvalidParams,`Cannot update task "${e}" from terminal status "${o.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,i,a,t);let s=await n.getTask(e,t);if(s){let t=Gs.parse({method:`notifications/tasks/status`,params:s});await r?.notification(t),Ql(s.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}processInboundRequest(e,t){let n=this.extractInboundTaskContext(e,t.sessionId),r=n?.relatedTaskId,i=r?this.wrapSendNotification(r,t.sendNotification):e=>t.sendNotification(e),a=r?this.wrapSendRequest(r,n?.taskContext?.store,t.sendRequest):n?.taskContext?this.wrapSendRequest(``,n.taskContext.store,t.sendRequest):t.sendRequest,o=!!n?.taskCreationParams;return{taskContext:n?.taskContext,sendNotification:i,sendRequest:a,routeResponse:async e=>r?this.routeResponse(r,e,t.sessionId):!1,hasTaskCreationParams:o,validateInbound:o?()=>this._requireHost.assertTaskHandlerCapability(e.method):void 0}}processOutboundRequest(e,t,n,r,i){return this._requireHost.enforceStrictCapabilities&&t?.task&&this._requireHost.assertTaskCapability(e.method),{queued:this.prepareOutboundRequest(e,t,n,r,i)}}processInboundResponse(e,t){return this.handleResponse(e)?{consumed:!0,preserveProgress:!1}:{consumed:!1,preserveProgress:this.shouldPreserveProgressHandler(e,t)}}async processOutboundNotification(e,t){if(await this.routeNotification(e,t))return{queued:!0};let n={...e,jsonrpc:`2.0`};return t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta,[Yo]:t.relatedTask}}}),{queued:!1,jsonrpcNotification:n}}onClose(){this._taskProgressTokens.clear(),this._requestResolvers.clear()}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);await this._taskMessageQueue.enqueue(e,t,n,this._options.maxTaskQueueSize)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&Hl(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new W(U.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._host?.reportError(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=e??this._options.defaultTaskPollInterval??1e3;return new Promise((e,r)=>{if(t.aborted){r(new W(U.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new W(U.InvalidRequest,`Request cancelled`))},{once:!0})})}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._host?.removeProgressHandler(t),this._taskProgressTokens.delete(e))}},tu=class extends eu{constructor(){super({})}processInboundRequest(e,t){let n=Kl(e.params)&&!!e.params.task;return{taskContext:void 0,sendNotification:e=>t.sendNotification(e),sendRequest:t.sendRequest,routeResponse:async()=>!1,hasTaskCreationParams:n,validateInbound:n?()=>this._requireHost.assertTaskHandlerCapability(e.method):void 0}}async processOutboundNotification(e,t){return{queued:!1,jsonrpcNotification:{...e,jsonrpc:`2.0`}}}};const nu=6e4;var ru=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_taskManager;_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Jo,this._taskManager=e?.tasks?new eu(e.tasks):new tu,this._bindTaskManager(),this.setNotificationHandler(`notifications/cancelled`,e=>{this._oncancel(e)}),this.setNotificationHandler(`notifications/progress`,e=>{this._onprogress(e)}),this.setRequestHandler(`ping`,e=>({}))}get taskManager(){return this._taskManager}_bindTaskManager(){let e=this._taskManager,t={request:(e,t,n)=>this._requestWithSchema(e,t,n),notification:(e,t)=>this.notification(e,t),reportError:e=>this._onerror(e),removeProgressHandler:e=>this._progressHandlers.delete(e),registerHandler:(e,t)=>{let n=zl(e);this._requestHandlers.set(e,(e,r)=>(n.parse(e),t(e,r)))},sendOnResponseStream:async(e,t)=>{await this._transport?.send(e,{relatedRequestId:t})},enforceStrictCapabilities:this._options?.enforceStrictCapabilities===!0,assertTaskCapability:e=>this.assertTaskCapability(e),assertTaskHandlerCapability:e=>this.assertTaskHandlerCapability(e)};e.bind(t)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new g(h.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),Wl(e)||Gl(e)?this._onresponse(e):Hl(e)?this._onrequest(e,t):Ul(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskManager.onClose(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new g(h.ConnectionClosed,`Connection closed`);this._transport=void 0;try{this.onclose?.()}finally{for(let t of e.values())t(n);for(let e of t.values())e.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i={sessionId:r?.sessionId,sendNotification:(t,n)=>this.notification(t,{...n,relatedRequestId:e.id}),sendRequest:(t,n,r)=>this._requestWithSchema(t,n,{...r,relatedRequestId:e.id})},a=this._taskManager.processInboundRequest(e,i),o=a.sendNotification,s=a.sendRequest,c=a.taskContext,l=a.routeResponse,u=[];if(a.validateInbound&&u.push(a.validateInbound),n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:U.MethodNotFound,message:`Method not found`}};l(t).then(e=>{e||r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))}).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`)));return}let d=new AbortController;this._requestHandlerAbortControllers.set(e.id,d);let f={sessionId:r?.sessionId,mcpReq:{id:e.id,method:e.method,_meta:e.params?._meta,signal:d.signal,send:(e,t)=>s(e,Fl(e.method),t),notify:o},http:t?.authInfo?{authInfo:t.authInfo}:void 0,task:c},p=this.buildContext(f,t);Promise.resolve().then(()=>{for(let e of u)e()}).then(()=>n(e,p)).then(async t=>{if(d.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};await l(n)||await r?.send(n)},async t=>{if(d.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:U.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};await l(n)||await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===d&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._taskManager.processInboundResponse(e,t);if(n.consumed)return;let r=n.preserveProgress,i=this._responseHandlers.get(t);if(i===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),r||this._progressHandlers.delete(t),Wl(e)?i(e):i(W.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t){let n=Fl(e.method);return this._requestWithSchema(e,n,t)}_requestWithSchema(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}=n??{},o,s;return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++;s=d;let f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta,progressToken:d}});let p=e=>{this._progressHandlers.delete(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof g?e:new g(h.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Zl(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),o=()=>p(n?.signal?.reason),n?.signal?.addEventListener(`abort`,o,{once:!0});let m=n?.timeout??nu;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(new g(h.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let _=e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))},v=!1;try{this._taskManager.processOutboundRequest(f,n,d,_,e=>{this._progressHandlers.delete(d),l(e)}).queued&&(v=!0)}catch(e){this._progressHandlers.delete(d),l(e);return}v||this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._progressHandlers.delete(d),l(e)})}).finally(()=>{o&&n?.signal?.removeEventListener(`abort`,o),s!==void 0&&(this._responseHandlers.delete(s),this._cleanupTimeout(s))})}async notification(e,t){if(!this._transport)throw new g(h.NotConnected,`Not connected`);this.assertNotificationCapability(e.method);let n=await this._taskManager.processOutboundNotification(e,t),r=n.queued,i=n.queued?void 0:n.jsonrpcNotification;if(!r){if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(e.method),this._transport&&this._transport?.send(i,t).catch(e=>this._onerror(e))});return}await this._transport.send(i,t)}}setRequestHandler(e,t){this.assertRequestHandlerCapability(e);let n=zl(e);this._requestHandlers.set(e,(e,r)=>{let i=n.parse(e);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=Bl(e);this._notificationHandlers.set(e,e=>{let r=n.parse(e);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function iu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function au(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=iu(a)&&iu(i)?{...a,...i}:i}return n}async function ou(e){let t=[];for await(let n of e)t.push(n);return t}async function su(e){for await(let t of e)if(t.type===`result`)return t.result;else if(t.type===`error`)throw t.error;throw Error(`No result in stream.`)}var cu=class{_buffer;append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){for(;this._buffer;){let e=this._buffer.indexOf(` `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);this._buffer=this._buffer.subarray(e+1);try{return lu(t)}catch(e){if(e instanceof SyntaxError)continue;throw e}}return null}clear(){this._buffer=void 0}};function lu(e){try{return vs.parse(JSON.parse(e))}catch(t){throw t instanceof SyntaxError&&t.message&&(t.message+=`. Original line: "${e}"`),t}}function uu(e){return JSON.stringify(e)+` `}function du(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function fu(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...du(t.headers),...du(r.headers)}:t.headers}):e}const pu=1e6,mu=1e6,hu=1e4;var gu=class e{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,n){if(e.length>t)throw Error(`${n} exceeds maximum length of ${t} characters (got ${e.length})`)}template;parts;get variableNames(){return this.parts.flatMap(e=>typeof e==`string`?[]:e.names)}constructor(t){e.validateLength(t,pu,`Template`),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){let n=[],r=``,i=0,a=0;for(;ihu)throw Error(`Template contains too many expressions (max ${hu})`);let s=t.slice(i+1,o),c=this.getOperator(s),l=s.includes(`*`),u=this.getNames(s),d=u[0];for(let t of u)e.validateLength(t,mu,`Variable name`);n.push({name:d,operator:c,names:u,exploded:l}),i=o+1}else r+=t[i],i++;return r&&n.push(r),n}getOperator(e){return[`+`,`#`,`.`,`/`,`?`,`&`].find(t=>e.startsWith(t))||``}getNames(e){let t=this.getOperator(e);return e.slice(t.length).split(`,`).map(e=>e.replace(`*`,``).trim()).filter(e=>e.length>0)}encodeValue(t,n){return e.validateLength(t,mu,`Variable value`),n===`+`||n===`#`?encodeURI(t):encodeURIComponent(t)}expandPart(e,t){if(e.operator===`?`||e.operator===`&`){let n=e.names.map(n=>{let r=t[n];return r===void 0?``:`${n}=${Array.isArray(r)?r.map(t=>this.encodeValue(t,e.operator)).join(`,`):this.encodeValue(r.toString(),e.operator)}`}).filter(e=>e.length>0);return n.length===0?``:(e.operator===`?`?`?`:`&`)+n.join(`&`)}if(e.names.length>1){let n=e.names.map(e=>t[e]).filter(e=>e!==void 0);return n.length===0?``:n.map(e=>Array.isArray(e)?e[0]:e).join(`,`)}let n=t[e.name];if(n===void 0)return``;let r=(Array.isArray(n)?n:[n]).map(t=>this.encodeValue(t,e.operator));switch(e.operator){case``:return r.join(`,`);case`+`:return r.join(`,`);case`#`:return`#`+r.join(`,`);case`.`:return`.`+r.join(`.`);case`/`:return`/`+r.join(`/`);default:return r.join(`,`)}}expand(e){let t=``,n=!1;for(let r of this.parts){if(typeof r==`string`){t+=r;continue}let i=this.expandPart(r,e);i&&(t+=(r.operator===`?`||r.operator===`&`)&&n?i.replace(`?`,`&`):i,(r.operator===`?`||r.operator===`&`)&&(n=!0))}return t}escapeRegExp(e){return e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(t){let n=[];for(let n of t.names)e.validateLength(n,mu,`Variable name`);if(t.operator===`?`||t.operator===`&`){for(let e=0;e{this.tasks.delete(i),this.cleanupTimers.delete(i)},a);this.cleanupTimers.set(i,e)}return s}getStoredTask(e,t){let n=this.tasks.get(e);if(n&&!(t!==void 0&&n.sessionId!==void 0&&n.sessionId!==t))return n}async getTask(e,t){let n=this.getStoredTask(e,t);return n?{...n.task}:null}async storeTaskResult(e,t,n,r){let i=this.getStoredTask(e,r);if(!i)throw Error(`Task with ID ${e} not found`);if(Ql(i.task.status))throw Error(`Cannot store result for task ${e} in terminal status '${i.task.status}'. Task results can only be stored once.`);if(i.result=n,i.task.status=t,i.task.lastUpdatedAt=new Date().toISOString(),i.task.ttl){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.tasks.delete(e),this.cleanupTimers.delete(e)},i.task.ttl);this.cleanupTimers.set(e,n)}}async getTaskResult(e,t){let n=this.getStoredTask(e,t);if(!n)throw Error(`Task with ID ${e} not found`);if(!n.result)throw Error(`Task ${e} has no result stored`);return n.result}async updateTaskStatus(e,t,n,r){let i=this.getStoredTask(e,r);if(!i)throw Error(`Task with ID ${e} not found`);if(Ql(i.task.status))throw Error(`Cannot update task ${e} from terminal status '${i.task.status}' to '${t}'. Terminal states (completed, failed, cancelled) cannot transition to other states.`);if(i.task.status=t,n&&(i.task.statusMessage=n),i.task.lastUpdatedAt=new Date().toISOString(),Ql(t)&&i.task.ttl){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.tasks.delete(e),this.cleanupTimers.delete(e)},i.task.ttl);this.cleanupTimers.set(e,n)}}async listTasks(e,t){let n=[...this.tasks.entries()].filter(([,e])=>t===void 0||e.sessionId===void 0?!0:e.sessionId===t).map(([e])=>e),r=0;if(e){let t=n.indexOf(e);if(t===-1)throw Error(`Invalid cursor: ${e}`);r=t+1}let i=n.slice(r,r+10);return{tasks:i.map(e=>({...this.tasks.get(e).task})),nextCursor:r+10({...e.task}))}},bu=class{queues=new Map;getQueueKey(e,t){return e}getQueue(e,t){let n=this.getQueueKey(e,t),r=this.queues.get(n);return r||(r=[],this.queues.set(n,r)),r}async enqueue(e,t,n,r){let i=this.getQueue(e,n);if(r!==void 0&&i.length>=r)throw Error(`Task message queue overflow: queue size (${i.length}) exceeds maximum (${r})`);i.push(t)}async dequeue(e,t){return this.getQueue(e,t).shift()}async dequeueAll(e,t){let n=this.getQueueKey(e,t),r=this.queues.get(n)??[];return this.queues.delete(n),r}},xu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=xu();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),J=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=xu(),n=Su();var r=xu();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return r.Name}});var i=Su();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=se(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=se(this.rhs,e,n),this}get names(){return oe(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=se(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(S(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>ae(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(ce(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=se(this.condition,e,t),this}get names(){let e=super.names;return oe(e,this.condition),this.else&&ae(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=se(this.iteration,e,t),this}get names(){return ae(super.names,this.iteration.names)}},ee=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return oe(oe(super.names,this.from),this.to)}},b=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=se(this.iterable,e,t),this}get names(){return ae(super.names,this.iterable.names)}},x=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};x.kind=`func`;var te=class extends p{render(e){return`return `+super.render(e)}};te.kind=`return`;var ne=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&ae(e,this.catch.names),this.finally&&ae(e,this.finally.names),e}},re=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};re.kind=`catch`;var ie=class extends m{render(e){return`finally`+super.render(e)}};ie.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new ee(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new b(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new b(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new te;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(te)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new ne;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new re(e),t(e)}return n&&(this._currNode=r.finally=new ie,this.code(n)),this._endBlockNode(re,ie)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new x(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(x)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function ae(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function oe(e,n){return n instanceof t._CodeOrName?ae(e,n.names):e}function se(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function S(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function ce(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${me(e)}`}e.not=ce;let le=pe(e.operators.AND);function ue(...e){return e.reduce(le)}e.and=ue;let de=pe(e.operators.OR);function fe(...e){return e.reduce(de)}e.or=fe;function pe(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${me(n)} ${e} ${me(r)}`}function me(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),Y=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=J(),n=xu();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||b(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0?!0:(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function ee(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=ee;function b(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=b})),Cu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=J();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),wu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=J(),n=Y(),r=Cu();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),Tu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=wu(),n=J(),r=Cu(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),Eu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),Du=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),Ou=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=Eu(),n=Du(),r=wu(),i=J(),a=Y();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(c,null);return;case`array`:r.elseIf((0,i._)`${s} === "string" || ${s} === "number" || ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;for(let e in s.number&&delete s.integer,s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),ku=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=J(),n=Y();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),Au=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=J(),n=Y(),r=Cu(),i=Y();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),ju=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=J(),n=Cu(),r=Au(),i=wu();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)ee(),i.modifying&&s(e),b(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),b(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>ee((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),ee(t.nil),e}function ee(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function b(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Mu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=J(),n=Y();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),Nu=l(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),Pu=l(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=Y(),n=Nu(),r=Pu(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),Iu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Tu(),n=Ou(),r=Du(),i=Ou(),a=ku(),o=ju(),s=Mu(),c=J(),l=Cu(),u=Fu(),d=Y(),f=wu();function p(e){if(x(e)&&(ne(e),b(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&S(e),ae(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),re(e),ce(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function ee(e,n){if(x(e)&&(ne(e),b(e))){te(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function b({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function x(e){return typeof e.schema!=`boolean`}function te(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&S(e),oe(e),se(e);let a=r.const(`_errs`,l.default.errors);re(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function ne(e){(0,d.checkUnknownRules)(e),ie(e)}function re(e,t){if(e.opts.jtd)return ue(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);ue(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function ie(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function ae(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function oe(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function se(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function S({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function ce(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&le(e),t.return((0,c._)`${l.default.errors} === 0`))}function le({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function ue(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>be(e,`$ref`,h.all.$ref.definition));return}p.jtd||fe(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),de(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):de(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function de(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&be(e,n.keyword,n.definition,t.type)})}function fe(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(pe(e,t),e.opts.allowUnionTypes||me(e,t),he(e,e.dataTypes))}function pe(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{_e(e.dataTypes,t)||ye(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),ve(e,t)}}function me(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ye(e,`use allowUnionTypes to allow union type keyword`)}function he(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>ge(t,e))&&ye(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function ge(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function _e(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function ve(e,t){let n=[];for(let r of e.dataTypes)_e(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ye(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var C=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,Ce(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return ee(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=C;function be(e,t,n,r){let i=new C(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let xe=/^\/(?:[^~]|~0|~1)*$/,Se=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ce(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!xe.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=Se.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=Ce})),Lu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),Ru=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Fu();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),zu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=J(),n=Lu(),r=Cu(),i=Fu(),a=Y(),o=Iu();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),Bu=l(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),Vu=l(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function i(e){let t=``,n=0,r=0;for(r=0;r=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let a=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function s(e,t,n){if(e.length){let r=i(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function c(e){let t=0,n={error:!1,address:``,zone:``},r=[],a=[],c=!1,l=!1,u=s;for(let i=0;i7){n.error=!0;break}i>0&&e[i-1]===`:`&&(c=!0),r.push(`:`);continue}else if(s===`%`){if(!u(a,r,n))break;u=o}else{a.push(s);continue}}return a.length&&(u===o?n.zone=a.join(``):l?r.push(a.join(``)):r.push(i(a))),n.address=r.join(``),n}function l(e){if(u(e,`:`)<2)return{host:e,isIPV6:!1};let t=c(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function u(e,t){let n=0;for(let r=0;r{let{isUUID:n}=Vu(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=x(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=x(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},y={scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},ee={scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0},b={http:h,https:g,ws:_,wss:v,urn:y,"urn:uuid":ee};Object.setPrototypeOf(b,null);function x(e){return e&&(b[e]||b[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:b,isValidSchemeName:a,getSchemeHandler:x}})),Uu=l(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=Vu(),{SCHEMES:c,getSchemeHandler:l}=Hu();function u(e,t){return typeof e==`string`?e=m(g(e,t),t):typeof e==`object`&&(e=g(m(e,t),t)),e}function d(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=f(g(e,r),g(t,r),r,!0);return r.skipEscape=!0,m(i,r)}function f(e,t,n,i){let a={};return i||(e=g(m(e,n),n),t=g(m(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path=`/`+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:a.path=t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,t.query===void 0?a.query=e.query:a.query=t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function p(e,t,n){return typeof e==`string`?(e=unescape(e),e=m(a(g(e,n),!0),{...n,skipEscape:!0})):typeof e==`object`&&(e=m(a(e,!0),{...n,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=m(a(g(t,n),!0),{...n,skipEscape:!0})):typeof t==`object`&&(t=m(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function m(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},a=Object.assign({},t),o=[],s=l(a.scheme||n.scheme);s&&s.serialize&&s.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),a.reference!==`suffix`&&n.scheme&&o.push(n.scheme,`:`);let c=i(n);if(c!==void 0&&(a.reference!==`suffix`&&o.push(`//`),o.push(c),n.path&&n.path[0]!==`/`&&o.push(`/`)),n.path!==void 0){let e=n.path;!a.absolutePath&&(!s||!s.absolutePath)&&(e=r(e)),c===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),o.push(e)}return n.query!==void 0&&o.push(`?`,n.query),n.fragment!==void 0&&o.push(`#`,n.fragment),o.join(``)}let h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let c=e.match(h);if(c){if(i.scheme=c[1],i.userinfo=c[3],i.host=c[4],i.port=parseInt(c[5],10),i.path=c[6]||``,i.query=c[7],i.fragment=c[8],isNaN(i.port)&&(i.port=c[5]),i.host)if(o(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),a=e.isIPV6}else a=!0;i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?i.reference=`same-document`:i.scheme===void 0?i.reference=`relative`:i.fragment===void 0?i.reference=`absolute`:i.reference=`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let t=l(r.scheme||i.scheme);if(!r.unicodeSupport&&(!t||!t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&a===!1&&s(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=unescape(i.host))),i.path&&=escape(unescape(i.path)),i.fragment&&=encodeURI(decodeURIComponent(i.fragment))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return i}let _={SCHEMES:c,normalize:u,resolve:d,resolveComponent:f,equal:p,serialize:m,parse:g};t.exports=_,t.exports.default=_,t.exports.fastUri=_})),Wu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Uu();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),Gu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Iu();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var n=J();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return n.CodeGen}});let r=Lu(),i=Ru(),a=Eu(),o=zu(),s=J(),c=Fu(),l=Ou(),u=Y(),d=Bu(),f=Wu(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=ae(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),ee.call(this,g,e,`NOT SUPPORTED`),ee.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=re.call(this),e.formats&&te.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&ne.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),x.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=b.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=b.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(se.call(this,n,t),!t)return(0,u.eachItem)(n,e=>S.call(this,e)),this;le.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>S.call(this,e,r):e=>r.type.forEach(t=>S.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=de(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function ee(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function b(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function x(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function te(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function ne(e){if(Array.isArray(e)){this.addVocabulary(e);return}for(let t in this.logger.warn(`keywords option as map is deprecated, pass array`),e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function re(){let e={...this.opts};for(let t of m)delete e[t];return e}let ie={log(){},warn(){},error(){}};function ae(e){if(e===!1)return ie;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let oe=/^[a-z_$][a-z0-9_$:-]*$/i;function se(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!oe.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function S(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?ce.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function ce(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function le(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=de(t)),e.validateSchema=this.compile(t,!0))}let ue={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function de(e){return{anyOf:[e,ue]}}})),Ku=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),qu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=Ru(),n=Au(),r=J(),i=Cu(),a=zu(),o=Y(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);if(h instanceof a.SchemaEnv)return _(h);return v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0)if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}if(l.items!==!0)if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}e.callRef=l,e.default=s})),Ju=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ku(),n=qu();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),Yu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=J(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),Xu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=J();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),Zu=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r=55296&&i<=56319&&r{Object.defineProperty(e,`__esModule`,{value:!0});let t=J(),n=Y(),r=Zu();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),$u=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Au(),n=Y(),r=J();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),ed=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=J();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),td=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Au(),n=J(),r=Y();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),nd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=J();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),rd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Nu();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),id=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ou(),n=J(),r=Y(),i=rd();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),ad=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=J(),n=Y(),r=rd();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),od=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=J(),n=Y(),r=rd();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),sd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Yu(),n=Xu(),r=Qu(),i=$u(),a=ed(),o=td(),s=nd(),c=id(),l=ad(),u=od();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),cd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=J(),n=Y(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),ld=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=J(),n=Y(),r=Au(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),ud=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=ld();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),dd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=J(),n=Y(),r=Au(),i=cd();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),fd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=J(),n=Y();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),pd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=J(),n=Y(),r=Au();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e}, missingProperty: ${i}, depsCount: ${n}, deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),md=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=J(),n=Y();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),hd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Au(),n=J(),r=Cu(),i=Y();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),gd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Iu(),n=Au(),r=Y(),i=hd();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),_d=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Au(),n=J(),r=Y(),i=Y();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),vd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Y();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),yd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Au().validateUnion,error:{message:`must match a schema in anyOf`}}})),bd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=J(),n=Y();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),xd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Y();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),Sd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=J(),n=Y(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),Cd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Y();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),wd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=cd(),n=ud(),r=ld(),i=dd(),a=fd(),o=pd(),s=md(),c=hd(),l=gd(),u=_d(),d=vd(),f=yd(),p=bd(),m=xd(),h=Sd(),g=Cd();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),Td=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=J();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),Ed=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[Td().default]})),Dd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),Od=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Ju(),n=sd(),r=wd(),i=Ed(),a=Dd();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),kd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),Ad=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=J(),n=kd(),r=zu(),i=Ru(),a=Y();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();for(let e in o.if(!1),r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),Md=l(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=Gu(),r=Od(),i=Ad(),a=jd(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=c;var l=Iu();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=J();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,`CodeGen`,{enumerable:!0,get:function(){return u.CodeGen}});var d=Lu();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=Ru();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),Nd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:ie,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:x},int64:{type:`number`,validate:te},float:{type:`number`,validate:ne},double:{type:`number`,validate:ne},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e=ee}function te(e){return Number.isInteger(e)}function ne(){return!0}let re=/[^\\]\\Z/;function ie(e){if(re.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Pd=l((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=Md(),n=J(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),Fd=l(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=Nd(),r=Pd(),i=J(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,`__esModule`,{value:!0}),e.default=s})),Id=Md(),Ld=d(Fd(),1);function Rd(){let e=new Id.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ld.default)(e),e}var zd=class{_ajv;constructor(e){this._ajv=e??Rd()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}};let Bd;Bd=globalThis.crypto?.webcrypto??globalThis.crypto??import(`node:crypto`).then(e=>e.webcrypto);async function Vd(e){return(await Bd).getRandomValues(new Uint8Array(e))}async function Hd(e){let t=``;for(;t.length128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Ud(e);return{code_verifier:t,code_challenge:await Wd(t)}}function Kd(e){if(e==null)return!1;let t=e;return typeof t.tokens==`function`&&typeof t.clientInformation==`function`}async function qd(e,t){let{resourceMetadataUrl:n,scope:r}=df(t.response);if(await of(e,{serverUrl:t.serverUrl,resourceMetadataUrl:n,scope:r,fetchFn:t.fetchFn})!==`AUTHORIZED`)throw new Yd}function Jd(e){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async t=>qd(e,t)}}var Yd=class extends Error{constructor(e){super(e??`Unauthorized`)}};function Xd(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}const Zd=`code`,Qd=`S256`;function $d(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&Xd(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function ef(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:tf(i,a,n);return;case`client_secret_post`:nf(i,a,r);return;case`none`:rf(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function tf(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function nf(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function rf(e,t){t.set(`client_id`,e)}async function af(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let e=Ro.parse(JSON.parse(n));return m.fromResponse(e)}catch(e){let r=`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`;return new m(p.ServerError,r)}}async function of(e,t){try{return await cf(e,t)}catch(n){if(n instanceof m){if(n.code===p.InvalidClient||n.code===p.UnauthorizedClient)return await e.invalidateCredentials?.(`all`),await cf(e,t);if(n.code===p.InvalidGrant)return await e.invalidateCredentials?.(`tokens`),await cf(e,t)}throw n}}function sf(e){let{requestedScope:t,resourceMetadata:n,authServerMetadata:r,clientMetadata:i}=e,a=t||n?.scopes_supported?.join(` `)||i.scope;return a&&r?.scopes_supported?.includes(`offline_access`)&&!a.split(` `).includes(`offline_access`)&&i.grant_types?.includes(`refresh_token`)&&(a=`${a} offline_access`),a}async function cf(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o=await e.discoveryState?.(),s,c,l,u=i;if(!u&&o?.resourceMetadataUrl&&(u=new URL(o.resourceMetadataUrl)),o?.authorizationServerUrl){if(c=o.authorizationServerUrl,s=o.resourceMetadata,l=o.authorizationServerMetadata??await Sf(c,{fetchFn:a}),!s)try{s=await mf(t,{resourceMetadataUrl:u},a)}catch(e){if(e instanceof TypeError)throw e}(l!==o.authorizationServerMetadata||s!==o.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let n=await Cf(t,{resourceMetadataUrl:u,fetchFn:a});c=n.authorizationServerUrl,l=n.authorizationServerMetadata,s=n.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}await e.saveAuthorizationServerUrl?.(String(c));let d=await uf(t,e,s);d&&await e.saveResourceUrl?.(String(d));let f=sf({requestedScope:r,resourceMetadata:s,authServerMetadata:l,clientMetadata:e.clientMetadata}),h=await Promise.resolve(e.clientInformation());if(!h){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=l?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!lf(r))throw new m(p.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)h={client_id:r},await e.saveClientInformation?.(h);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await Af(c,{metadata:l,clientMetadata:e.clientMetadata,scope:f,fetchFn:a});await e.saveClientInformation(t),h=t}}let g=!e.redirectUrl;if(n!==void 0||g){let t=await kf(e,c,{metadata:l,resource:d,authorizationCode:n,scope:f,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}let _=await e.tokens();if(_?.refresh_token)try{let t=await Of(c,{metadata:l,clientInformation:h,refreshToken:_.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof m)||e.code===p.ServerError))throw e}let v=e.state?await e.state():void 0,{authorizationUrl:y,codeVerifier:ee}=await wf(c,{metadata:l,clientInformation:h,state:v,redirectUrl:e.redirectUrl,scope:f,resource:d});return await e.saveCodeVerifier(ee),await e.redirectToAuthorization(y),`REDIRECT`}function lf(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function uf(e,t,n){let r=Uo(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!Wo({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function df(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n?.toLowerCase()!==`bearer`||!r)return{};let i=ff(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=ff(e,`scope`)||void 0,s=ff(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function ff(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),i=n.match(r);if(i){let e=i[1]||i[2];if(e)return e}return null}function pf(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return;let[n,r]=t.split(` `);if(n?.toLowerCase()!==`bearer`||!r)return;let i=/resource_metadata="([^"]*)"/.exec(t);if(!(!i||!i[1]))try{return new URL(i[1])}catch{return}}async function mf(e,t,n=fetch){let r=await yf(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.text?.().catch(()=>{}),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.text?.().catch(()=>{}),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return Po.parse(await r.json())}async function hf(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(!(r instanceof TypeError)||!0)throw r;if(t)try{return await n(e,{})}catch(e){if(!(e instanceof TypeError))throw e;return}return}}function gf(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function _f(e,t,n=fetch){return await hf(e,{"MCP-Protocol-Version":t},n)}function vf(e,t){return e?t===`/`?!1:e.status>=400&&e.status<500||e.status===502:!0}async function yf(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??Ko,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=gf(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await _f(o,a,n);return!r?.metadataUrl&&vf(s,i.pathname)&&(s=await _f(new URL(`/.well-known/${t}`,i),a,n)),s}async function bf(e,{authorizationServerUrl:t,protocolVersion:n}={},r=fetch){typeof e==`string`&&(e=new URL(e)),t||=e,typeof t==`string`&&(t=new URL(t)),n??=Ko;let i=await yf(t,`oauth-authorization-server`,r,{protocolVersion:n,metadataServerUrl:t});if(!i||i.status===404){await i?.text?.().catch(()=>{});return}if(!i.ok)throw await i.text?.().catch(()=>{}),Error(`HTTP ${i.status} trying to load well-known OAuth metadata`);return Fo.parse(await i.json())}function xf(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`},{url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`},{url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`},{url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function Sf(e,{fetchFn:t=fetch,protocolVersion:n=Ko}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=xf(e);for(let{url:e,type:n}of i){let i=await hf(e,r,t);if(i){if(!i.ok){if(await i.text?.().catch(()=>{}),i.status>=400&&i.status<500||i.status===502)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?Fo.parse(await i.json()):Io.parse(await i.json())}}}async function Cf(e,t){let n,r;try{n=await mf(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch(e){if(e instanceof TypeError)throw e}r||=String(new URL(`/`,e));let i=await Sf(r,{fetchFn:t?.fetchFn});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}async function wf(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Zd))throw Error(`Incompatible auth server: does not support response type ${Zd}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Qd))throw Error(`Incompatible auth server: does not support code challenge method ${Qd}`)}else s=new URL(`/authorize`,e);let c=await Gd(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,Zd),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,Qd),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.split(` `).includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function Tf(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function Ef(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&ef($d(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await af(l);let u=await l.json();try{return Lo.parse(u)}catch(e){throw typeof u==`object`&&u&&`error`in u?await af(JSON.stringify(u)):e}}async function Df(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){return Ef(e,{metadata:t,tokenRequestParams:Tf(r,i,a),clientInformation:n,addClientAuthentication:s,resource:o,fetchFn:c})}async function Of(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await Ef(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function kf(e,t,{metadata:n,resource:r,authorizationCode:i,scope:a,fetchFn:o}={}){let s=a??e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(s)),!c){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);c=Tf(i,await e.codeVerifier(),e.redirectUrl)}let l=await e.clientInformation();return Ef(t,{metadata:n,tokenRequestParams:c,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:o})}async function Af(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o=await(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...n,...r===void 0?{}:{scope:r}})});if(!o.ok)throw await af(o);return Ho.parse(await o.json())}async function jf(e,{metadata:t,clientInformation:n,refreshToken:r,accessToken:i,addClientAuthentication:a,fetchFn:o}){let s=t??await Sf(e,{fetchFn:o}),c=s&&`revocation_endpoint`in s?s.revocation_endpoint:void 0;if(!c)return;let l=new URL(c),u=async(e,t)=>{let r=new URLSearchParams({token:e,token_type_hint:t}),i=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a?await a(i,r,l,s):n&&ef($d(n,(s&&`revocation_endpoint_auth_methods_supported`in s?s.revocation_endpoint_auth_methods_supported:void 0)??s?.token_endpoint_auth_methods_supported??[]),n,i,r);let c=await(o??fetch)(l,{method:`POST`,headers:i,body:r});if(!c.ok&&c.status!==400)throw await af(c)};r&&await u(r,`refresh_token`),i&&await u(i,`access_token`)}var Mf=class{constructor(e){this._client=e}get _module(){return this._client.taskManager}async*callToolStream(e,t){let n=this._client,r={...t,task:t?.task??(n.isToolTask(e.name)?{}:void 0)},i=this._module.requestStream({method:`tools/call`,params:e},Wc,r),a=n.getToolOutputValidator(e.name);for await(let t of i){if(t.type===`result`&&a&&`content`in t.result){let n=t.result;if(!n.structuredContent&&!n.isError){yield{type:`error`,error:new W(U.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(n.structuredContent)try{let e=a(n.structuredContent);if(!e.valid){yield{type:`error`,error:new W(U.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)};return}}catch(e){if(e instanceof W){yield{type:`error`,error:e};return}yield{type:`error`,error:new W(U.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)};return}}yield t}}async getTask(e,t){return this._module.getTask({taskId:e},t)}async getTaskResult(e,t){return this._module.getTaskResult({taskId:e},Ys,t)}async listTasks(e,t){return this._module.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._module.cancelTask({taskId:e},t)}requestStream(e,t){let n=Fl(e.method);return this._module.requestStream(e,n,t)}};function Nf(e,t){if(!(!e||typeof t!=`object`||!t)){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&Nf(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&Nf(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&Nf(n,t)}}function Pf(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var Ff=class extends ru{_serverCapabilities;_serverVersion;_negotiatedProtocolVersion;_capabilities;_instructions;_jsonSchemaValidator;_cachedToolOutputValidators=new Map;_cachedKnownTaskTools=new Set;_cachedRequiredTaskTools=new Set;_experimental;_listChangedDebounceTimers=new Map;_pendingListChangedConfig;_enforceStrictCapabilities;constructor(e,t){if(super({...t,tasks:$l(t?.capabilities?.tasks)}),this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new zd,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,t?.capabilities?.tasks){let{taskStore:e,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i,...a}=t.capabilities.tasks;this._capabilities.tasks=a}t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}buildContext(e,t){return e}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,`notifications/tools/list_changed`,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,`notifications/prompts/list_changed`,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,`notifications/resources/list_changed`,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||={tasks:new Mf(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=au(this._capabilities,e)}setRequestHandler(e,t){return e===`elicitation/create`?super.setRequestHandler(e,async(e,n)=>{let r=Zl(_l,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new W(U.InvalidParams,`Invalid elicitation request: ${e}`)}let{params:i}=r.data;i.mode=i.mode??`form`;let{supportsFormMode:a,supportsUrlMode:o}=Pf(this._capabilities.elicitation);if(i.mode===`form`&&!a)throw new W(U.InvalidParams,`Client does not support form-mode elicitation requests`);if(i.mode===`url`&&!o)throw new W(U.InvalidParams,`Client does not support URL-mode elicitation requests`);let s=await Promise.resolve(t(e,n));if(i.task){let e=Zl(Us,s);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new W(U.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let c=Zl(bl,s);if(!c.success){let e=c.error instanceof Error?c.error.message:String(c.error);throw new W(U.InvalidParams,`Invalid elicitation result: ${e}`)}let l=c.data,u=i.mode===`form`?i.requestedSchema:void 0;if(i.mode===`form`&&l.action===`accept`&&l.content&&u&&this._capabilities.elicitation?.form?.applyDefaults)try{Nf(u,l.content)}catch{}return l}):e===`sampling/createMessage`?super.setRequestHandler(e,async(e,n)=>{let r=Zl(sl,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new W(U.InvalidParams,`Invalid sampling request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=Zl(Us,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new W(U.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=Zl(i.tools||i.toolChoice?ll:cl,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new W(U.InvalidParams,`Invalid sampling result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new g(h.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await this.internal_connect(e),e.sessionId!==void 0){this._negotiatedProtocolVersion!==void 0&&e.setProtocolVersion&&e.setProtocolVersion(this._negotiatedProtocolVersion);return}await this.internal_start(e,t)}async internal_connect(e){await super.connect(e)}async internal_start(e,t){try{let n=await this._requestWithSchema({method:`initialize`,params:{protocolVersion:this._supportedProtocolVersions[0]??Ko,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ms,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);if(!this._supportedProtocolVersions.includes(n.protocolVersion))throw Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,this._negotiatedProtocolVersion=n.protocolVersion,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:`notifications/initialized`}),this._pendingListChangedConfig&&=(this._setupListChangedHandlers(this._pendingListChangedConfig),void 0)}catch(e){throw this.close(),e}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw new g(h.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw new g(h.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw new g(h.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw new g(h.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw new g(h.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw new g(h.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`initialize`:break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/roots/list_changed`:if(!this._capabilities.roots?.listChanged)throw new g(h.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case`notifications/initialized`:break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw new g(h.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw new g(h.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw new g(h.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case`ping`:break}}assertTaskCapability(e){_u(this._serverCapabilities?.tasks?.requests,e,`Server`)}assertTaskHandlerCapability(e){vu(this._capabilities?.tasks?.requests,e,`Client`)}async ping(e){return this._requestWithSchema({method:`ping`},ys,e)}async complete(e,t){return this._requestWithSchema({method:`completion/complete`,params:e},Tl,t)}async setLoggingLevel(e,t){return this._requestWithSchema({method:`logging/setLevel`,params:{level:e}},ys,t)}async getPrompt(e,t){return this._requestWithSchema({method:`prompts/get`,params:e},Lc,t)}async listPrompts(e,t){return!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities?(console.debug(`Client.listPrompts() called but server does not advertise prompts capability - returning empty list`),{prompts:[]}):this._requestWithSchema({method:`prompts/list`,params:e},Ec,t)}async listResources(e,t){return!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities?(console.debug(`Client.listResources() called but server does not advertise resources capability - returning empty list`),{resources:[]}):this._requestWithSchema({method:`resources/list`,params:e},lc,t)}async listResourceTemplates(e,t){return!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities?(console.debug(`Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list`),{resourceTemplates:[]}):this._requestWithSchema({method:`resources/templates/list`,params:e},dc,t)}async readResource(e,t){return this._requestWithSchema({method:`resources/read`,params:e},hc,t)}async subscribeResource(e,t){return this._requestWithSchema({method:`resources/subscribe`,params:e},ys,t)}async unsubscribeResource(e,t){return this._requestWithSchema({method:`resources/unsubscribe`,params:e},ys,t)}async callTool(e,t){if(this.isToolTaskRequired(e.name))throw new W(U.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let n=await this._requestWithSchema({method:`tools/call`,params:e},Wc,t),r=this.getToolOutputValidator(e.name);if(r){if(!n.structuredContent&&!n.isError)throw new W(U.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{let e=r(n.structuredContent);if(!e.valid)throw new W(U.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof W?e:new W(U.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return n}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let t of e){if(t.outputSchema){let e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}let e=t.execution?.taskSupport;(e===`required`||e===`optional`)&&this._cachedKnownTaskTools.add(t.name),e===`required`&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug(`Client.listTools() called but server does not advertise tools capability - returning empty list`),{tools:[]};let n=await this._requestWithSchema({method:`tools/list`,params:e},Uc,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,r){let i=Zl(Jc,n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{s(null,await r())}catch(e){s(e instanceof Error?e:Error(String(e)),null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}},If=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function Lf(e){}function Rf(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Lf,onError:n=Lf,onRetry:r=Lf,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=zf(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1;f(n,e.slice(t+r),e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t} `;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new If(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new If(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(` `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function zf(e){let t=[],n=``,r=0;for(;r{throw TypeError(e)},Gf=(e,t,n)=>t.has(e)||Wf(`Cannot `+n),X=(e,t,n)=>(Gf(e,t,`read from private field`),n?n.call(e):t.get(e)),Z=(e,t,n)=>t.has(e)?Wf(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),Q=(e,t,n,r)=>(Gf(e,t,`write to private field`),t.set(e,n),n),Kf=(e,t,n)=>(Gf(e,t,`access private method`),n),$,qf,Jf,Yf,Xf,Zf,Qf,$f,ep,tp,np,rp,ip,ap,op,sp,cp,lp,up,dp,fp,pp,mp,hp=class extends EventTarget{constructor(e,t){super(),Z(this,ap),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Z(this,$),Z(this,qf),Z(this,Jf),Z(this,Yf),Z(this,Xf),Z(this,Zf),Z(this,Qf),Z(this,$f,null),Z(this,ep),Z(this,tp),Z(this,np,null),Z(this,rp,null),Z(this,ip,null),Z(this,sp,async e=>{var t;X(this,tp).reset();let{body:n,redirected:r,status:i,headers:a}=e;if(i===204){Kf(this,ap,fp).call(this,`Server sent HTTP 204, not reconnecting`,204),this.close();return}if(r?Q(this,Jf,new URL(e.url)):Q(this,Jf,void 0),i!==200){Kf(this,ap,fp).call(this,`Non-200 status code (${i})`,i);return}if(!(a.get(`content-type`)||``).startsWith(`text/event-stream`)){Kf(this,ap,fp).call(this,`Invalid content type, expected "text/event-stream"`,i);return}if(X(this,$)===this.CLOSED)return;Q(this,$,this.OPEN);let o=new Event(`open`);if((t=X(this,ip))==null||t.call(this,o),this.dispatchEvent(o),typeof n!=`object`||!n||!(`getReader`in n)){Kf(this,ap,fp).call(this,`Invalid response body, expected a web ReadableStream`,i),this.close();return}let s=new TextDecoder,c=n.getReader(),l=!0;do{let{done:e,value:t}=await c.read();t&&X(this,tp).feed(s.decode(t,{stream:!e})),e&&(l=!1,X(this,tp).reset(),Kf(this,ap,pp).call(this))}while(l)}),Z(this,cp,e=>{Q(this,ep,void 0),!(e.name===`AbortError`||e.type===`aborted`)&&Kf(this,ap,pp).call(this,Hf(e))}),Z(this,up,e=>{typeof e.id==`string`&&Q(this,$f,e.id);let t=new MessageEvent(e.event||`message`,{data:e.data,origin:X(this,Jf)?X(this,Jf).origin:X(this,qf).origin,lastEventId:e.id||``});X(this,rp)&&(!e.event||e.event===`message`)&&X(this,rp).call(this,t),this.dispatchEvent(t)}),Z(this,dp,e=>{Q(this,Zf,e)}),Z(this,mp,()=>{Q(this,Qf,void 0),X(this,$)===this.CONNECTING&&Kf(this,ap,op).call(this)});try{if(e instanceof URL)Q(this,qf,e);else if(typeof e==`string`)Q(this,qf,new URL(e,gp()));else throw Error(`Invalid URL`)}catch{throw Vf(`An invalid or illegal string was specified`)}Q(this,tp,Rf({onEvent:X(this,up),onRetry:X(this,dp)})),Q(this,$,this.CONNECTING),Q(this,Zf,3e3),Q(this,Xf,t?.fetch??globalThis.fetch),Q(this,Yf,t?.withCredentials??!1),Kf(this,ap,op).call(this)}get readyState(){return X(this,$)}get url(){return X(this,qf).href}get withCredentials(){return X(this,Yf)}get onerror(){return X(this,np)}set onerror(e){Q(this,np,e)}get onmessage(){return X(this,rp)}set onmessage(e){Q(this,rp,e)}get onopen(){return X(this,ip)}set onopen(e){Q(this,ip,e)}addEventListener(e,t,n){let r=t;super.addEventListener(e,r,n)}removeEventListener(e,t,n){let r=t;super.removeEventListener(e,r,n)}close(){X(this,Qf)&&clearTimeout(X(this,Qf)),X(this,$)!==this.CLOSED&&(X(this,ep)&&X(this,ep).abort(),Q(this,$,this.CLOSED),Q(this,ep,void 0))}};$=new WeakMap,qf=new WeakMap,Jf=new WeakMap,Yf=new WeakMap,Xf=new WeakMap,Zf=new WeakMap,Qf=new WeakMap,$f=new WeakMap,ep=new WeakMap,tp=new WeakMap,np=new WeakMap,rp=new WeakMap,ip=new WeakMap,ap=new WeakSet,op=function(){Q(this,$,this.CONNECTING),Q(this,ep,new AbortController),X(this,Xf)(X(this,qf),Kf(this,ap,lp).call(this)).then(X(this,sp)).catch(X(this,cp))},sp=new WeakMap,cp=new WeakMap,lp=function(){let e={mode:`cors`,redirect:`follow`,headers:{Accept:`text/event-stream`,...X(this,$f)?{"Last-Event-ID":X(this,$f)}:void 0},cache:`no-store`,signal:X(this,ep)?.signal};return`window`in globalThis&&(e.credentials=this.withCredentials?`include`:`same-origin`),e},up=new WeakMap,dp=new WeakMap,fp=function(e,t){var n;X(this,$)!==this.CLOSED&&Q(this,$,this.CLOSED);let r=new Bf(`error`,{code:t,message:e});(n=X(this,np))==null||n.call(this,r),this.dispatchEvent(r)},pp=function(e,t){var n;if(X(this,$)===this.CLOSED)return;Q(this,$,this.CONNECTING);let r=new Bf(`error`,{code:t,message:e});(n=X(this,np))==null||n.call(this,r),this.dispatchEvent(r),Q(this,Qf,setTimeout(X(this,mp),X(this,Zf)))},mp=new WeakMap,hp.CONNECTING=0,hp.OPEN=1,hp.CLOSED=2;function gp(){let e=`document`in globalThis?globalThis.document:void 0;return e&&typeof e==`object`&&`baseURI`in e&&typeof e.baseURI==`string`?e.baseURI:void 0}var _p=class extends Error{constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n}},vp=class{_eventSource;_endpoint;_abortController;_url;_resourceMetadataUrl;_scope;_eventSourceInit;_requestInit;_authProvider;_oauthProvider;_fetch;_fetchWithInit;_protocolVersion;onclose;onerror;onmessage;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,Kd(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=Jd(t.authProvider)):this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=fu(t?.fetch,t?.requestInit)}_last401Response;async _commonHeaders(){let e={},t=await this._authProvider?.token();t&&(e.Authorization=`Bearer ${t}`),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let n=du(this._requestInit?.headers);return new Headers({...e,...n})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((t,n)=>{this._eventSource=new hp(this._url.href,{...this._eventSourceInit,fetch:async(t,n)=>{let r=await this._commonHeaders();r.set(`Accept`,`text/event-stream`);let i=await e(t,{...n,headers:r});if(i.status===401&&(this._last401Response=i,i.headers.has(`www-authenticate`))){let{resourceMetadataUrl:e,scope:t}=df(i);this._resourceMetadataUrl=e,this._scope=t}return i}}),this._abortController=new AbortController,this._eventSource.onerror=e=>{if(e.code===401&&this._authProvider){if(this._authProvider.onUnauthorized&&this._last401Response){let e=this._last401Response;this._last401Response=void 0,this._eventSource?.close(),this._authProvider.onUnauthorized({response:e,serverUrl:this._url,fetchFn:this._fetchWithInit}).then(()=>this._startOrAuth().then(t,n),e=>{this.onerror?.(e),n(e)});return}let e=new Yd;n(e),this.onerror?.(e);return}let r=new _p(e.code,e.message,e);n(r),this.onerror?.(r)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener(`endpoint`,e=>{let r=e;try{if(this._endpoint=new URL(r.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){n(e),this.onerror?.(e),this.close();return}t()}),this._eventSource.onmessage=e=>{let t=e,n;try{n=vs.parse(JSON.parse(t.data))}catch(e){this.onerror?.(e);return}this.onmessage?.(n)}})}async start(){if(this._eventSource)throw Error(`SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return await this._startOrAuth()}async finishAuth(e){if(!this._oauthProvider)throw new Yd(`finishAuth requires an OAuthClientProvider`);if(await of(this._oauthProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Yd(`Failed to authorize`)}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){return this._send(e,!1)}async _send(e,t){if(!this._endpoint)throw new g(h.NotConnected,`Not connected`);try{let n=await this._commonHeaders();n.set(`content-type`,`application/json`);let r={...this._requestInit,method:`POST`,headers:n,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._endpoint,r);if(!i.ok){if(i.status===401&&this._authProvider){if(i.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=df(i);this._resourceMetadataUrl=e,this._scope=t}if(this._authProvider.onUnauthorized&&!t)return await this._authProvider.onUnauthorized({response:i,serverUrl:this._url,fetchFn:this._fetchWithInit}),await i.text?.().catch(()=>{}),this._send(e,!0);throw await i.text?.().catch(()=>{}),t?new g(h.ClientHttpAuthentication,`Server returned 401 after re-authentication`,{status:401}):new Yd}let n=await i.text?.().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${i.status}): ${n}`)}await i.text?.().catch(()=>{})}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}},yp=l(((e,t)=>{t.exports=a,a.sync=o;var n=f(`fs`);function r(e,t){var n=t.pathExt===void 0?process.env.PATHEXT:t.pathExt;if(!n||(n=n.split(`;`),n.indexOf(``)!==-1))return!0;for(var r=0;r{t.exports=r,r.sync=i;var n=f(`fs`);function r(e,t,r){n.stat(e,function(e,n){r(e,e?!1:a(n,t))})}function i(e,t){return a(n.statSync(e),t)}function a(e,t){return e.isFile()&&o(e,t)}function o(e,t){var n=e.mode,r=e.uid,i=e.gid,a=t.uid===void 0?process.getuid&&process.getuid():t.uid,o=t.gid===void 0?process.getgid&&process.getgid():t.gid,s=64,c=8,l=1,u=s|c;return n&l||n&c&&i===o||n&s&&r===a||n&u&&a===0}})),xp=l(((e,t)=>{f(`fs`);var n=process.platform===`win32`||global.TESTING_WINDOWS?yp():bp();t.exports=r,r.sync=i;function r(e,t,i){if(typeof t==`function`&&(i=t,t={}),!i){if(typeof Promise!=`function`)throw TypeError(`callback not provided`);return new Promise(function(n,i){r(e,t||{},function(e,t){e?i(e):n(t)})})}n(e,t||{},function(e,n){e&&(e.code===`EACCES`||t&&t.ignoreErrors)&&(e=null,n=!1),i(e,n)})}function i(e,t){try{return n.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||e.code===`EACCES`)return!1;throw e}}})),Sp=l(((e,t)=>{let n=process.platform===`win32`||process.env.OSTYPE===`cygwin`||process.env.OSTYPE===`msys`,r=f(`path`),i=n?`;`:`:`,a=xp(),o=e=>Object.assign(Error(`not found: ${e}`),{code:`ENOENT`}),s=(e,t)=>{let r=t.colon||i,a=e.match(/\//)||n&&e.match(/\\/)?[``]:[...n?[process.cwd()]:[],...(t.path||process.env.PATH||``).split(r)],o=n?t.pathExt||process.env.PATHEXT||`.EXE;.CMD;.BAT;.COM`:``,s=n?o.split(r):[``];return n&&e.indexOf(`.`)!==-1&&s[0]!==``&&s.unshift(``),{pathEnv:a,pathExt:s,pathExtExe:o}},c=(e,t,n)=>{typeof t==`function`&&(n=t,t={}),t||={};let{pathEnv:i,pathExt:c,pathExtExe:l}=s(e,t),u=[],d=n=>new Promise((a,s)=>{if(n===i.length)return t.all&&u.length?a(u):s(o(e));let c=i[n],l=/^".*"$/.test(c)?c.slice(1,-1):c,d=r.join(l,e);a(f(!l&&/^\.[\\\/]/.test(e)?e.slice(0,2)+d:d,n,0))}),f=(e,n,r)=>new Promise((i,o)=>{if(r===c.length)return i(d(n+1));let s=c[r];a(e+s,{pathExt:l},(a,o)=>{if(!a&&o)if(t.all)u.push(e+s);else return i(e+s);return i(f(e,n,r+1))})});return n?d(0).then(e=>n(null,e),n):d(0)};t.exports=c,c.sync=(e,t)=>{t||={};let{pathEnv:n,pathExt:i,pathExtExe:c}=s(e,t),l=[];for(let o=0;o{let n=(e={})=>{let t=e.env||process.env;return(e.platform||process.platform)===`win32`?Object.keys(t).reverse().find(e=>e.toUpperCase()===`PATH`)||`Path`:`PATH`};t.exports=n,t.exports.default=n})),wp=l(((e,t)=>{let n=f(`path`),r=Sp(),i=Cp();function a(e,t){let a=e.options.env||process.env,o=process.cwd(),s=e.options.cwd!=null,c=s&&process.chdir!==void 0&&!process.chdir.disabled;if(c)try{process.chdir(e.options.cwd)}catch{}let l;try{l=r.sync(e.command,{path:a[i({env:a})],pathExt:t?n.delimiter:void 0})}catch{}finally{c&&process.chdir(o)}return l&&=n.resolve(s?e.options.cwd:``,l),l}function o(e){return a(e)||a(e,!0)}t.exports=o})),Tp=l(((e,t)=>{let n=/([()\][%!^"`<>&|;, *?])/g;function r(e){return e=e.replace(n,`^$1`),e}function i(e,t){return e=`${e}`,e=e.replace(/(?=(\\+?)?)\1"/g,`$1$1\\"`),e=e.replace(/(?=(\\+?)?)\1$/,`$1$1`),e=`"${e}"`,e=e.replace(n,`^$1`),t&&(e=e.replace(n,`^$1`)),e}t.exports.command=r,t.exports.argument=i})),Ep=l(((e,t)=>{t.exports=/^#!(.*)/})),Dp=l(((e,t)=>{let n=Ep();t.exports=(e=``)=>{let t=e.match(n);if(!t)return null;let[r,i]=t[0].replace(/#! ?/,``).split(` `),a=r.split(`/`).pop();return a===`env`?i:i?`${a} ${i}`:a}})),Op=l(((e,t)=>{let n=f(`fs`),r=Dp();function i(e){let t=Buffer.alloc(150),i;try{i=n.openSync(e,`r`),n.readSync(i,t,0,150,0),n.closeSync(i)}catch{}return r(t.toString())}t.exports=i})),kp=l(((e,t)=>{let n=f(`path`),r=wp(),i=Tp(),a=Op(),o=process.platform===`win32`,s=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(e){e.file=r(e);let t=e.file&&a(e.file);return t?(e.args.unshift(e.file),e.command=t,r(e)):e.file}function u(e){if(!o)return e;let t=l(e),r=!s.test(t);if(e.options.forceShell||r){let r=c.test(t);e.command=n.normalize(e.command),e.command=i.command(e.command),e.args=e.args.map(e=>i.argument(e,r)),e.args=[`/d`,`/s`,`/c`,`"${[e.command].concat(e.args).join(` `)}"`],e.command=process.env.comspec||`cmd.exe`,e.options.windowsVerbatimArguments=!0}return e}function d(e,t,n){t&&!Array.isArray(t)&&(n=t,t=null),t=t?t.slice(0):[],n=Object.assign({},n);let r={command:e,args:t,options:n,file:void 0,original:{command:e,args:t}};return n.shell?r:u(r)}t.exports=d})),Ap=l(((e,t)=>{let n=process.platform===`win32`;function r(e,t){return Object.assign(Error(`${t} ${e.command} ENOENT`),{code:`ENOENT`,errno:`ENOENT`,syscall:`${t} ${e.command}`,path:e.command,spawnargs:e.args})}function i(e,t){if(!n)return;let r=e.emit;e.emit=function(n,i){if(n===`exit`){let n=a(i,t);if(n)return r.call(e,`error`,n)}return r.apply(e,arguments)}}function a(e,t){return n&&e===1&&!t.file?r(t.original,`spawn`):null}function o(e,t){return n&&e===1&&!t.file?r(t.original,`spawnSync`):null}t.exports={hookChildProcess:i,verifyENOENT:a,verifyENOENTSync:o,notFoundError:r}})),jp=d(l(((e,t)=>{let n=f(`child_process`),r=kp(),i=Ap();function a(e,t,a){let o=r(e,t,a),s=n.spawn(o.command,o.args,o.options);return i.hookChildProcess(s,o),s}function o(e,t,a){let o=r(e,t,a),s=n.spawnSync(o.command,o.args,o.options);return s.error=s.error||i.verifyENOENTSync(s.status,o),s}t.exports=a,t.exports.spawn=a,t.exports.sync=o,t.exports._parse=r,t.exports._enoent=i}))());const Mp=t.platform===`win32`?[`APPDATA`,`HOMEDRIVE`,`HOMEPATH`,`LOCALAPPDATA`,`PATH`,`PROCESSOR_ARCHITECTURE`,`SYSTEMDRIVE`,`SYSTEMROOT`,`TEMP`,`USERNAME`,`USERPROFILE`,`PROGRAMFILES`]:[`HOME`,`LOGNAME`,`PATH`,`SHELL`,`TERM`,`USER`];function Np(){let e={};for(let n of Mp){let r=t.env[n];r!==void 0&&(r.startsWith(`()`)||(e[n]=r))}return e}var Pp=class{_process;_readBuffer=new cu;_serverParams;_stderrStream=null;onclose;onerror;onmessage;constructor(e){this._serverParams=e,(e.stderr===`pipe`||e.stderr===`overlapped`)&&(this._stderrStream=new n)}async start(){if(this._process)throw Error(`StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.`);return new Promise((e,n)=>{this._process=(0,jp.default)(this._serverParams.command,this._serverParams.args??[],{env:{...Np(),...this._serverParams.env},stdio:[`pipe`,`pipe`,this._serverParams.stderr??`inherit`],shell:!1,windowsHide:t.platform===`win32`,cwd:this._serverParams.cwd}),this._process.on(`error`,e=>{n(e),this.onerror?.(e)}),this._process.on(`spawn`,()=>{e()}),this._process.on(`close`,e=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on(`error`,e=>{this.onerror?.(e)}),this._process.stdout?.on(`data`,e=>{this._readBuffer.append(e),this.processReadBuffer()}),this._process.stdout?.on(`error`,e=>{this.onerror?.(e)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let t=new Promise(t=>{e.once(`close`,()=>{t()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())]),e.exitCode===null){try{e.kill(`SIGTERM`)}catch{}await Promise.race([t,new Promise(e=>setTimeout(e,2e3).unref())])}if(e.exitCode===null)try{e.kill(`SIGKILL`)}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw new g(h.NotConnected,`Not connected`);let n=uu(e);this._process.stdin.write(n)?t():this._process.stdin.once(`drain`,t)})}},Fp=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Rf({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};const Ip={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var Lp=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_fetch;_fetchWithInit;_sessionId;_reconnectionOptions;_protocolVersion;_lastUpscopingHeader;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,Kd(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=Jd(t.authProvider)):this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=fu(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??Ip,this._reconnectionScheduler=t?.reconnectionScheduler}async _commonHeaders(){let e={},t=await this._authProvider?.token();t&&(e.Authorization=`Bearer ${t}`),this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let n=du(this._requestInit?.headers);return new Headers({...e,...n})}async _startOrAuthSse(e,t=!1){let{resumptionToken:n}=e;try{let r=await this._commonHeaders(),i=[...r.get(`accept`)?.split(`,`).map(e=>e.trim().toLowerCase())??[],`text/event-stream`];r.set(`accept`,[...new Set(i)].join(`, `)),n&&r.set(`last-event-id`,n);let a=await(this._fetch??fetch)(this._url,{...this._requestInit,method:`GET`,headers:r,signal:this._abortController?.signal});if(!a.ok){if(a.status===401&&this._authProvider){if(a.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=df(a);this._resourceMetadataUrl=e,this._scope=t}if(this._authProvider.onUnauthorized&&!t)return await this._authProvider.onUnauthorized({response:a,serverUrl:this._url,fetchFn:this._fetchWithInit}),await a.text?.().catch(()=>{}),this._startOrAuthSse(e,!0);throw await a.text?.().catch(()=>{}),t?new g(h.ClientHttpAuthentication,`Server returned 401 after re-authentication`,{status:401}):new Yd}if(await a.text?.().catch(()=>{}),a.status===405)return;throw new g(h.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${a.statusText}`,{status:a.status,statusText:a.statusText})}this._handleSseStream(a.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t),i=()=>{this._cancelReconnection=void 0,!this._abortController?.signal.aborted&&this._startOrAuthSse(e).catch(n=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`));try{this._scheduleReconnection(e,t+1)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}})};if(this._reconnectionScheduler){let e=this._reconnectionScheduler(i,r,t);this._cancelReconnection=typeof e==`function`?e:void 0}else{let e=setTimeout(i,r);this._cancelReconnection=()=>clearTimeout(e)}}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new Fp({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=vs.parse(JSON.parse(e.data));(Wl(t)||Gl(t))&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._oauthProvider)throw new Yd(`finishAuth requires an OAuthClientProvider`);if(await of(this._oauthProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Yd(`Failed to authorize`)}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,n){try{let{resumptionToken:r,onresumptiontoken:i}=t||{};if(r){this._startOrAuthSse({resumptionToken:r,replayMessageId:Hl(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let a=await this._commonHeaders();a.set(`content-type`,`application/json`);let o=[...a.get(`accept`)?.split(`,`).map(e=>e.trim().toLowerCase())??[],`application/json`,`text/event-stream`];a.set(`accept`,[...new Set(o)].join(`, `));let s={...this._requestInit,method:`POST`,headers:a,body:JSON.stringify(e),signal:this._abortController?.signal},c=await(this._fetch??fetch)(this._url,s),l=c.headers.get(`mcp-session-id`);if(l&&(this._sessionId=l),!c.ok){if(c.status===401&&this._authProvider){if(c.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=df(c);this._resourceMetadataUrl=e,this._scope=t}if(this._authProvider.onUnauthorized&&!n)return await this._authProvider.onUnauthorized({response:c,serverUrl:this._url,fetchFn:this._fetchWithInit}),await c.text?.().catch(()=>{}),this._send(e,t,!0);throw await c.text?.().catch(()=>{}),n?new g(h.ClientHttpAuthentication,`Server returned 401 after re-authentication`,{status:401}):new Yd}let r=await c.text?.().catch(()=>null);if(c.status===403&&this._oauthProvider){let{resourceMetadataUrl:i,scope:a,error:o}=df(c);if(o===`insufficient_scope`){let o=c.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===o)throw new g(h.ClientHttpForbidden,`Server returned 403 after trying upscoping`,{status:403,text:r});if(a&&(this._scope=a),i&&(this._resourceMetadataUrl=i),this._lastUpscopingHeader=o??void 0,await of(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Yd;return this._send(e,t,n)}}throw new g(h.ClientHttpNotImplemented,`Error POSTing to endpoint: ${r}`,{status:c.status,text:r})}if(this._lastUpscopingHeader=void 0,c.status===202){await c.text?.().catch(()=>{}),Jl(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let u=(Array.isArray(e)?e:[e]).some(e=>`method`in e&&`id`in e&&e.id!==void 0),d=c.headers.get(`content-type`);if(u)if(d?.includes(`text/event-stream`))this._handleSseStream(c.body,{onresumptiontoken:i},!1);else if(d?.includes(`application/json`)){let e=await c.json(),t=Array.isArray(e)?e.map(e=>vs.parse(e)):[vs.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await c.text?.().catch(()=>{}),new g(h.ClientHttpUnexpectedContent,`Unexpected content type: ${d}`,{contentType:d});else await c.text?.().catch(()=>{})}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.text?.().catch(()=>{}),!n.ok&&n.status!==405)throw new g(h.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${n.statusText}`,{status:n.status,statusText:n.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};export{zd as AjvJsonSchemaValidator,Ff as Client,Mp as DEFAULT_INHERITED_ENV_VARS,qo as DEFAULT_NEGOTIATED_PROTOCOL_VERSION,nu as DEFAULT_REQUEST_TIMEOUT_MSEC,ts as INTERNAL_ERROR,es as INVALID_PARAMS,Qo as INVALID_REQUEST,bu as InMemoryTaskMessageQueue,yu as InMemoryTaskStore,Xo as JSONRPC_VERSION,Ko as LATEST_PROTOCOL_VERSION,$o as METHOD_NOT_FOUND,m as OAuthError,p as OAuthErrorCode,Ro as OAuthErrorResponseSchema,Lo as OAuthTokensSchema,Zo as PARSE_ERROR,W as ProtocolError,U as ProtocolErrorCode,Yo as RELATED_TASK_META_KEY,cu as ReadBuffer,vp as SSEClientTransport,Jo as SUPPORTED_PROTOCOL_VERSIONS,g as SdkError,h as SdkErrorCode,_p as SseError,Pp as StdioClientTransport,Lp as StreamableHTTPClientTransport,Yd as UnauthorizedError,gu as UriTemplate,ns as UrlElicitationRequiredError,vu as assertClientRequestTaskCapability,Yl as assertCompleteRequestPrompt,Xl as assertCompleteRequestResourceTemplate,_u as assertToolsCallTaskCapability,of as auth,xf as buildDiscoveryUrls,Wo as checkResourceAllowed,fu as createFetchWithInit,lu as deserializeMessage,Sf as discoverAuthorizationServerMetadata,bf as discoverOAuthMetadata,mf as discoverOAuthProtectedResourceMetadata,Cf as discoverOAuthServerInfo,Df as exchangeAuthorization,pf as extractResourceMetadataUrl,df as extractWWWAuthenticateParams,kf as fetchToken,Np as getDefaultEnvironment,Go as getDisplayName,Pf as getSupportedElicitationModes,lf as isHttpsUrl,ql as isInitializeRequest,Jl as isInitializedNotification,Gl as isJSONRPCErrorResponse,Ul as isJSONRPCNotification,Hl as isJSONRPCRequest,Wl as isJSONRPCResultResponse,Kl as isTaskAugmentedRequestParams,Ql as isTerminal,af as parseErrorResponse,Vl as parseJSONRPCMessage,Tf as prepareAuthorizationCodeRequest,Of as refreshAuthorization,Af as registerClient,Uo as resourceUrlFromServerUrl,jf as revokeTokens,$d as selectClientAuthMethod,uf as selectResourceURL,uu as serializeMessage,wf as startAuthorization,su as takeResult,ou as toArrayAsync}; //# sourceMappingURL=index.mjs.map