mcp-zenskar 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import e from"node:crypto";import t,{existsSync as n,readFileSync as r}from"node:fs";import i,{dirname as a,resolve as o}from"node:path";import{fileURLToPath as s}from"node:url";import c from"node:process";var l=Object.create,u=Object.defineProperty,d=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyNames,p=Object.getPrototypeOf,m=Object.prototype.hasOwnProperty,h=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),g=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=f(t),a=0,o=i.length,s;a<o;a++)s=i[a],!m.call(e,s)&&s!==n&&u(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=d(t,s))||r.enumerable});return e},_=(e,t,n)=>(n=e==null?{}:l(p(e)),g(t||!e||!e.__esModule?u(n,`default`,{value:e,enumerable:!0}):n,e)),v;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(v||={});var ee;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(ee||={});const y=v.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),b=e=>{switch(typeof e){case`undefined`:return y.undefined;case`string`:return y.string;case`number`:return Number.isNaN(e)?y.nan:y.number;case`boolean`:return y.boolean;case`function`:return y.function;case`bigint`:return y.bigint;case`symbol`:return y.symbol;case`object`:return Array.isArray(e)?y.array:e===null?y.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?y.promise:typeof Map<`u`&&e instanceof Map?y.map:typeof Set<`u`&&e instanceof Set?y.set:typeof Date<`u`&&e instanceof Date?y.date:y.object;default:return y.unknown}},x=v.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var te=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,v.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};te.create=e=>new te(e);const ne=(e,t)=>{let n;switch(e.code){case x.invalid_type:n=e.received===y.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case x.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,v.jsonStringifyReplacer)}`;break;case x.unrecognized_keys:n=`Unrecognized key(s) in object: ${v.joinValues(e.keys,`, `)}`;break;case x.invalid_union:n=`Invalid input`;break;case x.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${v.joinValues(e.options)}`;break;case x.invalid_enum_value:n=`Invalid enum value. Expected ${v.joinValues(e.options)}, received '${e.received}'`;break;case x.invalid_arguments:n=`Invalid function arguments`;break;case x.invalid_return_type:n=`Invalid function return type`;break;case x.invalid_date:n=`Invalid date`;break;case x.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:v.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case x.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case x.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case x.custom:n=`Invalid input`;break;case x.invalid_intersection_types:n=`Intersection results could not be merged`;break;case x.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case x.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,v.assertNever(e)}return{message:n}};let re=ne;function ie(){return re}const ae=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function S(e,t){let n=ie(),r=ae({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===ne?void 0:ne].filter(e=>!!e)});e.common.issues.push(r)}var C=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return w;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return w;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const w=Object.freeze({status:`aborted`}),oe=e=>({status:`dirty`,value:e}),se=e=>({status:`valid`,value:e}),ce=e=>e.status===`aborted`,le=e=>e.status===`dirty`,ue=e=>e.status===`valid`,de=e=>typeof Promise<`u`&&e instanceof Promise;var T;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(T||={});var fe=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const pe=(e,t)=>{if(ue(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new te(e.common.issues);return this._error=t,this._error}}};function E(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var D=class{get description(){return this._def.description}_getType(e){return b(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:b(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new C,ctx:{common:e.parent.common,data:e.data,parsedType:b(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(de(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:b(e)};return pe(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:b(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ue(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>ue(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:b(e)},r=this._parse({data:e,path:n.path,parent:n});return pe(n,await(de(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:x.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new ht({schema:this,typeName:O.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return gt.create(this,this._def)}nullable(){return _t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Xe.create(this)}promise(){return mt.create(this,this._def)}or(e){return $e.create([this,e],this._def)}and(e){return rt.create(this,e,this._def)}transform(e){return new ht({...E(this._def),schema:this,typeName:O.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new vt({...E(this._def),innerType:this,defaultValue:t,typeName:O.ZodDefault})}brand(){return new xt({typeName:O.ZodBranded,type:this,...E(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new yt({...E(this._def),innerType:this,catchValue:t,typeName:O.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return St.create(this,e)}readonly(){return Ct.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const me=/^c[^\s-]{8,}$/i,he=/^[0-9a-z]+$/,ge=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_e=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ve=/^[a-z0-9_-]{21}$/i,ye=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,be=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,xe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Se;const Ce=/^(?:(?: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])$/,we=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,Te=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ee=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,De=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Oe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ke=`((\\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])))`,Ae=RegExp(`^${ke}$`);function je(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Me(e){return RegExp(`^${je(e)}$`)}function Ne(e){let t=`${ke}T${je(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Pe(e,t){return!!((t===`v4`||!t)&&Ce.test(e)||(t===`v6`||!t)&&Te.test(e))}function Fe(e,t){if(!ye.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Ie(e,t){return!!((t===`v4`||!t)&&we.test(e)||(t===`v6`||!t)&&Ee.test(e))}var Le=class e extends D{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==y.string){let t=this._getOrReturnCtx(e);return S(t,{code:x.invalid_type,expected:y.string,received:t.parsedType}),w}let t=new C,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),S(n,{code:x.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),S(n,{code:x.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?S(n,{code:x.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&S(n,{code:x.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)xe.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`email`,code:x.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Se||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),Se.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`emoji`,code:x.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)_e.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`uuid`,code:x.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)ve.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`nanoid`,code:x.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)me.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`cuid`,code:x.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)he.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`cuid2`,code:x.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)ge.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`ulid`,code:x.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),S(n,{validation:`url`,code:x.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`regex`,code:x.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),S(n,{code:x.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),S(n,{code:x.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),S(n,{code:x.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Ne(r).test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{code:x.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Ae.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{code:x.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Me(r).test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{code:x.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?be.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`duration`,code:x.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Pe(e.data,r.version)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`ip`,code:x.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Fe(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`jwt`,code:x.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Ie(e.data,r.version)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`cidr`,code:x.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?De.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`base64`,code:x.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Oe.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`base64url`,code:x.invalid_string,message:r.message}),t.dirty()):v.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:x.invalid_string,...T.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...T.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...T.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...T.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...T.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...T.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...T.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...T.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...T.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...T.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...T.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...T.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...T.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...T.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...T.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...T.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...T.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...T.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...T.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...T.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...T.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...T.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...T.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...T.errToObj(t)})}nonempty(e){return this.min(1,T.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Le.create=e=>new Le({checks:[],typeName:O.ZodString,coerce:e?.coerce??!1,...E(e)});function Re(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var ze=class e extends D{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==y.number){let t=this._getOrReturnCtx(e);return S(t,{code:x.invalid_type,expected:y.number,received:t.parsedType}),w}let t,n=new C;for(let r of this._def.checks)r.kind===`int`?v.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),S(t,{code:x.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),S(t,{code:x.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),S(t,{code:x.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Re(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),S(t,{code:x.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),S(t,{code:x.not_finite,message:r.message}),n.dirty()):v.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,T.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,T.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,T.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,T.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:T.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:T.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:T.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:T.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:T.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:T.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:T.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&v.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};ze.create=e=>new ze({checks:[],typeName:O.ZodNumber,coerce:e?.coerce||!1,...E(e)});var Be=class e extends D{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==y.bigint)return this._getInvalidInput(e);let t,n=new C;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),S(t,{code:x.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),S(t,{code:x.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),S(t,{code:x.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):v.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return S(t,{code:x.invalid_type,expected:y.bigint,received:t.parsedType}),w}gte(e,t){return this.setLimit(`min`,e,!0,T.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,T.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,T.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,T.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:T.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:T.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:T.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Be.create=e=>new Be({checks:[],typeName:O.ZodBigInt,coerce:e?.coerce??!1,...E(e)});var Ve=class extends D{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==y.boolean){let t=this._getOrReturnCtx(e);return S(t,{code:x.invalid_type,expected:y.boolean,received:t.parsedType}),w}return se(e.data)}};Ve.create=e=>new Ve({typeName:O.ZodBoolean,coerce:e?.coerce||!1,...E(e)});var He=class e extends D{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==y.date){let t=this._getOrReturnCtx(e);return S(t,{code:x.invalid_type,expected:y.date,received:t.parsedType}),w}if(Number.isNaN(e.data.getTime()))return S(this._getOrReturnCtx(e),{code:x.invalid_date}),w;let t=new C,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),S(n,{code:x.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),S(n,{code:x.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):v.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:T.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:T.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};He.create=e=>new He({checks:[],coerce:e?.coerce||!1,typeName:O.ZodDate,...E(e)});var Ue=class extends D{_parse(e){if(this._getType(e)!==y.symbol){let t=this._getOrReturnCtx(e);return S(t,{code:x.invalid_type,expected:y.symbol,received:t.parsedType}),w}return se(e.data)}};Ue.create=e=>new Ue({typeName:O.ZodSymbol,...E(e)});var We=class extends D{_parse(e){if(this._getType(e)!==y.undefined){let t=this._getOrReturnCtx(e);return S(t,{code:x.invalid_type,expected:y.undefined,received:t.parsedType}),w}return se(e.data)}};We.create=e=>new We({typeName:O.ZodUndefined,...E(e)});var Ge=class extends D{_parse(e){if(this._getType(e)!==y.null){let t=this._getOrReturnCtx(e);return S(t,{code:x.invalid_type,expected:y.null,received:t.parsedType}),w}return se(e.data)}};Ge.create=e=>new Ge({typeName:O.ZodNull,...E(e)});var Ke=class extends D{constructor(){super(...arguments),this._any=!0}_parse(e){return se(e.data)}};Ke.create=e=>new Ke({typeName:O.ZodAny,...E(e)});var qe=class extends D{constructor(){super(...arguments),this._unknown=!0}_parse(e){return se(e.data)}};qe.create=e=>new qe({typeName:O.ZodUnknown,...E(e)});var Je=class extends D{_parse(e){let t=this._getOrReturnCtx(e);return S(t,{code:x.invalid_type,expected:y.never,received:t.parsedType}),w}};Je.create=e=>new Je({typeName:O.ZodNever,...E(e)});var Ye=class extends D{_parse(e){if(this._getType(e)!==y.undefined){let t=this._getOrReturnCtx(e);return S(t,{code:x.invalid_type,expected:y.void,received:t.parsedType}),w}return se(e.data)}};Ye.create=e=>new Ye({typeName:O.ZodVoid,...E(e)});var Xe=class e extends D{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==y.array)return S(t,{code:x.invalid_type,expected:y.array,received:t.parsedType}),w;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(S(t,{code:e?x.too_big:x.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(S(t,{code:x.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(S(t,{code:x.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new fe(t,e,t.path,n)))).then(e=>C.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new fe(t,e,t.path,n)));return C.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:T.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:T.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:T.toString(n)}})}nonempty(e){return this.min(1,e)}};Xe.create=(e,t)=>new Xe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:O.ZodArray,...E(t)});function Ze(e){if(e instanceof Qe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=gt.create(Ze(r))}return new Qe({...e._def,shape:()=>t})}else if(e instanceof Xe)return new Xe({...e._def,type:Ze(e.element)});else if(e instanceof gt)return gt.create(Ze(e.unwrap()));else if(e instanceof _t)return _t.create(Ze(e.unwrap()));else if(e instanceof it)return it.create(e.items.map(e=>Ze(e)));else return e}var Qe=class e extends D{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=v.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==y.object){let t=this._getOrReturnCtx(e);return S(t,{code:x.invalid_type,expected:y.object,received:t.parsedType}),w}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Je&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new fe(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Je){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(S(n,{code:x.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new fe(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>C.mergeObjectSync(t,e)):C.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return T.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:T.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:O.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of v.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of v.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Ze(this)}partial(t){let n={};for(let e of v.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of v.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof gt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return dt(v.objectKeys(this.shape))}};Qe.create=(e,t)=>new Qe({shape:()=>e,unknownKeys:`strip`,catchall:Je.create(),typeName:O.ZodObject,...E(t)}),Qe.strictCreate=(e,t)=>new Qe({shape:()=>e,unknownKeys:`strict`,catchall:Je.create(),typeName:O.ZodObject,...E(t)}),Qe.lazycreate=(e,t)=>new Qe({shape:e,unknownKeys:`strip`,catchall:Je.create(),typeName:O.ZodObject,...E(t)});var $e=class extends D{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new te(e.ctx.common.issues));return S(t,{code:x.invalid_union,unionErrors:n}),w}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new te(e));return S(t,{code:x.invalid_union,unionErrors:i}),w}}get options(){return this._def.options}};$e.create=(e,t)=>new $e({options:e,typeName:O.ZodUnion,...E(t)});const et=e=>e instanceof lt?et(e.schema):e instanceof ht?et(e.innerType()):e instanceof ut?[e.value]:e instanceof ft?e.options:e instanceof pt?v.objectValues(e.enum):e instanceof vt?et(e._def.innerType):e instanceof We?[void 0]:e instanceof Ge?[null]:e instanceof gt?[void 0,...et(e.unwrap())]:e instanceof _t?[null,...et(e.unwrap())]:e instanceof xt||e instanceof Ct?et(e.unwrap()):e instanceof yt?et(e._def.innerType):[];var tt=class e extends D{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==y.object)return S(t,{code:x.invalid_type,expected:y.object,received:t.parsedType}),w;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(S(t,{code:x.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=et(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:O.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...E(r)})}};function nt(e,t){let n=b(e),r=b(t);if(e===t)return{valid:!0,data:e};if(n===y.object&&r===y.object){let n=v.objectKeys(t),r=v.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=nt(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===y.array&&r===y.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=nt(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===y.date&&r===y.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var rt=class extends D{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ce(e)||ce(r))return w;let i=nt(e.value,r.value);return i.valid?((le(e)||le(r))&&t.dirty(),{status:t.value,value:i.data}):(S(n,{code:x.invalid_intersection_types}),w)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};rt.create=(e,t,n)=>new rt({left:e,right:t,typeName:O.ZodIntersection,...E(n)});var it=class e extends D{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.array)return S(n,{code:x.invalid_type,expected:y.array,received:n.parsedType}),w;if(n.data.length<this._def.items.length)return S(n,{code:x.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),w;!this._def.rest&&n.data.length>this._def.items.length&&(S(n,{code:x.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new fe(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>C.mergeArray(t,e)):C.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};it.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new it({items:e,typeName:O.ZodTuple,rest:null,...E(t)})};var at=class e extends D{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.object)return S(n,{code:x.invalid_type,expected:y.object,received:n.parsedType}),w;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new fe(n,e,n.path,e)),value:a._parse(new fe(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?C.mergeObjectAsync(t,r):C.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof D?new e({keyType:t,valueType:n,typeName:O.ZodRecord,...E(r)}):new e({keyType:Le.create(),valueType:t,typeName:O.ZodRecord,...E(n)})}},ot=class extends D{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.map)return S(n,{code:x.invalid_type,expected:y.map,received:n.parsedType}),w;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new fe(n,e,n.path,[a,`key`])),value:i._parse(new fe(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return w;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return w;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};ot.create=(e,t,n)=>new ot({valueType:t,keyType:e,typeName:O.ZodMap,...E(n)});var st=class e extends D{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.set)return S(n,{code:x.invalid_type,expected:y.set,received:n.parsedType}),w;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(S(n,{code:x.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(S(n,{code:x.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return w;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new fe(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:T.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:T.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};st.create=(e,t)=>new st({valueType:e,minSize:null,maxSize:null,typeName:O.ZodSet,...E(t)});var ct=class e extends D{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==y.function)return S(t,{code:x.invalid_type,expected:y.function,received:t.parsedType}),w;function n(e,n){return ae({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ie(),ne].filter(e=>!!e),issueData:{code:x.invalid_arguments,argumentsError:n}})}function r(e,n){return ae({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ie(),ne].filter(e=>!!e),issueData:{code:x.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof mt){let e=this;return se(async function(...t){let o=new te([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return se(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new te([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new te([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:it.create(t).rest(qe.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||it.create([]).rest(qe.create()),returns:n||qe.create(),typeName:O.ZodFunction,...E(r)})}},lt=class extends D{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};lt.create=(e,t)=>new lt({getter:e,typeName:O.ZodLazy,...E(t)});var ut=class extends D{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return S(t,{received:t.data,code:x.invalid_literal,expected:this._def.value}),w}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ut.create=(e,t)=>new ut({value:e,typeName:O.ZodLiteral,...E(t)});function dt(e,t){return new ft({values:e,typeName:O.ZodEnum,...E(t)})}var ft=class e extends D{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return S(t,{expected:v.joinValues(n),received:t.parsedType,code:x.invalid_type}),w}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return S(t,{received:t.data,code:x.invalid_enum_value,options:n}),w}return se(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};ft.create=dt;var pt=class extends D{_parse(e){let t=v.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==y.string&&n.parsedType!==y.number){let e=v.objectValues(t);return S(n,{expected:v.joinValues(e),received:n.parsedType,code:x.invalid_type}),w}if(this._cache||=new Set(v.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=v.objectValues(t);return S(n,{received:n.data,code:x.invalid_enum_value,options:e}),w}return se(e.data)}get enum(){return this._def.values}};pt.create=(e,t)=>new pt({values:e,typeName:O.ZodNativeEnum,...E(t)});var mt=class extends D{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==y.promise&&t.common.async===!1?(S(t,{code:x.invalid_type,expected:y.promise,received:t.parsedType}),w):se((t.parsedType===y.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};mt.create=(e,t)=>new mt({type:e,typeName:O.ZodPromise,...E(t)});var ht=class extends D{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{S(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return w;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?w:r.status===`dirty`||t.value===`dirty`?oe(r.value):r});{if(t.value===`aborted`)return w;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?w:r.status===`dirty`||t.value===`dirty`?oe(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?w:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?w:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ue(e))return w;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>ue(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):w);v.assertNever(r)}};ht.create=(e,t,n)=>new ht({schema:e,typeName:O.ZodEffects,effect:t,...E(n)}),ht.createWithPreprocess=(e,t,n)=>new ht({schema:t,effect:{type:`preprocess`,transform:e},typeName:O.ZodEffects,...E(n)});var gt=class extends D{_parse(e){return this._getType(e)===y.undefined?se(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gt.create=(e,t)=>new gt({innerType:e,typeName:O.ZodOptional,...E(t)});var _t=class extends D{_parse(e){return this._getType(e)===y.null?se(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_t.create=(e,t)=>new _t({innerType:e,typeName:O.ZodNullable,...E(t)});var vt=class extends D{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===y.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};vt.create=(e,t)=>new vt({innerType:e,typeName:O.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...E(t)});var yt=class extends D{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return de(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new te(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new te(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};yt.create=(e,t)=>new yt({innerType:e,typeName:O.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...E(t)});var bt=class extends D{_parse(e){if(this._getType(e)!==y.nan){let t=this._getOrReturnCtx(e);return S(t,{code:x.invalid_type,expected:y.nan,received:t.parsedType}),w}return{status:`valid`,value:e.data}}};bt.create=e=>new bt({typeName:O.ZodNaN,...E(e)});var xt=class extends D{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},St=class e extends D{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?w:e.status===`dirty`?(t.dirty(),oe(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?w:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:O.ZodPipeline})}},Ct=class extends D{_parse(e){let t=this._def.innerType._parse(e),n=e=>(ue(e)&&(e.value=Object.freeze(e.value)),e);return de(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};Ct.create=(e,t)=>new Ct({innerType:e,typeName:O.ZodReadonly,...E(t)}),Qe.lazycreate;var O;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(O||={}),Le.create,ze.create,bt.create,Be.create,Ve.create,He.create,Ue.create,We.create,Ge.create,Ke.create,qe.create,Je.create,Ye.create,Xe.create;const wt=Qe.create;Qe.strictCreate,$e.create,tt.create,rt.create,it.create,at.create,ot.create,st.create,ct.create,lt.create,ut.create,ft.create,pt.create,mt.create,ht.create,gt.create,_t.create,ht.createWithPreprocess,St.create;var Tt;function k(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;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var Et=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Dt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Tt=globalThis).__zod_globalConfig??(Tt.__zod_globalConfig={});const Ot=globalThis.__zod_globalConfig;function kt(e){return e&&Object.assign(Ot,e),Ot}function At(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 jt(e,t){return typeof t==`bigint`?t.toString():t}function Mt(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function Nt(e){return e==null}function Pt(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ft(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}const It=Symbol(`evaluating`);function A(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==It)return r===void 0&&(r=It,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Lt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Rt(...e){let t={};for(let n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function zt(e){return JSON.stringify(e)}function Bt(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const Vt=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Ht(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ut=Mt(()=>{if(Ot.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Wt(e){if(Ht(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(Ht(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function Gt(e){return Wt(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Kt=new Set([`string`,`number`,`symbol`]);function qt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Jt(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function j(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Yt(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const Xt={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Zt(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 Jt(e,Rt(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 Lt(this,`shape`,e),e},checks:[]}))}function Qt(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 Jt(e,Rt(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 Lt(this,`shape`,r),r},checks:[]}))}function $t(e,t){if(!Wt(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 Jt(e,Rt(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Lt(this,`shape`,n),n}}))}function en(e,t){if(!Wt(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Jt(e,Rt(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Lt(this,`shape`,n),n}}))}function tn(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Jt(e,Rt(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Lt(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function nn(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 Jt(t,Rt(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 Lt(this,`shape`,i),i},checks:[]}))}function rn(e,t,n){return Jt(t,Rt(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 Lt(this,`shape`,i),i}}))}function an(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function on(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function sn(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function cn(e){return typeof e==`string`?e:e?.message}function ln(e,t,n){let r=e.message?e.message:cn(e.inst?._zod.def?.error?.(e))??cn(t?.error?.(e))??cn(n.customError?.(e))??cn(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function un(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function dn(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const fn=(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,jt,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},pn=k(`$ZodError`,fn),mn=k(`$ZodError`,fn,{Parent:Error});function hn(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 gn(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}const _n=e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Et;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>ln(e,a,kt())));throw Vt(t,i?.callee),t}return o.value},vn=_n(mn),yn=e=>async(t,n,r,i)=>{let a=r?{...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=>ln(e,a,kt())));throw Vt(t,i?.callee),t}return o.value},bn=yn(mn),xn=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 Et;return a.issues.length?{success:!1,error:new(e??pn)(a.issues.map(e=>ln(e,i,kt())))}:{success:!0,data:a.value}},Sn=xn(mn),Cn=e=>async(t,n,r)=>{let i=r?{...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=>ln(e,i,kt())))}:{success:!0,data:a.value}},wn=Cn(mn),Tn=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _n(e)(t,n,i)},En=e=>(t,n,r)=>_n(e)(t,n,r),Dn=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return yn(e)(t,n,i)},On=e=>async(t,n,r)=>yn(e)(t,n,r),kn=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return xn(e)(t,n,i)},An=e=>(t,n,r)=>xn(e)(t,n,r),jn=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Cn(e)(t,n,i)},Mn=e=>async(t,n,r)=>Cn(e)(t,n,r),Nn=/^[cC][0-9a-z]{6,}$/,Pn=/^[0-9a-z]+$/,Fn=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,In=/^[0-9a-vA-V]{20}$/,Ln=/^[A-Za-z0-9]{27}$/,Rn=/^[a-zA-Z0-9_-]{21}$/,zn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Bn=/^([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})$/,Vn=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)$/,Hn=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function Un(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const Wn=/^(?:(?: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])$/,Gn=/^(([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}|:))$/,Kn=/^((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])$/,qn=/^(([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])$/,Jn=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Yn=/^[A-Za-z0-9_-]*$/,Xn=/^https?$/,Zn=/^\+[1-9]\d{6,14}$/,Qn=`(?:(?:\\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])))`,$n=RegExp(`^${Qn}$`);function er(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 tr(e){return RegExp(`^${er(e)}$`)}function nr(e){let t=er({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(`^${Qn}T(?:${r})$`)}const rr=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},ir=/^-?\d+$/,ar=/^-?\d+(?:\.\d+)?$/,or=/^(?:true|false)$/i,sr=/^null$/i,cr=/^[^A-Z]*$/,lr=/^[^a-z]*$/,ur=k(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),dr={number:`number`,bigint:`bigint`,object:`date`},fr=k(`$ZodCheckLessThan`,(e,t)=>{ur.init(e,t);let n=dr[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),pr=k(`$ZodCheckGreaterThan`,(e,t)=>{ur.init(e,t);let n=dr[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})}}),mr=k(`$ZodCheckMultipleOf`,(e,t)=>{ur.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):Ft(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})}}),hr=k(`$ZodCheckNumberFormat`,(e,t)=>{ur.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Xt[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=ir)}),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}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),gr=k(`$ZodCheckMaxLength`,(e,t)=>{var n;ur.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Nt(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=un(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),_r=k(`$ZodCheckMinLength`,(e,t)=>{var n;ur.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Nt(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=un(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),vr=k(`$ZodCheckLengthEquals`,(e,t)=>{var n;ur.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Nt(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=un(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})}}),yr=k(`$ZodCheckStringFormat`,(e,t)=>{var n,r;ur.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=()=>{})}),br=k(`$ZodCheckRegex`,(e,t)=>{yr.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})}}),xr=k(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=cr,yr.init(e,t)}),Sr=k(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=lr,yr.init(e,t)}),Cr=k(`$ZodCheckIncludes`,(e,t)=>{ur.init(e,t);let n=qt(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})}}),wr=k(`$ZodCheckStartsWith`,(e,t)=>{ur.init(e,t);let n=RegExp(`^${qt(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})}}),Tr=k(`$ZodCheckEndsWith`,(e,t)=>{ur.init(e,t);let n=RegExp(`.*${qt(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})}}),Er=k(`$ZodCheckOverwrite`,(e,t)=>{ur.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Dr=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(`
2
+ import e from"node:crypto";import t,{existsSync as n,readFileSync as r}from"node:fs";import i,{dirname as a,resolve as o}from"node:path";import{fileURLToPath as s}from"node:url";import c from"node:process";var l=Object.create,u=Object.defineProperty,d=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyNames,p=Object.getPrototypeOf,m=Object.prototype.hasOwnProperty,h=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),g=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=f(t),a=0,o=i.length,s;a<o;a++)s=i[a],!m.call(e,s)&&s!==n&&u(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=d(t,s))||r.enumerable});return e},_=(e,t,n)=>(n=e==null?{}:l(p(e)),g(t||!e||!e.__esModule?u(n,`default`,{value:e,enumerable:!0}):n,e)),v;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(v||={});var y;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(y||={});const b=v.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),x=e=>{switch(typeof e){case`undefined`:return b.undefined;case`string`:return b.string;case`number`:return Number.isNaN(e)?b.nan:b.number;case`boolean`:return b.boolean;case`function`:return b.function;case`bigint`:return b.bigint;case`symbol`:return b.symbol;case`object`:return Array.isArray(e)?b.array:e===null?b.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?b.promise:typeof Map<`u`&&e instanceof Map?b.map:typeof Set<`u`&&e instanceof Set?b.set:typeof Date<`u`&&e instanceof Date?b.date:b.object;default:return b.unknown}},S=v.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var ee=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,v.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};ee.create=e=>new ee(e);const te=(e,t)=>{let n;switch(e.code){case S.invalid_type:n=e.received===b.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case S.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,v.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:n=`Unrecognized key(s) in object: ${v.joinValues(e.keys,`, `)}`;break;case S.invalid_union:n=`Invalid input`;break;case S.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${v.joinValues(e.options)}`;break;case S.invalid_enum_value:n=`Invalid enum value. Expected ${v.joinValues(e.options)}, received '${e.received}'`;break;case S.invalid_arguments:n=`Invalid function arguments`;break;case S.invalid_return_type:n=`Invalid function return type`;break;case S.invalid_date:n=`Invalid date`;break;case S.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:v.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case S.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case S.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case S.custom:n=`Invalid input`;break;case S.invalid_intersection_types:n=`Intersection results could not be merged`;break;case S.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case S.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,v.assertNever(e)}return{message:n}};let ne=te;function re(){return ne}const ie=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function C(e,t){let n=re(),r=ie({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===te?void 0:te].filter(e=>!!e)});e.common.issues.push(r)}var ae=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return w;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return w;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const w=Object.freeze({status:`aborted`}),oe=e=>({status:`dirty`,value:e}),se=e=>({status:`valid`,value:e}),ce=e=>e.status===`aborted`,le=e=>e.status===`dirty`,ue=e=>e.status===`valid`,de=e=>typeof Promise<`u`&&e instanceof Promise;var T;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(T||={});var fe=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const pe=(e,t)=>{if(ue(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new ee(e.common.issues);return this._error=t,this._error}}};function E(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var D=class{get description(){return this._def.description}_getType(e){return x(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:x(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ae,ctx:{common:e.parent.common,data:e.data,parsedType:x(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(de(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:x(e)};return pe(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:x(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ue(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>ue(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:x(e)},r=this._parse({data:e,path:n.path,parent:n});return pe(n,await(de(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:S.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new ht({schema:this,typeName:O.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return gt.create(this,this._def)}nullable(){return _t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Xe.create(this)}promise(){return mt.create(this,this._def)}or(e){return $e.create([this,e],this._def)}and(e){return rt.create(this,e,this._def)}transform(e){return new ht({...E(this._def),schema:this,typeName:O.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new vt({...E(this._def),innerType:this,defaultValue:t,typeName:O.ZodDefault})}brand(){return new xt({typeName:O.ZodBranded,type:this,...E(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new yt({...E(this._def),innerType:this,catchValue:t,typeName:O.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return St.create(this,e)}readonly(){return Ct.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const me=/^c[^\s-]{8,}$/i,he=/^[0-9a-z]+$/,ge=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_e=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ve=/^[a-z0-9_-]{21}$/i,ye=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,be=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,xe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Se;const Ce=/^(?:(?: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])$/,we=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,Te=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ee=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,De=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Oe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ke=`((\\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])))`,Ae=RegExp(`^${ke}$`);function je(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Me(e){return RegExp(`^${je(e)}$`)}function Ne(e){let t=`${ke}T${je(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Pe(e,t){return!!((t===`v4`||!t)&&Ce.test(e)||(t===`v6`||!t)&&Te.test(e))}function Fe(e,t){if(!ye.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Ie(e,t){return!!((t===`v4`||!t)&&we.test(e)||(t===`v6`||!t)&&Ee.test(e))}var Le=class e extends D{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==b.string){let t=this._getOrReturnCtx(e);return C(t,{code:S.invalid_type,expected:b.string,received:t.parsedType}),w}let t=new ae,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),C(n,{code:S.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),C(n,{code:S.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?C(n,{code:S.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&C(n,{code:S.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)xe.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:`email`,code:S.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Se||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),Se.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:`emoji`,code:S.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)_e.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:`uuid`,code:S.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)ve.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:`nanoid`,code:S.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)me.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:`cuid`,code:S.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)he.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:`cuid2`,code:S.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)ge.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:`ulid`,code:S.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),C(n,{validation:`url`,code:S.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:`regex`,code:S.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),C(n,{code:S.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),C(n,{code:S.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),C(n,{code:S.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Ne(r).test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{code:S.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Ae.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{code:S.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Me(r).test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{code:S.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?be.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:`duration`,code:S.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Pe(e.data,r.version)||(n=this._getOrReturnCtx(e,n),C(n,{validation:`ip`,code:S.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Fe(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),C(n,{validation:`jwt`,code:S.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Ie(e.data,r.version)||(n=this._getOrReturnCtx(e,n),C(n,{validation:`cidr`,code:S.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?De.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:`base64`,code:S.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Oe.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:`base64url`,code:S.invalid_string,message:r.message}),t.dirty()):v.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:S.invalid_string,...T.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...T.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...T.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...T.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...T.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...T.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...T.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...T.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...T.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...T.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...T.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...T.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...T.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...T.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...T.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...T.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...T.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...T.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...T.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...T.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...T.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...T.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...T.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...T.errToObj(t)})}nonempty(e){return this.min(1,T.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Le.create=e=>new Le({checks:[],typeName:O.ZodString,coerce:e?.coerce??!1,...E(e)});function Re(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var ze=class e extends D{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==b.number){let t=this._getOrReturnCtx(e);return C(t,{code:S.invalid_type,expected:b.number,received:t.parsedType}),w}let t,n=new ae;for(let r of this._def.checks)r.kind===`int`?v.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),C(t,{code:S.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),C(t,{code:S.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),C(t,{code:S.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Re(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),C(t,{code:S.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),C(t,{code:S.not_finite,message:r.message}),n.dirty()):v.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,T.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,T.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,T.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,T.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:T.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:T.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:T.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:T.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:T.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:T.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:T.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&v.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};ze.create=e=>new ze({checks:[],typeName:O.ZodNumber,coerce:e?.coerce||!1,...E(e)});var Be=class e extends D{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==b.bigint)return this._getInvalidInput(e);let t,n=new ae;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),C(t,{code:S.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),C(t,{code:S.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),C(t,{code:S.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):v.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return C(t,{code:S.invalid_type,expected:b.bigint,received:t.parsedType}),w}gte(e,t){return this.setLimit(`min`,e,!0,T.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,T.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,T.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,T.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:T.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:T.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:T.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Be.create=e=>new Be({checks:[],typeName:O.ZodBigInt,coerce:e?.coerce??!1,...E(e)});var Ve=class extends D{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==b.boolean){let t=this._getOrReturnCtx(e);return C(t,{code:S.invalid_type,expected:b.boolean,received:t.parsedType}),w}return se(e.data)}};Ve.create=e=>new Ve({typeName:O.ZodBoolean,coerce:e?.coerce||!1,...E(e)});var He=class e extends D{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==b.date){let t=this._getOrReturnCtx(e);return C(t,{code:S.invalid_type,expected:b.date,received:t.parsedType}),w}if(Number.isNaN(e.data.getTime()))return C(this._getOrReturnCtx(e),{code:S.invalid_date}),w;let t=new ae,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),C(n,{code:S.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),C(n,{code:S.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):v.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:T.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:T.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};He.create=e=>new He({checks:[],coerce:e?.coerce||!1,typeName:O.ZodDate,...E(e)});var Ue=class extends D{_parse(e){if(this._getType(e)!==b.symbol){let t=this._getOrReturnCtx(e);return C(t,{code:S.invalid_type,expected:b.symbol,received:t.parsedType}),w}return se(e.data)}};Ue.create=e=>new Ue({typeName:O.ZodSymbol,...E(e)});var We=class extends D{_parse(e){if(this._getType(e)!==b.undefined){let t=this._getOrReturnCtx(e);return C(t,{code:S.invalid_type,expected:b.undefined,received:t.parsedType}),w}return se(e.data)}};We.create=e=>new We({typeName:O.ZodUndefined,...E(e)});var Ge=class extends D{_parse(e){if(this._getType(e)!==b.null){let t=this._getOrReturnCtx(e);return C(t,{code:S.invalid_type,expected:b.null,received:t.parsedType}),w}return se(e.data)}};Ge.create=e=>new Ge({typeName:O.ZodNull,...E(e)});var Ke=class extends D{constructor(){super(...arguments),this._any=!0}_parse(e){return se(e.data)}};Ke.create=e=>new Ke({typeName:O.ZodAny,...E(e)});var qe=class extends D{constructor(){super(...arguments),this._unknown=!0}_parse(e){return se(e.data)}};qe.create=e=>new qe({typeName:O.ZodUnknown,...E(e)});var Je=class extends D{_parse(e){let t=this._getOrReturnCtx(e);return C(t,{code:S.invalid_type,expected:b.never,received:t.parsedType}),w}};Je.create=e=>new Je({typeName:O.ZodNever,...E(e)});var Ye=class extends D{_parse(e){if(this._getType(e)!==b.undefined){let t=this._getOrReturnCtx(e);return C(t,{code:S.invalid_type,expected:b.void,received:t.parsedType}),w}return se(e.data)}};Ye.create=e=>new Ye({typeName:O.ZodVoid,...E(e)});var Xe=class e extends D{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==b.array)return C(t,{code:S.invalid_type,expected:b.array,received:t.parsedType}),w;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(C(t,{code:e?S.too_big:S.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(C(t,{code:S.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(C(t,{code:S.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new fe(t,e,t.path,n)))).then(e=>ae.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new fe(t,e,t.path,n)));return ae.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:T.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:T.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:T.toString(n)}})}nonempty(e){return this.min(1,e)}};Xe.create=(e,t)=>new Xe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:O.ZodArray,...E(t)});function Ze(e){if(e instanceof Qe){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=gt.create(Ze(r))}return new Qe({...e._def,shape:()=>t})}else if(e instanceof Xe)return new Xe({...e._def,type:Ze(e.element)});else if(e instanceof gt)return gt.create(Ze(e.unwrap()));else if(e instanceof _t)return _t.create(Ze(e.unwrap()));else if(e instanceof it)return it.create(e.items.map(e=>Ze(e)));else return e}var Qe=class e extends D{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=v.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==b.object){let t=this._getOrReturnCtx(e);return C(t,{code:S.invalid_type,expected:b.object,received:t.parsedType}),w}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Je&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new fe(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Je){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(C(n,{code:S.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new fe(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>ae.mergeObjectSync(t,e)):ae.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return T.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:T.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:O.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of v.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of v.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Ze(this)}partial(t){let n={};for(let e of v.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of v.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof gt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return dt(v.objectKeys(this.shape))}};Qe.create=(e,t)=>new Qe({shape:()=>e,unknownKeys:`strip`,catchall:Je.create(),typeName:O.ZodObject,...E(t)}),Qe.strictCreate=(e,t)=>new Qe({shape:()=>e,unknownKeys:`strict`,catchall:Je.create(),typeName:O.ZodObject,...E(t)}),Qe.lazycreate=(e,t)=>new Qe({shape:e,unknownKeys:`strip`,catchall:Je.create(),typeName:O.ZodObject,...E(t)});var $e=class extends D{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new ee(e.ctx.common.issues));return C(t,{code:S.invalid_union,unionErrors:n}),w}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new ee(e));return C(t,{code:S.invalid_union,unionErrors:i}),w}}get options(){return this._def.options}};$e.create=(e,t)=>new $e({options:e,typeName:O.ZodUnion,...E(t)});const et=e=>e instanceof lt?et(e.schema):e instanceof ht?et(e.innerType()):e instanceof ut?[e.value]:e instanceof ft?e.options:e instanceof pt?v.objectValues(e.enum):e instanceof vt?et(e._def.innerType):e instanceof We?[void 0]:e instanceof Ge?[null]:e instanceof gt?[void 0,...et(e.unwrap())]:e instanceof _t?[null,...et(e.unwrap())]:e instanceof xt||e instanceof Ct?et(e.unwrap()):e instanceof yt?et(e._def.innerType):[];var tt=class e extends D{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==b.object)return C(t,{code:S.invalid_type,expected:b.object,received:t.parsedType}),w;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(C(t,{code:S.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=et(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:O.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...E(r)})}};function nt(e,t){let n=x(e),r=x(t);if(e===t)return{valid:!0,data:e};if(n===b.object&&r===b.object){let n=v.objectKeys(t),r=v.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=nt(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===b.array&&r===b.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=nt(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===b.date&&r===b.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var rt=class extends D{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ce(e)||ce(r))return w;let i=nt(e.value,r.value);return i.valid?((le(e)||le(r))&&t.dirty(),{status:t.value,value:i.data}):(C(n,{code:S.invalid_intersection_types}),w)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};rt.create=(e,t,n)=>new rt({left:e,right:t,typeName:O.ZodIntersection,...E(n)});var it=class e extends D{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.array)return C(n,{code:S.invalid_type,expected:b.array,received:n.parsedType}),w;if(n.data.length<this._def.items.length)return C(n,{code:S.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),w;!this._def.rest&&n.data.length>this._def.items.length&&(C(n,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new fe(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>ae.mergeArray(t,e)):ae.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};it.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new it({items:e,typeName:O.ZodTuple,rest:null,...E(t)})};var at=class e extends D{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.object)return C(n,{code:S.invalid_type,expected:b.object,received:n.parsedType}),w;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new fe(n,e,n.path,e)),value:a._parse(new fe(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?ae.mergeObjectAsync(t,r):ae.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof D?new e({keyType:t,valueType:n,typeName:O.ZodRecord,...E(r)}):new e({keyType:Le.create(),valueType:t,typeName:O.ZodRecord,...E(n)})}},ot=class extends D{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.map)return C(n,{code:S.invalid_type,expected:b.map,received:n.parsedType}),w;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new fe(n,e,n.path,[a,`key`])),value:i._parse(new fe(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return w;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return w;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};ot.create=(e,t,n)=>new ot({valueType:t,keyType:e,typeName:O.ZodMap,...E(n)});var st=class e extends D{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.set)return C(n,{code:S.invalid_type,expected:b.set,received:n.parsedType}),w;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(C(n,{code:S.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(C(n,{code:S.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return w;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new fe(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:T.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:T.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};st.create=(e,t)=>new st({valueType:e,minSize:null,maxSize:null,typeName:O.ZodSet,...E(t)});var ct=class e extends D{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==b.function)return C(t,{code:S.invalid_type,expected:b.function,received:t.parsedType}),w;function n(e,n){return ie({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,re(),te].filter(e=>!!e),issueData:{code:S.invalid_arguments,argumentsError:n}})}function r(e,n){return ie({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,re(),te].filter(e=>!!e),issueData:{code:S.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof mt){let e=this;return se(async function(...t){let o=new ee([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return se(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new ee([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new ee([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:it.create(t).rest(qe.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||it.create([]).rest(qe.create()),returns:n||qe.create(),typeName:O.ZodFunction,...E(r)})}},lt=class extends D{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};lt.create=(e,t)=>new lt({getter:e,typeName:O.ZodLazy,...E(t)});var ut=class extends D{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return C(t,{received:t.data,code:S.invalid_literal,expected:this._def.value}),w}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ut.create=(e,t)=>new ut({value:e,typeName:O.ZodLiteral,...E(t)});function dt(e,t){return new ft({values:e,typeName:O.ZodEnum,...E(t)})}var ft=class e extends D{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return C(t,{expected:v.joinValues(n),received:t.parsedType,code:S.invalid_type}),w}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return C(t,{received:t.data,code:S.invalid_enum_value,options:n}),w}return se(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};ft.create=dt;var pt=class extends D{_parse(e){let t=v.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==b.string&&n.parsedType!==b.number){let e=v.objectValues(t);return C(n,{expected:v.joinValues(e),received:n.parsedType,code:S.invalid_type}),w}if(this._cache||=new Set(v.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=v.objectValues(t);return C(n,{received:n.data,code:S.invalid_enum_value,options:e}),w}return se(e.data)}get enum(){return this._def.values}};pt.create=(e,t)=>new pt({values:e,typeName:O.ZodNativeEnum,...E(t)});var mt=class extends D{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==b.promise&&t.common.async===!1?(C(t,{code:S.invalid_type,expected:b.promise,received:t.parsedType}),w):se((t.parsedType===b.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};mt.create=(e,t)=>new mt({type:e,typeName:O.ZodPromise,...E(t)});var ht=class extends D{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{C(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return w;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?w:r.status===`dirty`||t.value===`dirty`?oe(r.value):r});{if(t.value===`aborted`)return w;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?w:r.status===`dirty`||t.value===`dirty`?oe(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?w:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?w:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ue(e))return w;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>ue(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):w);v.assertNever(r)}};ht.create=(e,t,n)=>new ht({schema:e,typeName:O.ZodEffects,effect:t,...E(n)}),ht.createWithPreprocess=(e,t,n)=>new ht({schema:t,effect:{type:`preprocess`,transform:e},typeName:O.ZodEffects,...E(n)});var gt=class extends D{_parse(e){return this._getType(e)===b.undefined?se(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gt.create=(e,t)=>new gt({innerType:e,typeName:O.ZodOptional,...E(t)});var _t=class extends D{_parse(e){return this._getType(e)===b.null?se(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_t.create=(e,t)=>new _t({innerType:e,typeName:O.ZodNullable,...E(t)});var vt=class extends D{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===b.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};vt.create=(e,t)=>new vt({innerType:e,typeName:O.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...E(t)});var yt=class extends D{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return de(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new ee(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new ee(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};yt.create=(e,t)=>new yt({innerType:e,typeName:O.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...E(t)});var bt=class extends D{_parse(e){if(this._getType(e)!==b.nan){let t=this._getOrReturnCtx(e);return C(t,{code:S.invalid_type,expected:b.nan,received:t.parsedType}),w}return{status:`valid`,value:e.data}}};bt.create=e=>new bt({typeName:O.ZodNaN,...E(e)});var xt=class extends D{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},St=class e extends D{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?w:e.status===`dirty`?(t.dirty(),oe(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?w:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:O.ZodPipeline})}},Ct=class extends D{_parse(e){let t=this._def.innerType._parse(e),n=e=>(ue(e)&&(e.value=Object.freeze(e.value)),e);return de(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};Ct.create=(e,t)=>new Ct({innerType:e,typeName:O.ZodReadonly,...E(t)}),Qe.lazycreate;var O;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(O||={}),Le.create,ze.create,bt.create,Be.create,Ve.create,He.create,Ue.create,We.create,Ge.create,Ke.create,qe.create,Je.create,Ye.create,Xe.create;const wt=Qe.create;Qe.strictCreate,$e.create,tt.create,rt.create,it.create,at.create,ot.create,st.create,ct.create,lt.create,ut.create,ft.create,pt.create,mt.create,ht.create,gt.create,_t.create,ht.createWithPreprocess,St.create;var Tt;function k(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;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var Et=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Dt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Tt=globalThis).__zod_globalConfig??(Tt.__zod_globalConfig={});const Ot=globalThis.__zod_globalConfig;function kt(e){return e&&Object.assign(Ot,e),Ot}function At(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 jt(e,t){return typeof t==`bigint`?t.toString():t}function Mt(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function Nt(e){return e==null}function Pt(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ft(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}const It=Symbol(`evaluating`);function A(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==It)return r===void 0&&(r=It,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Lt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Rt(...e){let t={};for(let n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function zt(e){return JSON.stringify(e)}function Bt(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const Vt=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Ht(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ut=Mt(()=>{if(Ot.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Wt(e){if(Ht(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(Ht(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function Gt(e){return Wt(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Kt=new Set([`string`,`number`,`symbol`]);function qt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Jt(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function j(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Yt(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const Xt={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Zt(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 Jt(e,Rt(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 Lt(this,`shape`,e),e},checks:[]}))}function Qt(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 Jt(e,Rt(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 Lt(this,`shape`,r),r},checks:[]}))}function $t(e,t){if(!Wt(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 Jt(e,Rt(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Lt(this,`shape`,n),n}}))}function en(e,t){if(!Wt(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Jt(e,Rt(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Lt(this,`shape`,n),n}}))}function tn(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Jt(e,Rt(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Lt(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function nn(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 Jt(t,Rt(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 Lt(this,`shape`,i),i},checks:[]}))}function rn(e,t,n){return Jt(t,Rt(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 Lt(this,`shape`,i),i}}))}function an(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function on(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function sn(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function cn(e){return typeof e==`string`?e:e?.message}function ln(e,t,n){let r=e.message?e.message:cn(e.inst?._zod.def?.error?.(e))??cn(t?.error?.(e))??cn(n.customError?.(e))??cn(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function un(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function dn(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const fn=(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,jt,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},pn=k(`$ZodError`,fn),mn=k(`$ZodError`,fn,{Parent:Error});function hn(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 gn(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}const _n=e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Et;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>ln(e,a,kt())));throw Vt(t,i?.callee),t}return o.value},vn=_n(mn),yn=e=>async(t,n,r,i)=>{let a=r?{...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=>ln(e,a,kt())));throw Vt(t,i?.callee),t}return o.value},bn=yn(mn),xn=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 Et;return a.issues.length?{success:!1,error:new(e??pn)(a.issues.map(e=>ln(e,i,kt())))}:{success:!0,data:a.value}},Sn=xn(mn),Cn=e=>async(t,n,r)=>{let i=r?{...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=>ln(e,i,kt())))}:{success:!0,data:a.value}},wn=Cn(mn),Tn=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _n(e)(t,n,i)},En=e=>(t,n,r)=>_n(e)(t,n,r),Dn=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return yn(e)(t,n,i)},On=e=>async(t,n,r)=>yn(e)(t,n,r),kn=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return xn(e)(t,n,i)},An=e=>(t,n,r)=>xn(e)(t,n,r),jn=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Cn(e)(t,n,i)},Mn=e=>async(t,n,r)=>Cn(e)(t,n,r),Nn=/^[cC][0-9a-z]{6,}$/,Pn=/^[0-9a-z]+$/,Fn=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,In=/^[0-9a-vA-V]{20}$/,Ln=/^[A-Za-z0-9]{27}$/,Rn=/^[a-zA-Z0-9_-]{21}$/,zn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Bn=/^([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})$/,Vn=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)$/,Hn=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function Un(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const Wn=/^(?:(?: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])$/,Gn=/^(([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}|:))$/,Kn=/^((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])$/,qn=/^(([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])$/,Jn=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Yn=/^[A-Za-z0-9_-]*$/,Xn=/^https?$/,Zn=/^\+[1-9]\d{6,14}$/,Qn=`(?:(?:\\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])))`,$n=RegExp(`^${Qn}$`);function er(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 tr(e){return RegExp(`^${er(e)}$`)}function nr(e){let t=er({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(`^${Qn}T(?:${r})$`)}const rr=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},ir=/^-?\d+$/,ar=/^-?\d+(?:\.\d+)?$/,or=/^(?:true|false)$/i,sr=/^null$/i,cr=/^[^A-Z]*$/,lr=/^[^a-z]*$/,ur=k(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),dr={number:`number`,bigint:`bigint`,object:`date`},fr=k(`$ZodCheckLessThan`,(e,t)=>{ur.init(e,t);let n=dr[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),pr=k(`$ZodCheckGreaterThan`,(e,t)=>{ur.init(e,t);let n=dr[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})}}),mr=k(`$ZodCheckMultipleOf`,(e,t)=>{ur.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):Ft(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})}}),hr=k(`$ZodCheckNumberFormat`,(e,t)=>{ur.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Xt[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=ir)}),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}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),gr=k(`$ZodCheckMaxLength`,(e,t)=>{var n;ur.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Nt(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=un(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),_r=k(`$ZodCheckMinLength`,(e,t)=>{var n;ur.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Nt(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=un(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),vr=k(`$ZodCheckLengthEquals`,(e,t)=>{var n;ur.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Nt(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=un(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})}}),yr=k(`$ZodCheckStringFormat`,(e,t)=>{var n,r;ur.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=()=>{})}),br=k(`$ZodCheckRegex`,(e,t)=>{yr.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})}}),xr=k(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=cr,yr.init(e,t)}),Sr=k(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=lr,yr.init(e,t)}),Cr=k(`$ZodCheckIncludes`,(e,t)=>{ur.init(e,t);let n=qt(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})}}),wr=k(`$ZodCheckStartsWith`,(e,t)=>{ur.init(e,t);let n=RegExp(`^${qt(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})}}),Tr=k(`$ZodCheckEndsWith`,(e,t)=>{ur.init(e,t);let n=RegExp(`.*${qt(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})}}),Er=k(`$ZodCheckOverwrite`,(e,t)=>{ur.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Dr=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(`
3
3
  `).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(`
4
4
  `))}};const Or={major:4,minor:4,patch:3},M=k(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Or;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=an(e),i;for(let a of t){if(a._zod.def.when){if(on(e)||!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 Et;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=an(e,t))});else{if(e.issues.length===t)continue;r||=an(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(an(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new Et;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 Et;return o.then(e=>t(e,r,a))}return t(o,r,a)}}A(e,`~standard`,()=>({validate:t=>{try{let n=Sn(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return wn(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),kr=k(`$ZodString`,(e,t)=>{M.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??rr(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}}),N=k(`$ZodStringFormat`,(e,t)=>{yr.init(e,t),kr.init(e,t)}),Ar=k(`$ZodGUID`,(e,t)=>{t.pattern??=Bn,N.init(e,t)}),jr=k(`$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??=Vn(e)}else t.pattern??=Vn();N.init(e,t)}),Mr=k(`$ZodEmail`,(e,t)=>{t.pattern??=Hn,N.init(e,t)}),Nr=k(`$ZodURL`,(e,t)=>{N.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===Xn.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let 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})}}}),Pr=k(`$ZodEmoji`,(e,t)=>{t.pattern??=Un(),N.init(e,t)}),Fr=k(`$ZodNanoID`,(e,t)=>{t.pattern??=Rn,N.init(e,t)}),Ir=k(`$ZodCUID`,(e,t)=>{t.pattern??=Nn,N.init(e,t)}),Lr=k(`$ZodCUID2`,(e,t)=>{t.pattern??=Pn,N.init(e,t)}),Rr=k(`$ZodULID`,(e,t)=>{t.pattern??=Fn,N.init(e,t)}),zr=k(`$ZodXID`,(e,t)=>{t.pattern??=In,N.init(e,t)}),Br=k(`$ZodKSUID`,(e,t)=>{t.pattern??=Ln,N.init(e,t)}),Vr=k(`$ZodISODateTime`,(e,t)=>{t.pattern??=nr(t),N.init(e,t)}),Hr=k(`$ZodISODate`,(e,t)=>{t.pattern??=$n,N.init(e,t)}),Ur=k(`$ZodISOTime`,(e,t)=>{t.pattern??=tr(t),N.init(e,t)}),Wr=k(`$ZodISODuration`,(e,t)=>{t.pattern??=zn,N.init(e,t)}),Gr=k(`$ZodIPv4`,(e,t)=>{t.pattern??=Wn,N.init(e,t),e._zod.bag.format=`ipv4`}),Kr=k(`$ZodIPv6`,(e,t)=>{t.pattern??=Gn,N.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})}}}),qr=k(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Kn,N.init(e,t)}),Jr=k(`$ZodCIDRv6`,(e,t)=>{t.pattern??=qn,N.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 Yr(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Xr=k(`$ZodBase64`,(e,t)=>{t.pattern??=Jn,N.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{Yr(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Zr(e){if(!Yn.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Yr(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const Qr=k(`$ZodBase64URL`,(e,t)=>{t.pattern??=Yn,N.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Zr(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),$r=k(`$ZodE164`,(e,t)=>{t.pattern??=Zn,N.init(e,t)});function ei(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 ti=k(`$ZodJWT`,(e,t)=>{N.init(e,t),e._zod.check=n=>{ei(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),ni=k(`$ZodNumber`,(e,t)=>{M.init(e,t),e._zod.pattern=e._zod.bag.pattern??ar,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}}),ri=k(`$ZodNumberFormat`,(e,t)=>{hr.init(e,t),ni.init(e,t)}),ii=k(`$ZodBoolean`,(e,t)=>{M.init(e,t),e._zod.pattern=or,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}}),ai=k(`$ZodNull`,(e,t)=>{M.init(e,t),e._zod.pattern=sr,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}}),oi=k(`$ZodAny`,(e,t)=>{M.init(e,t),e._zod.parse=e=>e}),si=k(`$ZodUnknown`,(e,t)=>{M.init(e,t),e._zod.parse=e=>e}),ci=k(`$ZodNever`,(e,t)=>{M.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function li(e,t,n){e.issues.length&&t.issues.push(...sn(n,e.issues)),t.value[n]=e.value}const ui=k(`$ZodArray`,(e,t)=>{M.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;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>li(t,n,e))):li(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function di(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...sn(n,e.issues))}if(!o&&!i){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function fi(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=Yt(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function pi(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||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=>di(e,n,i,t,u,d))):di(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}const mi=k(`$ZodObject`,(e,t)=>{if(M.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=Mt(()=>fi(t));A(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=Ht,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.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>di(n,t,e,s,r,i))):di(a,t,e,s,r,i)}return i?pi(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),hi=k(`$ZodObjectJIT`,(e,t)=>{mi.init(e,t);let n=e._zod.parse,r=Mt(()=>fi(t)),i=e=>{let t=new Dr([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=zt(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=zt(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(`
5
5
  if (${n}.issues.length) {
@@ -64,34 +64,36 @@ import e from"node:crypto";import t,{existsSync as n,readFileSync as r}from"node
64
64
 
65
65
  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 eo(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.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:ro(t,`input`,e.processors),output:ro(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function to(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 to(r.element,n);if(r.type===`set`)return to(r.valueType,n);if(r.type===`lazy`)return to(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 to(r.innerType,n);if(r.type===`intersection`)return to(r.left,n)||to(r.right,n);if(r.type===`record`||r.type===`map`)return to(r.keyType,n)||to(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:to(r.in,n)||to(r.out,n);if(r.type===`object`){for(let e in r.shape)if(to(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(to(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(to(e,n))return!0;return!!(r.rest&&to(r.rest,n))}return!1}const no=(e,t={})=>n=>{let r=Qa({...n,processors:t});return P(e,r),$a(r,e),eo(r,e)},ro=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Qa({...i??{},target:a,io:t,processors:n});return P(e,o),$a(o,e),eo(o,e)},io={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},ao=(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=io[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}))])}},oo=(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`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},so=(e,t,n,r)=>{n.type=`boolean`},co=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},lo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},uo=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},fo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},po=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},mo=(e,t,n,r)=>{n.not={}},ho=(e,t,n,r)=>{},go=(e,t,n,r)=>{},_o=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},vo=(e,t,n,r)=>{let i=e._zod.def,a=At(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},yo=(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},bo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},xo=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},So=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},Co=(e,t,n,r)=>{n.type=`boolean`},wo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},To=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},Eo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},Do=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},Oo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},ko=(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=P(a.element,t,{...r,path:[...r.path,`items`]})},Ao=(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]=P(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=P(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},jo=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>P(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Mo=(e,t,n,r)=>{let i=e._zod.def,a=P(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=P(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]]},No=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>P(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?P(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},Po=(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=P(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=P(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=P(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)}},Fo=(e,t,n,r)=>{let i=e._zod.def,a=P(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`}]},Io=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Lo=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},Ro=(e,t,n,r)=>{let i=e._zod.def;P(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)))},zo=(e,t,n,r)=>{let i=e._zod.def;P(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},Bo=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;P(o,t,r);let s=t.seen.get(e);s.ref=o},Vo=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Ho=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Uo=(e,t,n,r)=>{let i=e._zod.def;P(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Wo={string:ao,number:oo,boolean:so,bigint:co,symbol:lo,null:uo,undefined:fo,void:po,never:mo,any:ho,unknown:go,date:_o,enum:vo,literal:yo,nan:bo,template_literal:xo,file:So,success:Co,custom:wo,function:To,transform:Eo,map:Do,set:Oo,array:ko,object:Ao,union:jo,intersection:Mo,tuple:No,record:Po,nullable:Fo,nonoptional:Io,default:Lo,prefault:Ro,catch:zo,pipe:Bo,readonly:Vo,promise:Ho,optional:Uo,lazy:(e,t,n,r)=>{let i=e._zod.innerType;P(i,t,r);let a=t.seen.get(e);a.ref=i}};function Go(e,t){if(`_idmap`in e){let n=e,r=Qa({...t,processors:Wo}),i={};for(let e of n._idmap.entries()){let[t,n]=e;P(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;$a(r,n),a[t]=eo(r,n)}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=Qa({...t,processors:Wo});return P(e,n),$a(n,e),eo(n,e)}const Ko=k(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);M.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>vn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Sn(e,t,n),e.parseAsync=async(t,n)=>bn(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>wn(e,t,n),e.check=(...n)=>e.clone({...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)=>Jt(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),qo=k(`ZodMiniObject`,(e,t)=>{mi.init(e,t),Ko.init(e,t),A(e,`shape`,()=>t.shape)});function Jo(e,t){return new qo({type:`object`,shape:e??{},...j(t)})}function Yo(e){return!!e._zod}function Xo(e){let t=Object.values(e);if(t.length===0)return Jo({});let n=t.every(Yo),r=t.every(e=>!Yo(e));if(n)return Jo(e);if(r)return wt(e);throw Error(`Mixed Zod versions detected in object shape.`)}function Zo(e,t){return Yo(e)?Sn(e,t):e.safeParse(t)}async function Qo(e,t){return Yo(e)?await wn(e,t):await e.safeParseAsync(t)}function $o(e){if(!e)return;let t;if(t=Yo(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function es(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return Xo(e)}}if(Yo(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function ts(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function ns(e){return e.description}function rs(e){if(Yo(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function is(e){if(Yo(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const as=k(`ZodISODateTime`,(e,t)=>{Vr.init(e,t),L.init(e,t)});function os(e){return ga(as,e)}const ss=k(`ZodISODate`,(e,t)=>{Hr.init(e,t),L.init(e,t)});function cs(e){return _a(ss,e)}const ls=k(`ZodISOTime`,(e,t)=>{Ur.init(e,t),L.init(e,t)});function us(e){return va(ls,e)}const ds=k(`ZodISODuration`,(e,t)=>{Wr.init(e,t),L.init(e,t)});function fs(e){return ya(ds,e)}const ps=k(`ZodError`,(e,t)=>{pn.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>gn(e,t)},flatten:{value:t=>hn(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jt,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jt,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),ms=_n(ps),hs=yn(ps),gs=xn(ps),_s=Cn(ps),vs=Tn(ps),ys=En(ps),bs=Dn(ps),xs=On(ps),Ss=kn(ps),Cs=An(ps),ws=jn(ps),Ts=Mn(ps),Es=new WeakMap;function Ds(e,t,n){let r=Object.getPrototypeOf(e),i=Es.get(r);if(i||(i=new Set,Es.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}const F=k(`ZodType`,(e,t)=>(M.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:ro(e,`input`),output:ro(e,`output`)}}),e.toJSONSchema=no(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.parse=(t,n)=>ms(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>gs(e,t,n),e.parseAsync=async(t,n)=>hs(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>_s(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>vs(e,t,n),e.decode=(t,n)=>ys(e,t,n),e.encodeAsync=async(t,n)=>bs(e,t,n),e.decodeAsync=async(t,n)=>xs(e,t,n),e.safeEncode=(t,n)=>Ss(e,t,n),e.safeDecode=(t,n)=>Cs(e,t,n),e.safeEncodeAsync=async(t,n)=>ws(e,t,n),e.safeDecodeAsync=async(t,n)=>Ts(e,t,n),Ds(e,`ZodType`,{check(...e){let t=this.def;return this.clone(Rt(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Jt(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Vc(e,t))},superRefine(e,t){return this.check(Hc(e,t))},overwrite(e){return this.check(Va(e))},optional(){return G(this)},exactOptional(){return Cc(this)},nullable(){return Tc(this)},nullish(){return G(Tc(this))},nonoptional(e){return jc(this,e)},array(){return B(this)},or(e){return H([this,e])},and(e){return mc(this,e)},transform(e){return Fc(this,bc(e))},default(e){return Dc(this,e)},prefault(e){return kc(this,e)},catch(e){return Nc(this,e)},pipe(e){return Fc(this,e)},readonly(){return Rc(this)},describe(e){let t=this.clone();return Ki.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ki.get(this);let t=this.clone();return Ki.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,`description`,{get(){return Ki.get(e)?.description},configurable:!0}),e)),Os=k(`_ZodString`,(e,t)=>{kr.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ao(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ds(e,`_ZodString`,{regex(...e){return this.check(Fa(...e))},includes(...e){return this.check(Ra(...e))},startsWith(...e){return this.check(za(...e))},endsWith(...e){return this.check(Ba(...e))},min(...e){return this.check(Na(...e))},max(...e){return this.check(Ma(...e))},length(...e){return this.check(Pa(...e))},nonempty(...e){return this.check(Na(1,...e))},lowercase(e){return this.check(Ia(e))},uppercase(e){return this.check(La(e))},trim(){return this.check(Ua())},normalize(...e){return this.check(Ha(...e))},toLowerCase(){return this.check(Wa())},toUpperCase(){return this.check(Ga())},slugify(){return this.check(Ka())}})}),ks=k(`ZodString`,(e,t)=>{kr.init(e,t),Os.init(e,t),e.email=t=>e.check(Ji(As,t)),e.url=t=>e.check(ea(Ns,t)),e.jwt=t=>e.check(ha(Js,t)),e.emoji=t=>e.check(ta(Ps,t)),e.guid=t=>e.check(Yi(js,t)),e.uuid=t=>e.check(Xi(Ms,t)),e.uuidv4=t=>e.check(Zi(Ms,t)),e.uuidv6=t=>e.check(Qi(Ms,t)),e.uuidv7=t=>e.check($i(Ms,t)),e.nanoid=t=>e.check(na(Fs,t)),e.guid=t=>e.check(Yi(js,t)),e.cuid=t=>e.check(ra(Is,t)),e.cuid2=t=>e.check(ia(Ls,t)),e.ulid=t=>e.check(aa(Rs,t)),e.base64=t=>e.check(fa(Gs,t)),e.base64url=t=>e.check(pa(Ks,t)),e.xid=t=>e.check(oa(zs,t)),e.ksuid=t=>e.check(sa(Bs,t)),e.ipv4=t=>e.check(ca(Vs,t)),e.ipv6=t=>e.check(la(Hs,t)),e.cidrv4=t=>e.check(ua(Us,t)),e.cidrv6=t=>e.check(da(Ws,t)),e.e164=t=>e.check(ma(qs,t)),e.datetime=t=>e.check(os(t)),e.date=t=>e.check(cs(t)),e.time=t=>e.check(us(t)),e.duration=t=>e.check(fs(t))});function I(e){return qi(ks,e)}const L=k(`ZodStringFormat`,(e,t)=>{N.init(e,t),Os.init(e,t)}),As=k(`ZodEmail`,(e,t)=>{Mr.init(e,t),L.init(e,t)}),js=k(`ZodGUID`,(e,t)=>{Ar.init(e,t),L.init(e,t)}),Ms=k(`ZodUUID`,(e,t)=>{jr.init(e,t),L.init(e,t)}),Ns=k(`ZodURL`,(e,t)=>{Nr.init(e,t),L.init(e,t)}),Ps=k(`ZodEmoji`,(e,t)=>{Pr.init(e,t),L.init(e,t)}),Fs=k(`ZodNanoID`,(e,t)=>{Fr.init(e,t),L.init(e,t)}),Is=k(`ZodCUID`,(e,t)=>{Ir.init(e,t),L.init(e,t)}),Ls=k(`ZodCUID2`,(e,t)=>{Lr.init(e,t),L.init(e,t)}),Rs=k(`ZodULID`,(e,t)=>{Rr.init(e,t),L.init(e,t)}),zs=k(`ZodXID`,(e,t)=>{zr.init(e,t),L.init(e,t)}),Bs=k(`ZodKSUID`,(e,t)=>{Br.init(e,t),L.init(e,t)}),Vs=k(`ZodIPv4`,(e,t)=>{Gr.init(e,t),L.init(e,t)}),Hs=k(`ZodIPv6`,(e,t)=>{Kr.init(e,t),L.init(e,t)}),Us=k(`ZodCIDRv4`,(e,t)=>{qr.init(e,t),L.init(e,t)}),Ws=k(`ZodCIDRv6`,(e,t)=>{Jr.init(e,t),L.init(e,t)}),Gs=k(`ZodBase64`,(e,t)=>{Xr.init(e,t),L.init(e,t)}),Ks=k(`ZodBase64URL`,(e,t)=>{Qr.init(e,t),L.init(e,t)}),qs=k(`ZodE164`,(e,t)=>{$r.init(e,t),L.init(e,t)}),Js=k(`ZodJWT`,(e,t)=>{ti.init(e,t),L.init(e,t)}),Ys=k(`ZodNumber`,(e,t)=>{ni.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oo(e,t,n,r),Ds(e,`ZodNumber`,{gt(e,t){return this.check(ka(e,t))},gte(e,t){return this.check(Aa(e,t))},min(e,t){return this.check(Aa(e,t))},lt(e,t){return this.check(Da(e,t))},lte(e,t){return this.check(Oa(e,t))},max(e,t){return this.check(Oa(e,t))},int(e){return this.check(Zs(e))},safe(e){return this.check(Zs(e))},positive(e){return this.check(ka(0,e))},nonnegative(e){return this.check(Aa(0,e))},negative(e){return this.check(Da(0,e))},nonpositive(e){return this.check(Oa(0,e))},multipleOf(e,t){return this.check(ja(e,t))},step(e,t){return this.check(ja(e,t))},finite(){return this}});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 R(e){return ba(Ys,e)}const Xs=k(`ZodNumberFormat`,(e,t)=>{ri.init(e,t),Ys.init(e,t)});function Zs(e){return xa(Xs,e)}const Qs=k(`ZodBoolean`,(e,t)=>{ii.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>so(e,t,n,r)});function $s(e){return Sa(Qs,e)}const ec=k(`ZodNull`,(e,t)=>{ai.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uo(e,t,n,r)});function tc(e){return Ca(ec,e)}const nc=k(`ZodAny`,(e,t)=>{oi.init(e,t),F.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function rc(){return wa(nc)}const ic=k(`ZodUnknown`,(e,t)=>{si.init(e,t),F.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function z(){return Ta(ic)}const ac=k(`ZodNever`,(e,t)=>{ci.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mo(e,t,n,r)});function oc(e){return Ea(ac,e)}const sc=k(`ZodArray`,(e,t)=>{ui.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ko(e,t,n,r),e.element=t.element,Ds(e,`ZodArray`,{min(e,t){return this.check(Na(e,t))},nonempty(e){return this.check(Na(1,e))},max(e,t){return this.check(Ma(e,t))},length(e,t){return this.check(Pa(e,t))},unwrap(){return this.element}})});function B(e,t){return qa(sc,e,t)}const cc=k(`ZodObject`,(e,t)=>{hi.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ao(e,t,n,r),A(e,`shape`,()=>t.shape),Ds(e,`ZodObject`,{keyof(){return _c(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:z()})},loose(){return this.clone({...this._zod.def,catchall:z()})},strict(){return this.clone({...this._zod.def,catchall:oc()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return $t(this,e)},safeExtend(e){return en(this,e)},merge(e){return tn(this,e)},pick(e){return Zt(this,e)},omit(e){return Qt(this,e)},partial(...e){return nn(xc,this,e[0])},required(...e){return rn(Ac,this,e[0])}})});function V(e,t){return new cc({type:`object`,shape:e??{},...j(t)})}function lc(e,t){return new cc({type:`object`,shape:e,catchall:z(),...j(t)})}const uc=k(`ZodUnion`,(e,t)=>{_i.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jo(e,t,n,r),e.options=t.options});function H(e,t){return new uc({type:`union`,options:e,...j(t)})}const dc=k(`ZodDiscriminatedUnion`,(e,t)=>{uc.init(e,t),vi.init(e,t)});function fc(e,t,n){return new dc({type:`union`,options:t,discriminator:e,...j(n)})}const pc=k(`ZodIntersection`,(e,t)=>{yi.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mo(e,t,n,r)});function mc(e,t){return new pc({type:`intersection`,left:e,right:t})}const hc=k(`ZodRecord`,(e,t)=>{Si.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Po(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function U(e,t,n){return!t||!t._zod?new hc({type:`record`,keyType:I(),valueType:e,...j(t)}):new hc({type:`record`,keyType:e,valueType:t,...j(n)})}const gc=k(`ZodEnum`,(e,t)=>{Ci.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vo(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 gc({...t,checks:[],...j(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 gc({...t,checks:[],...j(r),entries:i})}});function _c(e,t){return new gc({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...j(t)})}const vc=k(`ZodLiteral`,(e,t)=>{wi.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yo(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 W(e,t){return new vc({type:`literal`,values:Array.isArray(e)?e:[e],...j(t)})}const yc=k(`ZodTransform`,(e,t)=>{Ti.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Eo(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Dt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(dn(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(dn(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function bc(e){return new yc({type:`transform`,transform:e})}const xc=k(`ZodOptional`,(e,t)=>{Di.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function G(e){return new xc({type:`optional`,innerType:e})}const Sc=k(`ZodExactOptional`,(e,t)=>{Oi.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Cc(e){return new Sc({type:`optional`,innerType:e})}const wc=k(`ZodNullable`,(e,t)=>{ki.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Tc(e){return new wc({type:`nullable`,innerType:e})}const Ec=k(`ZodDefault`,(e,t)=>{Ai.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Dc(e,t){return new Ec({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Gt(t)}})}const Oc=k(`ZodPrefault`,(e,t)=>{Mi.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ro(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function kc(e,t){return new Oc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Gt(t)}})}const Ac=k(`ZodNonOptional`,(e,t)=>{Ni.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Io(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function jc(e,t){return new Ac({type:`nonoptional`,innerType:e,...j(t)})}const Mc=k(`ZodCatch`,(e,t)=>{Fi.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Nc(e,t){return new Mc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const Pc=k(`ZodPipe`,(e,t)=>{Ii.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bo(e,t,n,r),e.in=t.in,e.out=t.out});function Fc(e,t){return new Pc({type:`pipe`,in:e,out:t})}const Ic=k(`ZodPreprocess`,(e,t)=>{Pc.init(e,t),Ri.init(e,t)}),Lc=k(`ZodReadonly`,(e,t)=>{zi.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Rc(e){return new Lc({type:`readonly`,innerType:e})}const zc=k(`ZodCustom`,(e,t)=>{Vi.init(e,t),F.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wo(e,t,n,r)});function Bc(e,t){return Ja(zc,e??(()=>!0),t)}function Vc(e,t={}){return Ya(zc,e,t)}function Hc(e,t){return Xa(e,t)}function Uc(e,t){return new Ic({type:`pipe`,in:bc(e),out:t})}const Wc=`2025-11-25`,Gc=[Wc,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Kc=`io.modelcontextprotocol/related-task`,qc=Bc(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Jc=H([I(),R().int()]),Yc=I();lc({ttl:R().optional(),pollInterval:R().optional()});const Xc=V({ttl:R().optional()}),Zc=V({taskId:I()}),Qc=lc({progressToken:Jc.optional(),[Kc]:Zc.optional()}),$c=V({_meta:Qc.optional()}),el=$c.extend({task:Xc.optional()}),tl=e=>el.safeParse(e).success,nl=V({method:I(),params:$c.loose().optional()}),rl=V({_meta:Qc.optional()}),il=V({method:I(),params:rl.loose().optional()}),al=lc({_meta:Qc.optional()}),ol=H([I(),R().int()]),sl=V({jsonrpc:W(`2.0`),id:ol,...nl.shape}).strict(),cl=e=>sl.safeParse(e).success,ll=V({jsonrpc:W(`2.0`),...il.shape}).strict(),ul=e=>ll.safeParse(e).success,dl=V({jsonrpc:W(`2.0`),id:ol,result:al}).strict(),fl=e=>dl.safeParse(e).success;var K;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(K||={});const pl=V({jsonrpc:W(`2.0`),id:ol.optional(),error:V({code:R().int(),message:I(),data:z().optional()})}).strict(),ml=e=>pl.safeParse(e).success,hl=H([sl,ll,dl,pl]);H([dl,pl]);const gl=al.strict(),_l=rl.extend({requestId:ol.optional(),reason:I().optional()}),vl=il.extend({method:W(`notifications/cancelled`),params:_l}),yl=V({icons:B(V({src:I(),mimeType:I().optional(),sizes:B(I()).optional(),theme:_c([`light`,`dark`]).optional()})).optional()}),bl=V({name:I(),title:I().optional()}),xl=bl.extend({...bl.shape,...yl.shape,version:I(),websiteUrl:I().optional(),description:I().optional()}),Sl=Uc(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,mc(V({form:mc(V({applyDefaults:$s().optional()}),U(I(),z())).optional(),url:qc.optional()}),U(I(),z()).optional())),Cl=lc({list:qc.optional(),cancel:qc.optional(),requests:lc({sampling:lc({createMessage:qc.optional()}).optional(),elicitation:lc({create:qc.optional()}).optional()}).optional()}),wl=lc({list:qc.optional(),cancel:qc.optional(),requests:lc({tools:lc({call:qc.optional()}).optional()}).optional()}),Tl=V({experimental:U(I(),qc).optional(),sampling:V({context:qc.optional(),tools:qc.optional()}).optional(),elicitation:Sl.optional(),roots:V({listChanged:$s().optional()}).optional(),tasks:Cl.optional(),extensions:U(I(),qc).optional()}),El=$c.extend({protocolVersion:I(),capabilities:Tl,clientInfo:xl}),Dl=nl.extend({method:W(`initialize`),params:El}),Ol=V({experimental:U(I(),qc).optional(),logging:qc.optional(),completions:qc.optional(),prompts:V({listChanged:$s().optional()}).optional(),resources:V({subscribe:$s().optional(),listChanged:$s().optional()}).optional(),tools:V({listChanged:$s().optional()}).optional(),tasks:wl.optional(),extensions:U(I(),qc).optional()}),kl=al.extend({protocolVersion:I(),capabilities:Ol,serverInfo:xl,instructions:I().optional()}),Al=il.extend({method:W(`notifications/initialized`),params:rl.optional()}),jl=nl.extend({method:W(`ping`),params:$c.optional()}),Ml=V({progress:R(),total:G(R()),message:G(I())}),Nl=V({...rl.shape,...Ml.shape,progressToken:Jc}),Pl=il.extend({method:W(`notifications/progress`),params:Nl}),Fl=$c.extend({cursor:Yc.optional()}),Il=nl.extend({params:Fl.optional()}),Ll=al.extend({nextCursor:Yc.optional()}),Rl=_c([`working`,`input_required`,`completed`,`failed`,`cancelled`]),zl=V({taskId:I(),status:Rl,ttl:H([R(),tc()]),createdAt:I(),lastUpdatedAt:I(),pollInterval:G(R()),statusMessage:G(I())}),Bl=al.extend({task:zl}),Vl=rl.merge(zl),Hl=il.extend({method:W(`notifications/tasks/status`),params:Vl}),Ul=nl.extend({method:W(`tasks/get`),params:$c.extend({taskId:I()})}),Wl=al.merge(zl),Gl=nl.extend({method:W(`tasks/result`),params:$c.extend({taskId:I()})});al.loose();const Kl=Il.extend({method:W(`tasks/list`)}),ql=Ll.extend({tasks:B(zl)}),Jl=nl.extend({method:W(`tasks/cancel`),params:$c.extend({taskId:I()})}),Yl=al.merge(zl),Xl=V({uri:I(),mimeType:G(I()),_meta:U(I(),z()).optional()}),Zl=Xl.extend({text:I()}),Ql=I().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),$l=Xl.extend({blob:Ql}),eu=_c([`user`,`assistant`]),tu=V({audience:B(eu).optional(),priority:R().min(0).max(1).optional(),lastModified:os({offset:!0}).optional()}),nu=V({...bl.shape,...yl.shape,uri:I(),description:G(I()),mimeType:G(I()),size:G(R()),annotations:tu.optional(),_meta:G(lc({}))}),ru=V({...bl.shape,...yl.shape,uriTemplate:I(),description:G(I()),mimeType:G(I()),annotations:tu.optional(),_meta:G(lc({}))}),iu=Il.extend({method:W(`resources/list`)}),au=Ll.extend({resources:B(nu)}),ou=Il.extend({method:W(`resources/templates/list`)}),su=Ll.extend({resourceTemplates:B(ru)}),cu=$c.extend({uri:I()}),lu=cu,uu=nl.extend({method:W(`resources/read`),params:lu}),du=al.extend({contents:B(H([Zl,$l]))}),fu=il.extend({method:W(`notifications/resources/list_changed`),params:rl.optional()}),pu=cu,mu=nl.extend({method:W(`resources/subscribe`),params:pu}),hu=cu,gu=nl.extend({method:W(`resources/unsubscribe`),params:hu}),_u=rl.extend({uri:I()}),vu=il.extend({method:W(`notifications/resources/updated`),params:_u}),yu=V({name:I(),description:G(I()),required:G($s())}),bu=V({...bl.shape,...yl.shape,description:G(I()),arguments:G(B(yu)),_meta:G(lc({}))}),xu=Il.extend({method:W(`prompts/list`)}),Su=Ll.extend({prompts:B(bu)}),Cu=$c.extend({name:I(),arguments:U(I(),I()).optional()}),wu=nl.extend({method:W(`prompts/get`),params:Cu}),Tu=V({type:W(`text`),text:I(),annotations:tu.optional(),_meta:U(I(),z()).optional()}),Eu=V({type:W(`image`),data:Ql,mimeType:I(),annotations:tu.optional(),_meta:U(I(),z()).optional()}),Du=V({type:W(`audio`),data:Ql,mimeType:I(),annotations:tu.optional(),_meta:U(I(),z()).optional()}),Ou=V({type:W(`tool_use`),name:I(),id:I(),input:U(I(),z()),_meta:U(I(),z()).optional()}),ku=V({type:W(`resource`),resource:H([Zl,$l]),annotations:tu.optional(),_meta:U(I(),z()).optional()}),Au=H([Tu,Eu,Du,nu.extend({type:W(`resource_link`)}),ku]),ju=V({role:eu,content:Au}),Mu=al.extend({description:I().optional(),messages:B(ju)}),Nu=il.extend({method:W(`notifications/prompts/list_changed`),params:rl.optional()}),Pu=V({title:I().optional(),readOnlyHint:$s().optional(),destructiveHint:$s().optional(),idempotentHint:$s().optional(),openWorldHint:$s().optional()}),Fu=V({taskSupport:_c([`required`,`optional`,`forbidden`]).optional()}),Iu=V({...bl.shape,...yl.shape,description:I().optional(),inputSchema:V({type:W(`object`),properties:U(I(),qc).optional(),required:B(I()).optional()}).catchall(z()),outputSchema:V({type:W(`object`),properties:U(I(),qc).optional(),required:B(I()).optional()}).catchall(z()).optional(),annotations:Pu.optional(),execution:Fu.optional(),_meta:U(I(),z()).optional()}),Lu=Il.extend({method:W(`tools/list`)}),Ru=Ll.extend({tools:B(Iu)}),zu=al.extend({content:B(Au).default([]),structuredContent:U(I(),z()).optional(),isError:$s().optional()});zu.or(al.extend({toolResult:z()}));const Bu=el.extend({name:I(),arguments:U(I(),z()).optional()}),Vu=nl.extend({method:W(`tools/call`),params:Bu}),Hu=il.extend({method:W(`notifications/tools/list_changed`),params:rl.optional()});V({autoRefresh:$s().default(!0),debounceMs:R().int().nonnegative().default(300)});const Uu=_c([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Wu=$c.extend({level:Uu}),Gu=nl.extend({method:W(`logging/setLevel`),params:Wu}),Ku=rl.extend({level:Uu,logger:I().optional(),data:z()}),qu=il.extend({method:W(`notifications/message`),params:Ku}),Ju=V({hints:B(V({name:I().optional()})).optional(),costPriority:R().min(0).max(1).optional(),speedPriority:R().min(0).max(1).optional(),intelligencePriority:R().min(0).max(1).optional()}),Yu=V({mode:_c([`auto`,`required`,`none`]).optional()}),Xu=V({type:W(`tool_result`),toolUseId:I().describe(`The unique identifier for the corresponding tool call.`),content:B(Au).default([]),structuredContent:V({}).loose().optional(),isError:$s().optional(),_meta:U(I(),z()).optional()}),Zu=fc(`type`,[Tu,Eu,Du]),Qu=fc(`type`,[Tu,Eu,Du,Ou,Xu]),$u=V({role:eu,content:H([Qu,B(Qu)]),_meta:U(I(),z()).optional()}),ed=el.extend({messages:B($u),modelPreferences:Ju.optional(),systemPrompt:I().optional(),includeContext:_c([`none`,`thisServer`,`allServers`]).optional(),temperature:R().optional(),maxTokens:R().int(),stopSequences:B(I()).optional(),metadata:qc.optional(),tools:B(Iu).optional(),toolChoice:Yu.optional()}),td=nl.extend({method:W(`sampling/createMessage`),params:ed}),nd=al.extend({model:I(),stopReason:G(_c([`endTurn`,`stopSequence`,`maxTokens`]).or(I())),role:eu,content:Zu}),rd=al.extend({model:I(),stopReason:G(_c([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(I())),role:eu,content:H([Qu,B(Qu)])}),id=V({type:W(`boolean`),title:I().optional(),description:I().optional(),default:$s().optional()}),ad=V({type:W(`string`),title:I().optional(),description:I().optional(),minLength:R().optional(),maxLength:R().optional(),format:_c([`email`,`uri`,`date`,`date-time`]).optional(),default:I().optional()}),od=V({type:_c([`number`,`integer`]),title:I().optional(),description:I().optional(),minimum:R().optional(),maximum:R().optional(),default:R().optional()}),sd=V({type:W(`string`),title:I().optional(),description:I().optional(),enum:B(I()),default:I().optional()}),cd=V({type:W(`string`),title:I().optional(),description:I().optional(),oneOf:B(V({const:I(),title:I()})),default:I().optional()}),ld=H([H([V({type:W(`string`),title:I().optional(),description:I().optional(),enum:B(I()),enumNames:B(I()).optional(),default:I().optional()}),H([sd,cd]),H([V({type:W(`array`),title:I().optional(),description:I().optional(),minItems:R().optional(),maxItems:R().optional(),items:V({type:W(`string`),enum:B(I())}),default:B(I()).optional()}),V({type:W(`array`),title:I().optional(),description:I().optional(),minItems:R().optional(),maxItems:R().optional(),items:V({anyOf:B(V({const:I(),title:I()}))}),default:B(I()).optional()})])]),id,ad,od]),ud=H([el.extend({mode:W(`form`).optional(),message:I(),requestedSchema:V({type:W(`object`),properties:U(I(),ld),required:B(I()).optional()})}),el.extend({mode:W(`url`),message:I(),elicitationId:I(),url:I().url()})]),dd=nl.extend({method:W(`elicitation/create`),params:ud}),fd=rl.extend({elicitationId:I()}),pd=il.extend({method:W(`notifications/elicitation/complete`),params:fd}),md=al.extend({action:_c([`accept`,`decline`,`cancel`]),content:Uc(e=>e===null?void 0:e,U(I(),H([I(),R(),$s(),B(I())])).optional())}),hd=V({type:W(`ref/resource`),uri:I()}),gd=V({type:W(`ref/prompt`),name:I()}),_d=$c.extend({ref:H([gd,hd]),argument:V({name:I(),value:I()}),context:V({arguments:U(I(),I()).optional()}).optional()}),vd=nl.extend({method:W(`completion/complete`),params:_d});function yd(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function bd(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const xd=al.extend({completion:lc({values:B(I()).max(100),total:G(R().int()),hasMore:G($s())})}),Sd=V({uri:I().startsWith(`file://`),name:I().optional(),_meta:U(I(),z()).optional()}),Cd=nl.extend({method:W(`roots/list`),params:$c.optional()}),wd=al.extend({roots:B(Sd)}),Td=il.extend({method:W(`notifications/roots/list_changed`),params:rl.optional()});H([jl,Dl,vd,Gu,wu,xu,iu,ou,uu,mu,gu,Vu,Lu,Ul,Gl,Kl,Jl]),H([vl,Pl,Al,Td,Hl]),H([gl,nd,rd,md,wd,Wl,ql,Bl]),H([jl,td,dd,Cd,Ul,Gl,Kl,Jl]),H([vl,Pl,qu,vu,fu,Hu,Nu,Hl,pd]),H([gl,kl,xd,Mu,Su,au,su,du,zu,Ru,Wl,ql,Bl]);var q=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===K.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Ed(e.elicitations,n)}return new e(t,n,r)}},Ed=class extends q{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(K.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Dd(e){return e===`completed`||e===`failed`||e===`cancelled`}const Od=Symbol(`Let zodToJsonSchema decide on which parser to use`),kd={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},Ad=e=>typeof e==`string`?{...kd,name:e}:{...kd,...e},jd=e=>{let t=Ad(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function Md(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function J(e,t,n,r,i){e[t]=n,Md(e,t,r,i)}const Nd=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function Pd(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?Nd(t,e.currentPath):t.join(`/`)}}function Fd(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==O.ZodAny&&(n.items=Y(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&J(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&J(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(J(n,`minItems`,e.exactLength.value,e.exactLength.message,t),J(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Id(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?J(n,`minimum`,r.value,r.message,t):J(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),J(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?J(n,`maximum`,r.value,r.message,t):J(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),J(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:J(n,`multipleOf`,r.value,r.message,t);break}return n}function Ld(){return{type:`boolean`}}function Rd(e,t){return Y(e.type._def,t)}const zd=(e,t)=>Y(e.innerType._def,t);function Bd(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Bd(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Vd(e,t)}}const Vd=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:J(n,`minimum`,r.value,r.message,t);break;case`max`:J(n,`maximum`,r.value,r.message,t);break}return n};function Hd(e,t){return{...Y(e.innerType._def,t),default:e.defaultValue()}}function Ud(e,t){return t.effectStrategy===`input`?Y(e.schema._def,t):Pd(t)}function Wd(e){return{type:`string`,enum:Array.from(e.values)}}const Gd=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Kd(e,t){let n=[Y(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Y(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Gd(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function qd(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let Jd;const Yd={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Jd===void 0&&(Jd=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Jd),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Xd(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:J(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:J(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:ef(n,`email`,r.message,t);break;case`format:idn-email`:ef(n,`idn-email`,r.message,t);break;case`pattern:zod`:tf(n,Yd.email,r.message,t);break}break;case`url`:ef(n,`uri`,r.message,t);break;case`uuid`:ef(n,`uuid`,r.message,t);break;case`regex`:tf(n,r.regex,r.message,t);break;case`cuid`:tf(n,Yd.cuid,r.message,t);break;case`cuid2`:tf(n,Yd.cuid2,r.message,t);break;case`startsWith`:tf(n,RegExp(`^${Zd(r.value,t)}`),r.message,t);break;case`endsWith`:tf(n,RegExp(`${Zd(r.value,t)}$`),r.message,t);break;case`datetime`:ef(n,`date-time`,r.message,t);break;case`date`:ef(n,`date`,r.message,t);break;case`time`:ef(n,`time`,r.message,t);break;case`duration`:ef(n,`duration`,r.message,t);break;case`length`:J(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),J(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:tf(n,RegExp(Zd(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&ef(n,`ipv4`,r.message,t),r.version!==`v4`&&ef(n,`ipv6`,r.message,t);break;case`base64url`:tf(n,Yd.base64url,r.message,t);break;case`jwt`:tf(n,Yd.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&tf(n,Yd.ipv4Cidr,r.message,t),r.version!==`v4`&&tf(n,Yd.ipv6Cidr,r.message,t);break;case`emoji`:tf(n,Yd.emoji(),r.message,t);break;case`ulid`:tf(n,Yd.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:ef(n,`binary`,r.message,t);break;case`contentEncoding:base64`:J(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:tf(n,Yd.base64,r.message,t);break}break;case`nanoid`:tf(n,Yd.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function Zd(e,t){return t.patternStrategy===`escape`?$d(e):e}const Qd=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function $d(e){let t=``;for(let n=0;n<e.length;n++)Qd.has(e[n])||(t+=`\\`),t+=e[n];return t}function ef(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):J(e,`format`,t,n,r)}function tf(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:nf(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):J(e,`pattern`,nf(t,r),n,r)}function nf(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
66
66
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
67
- ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function rf(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===O.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:Y(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??Pd(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:Y(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===O.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=Xd(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===O.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===O.ZodBranded&&e.keyType._def.type._def.typeName===O.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Rd(e.keyType._def,t);return{...n,propertyNames:i}}return n}function af(e,t){return t.mapStrategy===`record`?rf(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Y(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||Pd(t),Y(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||Pd(t)],minItems:2,maxItems:2}}}function of(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function sf(e){return e.target===`openAi`?void 0:{not:Pd({...e,currentPath:[...e.currentPath,`not`]})}}function cf(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const lf={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function uf(e,t){if(t.target===`openApi3`)return df(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in lf&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=lf[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return df(e,t)}const df=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Y(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function ff(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:lf[e.innerType._def.typeName],nullable:!0}:{type:[lf[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=Y(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=Y(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function pf(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,Md(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?J(n,`minimum`,r.value,r.message,t):J(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),J(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?J(n,`maximum`,r.value,r.message,t):J(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),J(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:J(n,`multipleOf`,r.value,r.message,t);break}return n}function mf(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=gf(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=Y(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=hf(e,t);return o!==void 0&&(r.additionalProperties=o),r}function hf(e,t){if(e.catchall._def.typeName!==`ZodNever`)return Y(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function gf(e){try{return e.isOptional()}catch{return!0}}const _f=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Y(e.innerType._def,t);let n=Y(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:Pd(t)},n]}:Pd(t)},vf=(e,t)=>{if(t.pipeStrategy===`input`)return Y(e.in._def,t);if(t.pipeStrategy===`output`)return Y(e.out._def,t);let n=Y(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,Y(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function yf(e,t){return Y(e.type._def,t)}function bf(e,t){let n={type:`array`,uniqueItems:!0,items:Y(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&J(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&J(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function xf(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Y(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Y(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Y(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Sf(e){return{not:Pd(e)}}function Cf(e){return Pd(e)}const wf=(e,t)=>Y(e.innerType._def,t),Tf=(e,t,n)=>{switch(t){case O.ZodString:return Xd(e,n);case O.ZodNumber:return pf(e,n);case O.ZodObject:return mf(e,n);case O.ZodBigInt:return Id(e,n);case O.ZodBoolean:return Ld();case O.ZodDate:return Bd(e,n);case O.ZodUndefined:return Sf(n);case O.ZodNull:return cf(n);case O.ZodArray:return Fd(e,n);case O.ZodUnion:case O.ZodDiscriminatedUnion:return uf(e,n);case O.ZodIntersection:return Kd(e,n);case O.ZodTuple:return xf(e,n);case O.ZodRecord:return rf(e,n);case O.ZodLiteral:return qd(e,n);case O.ZodEnum:return Wd(e);case O.ZodNativeEnum:return of(e);case O.ZodNullable:return ff(e,n);case O.ZodOptional:return _f(e,n);case O.ZodMap:return af(e,n);case O.ZodSet:return bf(e,n);case O.ZodLazy:return()=>e.getter()._def;case O.ZodPromise:return yf(e,n);case O.ZodNaN:case O.ZodNever:return sf(n);case O.ZodEffects:return Ud(e,n);case O.ZodAny:return Pd(n);case O.ZodUnknown:return Cf(n);case O.ZodDefault:return Hd(e,n);case O.ZodBranded:return Rd(e,n);case O.ZodReadonly:return wf(e,n);case O.ZodCatch:return zd(e,n);case O.ZodPipeline:return vf(e,n);case O.ZodFunction:case O.ZodVoid:case O.ZodSymbol:return;default:return(e=>void 0)(t)}};function Y(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==Od)return i}if(r&&!n){let e=Ef(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=Tf(e,e.typeName,t),o=typeof a==`function`?Y(a(),t):a;if(o&&Df(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const Ef=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:Nd(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),Pd(t)):t.$refStrategy===`seen`?Pd(t):void 0}},Df=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Of=(e,t)=>{let n=jd(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:Y(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Pd(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=Y(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??Pd(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function kf(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function Af(e,t){return Yo(e)?Go(e,{target:kf(t?.target),io:t?.pipeStrategy??`input`}):Of(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function jf(e){let t=$o(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=is(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Mf(e,t){let n=Zo(e,t);if(!n.success)throw n.error;return n.data}var Nf=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(vl,e=>{this._oncancel(e)}),this.setNotificationHandler(Pl,e=>{this._onprogress(e)}),this.setRequestHandler(jl,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ul,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new q(K.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(Gl,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new q(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new q(K.InvalidParams,`Task not found: ${r}`);if(!Dd(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(Dd(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[Kc]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Kl,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new q(K.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Jl,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new q(K.InvalidParams,`Task not found: ${e.params.taskId}`);if(Dd(n.status))throw new q(K.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new q(K.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof q?e:new q(K.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}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),q.fromError(K.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){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),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),fl(e)||ml(e)?this._onresponse(e):cl(e)?this._onrequest(e,t):ul(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=q.fromError(K.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_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=e.params?._meta?.[Kc]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:K.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=tl(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new q(K.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:K.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&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._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),fl(e)?n(e):n(new q(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(fl(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),fl(e)?r(e):r(q.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof q?e:new q(K.InternalError,String(e))}}return}let i;try{let r=await this.request(e,Bl,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new q(K.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},Dd(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new q(K.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new q(K.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},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 q?e:new q(K.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};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),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,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}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Kc]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(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 q?e:new q(K.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Zo(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(q.fromError(K.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},Wl,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},ql,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Yl,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[Kc]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}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(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Kc]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Kc]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=jf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Mf(e,n);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=jf(e);this._notificationHandlers.set(n,n=>{let r=Mf(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&cl(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new q(K.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new q(K.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new q(K.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);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 q(K.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=Hl.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),Dd(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new q(K.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Dd(a.status))throw new q(K.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=Hl.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),Dd(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Pf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ff(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];Pf(a)&&Pf(i)?n[r]={...a,...i}:n[r]=i}return n}var If=h((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<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),Lf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=If();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}}})),X=h((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=If(),n=Lf();var r=If();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=Lf();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&&=C(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=C(this.rhs,e,n),this}get names(){return S(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=C(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)||(w(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(oe(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=C(this.condition,e,t),this}get names(){let e=super.names;return S(e,this.condition),this.else&&ae(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var ee=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=C(this.iteration,e,t),this}get names(){return ae(super.names,this.iteration.names)}},y=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 S(S(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=C(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?`
68
- `:``},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 ee(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 y(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 S(e,n){return n instanceof t._CodeOrName?ae(e,n.names):e}function C(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 w(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function oe(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${T(e)}`}e.not=oe;let se=de(e.operators.AND);function ce(...e){return e.reduce(se)}e.and=ce;let le=de(e.operators.OR);function ue(...e){return e.reduce(le)}e.or=ue;function de(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${T(n)} ${e} ${T(r)}`}function T(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),Z=h((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=X(),n=If();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 ee;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(ee||(e.Type=ee={}));function y(e,n,r){if(e instanceof t.Name){let i=n===ee.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=y;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})),Rf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();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`)}})),zf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=X(),n=Z(),r=Rf();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])}})),Bf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=zf(),n=X(),r=Rf(),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)}})),Vf=h((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})),Hf=h((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})),Uf=h((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=Vf(),n=Hf(),r=zf(),i=X(),a=Z();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
67
+ ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function rf(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===O.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:Y(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??Pd(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:Y(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===O.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=Xd(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===O.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===O.ZodBranded&&e.keyType._def.type._def.typeName===O.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Rd(e.keyType._def,t);return{...n,propertyNames:i}}return n}function af(e,t){return t.mapStrategy===`record`?rf(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Y(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||Pd(t),Y(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||Pd(t)],minItems:2,maxItems:2}}}function of(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function sf(e){return e.target===`openAi`?void 0:{not:Pd({...e,currentPath:[...e.currentPath,`not`]})}}function cf(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const lf={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function uf(e,t){if(t.target===`openApi3`)return df(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in lf&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=lf[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return df(e,t)}const df=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Y(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function ff(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:lf[e.innerType._def.typeName],nullable:!0}:{type:[lf[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=Y(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=Y(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function pf(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,Md(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?J(n,`minimum`,r.value,r.message,t):J(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),J(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?J(n,`maximum`,r.value,r.message,t):J(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),J(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:J(n,`multipleOf`,r.value,r.message,t);break}return n}function mf(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=gf(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=Y(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=hf(e,t);return o!==void 0&&(r.additionalProperties=o),r}function hf(e,t){if(e.catchall._def.typeName!==`ZodNever`)return Y(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function gf(e){try{return e.isOptional()}catch{return!0}}const _f=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Y(e.innerType._def,t);let n=Y(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:Pd(t)},n]}:Pd(t)},vf=(e,t)=>{if(t.pipeStrategy===`input`)return Y(e.in._def,t);if(t.pipeStrategy===`output`)return Y(e.out._def,t);let n=Y(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,Y(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function yf(e,t){return Y(e.type._def,t)}function bf(e,t){let n={type:`array`,uniqueItems:!0,items:Y(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&J(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&J(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function xf(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Y(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Y(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Y(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Sf(e){return{not:Pd(e)}}function Cf(e){return Pd(e)}const wf=(e,t)=>Y(e.innerType._def,t),Tf=(e,t,n)=>{switch(t){case O.ZodString:return Xd(e,n);case O.ZodNumber:return pf(e,n);case O.ZodObject:return mf(e,n);case O.ZodBigInt:return Id(e,n);case O.ZodBoolean:return Ld();case O.ZodDate:return Bd(e,n);case O.ZodUndefined:return Sf(n);case O.ZodNull:return cf(n);case O.ZodArray:return Fd(e,n);case O.ZodUnion:case O.ZodDiscriminatedUnion:return uf(e,n);case O.ZodIntersection:return Kd(e,n);case O.ZodTuple:return xf(e,n);case O.ZodRecord:return rf(e,n);case O.ZodLiteral:return qd(e,n);case O.ZodEnum:return Wd(e);case O.ZodNativeEnum:return of(e);case O.ZodNullable:return ff(e,n);case O.ZodOptional:return _f(e,n);case O.ZodMap:return af(e,n);case O.ZodSet:return bf(e,n);case O.ZodLazy:return()=>e.getter()._def;case O.ZodPromise:return yf(e,n);case O.ZodNaN:case O.ZodNever:return sf(n);case O.ZodEffects:return Ud(e,n);case O.ZodAny:return Pd(n);case O.ZodUnknown:return Cf(n);case O.ZodDefault:return Hd(e,n);case O.ZodBranded:return Rd(e,n);case O.ZodReadonly:return wf(e,n);case O.ZodCatch:return zd(e,n);case O.ZodPipeline:return vf(e,n);case O.ZodFunction:case O.ZodVoid:case O.ZodSymbol:return;default:return(e=>void 0)(t)}};function Y(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==Od)return i}if(r&&!n){let e=Ef(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=Tf(e,e.typeName,t),o=typeof a==`function`?Y(a(),t):a;if(o&&Df(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const Ef=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:Nd(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),Pd(t)):t.$refStrategy===`seen`?Pd(t):void 0}},Df=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Of=(e,t)=>{let n=jd(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:Y(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Pd(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=Y(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??Pd(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function kf(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function Af(e,t){return Yo(e)?Go(e,{target:kf(t?.target),io:t?.pipeStrategy??`input`}):Of(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function jf(e){let t=$o(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=is(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Mf(e,t){let n=Zo(e,t);if(!n.success)throw n.error;return n.data}var Nf=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(vl,e=>{this._oncancel(e)}),this.setNotificationHandler(Pl,e=>{this._onprogress(e)}),this.setRequestHandler(jl,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ul,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new q(K.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(Gl,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new q(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new q(K.InvalidParams,`Task not found: ${r}`);if(!Dd(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(Dd(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[Kc]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Kl,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new q(K.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Jl,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new q(K.InvalidParams,`Task not found: ${e.params.taskId}`);if(Dd(n.status))throw new q(K.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new q(K.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof q?e:new q(K.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}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),q.fromError(K.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){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),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),fl(e)||ml(e)?this._onresponse(e):cl(e)?this._onrequest(e,t):ul(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=q.fromError(K.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_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=e.params?._meta?.[Kc]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:K.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=tl(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new q(K.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:K.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&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._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),fl(e)?n(e):n(new q(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(fl(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),fl(e)?r(e):r(q.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof q?e:new q(K.InternalError,String(e))}}return}let i;try{let r=await this.request(e,Bl,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new q(K.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},Dd(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new q(K.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new q(K.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},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 q?e:new q(K.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};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),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,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}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Kc]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(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 q?e:new q(K.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Zo(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(q.fromError(K.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},Wl,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},ql,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Yl,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[Kc]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}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(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Kc]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Kc]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=jf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Mf(e,n);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=jf(e);this._notificationHandlers.set(n,n=>{let r=Mf(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&cl(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new q(K.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new q(K.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new q(K.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);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 q(K.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=Hl.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),Dd(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new q(K.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Dd(a.status))throw new q(K.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=Hl.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),Dd(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Pf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ff(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];Pf(a)&&Pf(i)?n[r]={...a,...i}:n[r]=i}return n}var If=h((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<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),Lf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=If();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}}})),X=h((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=If(),n=Lf();var r=If();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=Lf();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&&=ae(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=ae(this.rhs,e,n),this}get names(){return C(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=ae(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)||(w(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>ie(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(oe(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=ae(this.condition,e,t),this}get names(){let e=super.names;return C(e,this.condition),this.else&&ie(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=ae(this.iteration,e,t),this}get names(){return ie(super.names,this.iteration.names)}},b=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 C(C(super.names,this.from),this.to)}},x=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=ae(this.iterable,e,t),this}get names(){return ie(super.names,this.iterable.names)}},S=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)}};S.kind=`func`;var ee=class extends p{render(e){return`return `+super.render(e)}};ee.kind=`return`;var te=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&&ie(e,this.catch.names),this.finally&&ie(e,this.finally.names),e}},ne=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ne.kind=`catch`;var re=class extends m{render(e){return`finally`+super.render(e)}};re.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
68
+ `:``},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 b(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 x(`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 x(`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 ee;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(ee)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new te;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new ne(e),t(e)}return n&&(this._currNode=r.finally=new re,this.code(n)),this._endBlockNode(ne,re)}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 S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}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 ie(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function C(e,n){return n instanceof t._CodeOrName?ie(e,n.names):e}function ae(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 w(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function oe(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${T(e)}`}e.not=oe;let se=de(e.operators.AND);function ce(...e){return e.reduce(se)}e.and=ce;let le=de(e.operators.OR);function ue(...e){return e.reduce(le)}e.or=ue;function de(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${T(n)} ${e} ${T(r)}`}function T(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),Z=h((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=X(),n=If();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]||x(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 b(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=b;function x(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=x})),Rf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();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`)}})),zf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=X(),n=Z(),r=Rf();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])}})),Bf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=zf(),n=X(),r=Rf(),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)}})),Vf=h((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})),Hf=h((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})),Uf=h((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=Vf(),n=Hf(),r=zf(),i=X(),a=Z();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
69
69
  || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
70
70
  || (${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"
71
- || ${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;s.number&&delete s.integer;for(let e in 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}}})),Wf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=X(),n=Z();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)}`)}})),Gf=h((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=X(),n=Z(),r=Rf(),i=Z();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})),Kf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=X(),n=Rf(),r=Gf(),i=zf();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)y(),i.modifying&&s(e),b(()=>e.error());else{let t=i.async?v():ee();i.modifying&&s(e),b(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>y((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 ee(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),y(t.nil),e}function y(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})),qf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=X(),n=Z();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})),Jf=h(((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}})),Yf=h(((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<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else (p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),Xf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=Z(),n=Jf(),r=Yf(),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})),Zf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Bf(),n=Uf(),r=Hf(),i=Uf(),a=Wf(),o=Kf(),s=qf(),c=X(),l=Rf(),u=Xf(),d=Z(),f=zf();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"; ${ee(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(ee(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&&w(e),ae(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),re(e),oe(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 ee(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 y(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&&w(e),S(e),C(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 ce(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);ce(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 S(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function C(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function w({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 oe(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&&se(e),t.return((0,c._)`${l.default.errors} === 0`))}function se({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 ce(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(()=>ge(e,`$ref`,h.all.$ref.definition));return}p.jtd||ue(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)),le(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):le(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function le(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)&&ge(e,n.keyword,n.definition,t.type)})}function ue(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(de(e,t),e.opts.allowUnionTypes||T(e,t),fe(e,e.dataTypes))}function de(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{E(e.dataTypes,t)||me(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),D(e,t)}}function T(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&me(e,`use allowUnionTypes to allow union type keyword`)}function fe(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=>pe(t,e))&&me(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function pe(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 D(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 me(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var he=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`,ye(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 y(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=he;function ge(e,t,n,r){let i=new he(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 _e=/^\/(?:[^~]|~0|~1)*$/,ve=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ye(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!_e.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=ve.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=ye})),Qf=h((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}}})),$f=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Xf();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))}}})),ep=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=X(),n=Qf(),r=Rf(),i=Xf(),a=Z(),o=Zf();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}})),tp=h(((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}})),np=h(((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),i=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),a=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function s(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let c=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function l(e){return e.length=0,!0}function u(e,t,n){if(e.length){let r=s(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function d(e){let t=0,n={error:!1,address:``,zone:``},r=[],i=[],a=!1,o=!1,c=u;for(let s=0;s<e.length;s++){let u=e[s];if(!(u===`[`||u===`]`))if(u===`:`){if(a===!0&&(o=!0),!c(i,r,n))break;if(++t>7){n.error=!0;break}s>0&&e[s-1]===`:`&&(a=!0),r.push(`:`);continue}else if(u===`%`){if(!c(i,r,n))break;c=l}else{i.push(u);continue}}return i.length&&(c===l?n.zone=i.join(``):o?r.push(i.join(``)):r.push(s(i))),n.address=r.join(``),n}function f(e){if(p(e,`:`)<2)return{host:e,isIPV6:!1};let t=d(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 p(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function m(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}else{n.push(t);break}}else if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}else if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}let h={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},g=/[@/?#:]/g,_=/[@/?#]/g;function v(e,t){let n=t?_:g;return n.lastIndex=0,e.replace(n,e=>h[e])}function ee(e,t=!1){if(e.indexOf(`%`)===-1)return e;let n=``;for(let r=0;r<e.length;r++){if(e[r]===`%`&&r+2<e.length){let o=e.slice(r+1,r+3);if(i(o)){let e=o.toUpperCase(),i=String.fromCharCode(parseInt(e,16));t&&a(i)?n+=i:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function y(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(i(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&a(i)?t+=i:t+=`%`+e,n+=2;continue}}o(e[n])?t+=e[n]:t+=escape(e[n])}return t}function b(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(i(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function x(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let e=f(n);n=e.isIPV6===!0?`[${e.escapedHost}]`:v(n,!1)}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:c,recomposeAuthority:x,reescapeHostDelimiters:v,normalizePercentEncoding:ee,normalizePathEncoding:y,escapePreservingEscapes:b,removeDotSegments:m,isIPv4:r,isUUID:n,normalizeIPv6:f,stringArrayToHexStripped:s}})),rp=h(((e,t)=>{let{isUUID:n}=np(),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=ee(`${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=ee(`${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={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function ee(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:ee}})),ip=h(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizePercentEncoding:a,normalizePathEncoding:o,escapePreservingEscapes:s,reescapeHostDelimiters:c,isIPv4:l,nonSimpleDomain:u}=np(),{SCHEMES:d,getSchemeHandler:f}=rp();function p(e,t){return typeof e==`string`?e=x(e,t):typeof e==`object`&&(e=b(_(e,t),t)),e}function m(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=h(b(e,r),b(t,r),r,!0);return r.skipEscape=!0,_(i,r)}function h(e,t,n,i){let a={};return i||(e=b(_(e,n),n),t=b(_(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 g(e,t,n){let r=ne(e,n),i=ne(t,n);return r!==void 0&&i!==void 0&&r.toLowerCase()===i.toLowerCase()}function _(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:``},o=Object.assign({},t),c=[],l=f(o.scheme||n.scheme);l&&l.serialize&&l.serialize(n,o),n.path!==void 0&&(o.skipEscape?n.path=a(n.path):(n.path=s(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),o.reference!==`suffix`&&n.scheme&&c.push(n.scheme,`:`);let u=i(n);if(u!==void 0&&(o.reference!==`suffix`&&c.push(`//`),c.push(u),n.path&&n.path[0]!==`/`&&c.push(`/`)),n.path!==void 0){let e=n.path;!o.absolutePath&&(!l||!l.absolutePath)&&(e=r(e)),u===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),c.push(e)}return n.query!==void 0&&c.push(`?`,n.query),n.fragment!==void 0&&c.push(`#`,n.fragment),c.join(``)}let v=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function ee(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!==`/`)return`URI path must start with "/" when authority is present.`;if(typeof e.port==`number`&&(e.port<0||e.port>65535))return`URI port is malformed.`}function y(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,s=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let d=e.match(v);if(d){i.scheme=d[1],i.userinfo=d[3],i.host=d[4],i.port=parseInt(d[5],10),i.path=d[6]||``,i.query=d[7],i.fragment=d[8],isNaN(i.port)&&(i.port=d[5]);let t=ee(i,d);if(t!==void 0&&(i.error=i.error||t,a=!0),i.host)if(l(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),s=e.isIPV6}else s=!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 p=f(r.scheme||i.scheme);if(!r.unicodeSupport&&(!p||!p.unicodeSupport)&&i.host&&(r.domainHost||p&&p.domainHost)&&s===!1&&u(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}if((!p||p&&!p.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=c(unescape(i.host),s))),i.path&&=o(i.path),i.fragment))try{i.fragment=encodeURI(decodeURIComponent(i.fragment))}catch{i.error=i.error||`URI malformed`}p&&p.parse&&p.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:a}}function b(e,t){return y(e,t).parsed}function x(e,t){return te(e,t).normalized}function te(e,t){let{parsed:n,malformedAuthorityOrPort:r}=y(e,t);return{normalized:r?e:_(n,t),malformedAuthorityOrPort:r}}function ne(e,t){if(typeof e==`string`){let{normalized:n,malformedAuthorityOrPort:r}=te(e,t);return r?void 0:n}if(typeof e==`object`)return _(e,t)}let re={SCHEMES:d,normalize:p,resolve:m,resolveComponent:h,equal:g,serialize:_,parse:b};t.exports=re,t.exports.default=re,t.exports.fastUri=re})),ap=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=ip();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),op=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Zf();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var n=X();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=Qf(),i=$f(),a=Vf(),o=ep(),s=X(),c=Xf(),l=Uf(),u=Z(),d=tp(),f=ap(),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 ee=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),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)(),y.call(this,g,e,`NOT SUPPORTED`),y.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(C.call(this,n,t),!t)return(0,u.eachItem)(n,e=>w.call(this,e)),this;se.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=>w.call(this,e,r):e=>r.type.forEach(t=>w.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]=le(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}}};ee.ValidationError=r.default,ee.MissingRefError=i.default,e.default=ee;function y(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}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in 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 S=/^[a-z_$][a-z0-9_$:-]*$/i;function C(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!S.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 w(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?oe.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 oe(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 se(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=le(t)),e.validateSchema=this.compile(t,!0))}let ce={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function le(e){return{anyOf:[e,ce]}}})),sp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),cp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=$f(),n=Gf(),r=X(),i=Rf(),a=ep(),o=Z(),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})),lp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=sp(),n=cp();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),up=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),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})`)}}})),dp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();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}))`)}}})),fp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),pp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=fp();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}`)}}})),mp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Gf(),n=Z(),r=X();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})`)}}}})),hp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();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}`)}}})),gp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Gf(),n=X(),r=Z();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)}}}})),_p=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();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}`)}}})),vp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Jf();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),yp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Uf(),n=X(),r=Z(),i=vp();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)})))}}}})),bp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=vp();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}`)}}})),xp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=vp();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}`}}}})),Sp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=up(),n=dp(),r=pp(),i=mp(),a=hp(),o=gp(),s=_p(),c=yp(),l=bp(),u=xp();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]})),Cp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=X(),n=Z(),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})),wp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=X(),n=Z(),r=Gf(),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})),Tp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=wp();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Ep=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=Gf(),i=Cp();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)))}}})),Dp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z();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)))}}}})),Op=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=X(),n=Z(),r=Gf();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},
71
+ || ${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;s.number&&delete s.integer;for(let e in 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}}})),Wf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.assignDefaults=void 0;let t=X(),n=Z();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)}`)}})),Gf=h((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=X(),n=Z(),r=Rf(),i=Z();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})),Kf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=X(),n=Rf(),r=Gf(),i=zf();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)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((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),b(t.nil),e}function b(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 x(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})),qf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=X(),n=Z();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})),Jf=h(((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}})),Yf=h(((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<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else (p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),Xf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=Z(),n=Jf(),r=Yf(),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})),Zf=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Bf(),n=Uf(),r=Hf(),i=Uf(),a=Wf(),o=Kf(),s=qf(),c=X(),l=Rf(),u=Xf(),d=Z(),f=zf();function p(e){if(S(e)&&(te(e),x(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&&w(e),ie(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),ne(e),oe(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 b(e,n){if(S(e)&&(te(e),x(e))){ee(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({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 S(e){return typeof e.schema!=`boolean`}function ee(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&w(e),C(e),ae(e);let a=r.const(`_errs`,l.default.errors);ne(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function te(e){(0,d.checkUnknownRules)(e),re(e)}function ne(e,t){if(e.opts.jtd)return ce(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);ce(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function re(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 ie(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 C(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function ae(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function w({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 oe(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&&se(e),t.return((0,c._)`${l.default.errors} === 0`))}function se({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 ce(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(()=>ge(e,`$ref`,h.all.$ref.definition));return}p.jtd||ue(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)),le(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):le(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function le(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)&&ge(e,n.keyword,n.definition,t.type)})}function ue(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(de(e,t),e.opts.allowUnionTypes||T(e,t),fe(e,e.dataTypes))}function de(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{E(e.dataTypes,t)||me(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),D(e,t)}}function T(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&me(e,`use allowUnionTypes to allow union type keyword`)}function fe(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=>pe(t,e))&&me(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function pe(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 D(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 me(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var he=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`,ye(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 b(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=he;function ge(e,t,n,r){let i=new he(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 _e=/^\/(?:[^~]|~0|~1)*$/,ve=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ye(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!_e.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=ve.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=ye})),Qf=h((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}}})),$f=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Xf();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))}}})),ep=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=X(),n=Qf(),r=Rf(),i=Xf(),a=Z(),o=Zf();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}})),tp=h(((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}})),np=h(((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),i=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),a=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function s(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let c=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function l(e){return e.length=0,!0}function u(e,t,n){if(e.length){let r=s(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function d(e){let t=0,n={error:!1,address:``,zone:``},r=[],i=[],a=!1,o=!1,c=u;for(let s=0;s<e.length;s++){let u=e[s];if(!(u===`[`||u===`]`))if(u===`:`){if(a===!0&&(o=!0),!c(i,r,n))break;if(++t>7){n.error=!0;break}s>0&&e[s-1]===`:`&&(a=!0),r.push(`:`);continue}else if(u===`%`){if(!c(i,r,n))break;c=l}else{i.push(u);continue}}return i.length&&(c===l?n.zone=i.join(``):o?r.push(i.join(``)):r.push(s(i))),n.address=r.join(``),n}function f(e){if(p(e,`:`)<2)return{host:e,isIPV6:!1};let t=d(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 p(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function m(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}else{n.push(t);break}}else if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}else if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}let h={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},g=/[@/?#:]/g,_=/[@/?#]/g;function v(e,t){let n=t?_:g;return n.lastIndex=0,e.replace(n,e=>h[e])}function y(e,t=!1){if(e.indexOf(`%`)===-1)return e;let n=``;for(let r=0;r<e.length;r++){if(e[r]===`%`&&r+2<e.length){let o=e.slice(r+1,r+3);if(i(o)){let e=o.toUpperCase(),i=String.fromCharCode(parseInt(e,16));t&&a(i)?n+=i:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function b(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(i(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&a(i)?t+=i:t+=`%`+e,n+=2;continue}}o(e[n])?t+=e[n]:t+=escape(e[n])}return t}function x(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(i(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function S(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let e=f(n);n=e.isIPV6===!0?`[${e.escapedHost}]`:v(n,!1)}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:c,recomposeAuthority:S,reescapeHostDelimiters:v,normalizePercentEncoding:y,normalizePathEncoding:b,escapePreservingEscapes:x,removeDotSegments:m,isIPv4:r,isUUID:n,normalizeIPv6:f,stringArrayToHexStripped:s}})),rp=h(((e,t)=>{let{isUUID:n}=np(),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=y(`${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=y(`${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={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),ip=h(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizePercentEncoding:a,normalizePathEncoding:o,escapePreservingEscapes:s,reescapeHostDelimiters:c,isIPv4:l,nonSimpleDomain:u}=np(),{SCHEMES:d,getSchemeHandler:f}=rp();function p(e,t){return typeof e==`string`?e=S(e,t):typeof e==`object`&&(e=x(_(e,t),t)),e}function m(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=h(x(e,r),x(t,r),r,!0);return r.skipEscape=!0,_(i,r)}function h(e,t,n,i){let a={};return i||(e=x(_(e,n),n),t=x(_(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 g(e,t,n){let r=te(e,n),i=te(t,n);return r!==void 0&&i!==void 0&&r.toLowerCase()===i.toLowerCase()}function _(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:``},o=Object.assign({},t),c=[],l=f(o.scheme||n.scheme);l&&l.serialize&&l.serialize(n,o),n.path!==void 0&&(o.skipEscape?n.path=a(n.path):(n.path=s(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),o.reference!==`suffix`&&n.scheme&&c.push(n.scheme,`:`);let u=i(n);if(u!==void 0&&(o.reference!==`suffix`&&c.push(`//`),c.push(u),n.path&&n.path[0]!==`/`&&c.push(`/`)),n.path!==void 0){let e=n.path;!o.absolutePath&&(!l||!l.absolutePath)&&(e=r(e)),u===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),c.push(e)}return n.query!==void 0&&c.push(`?`,n.query),n.fragment!==void 0&&c.push(`#`,n.fragment),c.join(``)}let v=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function y(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!==`/`)return`URI path must start with "/" when authority is present.`;if(typeof e.port==`number`&&(e.port<0||e.port>65535))return`URI port is malformed.`}function b(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,s=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let d=e.match(v);if(d){i.scheme=d[1],i.userinfo=d[3],i.host=d[4],i.port=parseInt(d[5],10),i.path=d[6]||``,i.query=d[7],i.fragment=d[8],isNaN(i.port)&&(i.port=d[5]);let t=y(i,d);if(t!==void 0&&(i.error=i.error||t,a=!0),i.host)if(l(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),s=e.isIPV6}else s=!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 p=f(r.scheme||i.scheme);if(!r.unicodeSupport&&(!p||!p.unicodeSupport)&&i.host&&(r.domainHost||p&&p.domainHost)&&s===!1&&u(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}if((!p||p&&!p.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=c(unescape(i.host),s))),i.path&&=o(i.path),i.fragment))try{i.fragment=encodeURI(decodeURIComponent(i.fragment))}catch{i.error=i.error||`URI malformed`}p&&p.parse&&p.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:a}}function x(e,t){return b(e,t).parsed}function S(e,t){return ee(e,t).normalized}function ee(e,t){let{parsed:n,malformedAuthorityOrPort:r}=b(e,t);return{normalized:r?e:_(n,t),malformedAuthorityOrPort:r}}function te(e,t){if(typeof e==`string`){let{normalized:n,malformedAuthorityOrPort:r}=ee(e,t);return r?void 0:n}if(typeof e==`object`)return _(e,t)}let ne={SCHEMES:d,normalize:p,resolve:m,resolveComponent:h,equal:g,serialize:_,parse:x};t.exports=ne,t.exports.default=ne,t.exports.fastUri=ne})),ap=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=ip();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),op=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Zf();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return t.KeywordCxt}});var n=X();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=Qf(),i=$f(),a=Vf(),o=ep(),s=X(),c=Xf(),l=Uf(),u=Z(),d=tp(),f=ap(),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=Object.create(null),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=ie(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=ne.call(this),e.formats&&ee.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&te.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.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=x.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=x.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(ae.call(this,n,t),!t)return(0,u.eachItem)(n,e=>w.call(this,e)),this;se.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=>w.call(this,e,r):e=>r.type.forEach(t=>w.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]=le(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 b(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 x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){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 ee(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function te(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function ne(){let e={...this.opts};for(let t of m)delete e[t];return e}let re={log(){},warn(){},error(){}};function ie(e){if(e===!1)return re;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 C=/^[a-z_$][a-z0-9_$:-]*$/i;function ae(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!C.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 w(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?oe.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 oe(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 se(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=le(t)),e.validateSchema=this.compile(t,!0))}let ce={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function le(e){return{anyOf:[e,ce]}}})),sp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),cp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callRef=e.getValidate=void 0;let t=$f(),n=Gf(),r=X(),i=Rf(),a=ep(),o=Z(),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})),lp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=sp(),n=cp();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),up=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),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})`)}}})),dp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();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}))`)}}})),fp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),pp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=fp();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}`)}}})),mp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Gf(),n=Z(),r=X();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})`)}}}})),hp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();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}`)}}})),gp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Gf(),n=X(),r=Z();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)}}}})),_p=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();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}`)}}})),vp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Jf();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),yp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Uf(),n=X(),r=Z(),i=vp();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)})))}}}})),bp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=vp();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}`)}}})),xp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=vp();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}`}}}})),Sp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=up(),n=dp(),r=pp(),i=mp(),a=hp(),o=gp(),s=_p(),c=yp(),l=bp(),u=xp();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]})),Cp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateAdditionalItems=void 0;let t=X(),n=Z(),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})),wp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateTuple=void 0;let t=X(),n=Z(),r=Gf(),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})),Tp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=wp();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Ep=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),r=Gf(),i=Cp();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)))}}})),Dp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z();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)))}}}})),Op=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=X(),n=Z(),r=Gf();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},
72
72
  missingProperty: ${i},
73
73
  depsCount: ${n},
74
- 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})),kp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z();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)}}})),Ap=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Gf(),n=X(),r=Rf(),i=Z();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`?(ee(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(ee(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function ee(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)}}}})),jp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Zf(),n=Gf(),r=Z(),i=Ap();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)}}}})),Mp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Gf(),n=X(),r=Z(),i=Z();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())})})}}}})),Np=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();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`}}})),Pp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Gf().validateUnion,error:{message:`must match a schema in anyOf`}}})),Fp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z();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)})})}}}})),Ip=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();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)})}}})),Lp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),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})),Rp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();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`)}}})),zp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Cp(),n=Tp(),r=wp(),i=Ep(),a=Dp(),o=Op(),s=kp(),c=Ap(),l=jp(),u=Mp(),d=Np(),f=Pp(),p=Fp(),m=Ip(),h=Lp(),g=Rp();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=_})),Bp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();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})`}}}}})),Vp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[Bp().default]})),Hp=h((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`]})),Up=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=lp(),n=Sp(),r=zp(),i=Vp(),a=Hp();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Wp=h((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={}))})),Gp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Wp(),r=ep(),i=$f(),a=Z();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=_();o.if(!1);for(let e in 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<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),Kp=h(((e,t)=>{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}})),qp=h(((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=op(),r=Up(),i=Gp(),a=Kp(),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=Zf();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=X();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=Qf();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=$f();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),Jp=h((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:ee,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:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||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);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<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function ee(e){return v.lastIndex=0,v.test(e)}let y=-(2**31),b=2**31-1;function x(e){return Number.isInteger(e)&&e<=b&&e>=y}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}}})),Yp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=qp(),n=X(),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)})),Xp=h(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=Jp(),r=Yp(),i=X(),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})),Zp=_(qp(),1),Qp=_(Xp(),1);function $p(){let e=new Zp.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Qp.default)(e),e}var em=class{constructor(e){this._ajv=e??$p()}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)}}},tm=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},nd,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},md,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function nm(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function rm(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var im=class extends Nf{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Uu.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new em,this.setRequestHandler(Dl,e=>this._oninitialize(e)),this.setNotificationHandler(Al,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Gu,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=Uu.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new tm(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Ff(this._capabilities,e)}setRequestHandler(e,t){let n=$o(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(Yo(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=Zo(Vu,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new q(K.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=Zo(Bl,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new q(K.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=Zo(zu,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new q(K.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){rm(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&nm(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Gc.includes(t)?t:Wc,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},gl)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},rd,t):this.request({method:`sampling/createMessage`,params:e},nd,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},md,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},md,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new q(K.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof q?e:new q(K.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},wd,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const am=Symbol.for(`mcp.completable`);function om(e){return!!e&&typeof e==`object`&&am in e}function sm(e){return e[am]?.complete}var cm;(function(e){e.Completable=`McpCompletable`})(cm||={});const lm=/^[A-Za-z0-9._-]{1,128}$/;function um(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!lm.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function dm(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function fm(e){let t=um(e);return dm(e,t.warnings),t.isValid}var pm=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},mm=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new im(e,t)}get experimental(){return this._experimental||={tasks:new pm(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(xm(Lu)),this.server.assertCanSetRequestHandler(xm(Vu)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Lu,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=es(t.inputSchema);return e?Af(e,{strictUnions:!0,pipeStrategy:`input`}):hm})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=es(t.outputSchema);e&&(n.outputSchema=Af(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Vu,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new q(K.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new q(K.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new q(K.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new q(K.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof q&&e.code===K.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await Qo(es(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=ts(`error`in r?r.error:`Unknown error`);throw new q(K.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new q(K.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await Qo(es(e.outputSchema),t.structuredContent);if(!r.success){let e=ts(`error`in r?r.error:`Unknown error`);throw new q(K.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new q(K.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(xm(vd)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(vd,async e=>{switch(e.params.ref.type){case`ref/prompt`:return yd(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return bd(e),this.handleResourceCompletion(e,e.params.ref);default:throw new q(K.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new q(K.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new q(K.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Cm;let r=$o(n.argsSchema)?.[e.params.argument.name];if(!om(r))return Cm;let i=sm(r);return i?Sm(await i(e.params.argument.value,e.params.context)):Cm}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Cm;throw new q(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Sm(await r(e.params.argument.value,e.params.context)):Cm}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(xm(iu)),this.server.assertCanSetRequestHandler(xm(ou)),this.server.assertCanSetRequestHandler(xm(uu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(iu,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(ou,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(uu,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new q(K.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new q(K.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(xm(xu)),this.server.assertCanSetRequestHandler(xm(wu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(xu,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?bm(t.argsSchema):void 0}))})),this.server.setRequestHandler(wu,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new q(K.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new q(K.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await Qo(es(n.argsSchema),e.params.arguments);if(!r.success){let t=ts(`error`in r?r.error:`Unknown error`);throw new q(K.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:Xo(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=Xo(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>om(e instanceof xc?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){fm(e);let l={title:t,description:n,inputSchema:ym(r),outputSchema:ym(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&fm(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=Xo(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=Xo(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(vm(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!vm(t[0])&&(i=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let a=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,i,{taskSupport:`forbidden`},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const hm={type:`object`,properties:{}};function gm(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function _m(e){return`_def`in e||`_zod`in e||gm(e)}function vm(e){return typeof e!=`object`||!e||_m(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(gm)}function ym(e){if(e){if(vm(e))return Xo(e);if(!_m(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function bm(e){let t=$o(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:ns(t),required:!rs(t)})):[]}function xm(e){let t=$o(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=is(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Sm(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Cm={completion:{values:[],hasMore:!1}};var wm=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
74
+ 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})),kp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z();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)}}})),Ap=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Gf(),n=X(),r=Rf(),i=Z();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)}}}})),jp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Zf(),n=Gf(),r=Z(),i=Ap();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)}}}})),Mp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Gf(),n=X(),r=Z(),i=Z();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())})})}}}})),Np=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();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`}}})),Pp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Gf().validateUnion,error:{message:`must match a schema in anyOf`}}})),Fp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z();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)})})}}}})),Ip=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();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)})}}})),Lp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Z(),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})),Rp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Z();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`)}}})),zp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Cp(),n=Tp(),r=wp(),i=Ep(),a=Dp(),o=Op(),s=kp(),c=Ap(),l=jp(),u=Mp(),d=Np(),f=Pp(),p=Fp(),m=Ip(),h=Lp(),g=Rp();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=_})),Bp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X();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})`}}}}})),Vp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=[Bp().default]})),Hp=h((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`]})),Up=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=lp(),n=Sp(),r=zp(),i=Vp(),a=Hp();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Wp=h((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={}))})),Gp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=Wp(),r=ep(),i=$f(),a=Z();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=_();o.if(!1);for(let e in 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<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),Kp=h(((e,t)=>{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}})),qp=h(((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=op(),r=Up(),i=Gp(),a=Kp(),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=Zf();Object.defineProperty(e,`KeywordCxt`,{enumerable:!0,get:function(){return l.KeywordCxt}});var u=X();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=Qf();Object.defineProperty(e,`ValidationError`,{enumerable:!0,get:function(){return d.default}});var f=$f();Object.defineProperty(e,`MissingRefError`,{enumerable:!0,get:function(){return f.default}})})),Jp=h((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:re,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:S},int64:{type:`number`,validate:ee},float:{type:`number`,validate:te},double:{type:`number`,validate:te},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:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||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);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<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function ee(e){return Number.isInteger(e)}function te(){return!0}let ne=/[^\\]\\Z/;function re(e){if(ne.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Yp=h((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.formatLimitDefinition=void 0;let t=qp(),n=X(),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)})),Xp=h(((e,t)=>{Object.defineProperty(e,`__esModule`,{value:!0});let n=Jp(),r=Yp(),i=X(),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})),Zp=_(qp(),1),Qp=_(Xp(),1);function $p(){let e=new Zp.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Qp.default)(e),e}var em=class{constructor(e){this._ajv=e??$p()}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)}}},tm=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},nd,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},md,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function nm(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function rm(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var im=class extends Nf{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Uu.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new em,this.setRequestHandler(Dl,e=>this._oninitialize(e)),this.setNotificationHandler(Al,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Gu,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=Uu.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new tm(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Ff(this._capabilities,e)}setRequestHandler(e,t){let n=$o(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(Yo(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=Zo(Vu,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new q(K.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=Zo(Bl,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new q(K.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=Zo(zu,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new q(K.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){rm(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&nm(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Gc.includes(t)?t:Wc,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},gl)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},rd,t):this.request({method:`sampling/createMessage`,params:e},nd,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},md,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},md,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new q(K.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof q?e:new q(K.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},wd,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const am=Symbol.for(`mcp.completable`);function om(e){return!!e&&typeof e==`object`&&am in e}function sm(e){return e[am]?.complete}var cm;(function(e){e.Completable=`McpCompletable`})(cm||={});const lm=/^[A-Za-z0-9._-]{1,128}$/;function um(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!lm.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function dm(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function fm(e){let t=um(e);return dm(e,t.warnings),t.isValid}var pm=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},mm=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new im(e,t)}get experimental(){return this._experimental||={tasks:new pm(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(xm(Lu)),this.server.assertCanSetRequestHandler(xm(Vu)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Lu,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=es(t.inputSchema);return e?Af(e,{strictUnions:!0,pipeStrategy:`input`}):hm})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=es(t.outputSchema);e&&(n.outputSchema=Af(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Vu,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new q(K.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new q(K.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new q(K.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new q(K.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof q&&e.code===K.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await Qo(es(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=ts(`error`in r?r.error:`Unknown error`);throw new q(K.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new q(K.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await Qo(es(e.outputSchema),t.structuredContent);if(!r.success){let e=ts(`error`in r?r.error:`Unknown error`);throw new q(K.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new q(K.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(xm(vd)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(vd,async e=>{switch(e.params.ref.type){case`ref/prompt`:return yd(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return bd(e),this.handleResourceCompletion(e,e.params.ref);default:throw new q(K.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new q(K.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new q(K.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Cm;let r=$o(n.argsSchema)?.[e.params.argument.name];if(!om(r))return Cm;let i=sm(r);return i?Sm(await i(e.params.argument.value,e.params.context)):Cm}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Cm;throw new q(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Sm(await r(e.params.argument.value,e.params.context)):Cm}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(xm(iu)),this.server.assertCanSetRequestHandler(xm(ou)),this.server.assertCanSetRequestHandler(xm(uu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(iu,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(ou,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(uu,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new q(K.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new q(K.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(xm(xu)),this.server.assertCanSetRequestHandler(xm(wu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(xu,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?bm(t.argsSchema):void 0}))})),this.server.setRequestHandler(wu,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new q(K.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new q(K.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await Qo(es(n.argsSchema),e.params.arguments);if(!r.success){let t=ts(`error`in r?r.error:`Unknown error`);throw new q(K.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:Xo(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=Xo(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>om(e instanceof xc?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){fm(e);let l={title:t,description:n,inputSchema:ym(r),outputSchema:ym(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&fm(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=Xo(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=Xo(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(vm(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!vm(t[0])&&(i=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let a=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,i,{taskSupport:`forbidden`},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const hm={type:`object`,properties:{}};function gm(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function _m(e){return`_def`in e||`_zod`in e||gm(e)}function vm(e){return typeof e!=`object`||!e||_m(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(gm)}function ym(e){if(e){if(vm(e))return Xo(e);if(!_m(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function bm(e){let t=$o(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:ns(t),required:!rs(t)})):[]}function xm(e){let t=$o(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=is(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Sm(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Cm={completion:{values:[],hasMore:!1}};var wm=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
75
75
  `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),Tm(t)}clear(){this._buffer=void 0}};function Tm(e){return hl.parse(JSON.parse(e))}function Em(e){return JSON.stringify(e)+`
76
76
  `}var Dm=class{constructor(e=c.stdin,t=c.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new wm,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=Em(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};const Om=[];for(let e=0;e<256;++e)Om.push((e+256).toString(16).slice(1));function km(e,t=0){return(Om[e[t+0]]+Om[e[t+1]]+Om[e[t+2]]+Om[e[t+3]]+`-`+Om[e[t+4]]+Om[e[t+5]]+`-`+Om[e[t+6]]+Om[e[t+7]]+`-`+Om[e[t+8]]+Om[e[t+9]]+`-`+Om[e[t+10]]+Om[e[t+11]]+Om[e[t+12]]+Om[e[t+13]]+Om[e[t+14]]+Om[e[t+15]]).toLowerCase()}const Am=new Uint8Array(16);function jm(){return crypto.getRandomValues(Am)}function Mm(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():Nm(e,t,n)}function Nm(e,t,n){e||={};let r=e.random??e.rng?.()??jm();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return km(r)}var Pm=class{constructor(){this.maxResponseLength=2e6}processResponse(e,t){try{let t=typeof e==`string`?e:JSON.stringify(e,null,2);return t.length>this.maxResponseLength&&(t=t.substring(0,this.maxResponseLength)+`
77
77
 
78
- [Response truncated due to length]`),t}catch(e){return console.error(`Response processing error:`,e),`Error processing response`}}};const Fm=new Set([`getInvoiceSummary`,`getCustomerBalance`,`getPaymentStatus`]),Im={listCustomers:{shape:`customer-table`,noun:`customer`,toPayload:zm,threshold:0},listInvoices:{shape:`invoice-table`,noun:`invoice`,toPayload:Bm,threshold:0},getInvoiceLineItems:{shape:`invoice-line-items`,noun:`line item`,toPayload:Hm,threshold:0},listAllPayments:{shape:`payment-table`,noun:`payment`,toPayload:qm,threshold:0},listCreditNotes:{shape:`credit-note-table`,noun:`credit note`,toPayload:Ym,threshold:0},listContracts:{shape:`contract-table`,noun:`contract`,toPayload:Zm,threshold:0},getCustomerById:{shape:`customer-detail`,noun:`customer`,toPayload:$m,threshold:0},getInvoiceById:{shape:`invoice-detail`,noun:`invoice`,toPayload:eh,threshold:0},getContractById:{shape:`contract-detail`,noun:`contract`,toPayload:th,threshold:0},getCreditNoteById:{shape:`credit-note-detail`,noun:`credit note`,toPayload:rh,threshold:0},listProducts:{shape:`product-table`,noun:`product`,toPayload:ih,threshold:0},listPlans:{shape:`plan-table`,noun:`plan`,toPayload:oh,threshold:0},listJournalEntries:{shape:`journal-table`,noun:`journal entry`,toPayload:ch,threshold:0},listJobs:{shape:`job-table`,noun:`job`,toPayload:uh,threshold:0},listContacts:{shape:`contact-table`,noun:`contact`,toPayload:fh,threshold:0},listRawMetrics:{shape:`raw-metric-table`,noun:`raw metric`,toPayload:mh,threshold:0},listAggregates:{shape:`aggregate-table`,noun:`aggregate`,toPayload:gh,threshold:0},listCustomerAddresses:{shape:`address-list`,noun:`address`,toPayload:vh,threshold:0},listPaymentMethods:{shape:`payment-method-list`,noun:`payment method`,toPayload:bh,threshold:0},listBusinessEntities:{shape:`entity-table`,noun:`business entity`,toPayload:Sh,threshold:0},listEntitlements:{shape:`entitlement-table`,noun:`entitlement`,toPayload:wh,threshold:0},getInvoicePreviewHtml:{shape:`invoice-preview`,noun:`invoice preview`,toPayload:Ah,threshold:0}},Lm=Object.freeze([`app`]);function Rm(e){return`ui://zenskar/app.html`}function zm(e,t){let n=Q(e),r=Eh(n,[`customers`,`data`,`results`]),i=Oh(n,[`total`,`count`,`total_count`])??r.length,a=Dh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search_name_external_id||t.search)||void 0;return{customers:r.map(Km),total:i,cursor:{next:o,prev:s},scope:c}}function Q(e){return e&&typeof e==`object`&&e.api_response&&typeof e.api_response==`object`?e.api_response:e||{}}function Bm(e,t){let n=Q(e),r=Eh(n,[`invoices`,`data`,`results`]),i=Oh(n,[`total`,`count`,`total_count`])??r.length,a=Dh(n,[`cursor`,`pagination`])||{},o=a.next??n.next??null,s=a.prev??n.previous??null;return{invoices:r.map(Vm),total:i,cursor:{next:o,prev:s},scope:t&&(t.customer__customer_name__ilike||t.invoice_number__like||t.status)||void 0,default_currency:`USD`}}function Vm(e){if(!e||typeof e!=`object`)return{id:``,invoice_number:null,customer_id:null,customer_name:null,status:null,invoice_total:null,amount_due:null,due_date:null,invoice_period_begin:null,invoice_period_end:null,external_id:null,created_at:null,payment_url:null};let t=e.invoice_period||{},n=e.customer&&typeof e.customer==`object`?e.customer:null;return{id:String(e.id||e.invoice_id||``),invoice_number:e.invoice_number??null,customer_id:n?.id??e.customer_id??null,customer_name:n?.customer_name??n?.name??null,status:e.status??null,invoice_total:kh(e.net_invoice_total??e.invoice_total),amount_due:kh(e.amount_due),due_date:e.due_date??e.promise_due_date??null,invoice_period_begin:t.begin_date??e.period_begin_date??null,invoice_period_end:t.end_date_exclusive??e.period_end_date??null,external_id:e.external_id??null,created_at:e.created_at??null,payment_url:e.payment_url??null}}function Hm(e,t){let n=Q(e),r=Array.isArray(n.lines)?n.lines:Array.isArray(n)?n:[],i=kh(n.total),a=Um(r)||`USD`;return{invoice_id:t&&t.invoiceId?String(t.invoiceId):void 0,total:i,currency:a,lines:r.map(Wm)}}function Um(e){for(let t of e){if(t&&t.subtotal&&t.subtotal.unit)return t.subtotal.unit;if(t&&t.features&&t.features[0]&&t.features[0].currency)return t.features[0].currency}return null}function Wm(e){return!e||typeof e!=`object`?{name:``,description:null,pricing_model:null,subtotal:{value:null,unit:null},quantity:{value:null,unit:null},price:null,service_start_date:null,service_end_date:null,is_billed:null}:{name:e.name??e.description??``,description:e.description??null,pricing_model:e.pricing_model??null,subtotal:Gm(e.subtotal),quantity:Gm(e.quantity),price:e.price?Gm(e.price):null,service_start_date:e.service_start_date??e.billing_period_start??null,service_end_date:e.service_end_date??e.billing_period_end??null,is_billed:typeof e.is_billed==`boolean`?e.is_billed:null,line_item_type:e.line_item_type??null,is_adjustment:typeof e.is_adjustment==`boolean`?e.is_adjustment:null,adjustment_type:e.adjustment_type??null}}function Gm(e){return e?{value:kh(e.value),unit:e.unit??null,display:e.display??null}:{value:null,unit:null,display:null}}function Km(e){return!e||typeof e!=`object`?{id:``,name:null,external_id:null,email:null}:{id:String(e.id||e.customer_id||``),name:e.customer_name??e.name??null,external_id:e.external_id??null,email:e.email??e.primary_email??null,created_at:e.created_at??e.created??null}}function qm(e,t){let n=Q(e),r=Eh(n,[`payments`,`data`,`results`]),i=Oh(n,[`total`,`count`,`total_count`])??r.length,a=Dh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search||t.customer_id||t.type||t.payment_method)||void 0;return{payments:r.map(Jm),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0,default_currency:`USD`}}function Jm(e){if(!e||typeof e!=`object`)return{id:``,external_id:null,customer_id:null,customer_name:null,invoice_id:null,invoice_name:null,amount:null,currency:null,payment_method:null,type:null,status:null,description:null,payment_date:null,created_at:null};let t=((Array.isArray(e.payment_parts)?e.payment_parts:[]).find(e=>e&&e.invoice_id)||{}).invoice_id||e.invoice_id||null,n=e.customer&&typeof e.customer==`object`?e.customer:null,r=e.invoice&&typeof e.invoice==`object`?e.invoice:null;return{id:String(e.id||e.payment_id||``),external_id:e.external_id??null,customer_id:n?.id??e.customer_id??null,customer_name:n?.customer_name??n?.name??null,invoice_id:r?.id??t,invoice_name:r?.name??r?.invoice_number??null,amount:kh(e.amount??e.value),currency:e.currency_code??e.currency??null,payment_method:e.payment_method??null,type:e.type??null,status:e.status??null,description:e.description??e.notes??null,payment_date:e.payment_date??e.received_at??e.processed_at??null,created_at:e.created_at??null}}function Ym(e,t){let n=Q(e),r=Eh(n,[`credit_notes`,`creditNotes`,`data`,`results`]),i=Oh(n,[`total`,`count`,`total_count`])??r.length,a=Dh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.customer_id||t.invoice_id||t.status)||void 0;return{credit_notes:r.map(Xm),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0,default_currency:`USD`}}function Xm(e){if(!e||typeof e!=`object`)return{id:``,credit_note_number:null,customer_id:null,customer_name:null,invoice_id:null,invoice_name:null,status:null,amount:null,currency:null,repayment_method:null,created_at:null};let t=e.customer&&typeof e.customer==`object`?e.customer:null,n=e.invoice&&typeof e.invoice==`object`?e.invoice:null;return{id:String(e.id||e.credit_note_id||``),credit_note_number:e.credit_note_number??null,customer_id:t?.id??e.customer_id??null,customer_name:t?.customer_name??t?.name??null,invoice_id:n?.id??e.invoice_id??null,invoice_name:n?.name??n?.invoice_number??null,status:e.status??null,amount:kh(e.amount??e.total??e.value),currency:e.currency_code??e.currency??null,repayment_method:e.repayment_method??null,created_at:e.created_at??null}}function Zm(e,t){let n=Q(e),r=Eh(n,[`contracts`,`data`,`results`]),i=Oh(n,[`total`,`count`,`total_count`])??r.length,a=Dh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.customer_id||t.name__ilike||t.status)||void 0;return{contracts:r.map(Qm),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0}}function Qm(e){if(!e||typeof e!=`object`)return{id:``,customer_id:null,customer_name:null,name:null,status:null,currency:null,start_date:null,end_date:null,created_at:null};let t=e.customer&&typeof e.customer==`object`?e.customer:null;return{id:String(e.id||e.contract_id||``),customer_id:t?.id??e.customer_id??null,customer_name:t?.customer_name??t?.name??null,name:e.name??e.contract_name??null,status:e.status??e.state??null,currency:e.currency??e.currency_code??null,start_date:e.start_date??null,end_date:e.end_date??null,created_at:e.created_at??null}}function $m(e){let t=Q(e),n=t.customer??t,r=Km(n),i=n.business_entity,a=n.default_payment_method,o=Array.isArray(n.contacts)?n.contacts:[],s=Array.isArray(n.tax_info)?n.tax_info:[];return{customer:{...r,phone:n.phone_number??n.phone??n.primary_phone??null,business_entity_id:n.business_entity_id??null,business_entity_name:(i&&typeof i==`object`?i.name:null)??null,address:n.address??null,ship_to_address:n.ship_to_address??null,communications_enabled:typeof n.communications_enabled==`boolean`?n.communications_enabled:null,auto_charge_enabled:typeof n.auto_charge_enabled==`boolean`?n.auto_charge_enabled:null,custom_data:n.custom_data??null,tax_info:s.length?s.map(e=>({country_code:e.country_code??null,tax_code:e.tax_code??null,tax_id:e.tax_id??null})):null,contacts:o.length?o.map(e=>({name:[e.first_name??``,e.last_name??``].filter(Boolean).join(` `)||null,email:e.email??null,send_invoice:typeof e.send_invoice==`boolean`?e.send_invoice:null,send_contract:typeof e.send_contract==`boolean`?e.send_contract:null})):null,default_payment_method:a&&typeof a==`object`?{type:a.type??null,brand:(a.details&&a.details.brand)??a.brand??null,last4:(a.details&&a.details.last4)??a.last4??null,connector_name:a.connector_name??null}:null,updated_at:n.updated_at??null}}}function eh(e){let t=Q(e),n=t.invoice??t,r=Vm(n),i=n.customer,a=n.contract;return{invoice:{...r,paid_amount:kh(n.paid_amount??(r.invoice_total!=null&&r.amount_due!=null?r.invoice_total-r.amount_due:null)),currency:n.currency_code??n.currency??null,business_entity_id:n.business_entity_id??null,notes:n.notes??null,custom_data:n.custom_data??n.custom_attributes??null,customer_name:(i&&typeof i==`object`?i.name:null)??null,contract_id:n.contract_id??(a&&typeof a==`object`?a.id:null)??null,contract_name:(a&&typeof a==`object`?a.name:null)??null,invoice_pdf:n.invoice_pdf??null,approved_at:n.approved_at??null,paid_at:n.paid_at??null,sent_at:n.sent_at??null}}}function th(e){let t=Q(e),n=t.contract??t,r=Qm(n),i=Array.isArray(n.phases)?n.phases:[],a=n.customer,o=Array.isArray(n.tags)?n.tags:[];return{contract:{...r,description:n.description??null,custom_attributes:n.custom_attributes??null,renewal_policy:n.renewal_policy??null,anchor_date:n.anchor_date??null,plan_id:n.plan_id??null,customer_name:(a&&typeof a==`object`?a.customer_name??a.name:null)??null,contract_type:n.contract_type??null,tags:o.length?o:null,contract_link:n.contract_link??null},phases:i.map(nh)}}function nh(e){if(!e||typeof e!=`object`)return{id:null,name:null,start_date:null,end_date:null,pricing_summary:null,product_count:null};let t=Array.isArray(e.products)?e.products:[];return{id:e.id??null,name:e.name??e.phase_name??null,start_date:e.start_date??null,end_date:e.end_date??null,pricing_summary:e.pricing_summary??null,product_count:t.length||kh(e.product_count)}}function rh(e){let t=Q(e),n=t.credit_note??t.creditNote??t,r=Xm(n),i=n.customer,a=n.invoice;return{credit_note:{...r,line_items_url:n.line_items_url??null,credits_returned:kh(n.credits_returned),custom_data:n.custom_data??null,customer_name:(i&&typeof i==`object`?i.name:null)??null,invoice_number:(a&&typeof a==`object`?a.invoice_number??a.name:null)??null}}}function ih(e,t){let n=Q(e),r=Eh(n,[`products`,`data`,`results`]),i=Oh(n,[`total`,`count`,`total_count`])??r.length,a=Dh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.name__ilike||void 0;return{products:r.map(ah),total:i,cursor:{next:o,prev:s},scope:c}}function ah(e){return!e||typeof e!=`object`?{id:``,name:null,sku:null,description:null,product_type:null,is_active:null,created_at:null}:{id:String(e.id||e.product_id||``),name:e.name??e.product_name??null,sku:e.sku??null,description:e.description??null,product_type:e.product_type??e.type??null,is_active:typeof e.is_active==`boolean`?e.is_active:null,created_at:e.created_at??null}}function oh(e,t){let n=Q(e),r=Eh(n,[`plans`,`data`,`results`]),i=Oh(n,[`total`,`count`,`total_count`])??r.length,a=Dh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.name__ilike||t.status)||void 0;return{plans:r.map(sh),total:i,cursor:{next:o,prev:s},scope:c}}function sh(e){return!e||typeof e!=`object`?{id:``,name:null,description:null,status:null,plan_version:null,created_at:null}:{id:String(e.id||e.plan_id||``),name:e.name??e.plan_name??null,description:e.description??null,status:e.status??e.state??null,plan_version:kh(e.plan_version),created_at:e.created_at??null}}function ch(e,t){let n=Q(e),r=Eh(n,[`entries`,`journal_entries`,`data`,`results`]),i=Oh(n,[`total`,`count`,`total_count`])??r.length,a=Dh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.search_query||void 0;return{entries:r.map(lh),total:i,cursor:{next:o,prev:s},scope:c,default_currency:`USD`}}function lh(e){if(!e||typeof e!=`object`)return{id:``,posted_at:null,event:null,description:null,status_type:null,currency:null,total_debit:null,total_credit:null,line_count:null,created_at:null};let t=Array.isArray(e.journal_lines)?e.journal_lines:[],n=0,r=0;for(let e of t)Number.isFinite(e?.debits)&&(n+=e.debits),Number.isFinite(e?.credits)&&(r+=e.credits);return{id:String(e.id||e.journal_entry_id||``),posted_at:e.posted_at??null,event:e.event??null,description:e.description??null,status_type:e.status_type??null,currency:e.currency??e.currency_code??null,total_debit:t.length?n:null,total_credit:t.length?r:null,line_count:t.length||null,created_at:e.created_at??null}}function uh(e,t){let n=Q(e),r=Eh(n,[`jobs`,`data`,`results`]),i=Oh(n,[`total`,`count`,`total_count`])??r.length,a=Dh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.search||void 0,l={};for(let e of r){let t=e&&e.status||`unknown`;l[t]=(l[t]||0)+1}return{jobs:r.map(dh),total:i,cursor:{next:o,prev:s},scope:c,status_counts:l}}function dh(e){return!e||typeof e!=`object`?{id:``,name:null,description:null,job_type:null,resource:null,status:null,created_at:null}:{id:String(e.id||e.job_id||``),name:e.name??null,description:e.description??null,job_type:e.job_type??e.type??null,resource:e.resource??null,status:e.status??null,created_at:e.created_at??null}}function fh(e,t){let n=Q(e),r=Eh(n,[`contacts`,`data`,`results`]),i=Oh(n,[`total`,`count`,`total_count`])??r.length,a=Dh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.customer_id||void 0;return{contacts:r.map(ph),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0}}function ph(e){if(!e||typeof e!=`object`)return{id:``,name:null,email:null,customer_id:null,send_invoice:null,send_contract:null};let t=[e.first_name??``,e.last_name??``].filter(Boolean).join(` `).trim(),n=e.customer,r=typeof n==`string`?n:(n&&typeof n==`object`?n.id:null)??e.customer_id??null;return{id:String(e.id||e.contact_id||``),name:e.name??(t||null),email:e.email??e.primary_email??null,customer_id:r??null,send_invoice:typeof e.send_invoice==`boolean`?e.send_invoice:null,send_contract:typeof e.send_contract==`boolean`?e.send_contract:null}}function mh(e,t){let n=Q(e),r=Eh(n,[`raw_metrics`,`rawmetrics`,`rawMetrics`,`data`,`results`]),i=Oh(n,[`total`,`count`,`total_count`])??r.length,a=Dh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search||t.name__ilike)||void 0;return{raw_metrics:r.map(hh),total:i,cursor:{next:o,prev:s},scope:c}}function hh(e){return!e||typeof e!=`object`?{id:``,name:null,api_slug:null,usage_upload_enabled:null,created_at:null}:{id:String(e.id||e.raw_metric_id||``),name:e.name??null,api_slug:e.api_slug??null,usage_upload_enabled:typeof e.usage_upload_enabled==`boolean`?e.usage_upload_enabled:null,created_at:e.created_at??null}}function gh(e,t){let n=Q(e),r=Eh(n,[`aggregates`,`data`,`results`]),i=Oh(n,[`total`,`count`,`total_count`])??r.length,a=Dh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.name__ilike||t.datasource)||void 0;return{aggregates:r.map(_h),total:i,cursor:{next:o,prev:s},scope:c}}function _h(e){return!e||typeof e!=`object`?{id:``,name:null,datasource:null,created_at:null}:{id:String(e.id||e.aggregate_id||``),name:e.name??null,datasource:e.datasource??e.data_source??e.raw_metric_name??null,created_at:e.created_at??null}}function vh(e,t){let n=Eh(Q(e),[`addresses`,`data`,`results`]);return{customer_id:t&&t.customerId?String(t.customerId):void 0,addresses:n.map(yh),total:n.length}}function yh(e){return!e||typeof e!=`object`?{id:``,label:null,line1:null,line2:null,city:null,state:null,zip_code:null,country:null,is_primary:null}:{id:String(e.id||``),label:e.label??e.name??e.address_type??null,line1:e.line1??e.address_line_1??null,line2:e.line2??e.address_line_2??null,line3:e.line3??null,city:e.city??null,state:e.state??null,zip_code:e.zipCode??e.zip_code??e.postal_code??null,country:e.country??e.country_code??null,validation_status:e.validation_status??null,is_primary:typeof e.is_primary==`boolean`?e.is_primary:typeof e.primary==`boolean`?e.primary:null}}function bh(e,t){let n=Eh(Q(e),[`payment_methods`,`paymentMethods`,`data`,`results`]);return{customer_id:t&&t.customerId?String(t.customerId):void 0,payment_methods:n.map(xh),total:n.length}}function xh(e){if(!e||typeof e!=`object`)return{id:``,type:null,brand:null,last4:null,exp_month:null,exp_year:null,is_default:null,created_at:null};let t=e.card||e.details||{};return{id:String(e.id||``),type:e.type??e.payment_method_type??null,brand:t.brand??e.brand??null,last4:t.last4??e.last4??null,exp_month:kh(t.exp_month??e.exp_month),exp_year:kh(t.exp_year??e.exp_year),is_default:typeof e.is_default==`boolean`?e.is_default:typeof e.default==`boolean`?e.default:null,created_at:e.created_at??null,connector_name:e.connector_name??null,status:e.status??null}}function Sh(e,t){let n=Q(e),r=Eh(n,[`business_entities`,`businessEntities`,`entities`,`data`,`results`]),i=Oh(n,[`total`,`count`,`total_count`])??r.length,a=Dh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null;return{entities:r.map(Ch),total:i,cursor:{next:o,prev:s}}}function Ch(e){return!e||typeof e!=`object`?{id:``,name:null,email:null,phone_number:null,country:null,is_default:null}:{id:String(e.id||e.business_entity_id||``),name:e.name??e.business_entity_name??null,email:e.email??null,phone_number:e.phone_number??null,country:(e.address&&e.address.country)??e.country??null,is_default:typeof e.is_default==`boolean`?e.is_default:null}}function wh(e,t){let n=Q(e),r=Eh(n,[`entitlements`,`data`,`results`]),i=Oh(n,[`total`,`count`,`total_count`])??r.length,a=Dh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search||t.name__ilike)||void 0;return{entitlements:r.map(Th),total:i,cursor:{next:o,prev:s},scope:c}}function Th(e){return!e||typeof e!=`object`?{id:``,name:null,entitlement_type:null,units:null,is_active:null,product_name:null,created_at:null}:{id:String(e.id||e.entitlement_id||``),name:e.name??null,entitlement_type:e.entitlement_type??null,units:e.units??null,is_active:typeof e.is_active==`boolean`?e.is_active:null,product_name:(e.product&&(e.product.name??e.product.product_name))??null,created_at:e.created_at??null}}function Eh(e,t){if(Array.isArray(e))return e;for(let n of t)if(e&&Array.isArray(e[n]))return e[n];return[]}function Dh(e,t){for(let n of t)if(e&&e[n]&&typeof e[n]==`object`)return e[n];return null}function Oh(e,t){for(let n of t)if(e&&Number.isFinite(e[n]))return e[n];return null}function kh(e){return Number.isFinite(e)?e:null}function Ah(e,t){let n=Q(e);return{html:n.html??(typeof n==`string`?n:``),invoice_id:t&&t.invoiceId?String(t.invoiceId):void 0}}function jh(e){if(Fm.has(e))return{mode:`text-only`};let t=Im[e];return t?{mode:`ui`,...t}:{mode:`unmapped`}}const Mh=a(s(import.meta.url)),Nh=[o(Mh,`..`,`..`,`..`,`dist`,`ui`),o(Mh,`ui`)];function Ph(e){for(let t of Nh){let i=o(t,`${e}.html`);if(n(i))return r(i,`utf8`)}return`<!doctype html><html><body style="font-family:sans-serif;padding:16px;">UI bundle missing: ${e}.html. Run <code>pnpm run build:ui</code>.</body></html>`}function Fh(){let e=new Set,t=t=>{if(t)try{e.add(new URL(t).origin)}catch{}};return t(process.env.ZENSKAR_MCP_PUBLIC_BASE_URL||process.env.MCP_PUBLIC_BASE_URL),t(process.env.ZENSKAR_API_BASE_URL),t(process.env.ZENSKAR_APP_BASE_URL),Array.from(e)}function Ih(){let e={prefersBorder:!0},t=Fh();return t.length>0&&(e.csp={connectDomains:t,resourceDomains:t}),e}function Lh(e){for(let t of Lm){let n=Rm(t);e.registerResource(`zenskar-app`,n,{},async()=>({contents:[{uri:n,mimeType:`text/html;profile=mcp-app`,text:Ph(t),_meta:{"openai/widgetPrefersBorder":!0,ui:Ih()}}]}))}}function Rh(e,t){return t===1?e:e.endsWith(`y`)?e.slice(0,-1)+`ies`:e+`s`}function zh(e,t,n){let r=Number.isFinite(t)?t:0,i=r===1?`Rendered ${e} detail view`:`Rendered ${r} ${Rh(e,r)}`,a=n?`${i} for ${n}.`:`${i}.`;return a.length>200?a.slice(0,199)+`…`:a}function Bh(){let e=process.env.ZENSKAR_MCP_UI_ENABLED;return e==null||e===``?!0:!/^(0|false|no|off)$/i.test(String(e).trim())}function Vh(){let e=process.env.ZENSKAR_MCP_UI_DISABLED_TOOLS;return e?new Set(String(e).split(`,`).map(e=>e.trim()).filter(Boolean)):new Set}const Hh=process.env.ZENSKAR_MCP_UI_DEBUG===`true`||process.env.MCP_DEBUG===`true`;function Uh(...e){Hh&&console.error(`[ui-wrap]`,...e)}function Wh(e,t,n,r){if(!Bh())return Uh(e,`skipped: ZENSKAR_MCP_UI_ENABLED explicitly disabled`),Kh(n);let i=jh(e);if(i.mode!==`ui`)return Uh(e,`skipped: not in registry, mode=`,i.mode),Kh(n);if(Vh().has(e))return Uh(e,`skipped: in ZENSKAR_MCP_UI_DISABLED_TOOLS`),Kh(n);let a;try{a=i.toPayload(t,r)}catch(t){return Uh(e,`toPayload threw:`,t.message),Kh(n)}let o=Gh(a);if(o<(i.threshold??0))return Uh(e,`below threshold:`,o,`<`,i.threshold),Kh(n);let s=zh(i.noun,o,a&&a.scope);return Uh(e,`OK shape=`,i.shape,`items=`,o,`stub=`,s),{content:[{type:`text`,text:s},{type:`text`,text:n}],structuredContent:a}}function Gh(e){if(!e||typeof e!=`object`)return 0;for(let t of[`customers`,`invoices`,`lines`,`payments`,`credit_notes`,`contracts`,`transactions`,`rows`,`items`,`data`,`addresses`,`payment_methods`,`products`,`plans`,`entries`,`jobs`,`contacts`,`raw_metrics`,`aggregates`,`entities`])if(Array.isArray(e[t]))return e[t].length;if(Number.isFinite(e.total))return e.total;for(let t of[`customer`,`invoice`,`contract`,`credit_note`])if(e[t]&&typeof e[t]==`object`)return 1;return+!!e.html}function Kh(e){return{content:[{type:`text`,text:e}]}}const qh=s(import.meta.url),Jh=i.dirname(qh),Yh={logUsage:async()=>{}},Xh=(e,t)=>({valid:!0,adjustedArgs:t,warnings:[],errors:[]}),Zh=()=>({message:`Limits validation unavailable`,severity:`info`,suggestions:[]}),$={debug:(e,t)=>{if(process.env.MCP_DEBUG===`true`){let n=new Date().toISOString();console.error(`[${n}] [MCP-DEBUG] ${e}`,t?JSON.stringify(t,null,2):``)}},info:(e,t)=>{let n=new Date().toISOString();console.error(`[${n}] [MCP-INFO] ${e}`,t?JSON.stringify(t,null,2):``)},error:(e,t)=>{let n=new Date().toISOString();console.error(`[${n}] [MCP-ERROR] ${e}`,t?JSON.stringify(t,null,2):``)},warn:(e,t)=>{let n=new Date().toISOString();console.error(`[${n}] [MCP-WARN] ${e}`,t?JSON.stringify(t,null,2):``)}},Qh=i.join(Jh,`mcp-config.json`);let $h;try{$h=JSON.parse(t.readFileSync(Qh,`utf8`))}catch(e){console.error(`Failed to load MCP config:`,e.message),console.error(`Please ensure mcp-config.json exists in the project root`),process.exit(1)}const eg=new mm({name:$h.server?.name||`zenskar-api-server`,version:`1.0.0`}),tg=new Pm;function ng(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t={...e};return typeof t.timestamp==`string`&&(t.timestamp=rg(t.timestamp)),t.data&&typeof t.data==`object`&&!Array.isArray(t.data)&&(t.data={...t.data},[`DateTime64`,`DateTime`,`DateTime32`].forEach(e=>{typeof t.data[e]==`string`&&(t.data[e]=rg(t.data[e]))})),t}function rg(e){return typeof e==`string`?e.replace(`T`,` `).replace(`t`,` `).replace(/Z$/i,``).trim():e}function ig(e){if(typeof e!=`string`)return e;let t=e.trim();if(!t)return e;switch(t.toLowerCase()){case`boolean`:return`Bool`;case`string`:return`String`;case`int`:case`int64`:return`Int64`;case`float`:case`float64`:case`double`:return`Float64`;case`date`:case`date32`:return`Date32`;case`datetime`:case`datetime64`:return`DateTime64`;case`uuid`:return`UUID`;default:return t}}function ag(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t={...e};if(t.customer_id&&=ig(t.customer_id),t.timestamp&&=ig(t.timestamp),t.data&&typeof t.data==`object`&&!Array.isArray(t.data)){let e={};Object.entries(t.data).forEach(([t,n])=>{e[t]=ig(n)}),t.data=e}return t}function og(e){return e?Array.isArray(e)?e:Array.isArray(e.results)?e.results:e.api_response===void 0?[]:og(e.api_response):[]}function sg(e){return!e||typeof e!=`string`?`Uncategorized`:e.trim()||`Uncategorized`}function cg(e){let t=Number(e);return Number.isFinite(t)?t/100:null}function lg(e,t){let n=sg(t);return e===`getBalanceSheet`&&n===`Liabilities`?`Liabilities & Equity`:n}function ug(e,t){return(e===`getBalanceSheet`?{Assets:1,Liabilities:2,Equity:3}:{Income:1,Revenue:1,"Cost of Goods Sold":2,Expense:3,Expenses:3,"Other Income":4,"Other Expense":5,"Other Expenses":5})[t]||999}function dg(e){return`${e?.interval_start||`unknown_start`}__${e?.interval_end||`unknown_end`}`}function fg(e){return Object.values(e).sort((e,t)=>String(e.interval_start).localeCompare(String(t.interval_start)))}function pg(e,t,n){let r=new Map,i=new Map;t.forEach(t=>{let a=lg(e,t.account_category),o=dg(t),s=r.get(o)||{key:o,interval_start:t.interval_start||null,interval_end:t.interval_end||null};r.set(o,s),i.has(a)||i.set(a,{category:a,accounts:new Map,totals_by_period:{},total_balance:0,total_debits:0,total_credits:0});let c=i.get(a),l=t.account_id||`unknown_account`,u=n.get(l)||{};c.accounts.has(l)||c.accounts.set(l,{account_id:l,account_name:t.account_name||u.name||l,account_description:t.account_description||u.description||null,account_category:a,parent_path:t.account_parent_path||u.parent_path||null,balance_normality:t.balance_normality||u.balance_normality||null,periods:{},total_balance:0,total_debits:0,total_credits:0});let d=c.accounts.get(l);d.periods[o]={interval_start:t.interval_start||null,interval_end:t.interval_end||null,balance:t.balance??0,display_balance:cg(t.balance??0),debits:t.debits??0,display_debits:cg(t.debits??0),credits:t.credits??0,display_credits:cg(t.credits??0)},d.total_balance+=Number(t.balance||0),d.total_debits+=Number(t.debits||0),d.total_credits+=Number(t.credits||0);let f=c.totals_by_period[o]||{interval_start:t.interval_start||null,interval_end:t.interval_end||null,balance:0,debits:0,credits:0,display_balance:0,display_debits:0,display_credits:0};f.balance+=Number(t.balance||0),f.debits+=Number(t.debits||0),f.credits+=Number(t.credits||0),f.display_balance=cg(f.balance),f.display_debits=cg(f.debits),f.display_credits=cg(f.credits),c.totals_by_period[o]=f,c.total_balance+=Number(t.balance||0),c.total_debits+=Number(t.debits||0),c.total_credits+=Number(t.credits||0)});let a=Array.from(i.values()).sort((t,n)=>{let r=ug(e,t.category)-ug(e,n.category);return r===0?t.category.localeCompare(n.category):r}).map(e=>({category:e.category,accounts:Array.from(e.accounts.values()).sort((e,t)=>e.account_name.localeCompare(t.account_name)).map(e=>({...e,periods:fg(e.periods)})),totals_by_period:fg(e.totals_by_period),total_balance:e.total_balance,display_total_balance:cg(e.total_balance),total_debits:e.total_debits,display_total_debits:cg(e.total_debits),total_credits:e.total_credits,display_total_credits:cg(e.total_credits)}));return{report_type:e===`getBalanceSheet`?`balance_sheet`:`income_statement`,periods:Array.from(r.values()).sort((e,t)=>String(e.interval_start).localeCompare(String(t.interval_start))),sections:a}}function mg(e){if(!e)return``;let t=e.account_category||``;return t===`Liabilities`?`Liabilities & Equity`:t}function hg(e){let t=[...e].map(e=>({...e,account_category:mg(e)})).sort((e,t)=>{let n=mg(e).localeCompare(mg(t));return n===0?String(e.name||``).localeCompare(String(t.name||``)):n}),n=new Map;t.forEach(e=>{let t=mg(e)||`Uncategorized`;n.has(t)||n.set(t,[]),n.get(t).push(e)}),[`Assets`,`Liabilities & Equity`,`Equity`,`Income`,`Expenses`].forEach(e=>{n.has(e)||n.set(e,[])});let r=Array.from(n.entries()).sort((e,t)=>e[0].localeCompare(t[0])).map(([e,t])=>({id:e,name:e,description:e,account_category:e,is_parent:!0,parent_path:null,children:t.map(t=>({...t,parent_path:t.parent_path||e}))})),i=r.find(e=>e.name===`Liabilities & Equity`);return i&&(i.children.some(e=>e.name===`Equity`)||(i.children.push({id:`Equity`,name:`Equity`,description:`Equity`,account_category:`Liabilities & Equity`,balance_normality:`credit`,is_parent:!0,parent_path:`Liabilities & Equity`,custom_data:{default_account:!1},children:[]}),i.children.push({id:`Equity:Retained Earnings`,name:`Retained Earnings`,description:`Retained Earnings`,account_category:`Liabilities & Equity`,balance_normality:`credit`,is_parent:!1,parent_path:`Equity`,custom_data:{default_account:!1}}))),r}function gg(e){if(!e||!Array.isArray(e.results))return e;let t=e.results.reduce((e,t)=>{let n=t.status||`unknown`;return e[n]=(e[n]||0)+1,e},{});return{...e,summary:{total_count:e.total_count??e.results.length,returned_count:e.results.length,page_status_counts:t,has_more:!!e.next,note:e.next?`Showing ${e.results.length} jobs from the current page. Use the cursor to continue through the remaining jobs.`:`Showing ${e.results.length} jobs from the current page.`}}}function _g(e){if(!e||!Array.isArray(e.results))return e;let t=[...e.results].sort((e,t)=>{let n=sg(e.account_category),r=sg(t.account_category),i=n.localeCompare(r);return i===0?String(e.name||``).localeCompare(String(t.name||``)):i}),n=t.reduce((e,t)=>{let n=sg(t.account_category);return e[n]=e[n]||[],e[n].push(t),e},{});return{...e,results:t,grouped_view:n}}async function vg(e,t){let n=await fetch(e,{method:`GET`,headers:t}),r=await n.text();if(!n.ok)throw Error(`Supplemental fetch failed: ${n.status} ${n.statusText}\nResponse: ${r}`);try{return JSON.parse(r)}catch{throw Error(`Supplemental fetch returned non-JSON response: ${r}`)}}async function yg(e,t,n){let r=e.rawMetricId,i=await vg(`${n}/rawmetric/${encodeURIComponent(r)}`,t);if(!i?.api_slug)throw Error(`Unable to resolve api_slug for raw metric ${r}`);let a={...t,apiversion:`20240301`},o={limit:e.limit??20,offset:e.offset??0,order_by:e.order_by??[{column:`timestamp`,type:`DESC`}],aggregate_operation:e.aggregate_operation??null,customer_mapping:null,end_date_mapping:null,start_date_mapping:null,table_name:`raw_metric_${i.api_slug}`,visual_query:{groups:[{filters:Array.isArray(e.filters)?e.filters:[],logic:`AND`}],logic:`AND`}},s=await fetch(`${n}/aggregate/visualquery/preview`,{method:`POST`,headers:a,body:JSON.stringify(o)}),c=await s.text();if(!s.ok)throw Error(`API request failed: ${s.status} ${s.statusText}\nResponse: ${c}`);try{return JSON.parse(c)}catch{return c}}async function bg(e,t,n,r){if(!t||!Array.isArray(t.results))return t;try{let i=og(await vg(`${r}/accounting_new/chart_of_accounts`,n)),a=new Map(i.filter(e=>e&&e.id).map(e=>[e.id,e])),o=t.results.map(t=>{let n=a.get(t.account_id)||{};return{...t,account_name:n.name||t.account_id||null,account_description:n.description||null,account_category:lg(e,n.account_category),account_parent_path:n.parent_path||null,balance_normality:n.balance_normality||null,display_balance:cg(t.balance??0),display_debits:cg(t.debits??0),display_credits:cg(t.credits??0)}}),s=pg(e,o,a);if(e===`getBalanceSheet`){let e=new URLSearchParams;n.apiversion&&e.set(`apiversion`,n.apiversion);let t=await vg(`${r}/accounting_new/income_statement/v2`,n),i=Array.isArray(t?.results)?t.results:[],a={};i.forEach(e=>{let t=dg(e),n=a[t]||{interval_start:e.interval_start||null,interval_end:e.interval_end||null,balance:0,debits:0,credits:0};n.balance+=Number(e.balance||0),n.debits+=Number(e.debits||0),n.credits+=Number(e.credits||0),a[t]=n});let o=fg(Object.fromEntries(Object.entries(a).map(([e,t])=>[e,{...t,display_balance:cg(t.balance),display_debits:cg(t.debits),display_credits:cg(t.credits)}]))),c={account_id:`Equity:Retained Earnings`,account_name:`Retained Earnings (Derived)`,account_description:`Derived from the companion income statement for MCP presentation.`,account_category:`Liabilities & Equity`,parent_path:`Equity`,balance_normality:`credit`,periods:o,total_balance:o.reduce((e,t)=>e+Number(t.balance||0),0),display_total_balance:cg(o.reduce((e,t)=>e+Number(t.balance||0),0)),total_debits:o.reduce((e,t)=>e+Number(t.debits||0),0),display_total_debits:cg(o.reduce((e,t)=>e+Number(t.debits||0),0)),total_credits:o.reduce((e,t)=>e+Number(t.credits||0),0),display_total_credits:cg(o.reduce((e,t)=>e+Number(t.credits||0),0))},l=s.sections.find(e=>e.category===`Liabilities & Equity`);l||(l={category:`Liabilities & Equity`,accounts:[],totals_by_period:[],total_balance:0,display_total_balance:0,total_debits:0,display_total_debits:0,total_credits:0,display_total_credits:0},s.sections.push(l)),l.accounts.push(c)}return{...t,results:o,statement_view:s}}catch(n){return $.warn(`[${e}] Failed to enrich accounting report output; returning raw report`,{error:n.message}),t}}function xg(e){let t={};return e.forEach(e=>{let n;n=e.type===`integer`||e.type===`number`?R():e.type===`boolean`?$s():e.type===`object`?U(rc()):e.type===`array`?B(rc()):e.type===`datetime`?H([I(),R()]):I(),e.default!==void 0&&(n=n.default(e.default)),e.required||(n=n.optional()),e.description&&(n=n.describe(e.description)),t[e.name]=n}),t.__userContext=V({userId:I().optional(),authorization:I().optional(),organization:I().optional(),apiKey:I().optional(),headers:V({}).optional(),approval:V({approved:$s(),token:I().optional(),modifiedArguments:U(rc()).optional(),originalArguments:U(rc()).optional(),toolName:I().optional()}).optional()}).optional().describe(`Internal user context for multi-tenant authentication and approval workflow`),t}async function Sg(e,t){let n=Date.now();if(e.name===`getCurrentDateTime`){let e=new Date;return{currentDate:e.toISOString().split(`T`)[0],currentDateTime:e.toISOString(),timestamp:e.getTime(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,humanReadable:e.toLocaleString()}}$.debug(`[${e.name}] Raw args received:`,{argKeys:Object.keys(t),argValues:JSON.stringify(t,null,2)});let r=t.__userContext,i={...t};delete i.__userContext,$.debug(`[${e.name}] User context received:`,r?{hasUserId:!!r.userId,hasAuthorization:!!r.authorization,hasOrganization:!!r.organization,authPrefix:r.authorization?r.authorization.substring(0,20)+`...`:`none`}:`NO USER CONTEXT`);let a=e.requestTemplate?.url||`/`,o=e.requestTemplate?.method||`GET`,s=a.startsWith(`http://`)||a.startsWith(`https://`);$.debug(`[${e.name}] Executing ${o} request with args:`,JSON.stringify(i,null,2)),r&&$.debug(`[${e.name}] Using user context:`,{hasApiKey:!!r.apiKey,hasOrganization:!!r.organization,userId:r.userId}),e.args&&e.args.forEach(e=>{e.position===`path`&&i[e.name]!==void 0&&(a=a.replace(`{${e.name}}`,encodeURIComponent(i[e.name])))});let c=new URLSearchParams;e.args&&e.args.forEach(e=>{e.position===`query`&&i[e.name]!==void 0&&i[e.name]!==null&&i[e.name]!==``&&(typeof i[e.name]==`boolean`?c.append(e.name,i[e.name].toString()):Array.isArray(i[e.name])?i[e.name].forEach(t=>{c.append(e.name,t)}):c.append(e.name,i[e.name]))}),Object.keys(i).forEach(t=>{if(!c.has(t)&&i[t]!==void 0&&i[t]!==null&&i[t]!==``){let n=e.args?.some(e=>e.position===`path`&&e.name===t),r=e.args?.some(e=>e.position===`body`&&e.name===t);!n&&!r&&(typeof i[t]==`boolean`?c.append(t,i[t].toString()):Array.isArray(i[t])?i[t].forEach(e=>{c.append(t,e)}):c.append(t,i[t]))}}),c.toString()&&(a+=`?`+c.toString());let l=null;if(o!==`GET`&&o!==`DELETE`&&e.args){let t=e=>{if(typeof e==`number`)return Number.isFinite(e)?Math.floor(e):e;if(typeof e==`string`){let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):e}return e},n={};if(e.args.forEach(r=>{if(r.position===`body`&&i[r.name]!==void 0){if(r.type===`datetime`){n[r.name]=t(i[r.name]);return}if(e.name===`ingestRawMetricEvent`&&r.name===`event`){let e=ng(i[r.name]);e&&typeof e==`object`&&!Array.isArray(e)?Object.entries(e).forEach(([e,t])=>{t!==void 0&&(n[e]=t)}):n[r.name]=e}else n[r.name]=i[r.name]}}),e.name===`createCustomer`||e.name===`updateCustomer`){let t=(t,r)=>{let i={[`${t}line1`]:`line1`,[`${t}line2`]:`line2`,[`${t}line3`]:`line3`,[`${t}city`]:`city`,[`${t}state`]:`state`,[`${t}zipCode`]:`zipCode`,[`${t}country`]:`country`,[`${t}country_code`]:`country_code`},a={},o=!1;Object.entries(i).forEach(([e,t])=>{n[e]!==void 0&&(a[t]=n[e],delete n[e],o=!0)}),o&&(n[r]=a,$.debug(`[${e.name}] Transformed flat ${t}* fields into ${r} object`))};t(`address_`,`address`),t(`ship_to_`,`ship_to_address`)}if(e.name===`createBusinessEntity`&&((t,r)=>{let i={[`${t}line1`]:`line1`,[`${t}line2`]:`line2`,[`${t}line3`]:`line3`,[`${t}city`]:`city`,[`${t}state`]:`state`,[`${t}zipCode`]:`zipCode`,[`${t}country`]:`country`},a={},o=!1;Object.entries(i).forEach(([e,t])=>{n[e]!==void 0&&(a[t]=n[e],delete n[e],o=!0)}),o&&(n[r]=a,$.debug(`[${e.name}] Transformed flat ${t}* fields into ${r} object`))})(`address_`,`address`),e.name===`getInvoicePreviewHtml`&&!i.orgId){let e=r?.organization||process.env.ZENSKAR_ORGANIZATION;e&&(i.orgId=e)}if(e.name===`extractContractFromRaw`&&!n.organization_id){let t=r?.organization||process.env.ZENSKAR_ORGANIZATION;t&&(n.organization_id=t,$.debug(`[${e.name}] Auto-populated organization_id: ${t}`))}e.name===`createRawMetric`&&(n.connector||=i.connector||`push_to_zenskar`,n.api_type||=i.api_type||`PUSH`,n.dataschema||={customer_id:`string`,timestamp:`timestamp`,data:{usage_amount:`decimal`,feature_id:`string`}},n.dataschema&&=ag(n.dataschema),n.column_order=[`timestamp`]),Object.keys(n).length>0?l=JSON.stringify(n):(o===`PATCH`||o===`POST`||o===`PUT`)&&(l=`{}`)}let u={"Content-Type":`application/json`,"User-Agent":`Zenskar-MCP-Server/1.0.0`,apiversion:`20230501`},d=r?.organization||process.env.ZENSKAR_ORGANIZATION,f=r?.authorization||r?.headers?.authorization||r?.headers?.Authorization||process.env.ZENSKAR_AUTH_TOKEN,p=r?.apiKey||r?.headers?.[`x-api-key`]||process.env.ZENSKAR_API_KEY||process.env.ZENSKAR_AUTH_TOKEN;if(d)u.organisation=d;else throw $.error(`[${e.name}] SECURITY ERROR: No organization ID provided`),Error(`Organization ID is required for API access. Set ZENSKAR_ORGANIZATION env var or provide in user context.`);if(f&&f.startsWith(`eyJ`))u.Authorization=f.startsWith(`Bearer `)?f:`Bearer ${f}`;else if(p)u[`x-api-key`]=p;else throw $.error(`[${e.name}] SECURITY ERROR: No authorization provided`),Error(`Authorization is required. Set ZENSKAR_AUTH_TOKEN (JWT) or ZENSKAR_API_KEY env var.`);if(r?.headers){let e=new Set(Object.keys(u).map(e=>e.toLowerCase())),t=new Set([`__proto__`,`prototype`,`constructor`]);Object.keys(r.headers).forEach(n=>{t.has(n)||Object.prototype.hasOwnProperty.call(r.headers,n)&&r.headers[n]&&!e.has(n.toLowerCase())&&(u[n]=r.headers[n])})}$.debug(`[${e.name}] Using headers:`,{hasOrganization:!!u.organisation,hasAuthorization:!!u.Authorization,hasApiKey:!!u[`x-api-key`],source:r?.organization?`userContext`:`env`}),e.requestTemplate?.headers&&(Array.isArray(e.requestTemplate.headers)?e.requestTemplate.headers.forEach(e=>{u[e.key]=e.value}):Object.keys(e.requestTemplate.headers).forEach(t=>{u[t]=e.requestTemplate.headers[t]}));let m;if(s)m=a,$.debug(`[${e.name}] Using absolute URL: ${m}`);else{let t=process.env.ZENSKAR_API_BASE_URL||`https://api.zenskar.com`;m=t+a,$.debug(`[${e.name}] Using relative URL with base: ${t} + ${a} = ${m}`)}$.debug(`[${e.name}] Making ${o} request to: ${m}`),$.info(`[${e.name}] MULTI-TENANT SECURITY CHECK - Headers being sent:`,{organization:u.organisation||`MISSING`,hasAuth:!!u.Authorization,authPrefix:u.Authorization?u.Authorization.substring(0,30)+`...`:`NONE`,allHeaders:JSON.stringify(u,null,2)});try{if(e.name===`getRawMetricLogs`){let t=await yg(i,u,process.env.ZENSKAR_API_BASE_URL||`https://api.zenskar.com`);return $.debug(`[${e.name}] Successfully processed frontend-style usage-event logs`),t}let t=await fetch(m,{method:o,headers:u,body:l}),r=await t.text(),a=Date.now()-n;if($.info(`[${e.name}] Response received in ${a}ms - Status: ${t.status}, Size: ${r.length} chars`),$.info(`[${e.name}] Raw response body:`,r),!t.ok){$.error(`[${e.name}] API Error Response:`,r);let n=`API request failed: ${t.status} ${t.statusText}\nResponse: ${r}`;throw Error(n)}let s;try{s=JSON.parse(r)}catch{$.debug(`[${e.name}] Failed to parse JSON response, returning as text`),s=r}if(e.name===`getInvoicePreviewHtml`)if(typeof s==`string`)try{let e=Buffer.from(s,`base64`).toString(`utf8`);s=e.includes(`<`)?{html:e}:{html:s}}catch{s={html:s}}else s={html:``};if(e.name===`getBalanceSheet`||e.name===`getIncomeStatement`){let t=process.env.ZENSKAR_API_BASE_URL||`https://api.zenskar.com`;s=await bg(e.name,s,u,t)}return e.name===`listJobs`&&(s=gg(s)),e.name===`listAccounts`&&(s=_g(s)),e.name===`getChartOfAccounts`&&Array.isArray(s)&&(s={raw_accounts:s,chart_view:hg(s)}),e.responseTemplate?.prependBody&&(s={template_info:e.responseTemplate.prependBody,api_response:s}),$.debug(`[${e.name}] Successfully processed response`),s}catch(t){throw $.error(`[${e.name}] Network error:`,t),Error(`Network error: ${t.message}`)}}const Cg=300*1e3,wg=process.env.APPROVAL_HMAC_SECRET,Tg=!!wg,Eg=new Map,Dg=new Map;function Og(e){if(e==null)return e;if(typeof structuredClone==`function`)try{return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}function kg(e){let t=e?Og(e):{};return delete t.__userContext,t}function Ag(t){return e.createHmac(`sha256`,wg).update(t).digest(`base64url`)}function jg(t,n){let r=Date.now(),i=r+Cg,a=kg(n);if(Tg){let n={toolName:t,args:a,issuedAt:r,expiresAt:i,nonce:e.randomBytes(12).toString(`base64url`)},o=Buffer.from(JSON.stringify(n),`utf8`).toString(`base64url`);return`v1.${o}.${Ag(o)}`}let o=Mm();return Eg.set(o,{toolName:t,issuedAt:r,expiresAt:i,args:a}),o}function Mg(t,n){if(!t||typeof t!=`string`)return null;if(Tg){let r=t.split(`.`);if(r.length!==3)return null;let[i,a,o]=r;if(i!==`v1`)return null;let s=Ag(a),c=Buffer.from(o,`base64url`),l=Buffer.from(s,`base64url`);if(c.length!==l.length||!e.timingSafeEqual(c,l))return null;let u;try{u=JSON.parse(Buffer.from(a,`base64url`).toString(`utf8`))}catch{return null}return u.toolName!==n||typeof u.expiresAt!=`number`||u.expiresAt<Date.now()||Dg.has(t)?null:(Dg.set(t,u.expiresAt),u)}let r=Eg.get(t);return!r||(Eg.delete(t),r.toolName!==n)||r.expiresAt<Date.now()?null:r}setInterval(()=>{let e=Date.now();for(let[t,n]of Eg)n.expiresAt<e&&Eg.delete(t);for(let[t,n]of Dg)n<e&&Dg.delete(t)},6e4).unref();function Ng(e,t){return(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0)(e.modifiedArguments)?{args:e.modifiedArguments,source:`modifiedArguments`}:{args:t.args,source:`tokenSnapshot`}}function Pg(e,t){let n=e.__userContext;Object.keys(e).forEach(t=>{t!==`__userContext`&&delete e[t]}),Object.assign(e,t),e.__userContext=n}function Fg(e,t){if(!e.needsApproval)return!1;let n=t.__userContext,r=n&&n.approval;if(r&&r.approved===!0){let n=Mg(r.token,e.name);if(n){let{args:i,source:a}=Ng(r,n);return $.info(`[${e.name}] Approval token verified; arg source=${a}`),Pg(t,i),$.info(`[${e.name}] Restored arguments for approved execution:`,Object.keys(i)),!1}$.warn(`[${e.name}] Approval received without valid token (got: ${r.token?`expired/mismatched`:`missing`}); requiring re-approval`)}return typeof e.needsApproval==`function`?e.needsApproval(t):e.needsApproval===!0}function Ig(e,t){t.__userContext;let n={...t};delete n.__userContext;let r=jg(e.name,t);return{type:`approval_required`,toolName:e.name,toolDescription:e.description,arguments:n,approvalToken:r,approvalTokenExpiresInSeconds:Math.floor(Cg/1e3),approvalConfig:e.approvalConfig||{title:`Approve ${e.name}`,description:`This action requires your approval: ${e.description}`,warningText:`Please review the parameters carefully before proceeding.`,confirmText:`Approve`,cancelText:`Cancel`},fields:(e.args||[]).map(t=>({name:t.name,label:t.description||t.name,type:Rg(t.type),required:t.required||!1,value:n[t.name],sensitive:e.approvalConfig?.sensitiveFields?.includes(t.name)||!1}))}}function Lg(e,t){let n=[];if(e===`createProductPricing`){let e=t.pricing_data;!e||typeof e!=`object`?n.push(`'pricing_data' is required and must be an object containing 'pricing_type' and 'currency'.`):(e.pricing_type||n.push(`'pricing_data.pricing_type' is required (e.g. 'per_unit', 'flat_fee', 'tiered', 'volume', 'percent', 'package').`),e.currency||n.push(`'pricing_data.currency' is required (ISO 4217, e.g. 'USD').`));let r=t.quantity;!r||typeof r!=`object`?n.push(`'quantity' is required and must be an object: {type:'fixed'|'metered', quantity?, unit?, aggregate_id?}. Without it the UI shows 0 for billing_metric.`):(r.type!==`fixed`&&r.type!==`metered`&&n.push(`'quantity.type' must be exactly 'fixed' or 'metered'.`),r.type===`fixed`&&(r.quantity==null||!r.unit)&&n.push(`'quantity.type'='fixed' requires both 'quantity' (number) and 'unit' (label string).`),r.type===`metered`&&!r.aggregate_id&&n.push(`'quantity.type'='metered' requires 'aggregate_id' (UUID of the billable metric).`));let i=t.billing_period;!i||typeof i!=`object`?n.push(`'billing_period' is required and must be an object: {cadence:'P1M'|'P3M'|'P1Y'|..., offset:'P0D'|...}. Without it the UI renders 'Undefined- Every Undefined Undefined'.`):(i.cadence||n.push(`'billing_period.cadence' is required (ISO-8601 duration: 'P1M'=monthly, 'P3M'=quarterly, 'P1Y'=yearly).`),i.offset||n.push(`'billing_period.offset' is required (ISO-8601 duration, 'P0D' for no offset).`))}if(e===`createPlan`){(!t.schedule||typeof t.schedule!=`object`||!t.schedule.duration)&&n.push(`'schedule' is required and must include 'duration' (ISO-8601, e.g. 'P1Y').`),t.status||n.push(`'status' is required: 'draft' | 'active' | 'archived'.`);let e=t.phases;!Array.isArray(e)||e.length===0?n.push(`'phases' must be a non-empty array. A plan with no phases is unusable in PlansV2 — include at least one phase with name, schedule, order, and either features or pricings.`):e.forEach((e,t)=>{if(!e||typeof e!=`object`){n.push(`'phases[${t}]' must be an object.`);return}e.name||n.push(`'phases[${t}].name' is required.`),(!e.schedule||!e.schedule.duration)&&n.push(`'phases[${t}].schedule.duration' is required (ISO-8601).`),typeof e.order!=`number`&&n.push(`'phases[${t}].order' is required (integer, 0-indexed).`),!e.features&&(!Array.isArray(e.pricings)||e.pricings.length===0)&&n.push(`'phases[${t}]' has neither 'features' nor non-empty 'pricings' — phase will be empty in the UI.`)})}if(e===`generateInvoice`){let e=e=>{if(typeof e==`number`)return Number.isInteger(e)?e:null;if(typeof e==`string`){let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):null}return null},r=e(t.from_date),i=e(t.to_date);r===null&&n.push(`'from_date' must be either an integer UNIX timestamp (seconds) or an ISO-8601 datetime string. Copy from getContractBillingCycles.start_date.`),i===null&&n.push(`'to_date' must be either an integer UNIX timestamp (seconds) or an ISO-8601 datetime string. Copy from getContractBillingCycles.end_date.`),r!==null&&i!==null&&i<=r&&n.push(`'to_date' must be strictly greater than 'from_date'.`),e(t.bill_for_date)===null&&n.push(`'bill_for_date' is REQUIRED (UNIX seconds or ISO-8601 string). Without it the API returns a $0 invoice. Copy from getContractBillingCycles.bill_for_date — do NOT compute.`),(!Number.isInteger(t.billing_cycle_start_day)||t.billing_cycle_start_day<1||t.billing_cycle_start_day>31)&&n.push(`'billing_cycle_start_day' is REQUIRED and must be an integer 1-31. Copy from getContractBillingCycles.billing_cycle_start_day.`)}return e===`pauseContract`&&(t.start_date||n.push(`'start_date' is required (ISO 8601).`),t.unpause_extension_policy||n.push(`'unpause_extension_policy' is required: 'extend' or 'overlap'.`)),{valid:n.length===0,errors:n}}function Rg(e){switch(e){case`string`:return`text`;case`integer`:case`number`:return`number`;case`boolean`:return`checkbox`;default:return`text`}}Lh(eg),$h.tools&&$h.tools.length>0&&$h.tools.forEach(e=>{$.info(`Registering tool: ${e.name}`);let t=xg(e.args||[]),n=jh(e.name),r=n.mode===`ui`?(()=>{let e=Rm(n.shape);return{"openai/outputTemplate":e,"ui/resourceUri":e,ui:{resourceUri:e}}})():void 0;eg.registerTool(e.name,{title:e.name,description:e.description,inputSchema:t,...r?{_meta:r}:{}},async t=>{let n=Date.now(),r=`success`,i=null,a=0,o=0,s=null,c=null;try{$.debug(`[${e.name}] Tool execution started`),$.info(`[${e.name}] Raw args received:`,{argKeys:Object.keys(t),hasUserContextInArgs:!!t.__userContext,userContextInArgs:t.__userContext,approvedInArgs:t.__userContext?.approved});let l=Lg(e.name,t);if(!l.valid){$.error(`[${e.name}] Tool execution blocked due to invalid arguments (pre-approval):`,l.errors),r=`blocked`,i=`invalid_args: ${l.errors.join(`; `)}`;let t={type:`invalid_arguments`,toolName:e.name,errors:l.errors};return{content:[{type:`text`,text:JSON.stringify(t,null,2)},{type:`text`,text:`ACTION_NOT_EXECUTED — INVALID_ARGUMENTS\n\nTool '${e.name}' was NOT executed because the supplied arguments are invalid or incomplete:\n\n`+l.errors.map((e,t)=>`${t+1}. ${e}`).join(`
78
+ [Response truncated due to length]`),t}catch(e){return console.error(`Response processing error:`,e),`Error processing response`}}};function Fm(e){return!e||typeof e!=`string`?``:e.replace(/[_-]+/g,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/\b\w/g,e=>e.toUpperCase()).trim()}const Im=new Set([`getInvoiceSummary`,`getCustomerBalance`,`getPaymentStatus`]),Lm={listCustomers:{shape:`customer-table`,noun:`customer`,toPayload:Bm,threshold:0},listInvoices:{shape:`invoice-table`,noun:`invoice`,toPayload:Vm,threshold:0},getInvoiceLineItems:{shape:`invoice-line-items`,noun:`line item`,toPayload:Um,threshold:0},listAllPayments:{shape:`payment-table`,noun:`payment`,toPayload:Jm,threshold:0},listCreditNotes:{shape:`credit-note-table`,noun:`credit note`,toPayload:Xm,threshold:0},listContracts:{shape:`contract-table`,noun:`contract`,toPayload:Qm,threshold:0},getCustomerById:{shape:`customer-detail`,noun:`customer`,toPayload:eh,threshold:0},getInvoiceById:{shape:`invoice-detail`,noun:`invoice`,toPayload:th,threshold:0},getContractById:{shape:`contract-detail`,noun:`contract`,toPayload:nh,threshold:0},getCreditNoteById:{shape:`credit-note-detail`,noun:`credit note`,toPayload:sh,threshold:0},listProducts:{shape:`product-table`,noun:`product`,toPayload:ch,threshold:0},listPlans:{shape:`plan-table`,noun:`plan`,toPayload:uh,threshold:0},listJournalEntries:{shape:`journal-table`,noun:`journal entry`,toPayload:fh,threshold:0},listJobs:{shape:`job-table`,noun:`job`,toPayload:mh,threshold:0},listContacts:{shape:`contact-table`,noun:`contact`,toPayload:gh,threshold:0},listRawMetrics:{shape:`raw-metric-table`,noun:`raw metric`,toPayload:vh,threshold:0},listAggregates:{shape:`aggregate-table`,noun:`aggregate`,toPayload:bh,threshold:0},listCustomerAddresses:{shape:`address-list`,noun:`address`,toPayload:Sh,threshold:0},listPaymentMethods:{shape:`payment-method-list`,noun:`payment method`,toPayload:wh,threshold:0},listBusinessEntities:{shape:`entity-table`,noun:`business entity`,toPayload:Eh,threshold:0},listEntitlements:{shape:`entitlement-table`,noun:`entitlement`,toPayload:Oh,threshold:0},getInvoicePreviewHtml:{shape:`invoice-preview`,noun:`invoice preview`,toPayload:Ph,threshold:0}},Rm=Object.freeze([`app`]);function zm(e){return`ui://zenskar/app.html`}function Bm(e,t){let n=Q(e),r=Ah(n,[`customers`,`data`,`results`]),i=Mh(n,[`total`,`count`,`total_count`])??r.length,a=jh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search_name_external_id||t.search)||void 0;return{customers:r.map(qm),total:i,cursor:{next:o,prev:s},scope:c}}function Q(e){return e&&typeof e==`object`&&e.api_response&&typeof e.api_response==`object`?e.api_response:e||{}}function Vm(e,t){let n=Q(e),r=Ah(n,[`invoices`,`data`,`results`]),i=Mh(n,[`total`,`count`,`total_count`])??r.length,a=jh(n,[`cursor`,`pagination`])||{},o=a.next??n.next??null,s=a.prev??n.previous??null;return{invoices:r.map(Hm),total:i,cursor:{next:o,prev:s},scope:t&&(t.customer__customer_name__ilike||t.invoice_number__like||t.status)||void 0,default_currency:`USD`}}function Hm(e){if(!e||typeof e!=`object`)return{id:``,invoice_number:null,customer_id:null,customer_name:null,status:null,invoice_total:null,amount_due:null,due_date:null,invoice_period_begin:null,invoice_period_end:null,external_id:null,created_at:null,payment_url:null};let t=e.invoice_period||{},n=e.customer&&typeof e.customer==`object`?e.customer:null;return{id:String(e.id||e.invoice_id||``),invoice_number:e.invoice_number??null,customer_id:n?.id??e.customer_id??null,customer_name:n?.customer_name??n?.name??null,status:e.status??null,invoice_total:Nh(e.net_invoice_total??e.invoice_total),amount_due:Nh(e.amount_due),due_date:e.due_date??e.promise_due_date??null,invoice_period_begin:t.begin_date??e.period_begin_date??null,invoice_period_end:t.end_date_exclusive??e.period_end_date??null,external_id:e.external_id??null,created_at:e.created_at??null,payment_url:e.payment_url??null}}function Um(e,t){let n=Q(e),r=Array.isArray(n.lines)?n.lines:Array.isArray(n)?n:[],i=Nh(n.total),a=Wm(r)||`USD`;return{invoice_id:t&&t.invoiceId?String(t.invoiceId):void 0,total:i,currency:a,lines:r.map(Gm)}}function Wm(e){for(let t of e){if(t&&t.subtotal&&t.subtotal.unit)return t.subtotal.unit;if(t&&t.features&&t.features[0]&&t.features[0].currency)return t.features[0].currency}return null}function Gm(e){return!e||typeof e!=`object`?{name:``,description:null,pricing_model:null,subtotal:{value:null,unit:null},quantity:{value:null,unit:null},price:null,service_start_date:null,service_end_date:null,is_billed:null}:{name:e.name??e.description??``,description:e.description??null,pricing_model:e.pricing_model??null,subtotal:Km(e.subtotal),quantity:Km(e.quantity),price:e.price?Km(e.price):null,service_start_date:e.service_start_date??e.billing_period_start??null,service_end_date:e.service_end_date??e.billing_period_end??null,is_billed:typeof e.is_billed==`boolean`?e.is_billed:null,line_item_type:e.line_item_type??null,is_adjustment:typeof e.is_adjustment==`boolean`?e.is_adjustment:null,adjustment_type:e.adjustment_type??null}}function Km(e){return e?{value:Nh(e.value),unit:e.unit??null,display:e.display??null}:{value:null,unit:null,display:null}}function qm(e){return!e||typeof e!=`object`?{id:``,name:null,external_id:null,email:null}:{id:String(e.id||e.customer_id||``),name:e.customer_name??e.name??null,external_id:e.external_id??null,email:e.email??e.primary_email??null,created_at:e.created_at??e.created??null}}function Jm(e,t){let n=Q(e),r=Ah(n,[`payments`,`data`,`results`]),i=Mh(n,[`total`,`count`,`total_count`])??r.length,a=jh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search||t.customer_id||t.type||t.payment_method)||void 0;return{payments:r.map(Ym),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0,default_currency:`USD`}}function Ym(e){if(!e||typeof e!=`object`)return{id:``,external_id:null,customer_id:null,customer_name:null,invoice_id:null,invoice_name:null,amount:null,currency:null,payment_method:null,type:null,status:null,description:null,payment_date:null,created_at:null};let t=((Array.isArray(e.payment_parts)?e.payment_parts:[]).find(e=>e&&e.invoice_id)||{}).invoice_id||e.invoice_id||null,n=e.customer&&typeof e.customer==`object`?e.customer:null,r=e.invoice&&typeof e.invoice==`object`?e.invoice:null;return{id:String(e.id||e.payment_id||``),external_id:e.external_id??null,customer_id:n?.id??e.customer_id??null,customer_name:n?.customer_name??n?.name??null,invoice_id:r?.id??t,invoice_name:r?.name??r?.invoice_number??null,amount:Nh(e.amount??e.value),currency:e.currency_code??e.currency??null,payment_method:e.payment_method??null,type:e.type??null,status:e.status??null,description:e.description??e.notes??null,payment_date:e.payment_date??e.received_at??e.processed_at??null,created_at:e.created_at??null}}function Xm(e,t){let n=Q(e),r=Ah(n,[`credit_notes`,`creditNotes`,`data`,`results`]),i=Mh(n,[`total`,`count`,`total_count`])??r.length,a=jh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.customer_id||t.invoice_id||t.status)||void 0;return{credit_notes:r.map(Zm),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0,default_currency:`USD`}}function Zm(e){if(!e||typeof e!=`object`)return{id:``,credit_note_number:null,customer_id:null,customer_name:null,invoice_id:null,invoice_name:null,status:null,amount:null,currency:null,repayment_method:null,created_at:null};let t=e.customer&&typeof e.customer==`object`?e.customer:null,n=e.invoice&&typeof e.invoice==`object`?e.invoice:null;return{id:String(e.id||e.credit_note_id||``),credit_note_number:e.credit_note_number??null,customer_id:t?.id??e.customer_id??null,customer_name:t?.customer_name??t?.name??null,invoice_id:n?.id??e.invoice_id??null,invoice_name:n?.name??n?.invoice_number??null,status:e.status??null,amount:Nh(e.amount??e.total??e.value),currency:e.currency_code??e.currency??null,repayment_method:e.repayment_method??null,created_at:e.created_at??null}}function Qm(e,t){let n=Q(e),r=Ah(n,[`contracts`,`data`,`results`]),i=Mh(n,[`total`,`count`,`total_count`])??r.length,a=jh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.customer_id||t.name__ilike||t.status)||void 0;return{contracts:r.map($m),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0}}function $m(e){if(!e||typeof e!=`object`)return{id:``,customer_id:null,customer_name:null,name:null,status:null,currency:null,start_date:null,end_date:null,created_at:null};let t=e.customer&&typeof e.customer==`object`?e.customer:null;return{id:String(e.id||e.contract_id||``),customer_id:t?.id??e.customer_id??null,customer_name:t?.customer_name??t?.name??null,name:e.name??e.contract_name??null,status:e.status??e.state??null,currency:e.currency??e.currency_code??null,start_date:e.start_date??null,end_date:e.end_date??null,created_at:e.created_at??null}}function eh(e){let t=Q(e),n=t.customer??t,r=qm(n),i=n.business_entity,a=n.default_payment_method,o=Array.isArray(n.contacts)?n.contacts:[],s=Array.isArray(n.tax_info)?n.tax_info:[];return{customer:{...r,phone:n.phone_number??n.phone??n.primary_phone??null,business_entity_id:n.business_entity_id??null,business_entity_name:(i&&typeof i==`object`?i.name:null)??null,address:n.address??null,ship_to_address:n.ship_to_address??null,communications_enabled:typeof n.communications_enabled==`boolean`?n.communications_enabled:null,auto_charge_enabled:typeof n.auto_charge_enabled==`boolean`?n.auto_charge_enabled:null,custom_data:n.custom_data??null,tax_info:s.length?s.map(e=>({country_code:e.country_code??null,tax_code:e.tax_code??null,tax_id:e.tax_id??null})):null,contacts:o.length?o.map(e=>({name:[e.first_name??``,e.last_name??``].filter(Boolean).join(` `)||null,email:e.email??null,send_invoice:typeof e.send_invoice==`boolean`?e.send_invoice:null,send_contract:typeof e.send_contract==`boolean`?e.send_contract:null})):null,default_payment_method:a&&typeof a==`object`?{type:a.type??null,brand:(a.details&&a.details.brand)??a.brand??null,last4:(a.details&&a.details.last4)??a.last4??null,connector_name:a.connector_name??null}:null,updated_at:n.updated_at??null}}}function th(e){let t=Q(e),n=t.invoice??t,r=Hm(n),i=n.customer,a=n.contract;return{invoice:{...r,paid_amount:Nh(n.paid_amount??(r.invoice_total!=null&&r.amount_due!=null?r.invoice_total-r.amount_due:null)),currency:n.currency_code??n.currency??null,business_entity_id:n.business_entity_id??null,notes:n.notes??null,custom_data:n.custom_data??n.custom_attributes??null,customer_name:(i&&typeof i==`object`?i.name:null)??null,contract_id:n.contract_id??(a&&typeof a==`object`?a.id:null)??null,contract_name:(a&&typeof a==`object`?a.name:null)??null,invoice_pdf:n.invoice_pdf??null,approved_at:n.approved_at??null,paid_at:n.paid_at??null,sent_at:n.sent_at??null}}}function nh(e){let t=Q(e),n=t.contract??t,r=$m(n),i=Array.isArray(n.phases)?n.phases:[],a=n.customer,o=Array.isArray(n.tags)?n.tags:[];return{contract:{...r,description:n.description??null,custom_attributes:n.custom_attributes??null,renewal_policy:n.renewal_policy??null,anchor_date:n.anchor_date??null,plan_id:n.plan_id??null,customer_name:(a&&typeof a==`object`?a.customer_name??a.name:null)??null,contract_type:n.contract_type??null,tags:o.length?o:null,contract_link:n.contract_link??null},phases:i.map(rh)}}function rh(e){if(!e||typeof e!=`object`)return{id:null,name:null,start_date:null,end_date:null,pricing_summary:null,product_count:null,pricings:[]};let t=Array.isArray(e.products)?e.products:[],n=Array.isArray(e.pricings)?e.pricings:t;return{id:e.id??null,name:e.name??e.phase_name??null,start_date:e.start_date??null,end_date:e.end_date??null,pricing_summary:e.pricing_summary??null,product_count:n.length||Nh(e.product_count),pricings:n.map(ah)}}function ih(e){return!e||!Array.isArray(e.prices)||!Array.isArray(e.dimensions)||e.prices.length===0?null:e.prices.map((t,n)=>({dimension:e.dimensions[n]?.name??null,display_alias:Array.isArray(e.display_alias)?e.display_alias[n]??null:null,price:typeof t==`number`?t:null}))}function ah(e){if(!e||typeof e!=`object`)return{product_name:null,pricing_model:null};let t=e.pricing??{},n=e.pricing_data??t.pricing_data??e,r=t.quantity??e.quantity??{},i=t.billing_period??e.billing_period??{},a=e.product??{};return{id:e.id??null,product_name:a.name??e.name??e.product_name??null,product_type:a.type??null,description:e.description??t.description??a.description??null,pricing_model:n.pricing_type??e.pricing_model??null,currency:n.currency??null,unit_amount:n.unit_amount??null,tiers:Array.isArray(n.tiers)?n.tiers:null,package_size:n.package_size??null,matrix:ih(n),quantity_type:r.type??null,quantity_value:r.quantity??null,quantity_unit:r.unit??null,meter_name:r.aggregate?.name??r.aggregate_name??null,billing_cadence:i.cadence??null,billing_timing:e.billing_timing??t.billing_timing??null,is_recurring:typeof t.is_recurring==`boolean`?t.is_recurring:typeof e.is_recurring==`boolean`?e.is_recurring:null,start_date:e.start_date??null,end_date:e.end_date??null,features:oh(t)}}function oh(e){let t=[],n=t=>Array.isArray(e[t])?e[t]:[];for(let e of n(`discounts`)){let n=e.type===`percentage`;t.push({type:`Discount`,label:e.label??null,summary:`${e.unit_amount??`?`}${n?`%`:` (Fixed)`}`})}for(let e of n(`taxes`)){let n=e.type===`avalara`;t.push({type:`Tax`,label:e.label??null,summary:n?`Avalara - ${e.code??`?`}`:`${e.unit_amount??`?`}%`})}for(let e of n(`free_units`))t.push({type:`Free Units`,label:e.label??null,summary:`${e.unit_amount??`?`} units`});for(let e of n(`commitments`)){let n=e.type?Fm(e.type):`Commitment`;t.push({type:`Commitment`,label:e.label??null,summary:`${n}: ${e.unit_amount??`?`}`})}for(let e of n(`grants`)){let n=e.trigger_event?Fm(e.trigger_event):``,r=e.expires_at?`, expires ${Fm(e.expires_at)}`:``,i=e.entitlement?.name?` → ${e.entitlement.name}`:``;t.push({type:`Grant`,label:e.label??null,summary:`${e.unit_amount??`?`} units on ${n}${r}${i}`})}for(let e of n(`consumptions`)){let n=e.entitlement?.name??`Entitlement`,r=e.trigger_event?Fm(e.trigger_event):``;t.push({type:`Consumption`,label:e.label??null,summary:`${n} (${Fm(e.type??``)}) on ${r}`})}for(let e of n(`service_fees`)){let n=e.type===`percentage`;t.push({type:`Service Fee`,label:e.label??null,summary:`${e.unit_amount??`?`}${n?`%`:` (Fixed)`}`})}for(let e of n(`payment_terms`)){let n=e.due_days==null?``:`Due in ${e.due_days} days`;t.push({type:`Payment Terms`,label:e.label??null,summary:n||`Custom`})}return t.length>0?t:null}function sh(e){let t=Q(e),n=t.credit_note??t.creditNote??t,r=Zm(n),i=n.customer,a=n.invoice;return{credit_note:{...r,line_items_url:n.line_items_url??null,credits_returned:Nh(n.credits_returned),custom_data:n.custom_data??null,customer_name:(i&&typeof i==`object`?i.name:null)??null,invoice_number:(a&&typeof a==`object`?a.invoice_number??a.name:null)??null}}}function ch(e,t){let n=Q(e),r=Ah(n,[`products`,`data`,`results`]),i=Mh(n,[`total`,`count`,`total_count`])??r.length,a=jh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.name__ilike||void 0;return{products:r.map(lh),total:i,cursor:{next:o,prev:s},scope:c}}function lh(e){return!e||typeof e!=`object`?{id:``,name:null,sku:null,description:null,product_type:null,is_active:null,created_at:null}:{id:String(e.id||e.product_id||``),name:e.name??e.product_name??null,sku:e.sku??null,description:e.description??null,product_type:e.product_type??e.type??null,is_active:typeof e.is_active==`boolean`?e.is_active:null,created_at:e.created_at??null}}function uh(e,t){let n=Q(e),r=Ah(n,[`plans`,`data`,`results`]),i=Mh(n,[`total`,`count`,`total_count`])??r.length,a=jh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.name__ilike||t.status)||void 0;return{plans:r.map(dh),total:i,cursor:{next:o,prev:s},scope:c}}function dh(e){return!e||typeof e!=`object`?{id:``,name:null,description:null,status:null,plan_version:null,created_at:null}:{id:String(e.id||e.plan_id||``),name:e.name??e.plan_name??null,description:e.description??null,status:e.status??e.state??null,plan_version:Nh(e.plan_version),created_at:e.created_at??null}}function fh(e,t){let n=Q(e),r=Ah(n,[`entries`,`journal_entries`,`data`,`results`]),i=Mh(n,[`total`,`count`,`total_count`])??r.length,a=jh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.search_query||void 0;return{entries:r.map(ph),total:i,cursor:{next:o,prev:s},scope:c,default_currency:`USD`}}function ph(e){if(!e||typeof e!=`object`)return{id:``,posted_at:null,event:null,description:null,status_type:null,currency:null,total_debit:null,total_credit:null,line_count:null,created_at:null};let t=Array.isArray(e.journal_lines)?e.journal_lines:[],n=0,r=0;for(let e of t)Number.isFinite(e?.debits)&&(n+=e.debits),Number.isFinite(e?.credits)&&(r+=e.credits);return{id:String(e.id||e.journal_entry_id||``),posted_at:e.posted_at??null,event:e.event??null,description:e.description??null,status_type:e.status_type??null,currency:e.currency??e.currency_code??null,total_debit:t.length?n:null,total_credit:t.length?r:null,line_count:t.length||null,created_at:e.created_at??null}}function mh(e,t){let n=Q(e),r=Ah(n,[`jobs`,`data`,`results`]),i=Mh(n,[`total`,`count`,`total_count`])??r.length,a=jh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.search||void 0,l={};for(let e of r){let t=e&&e.status||`unknown`;l[t]=(l[t]||0)+1}return{jobs:r.map(hh),total:i,cursor:{next:o,prev:s},scope:c,status_counts:l}}function hh(e){return!e||typeof e!=`object`?{id:``,name:null,description:null,job_type:null,resource:null,status:null,created_at:null}:{id:String(e.id||e.job_id||``),name:e.name??null,description:e.description??null,job_type:e.job_type??e.type??null,resource:e.resource??null,status:e.status??null,created_at:e.created_at??null}}function gh(e,t){let n=Q(e),r=Ah(n,[`contacts`,`data`,`results`]),i=Mh(n,[`total`,`count`,`total_count`])??r.length,a=jh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.customer_id||void 0;return{contacts:r.map(_h),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0}}function _h(e){if(!e||typeof e!=`object`)return{id:``,name:null,email:null,customer_id:null,send_invoice:null,send_contract:null};let t=[e.first_name??``,e.last_name??``].filter(Boolean).join(` `).trim(),n=e.customer,r=typeof n==`string`?n:(n&&typeof n==`object`?n.id:null)??e.customer_id??null;return{id:String(e.id||e.contact_id||``),name:e.name??(t||null),email:e.email??e.primary_email??null,customer_id:r??null,send_invoice:typeof e.send_invoice==`boolean`?e.send_invoice:null,send_contract:typeof e.send_contract==`boolean`?e.send_contract:null}}function vh(e,t){let n=Q(e),r=Ah(n,[`raw_metrics`,`rawmetrics`,`rawMetrics`,`data`,`results`]),i=Mh(n,[`total`,`count`,`total_count`])??r.length,a=jh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search||t.name__ilike)||void 0;return{raw_metrics:r.map(yh),total:i,cursor:{next:o,prev:s},scope:c}}function yh(e){return!e||typeof e!=`object`?{id:``,name:null,api_slug:null,usage_upload_enabled:null,created_at:null}:{id:String(e.id||e.raw_metric_id||``),name:e.name??null,api_slug:e.api_slug??null,usage_upload_enabled:typeof e.usage_upload_enabled==`boolean`?e.usage_upload_enabled:null,created_at:e.created_at??null}}function bh(e,t){let n=Q(e),r=Ah(n,[`aggregates`,`data`,`results`]),i=Mh(n,[`total`,`count`,`total_count`])??r.length,a=jh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.name__ilike||t.datasource)||void 0;return{aggregates:r.map(xh),total:i,cursor:{next:o,prev:s},scope:c}}function xh(e){return!e||typeof e!=`object`?{id:``,name:null,datasource:null,created_at:null}:{id:String(e.id||e.aggregate_id||``),name:e.name??null,datasource:e.datasource??e.data_source??e.raw_metric_name??null,created_at:e.created_at??null}}function Sh(e,t){let n=Ah(Q(e),[`addresses`,`data`,`results`]);return{customer_id:t&&t.customerId?String(t.customerId):void 0,addresses:n.map(Ch),total:n.length}}function Ch(e){return!e||typeof e!=`object`?{id:``,label:null,line1:null,line2:null,city:null,state:null,zip_code:null,country:null,is_primary:null}:{id:String(e.id||``),label:e.label??e.name??e.address_type??null,line1:e.line1??e.address_line_1??null,line2:e.line2??e.address_line_2??null,line3:e.line3??null,city:e.city??null,state:e.state??null,zip_code:e.zipCode??e.zip_code??e.postal_code??null,country:e.country??e.country_code??null,validation_status:e.validation_status??null,is_primary:typeof e.is_primary==`boolean`?e.is_primary:typeof e.primary==`boolean`?e.primary:null}}function wh(e,t){let n=Ah(Q(e),[`payment_methods`,`paymentMethods`,`data`,`results`]);return{customer_id:t&&t.customerId?String(t.customerId):void 0,payment_methods:n.map(Th),total:n.length}}function Th(e){if(!e||typeof e!=`object`)return{id:``,type:null,brand:null,last4:null,exp_month:null,exp_year:null,is_default:null,created_at:null};let t=e.card||e.details||{};return{id:String(e.id||``),type:e.type??e.payment_method_type??null,brand:t.brand??e.brand??null,last4:t.last4??e.last4??null,exp_month:Nh(t.exp_month??e.exp_month),exp_year:Nh(t.exp_year??e.exp_year),is_default:typeof e.is_default==`boolean`?e.is_default:typeof e.default==`boolean`?e.default:null,created_at:e.created_at??null,connector_name:e.connector_name??null,status:e.status??null}}function Eh(e,t){let n=Q(e),r=Ah(n,[`business_entities`,`businessEntities`,`entities`,`data`,`results`]),i=Mh(n,[`total`,`count`,`total_count`])??r.length,a=jh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null;return{entities:r.map(Dh),total:i,cursor:{next:o,prev:s}}}function Dh(e){return!e||typeof e!=`object`?{id:``,name:null,email:null,phone_number:null,country:null,is_default:null}:{id:String(e.id||e.business_entity_id||``),name:e.name??e.business_entity_name??null,email:e.email??null,phone_number:e.phone_number??null,country:(e.address&&e.address.country)??e.country??null,is_default:typeof e.is_default==`boolean`?e.is_default:null}}function Oh(e,t){let n=Q(e),r=Ah(n,[`entitlements`,`data`,`results`]),i=Mh(n,[`total`,`count`,`total_count`])??r.length,a=jh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search||t.name__ilike)||void 0;return{entitlements:r.map(kh),total:i,cursor:{next:o,prev:s},scope:c}}function kh(e){return!e||typeof e!=`object`?{id:``,name:null,entitlement_type:null,units:null,is_active:null,product_name:null,created_at:null}:{id:String(e.id||e.entitlement_id||``),name:e.name??null,entitlement_type:e.entitlement_type??null,units:e.units??null,is_active:typeof e.is_active==`boolean`?e.is_active:null,product_name:(e.product&&(e.product.name??e.product.product_name))??null,created_at:e.created_at??null}}function Ah(e,t){if(Array.isArray(e))return e;for(let n of t)if(e&&Array.isArray(e[n]))return e[n];return[]}function jh(e,t){for(let n of t)if(e&&e[n]&&typeof e[n]==`object`)return e[n];return null}function Mh(e,t){for(let n of t)if(e&&Number.isFinite(e[n]))return e[n];return null}function Nh(e){return Number.isFinite(e)?e:null}function Ph(e,t){let n=Q(e);return{html:n.html??(typeof n==`string`?n:``),invoice_id:t&&t.invoiceId?String(t.invoiceId):void 0}}function Fh(e){if(Im.has(e))return{mode:`text-only`};let t=Lm[e];return t?{mode:`ui`,...t}:{mode:`unmapped`}}const Ih=a(s(import.meta.url)),Lh=[o(Ih,`..`,`..`,`..`,`dist`,`ui`),o(Ih,`ui`)];function Rh(e){for(let t of Lh){let i=o(t,`${e}.html`);if(n(i))return r(i,`utf8`)}return`<!doctype html><html><body style="font-family:sans-serif;padding:16px;">UI bundle missing: ${e}.html. Run <code>pnpm run build:ui</code>.</body></html>`}function zh(){let e=new Set,t=t=>{if(t)try{e.add(new URL(t).origin)}catch{}};return t(process.env.ZENSKAR_MCP_PUBLIC_BASE_URL||process.env.MCP_PUBLIC_BASE_URL),t(process.env.ZENSKAR_API_BASE_URL),t(process.env.ZENSKAR_APP_BASE_URL),Array.from(e)}function Bh(){let e={prefersBorder:!0},t=zh();return t.length>0&&(e.csp={connectDomains:t,resourceDomains:t}),e}function Vh(e){for(let t of Rm){let n=zm(t);e.registerResource(`zenskar-app`,n,{},async()=>({contents:[{uri:n,mimeType:`text/html;profile=mcp-app`,text:Rh(t),_meta:{"openai/widgetPrefersBorder":!0,ui:Bh()}}]}))}}const Hh=[`claude-code`,`cline`,`roo-code`,`continue`,`codex`,`windsurf`,`zed`,`aider`,`copilot`,`gemini-cli`],Uh=[`claude-desktop`,`claude-ai`,`chatgpt`,`mcp-inspector`,`toon`,`cursor`];let Wh=null,Gh=null;function Kh(e){Wh=e?String(e).toLowerCase().trim():null}function qh(e){Gh=e}function Jh(){if(Wh==null&&Gh){let e=Gh();e&&Kh(e)}return Wh}function Yh(e){let t=(e??Wh??``).toLowerCase().trim();return t?Hh.some(e=>t.includes(e))?`coding-agent`:Uh.some(e=>t.includes(e))?`widget-host`:`default`:`default`}const Xh={comma:`,`,tab:` `,pipe:`|`}.comma;function Zh(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}function Qh(e){return e===`true`||e===`false`||e===`null`}function $h(e){if(e===null)return null;if(typeof e==`object`&&e&&`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();if(t!==e)return $h(t)}if(typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e==`bigint`)return e>=-(2**53-1)&&e<=2**53-1?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map($h);if(e instanceof Set)return Array.from(e).map($h);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),$h(t)]));if(ig(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&(t[n]=$h(e[n]));return t}return null}function eg(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function tg(e){return Array.isArray(e)}function ng(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rg(e){return Object.keys(e).length===0}function ig(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ag(e){return e.length===0||e.every(e=>eg(e))}function og(e){return e.length===0||e.every(e=>tg(e))}function sg(e){return e.length===0||e.every(e=>ng(e))}const cg=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,lg=/^0\d+$/;function ug(e){return/^[A-Z_][\w.]*$/i.test(e)}function dg(e){return/^[A-Z_]\w*$/i.test(e)}function fg(e,t=Xh){return!(!e||e!==e.trim()||Qh(e)||pg(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\n\r\t]/.test(e)||e.includes(t)||e.startsWith(`-`))}function pg(e){return cg.test(e)||lg.test(e)}function mg(e,t,n,r,i,a,o){if(r.keyFolding!==`safe`||!ng(t))return;let{segments:s,tail:c,leafValue:l}=hg(e,t,o??r.flattenDepth);if(s.length<2||!s.every(e=>dg(e)))return;let u=gg(s),d=a?`${a}.${u}`:u;if(!n.includes(u)&&!(i&&i.has(d)))return{foldedKey:u,remainder:c,leafValue:l,segmentCount:s.length}}function hg(e,t,n){let r=[e],i=t;for(;r.length<n&&ng(i);){let e=Object.keys(i);if(e.length!==1)break;let t=e[0],n=i[t];r.push(t),i=n}return!ng(i)||rg(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function gg(e){return e.join(`.`)}function _g(e,t){return e===null?`null`:typeof e==`boolean`||typeof e==`number`?String(e):vg(e,t)}function vg(e,t=Xh){return fg(e,t)?e:`"${Zh(e)}"`}function yg(e){return ug(e)?e:`"${Zh(e)}"`}function bg(e,t=Xh){return e.map(e=>_g(e,t)).join(t)}function xg(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;if(n!=null&&(a+=yg(n)),a+=`[${e}${i===Xh?``:i}]`,r){let e=r.map(e=>yg(e));a+=`{${e.join(i)}}`}return a+=`:`,a}function*Sg(e,t,n){if(eg(e)){let n=_g(e,t.delimiter);n!==``&&(yield n);return}tg(e)?yield*Tg(void 0,e,n,t):ng(e)&&(yield*Cg(e,n,t))}function*Cg(e,t,n,r,i,a){let o=Object.keys(e);t===0&&!r&&(r=new Set(o.filter(e=>e.includes(`.`))));let s=a??n.flattenDepth;for(let[a,c]of Object.entries(e))yield*wg(a,c,t,n,o,r,i,s)}function*wg(e,t,n,r,i,a,o,s){let c=o?`${o}.${e}`:e,l=s??r.flattenDepth;if(r.keyFolding===`safe`&&i){let s=mg(e,t,i,r,a,o,l);if(s){let{foldedKey:e,remainder:t,leafValue:i,segmentCount:c}=s,u=yg(e);if(t===void 0){if(eg(i)){yield Fg(n,`${u}: ${_g(i,r.delimiter)}`,r.indent);return}else if(tg(i)){yield*Tg(e,i,n,r);return}else if(ng(i)&&rg(i)){yield Fg(n,`${u}:`,r.indent);return}}if(ng(t)){yield Fg(n,`${u}:`,r.indent);let i=l-c,s=o?`${o}.${e}`:e;yield*Cg(t,n+1,r,a,s,i);return}}}let u=yg(e);eg(t)?yield Fg(n,`${u}: ${_g(t,r.delimiter)}`,r.indent):tg(t)?yield*Tg(e,t,n,r):ng(t)&&(yield Fg(n,`${u}:`,r.indent),rg(t)||(yield*Cg(t,n+1,r,a,c,l)))}function*Tg(e,t,n,r){if(t.length===0){yield Fg(n,xg(0,{key:e,delimiter:r.delimiter}),r.indent);return}if(ag(t)){yield Fg(n,Dg(t,r.delimiter,e),r.indent);return}if(og(t)&&t.every(e=>ag(e))){yield*Eg(e,t,n,r);return}if(sg(t)){let i=kg(t);i?yield*Og(e,t,i,n,r):yield*Mg(e,t,n,r);return}yield*Mg(e,t,n,r)}function*Eg(e,t,n,r){yield Fg(n,xg(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)if(ag(e)){let t=Dg(e,r.delimiter);yield Ig(n+1,t,r.indent)}}function Dg(e,t,n){let r=xg(e.length,{key:n,delimiter:t}),i=bg(e,t);return e.length===0?r:`${r} ${i}`}function*Og(e,t,n,r,i){yield Fg(r,xg(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*jg(t,n,r+1,i)}function kg(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&Ag(e,n))return n}function Ag(e,t){for(let n of e){if(Object.keys(n).length!==t.length)return!1;for(let e of t)if(!(e in n)||!eg(n[e]))return!1}return!0}function*jg(e,t,n,r){for(let i of e)yield Fg(n,bg(t.map(e=>i[e]),r.delimiter),r.indent)}function*Mg(e,t,n,r){yield Fg(n,xg(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)yield*Pg(e,n+1,r)}function*Ng(e,t,n){if(rg(e)){yield Fg(t,`-`,n.indent);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(tg(a)&&sg(a)){let e=kg(a);if(e){yield Ig(t,xg(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indent),yield*jg(a,e,t+2,n),o.length>0&&(yield*Cg(Object.fromEntries(o),t+1,n));return}}let s=yg(i);if(eg(a))yield Ig(t,`${s}: ${_g(a,n.delimiter)}`,n.indent);else if(tg(a))if(a.length===0)yield Ig(t,`${s}${xg(0,{delimiter:n.delimiter})}`,n.indent);else if(ag(a))yield Ig(t,`${s}${Dg(a,n.delimiter)}`,n.indent);else{yield Ig(t,`${s}${xg(a.length,{delimiter:n.delimiter})}`,n.indent);for(let e of a)yield*Pg(e,t+2,n)}else ng(a)&&(yield Ig(t,`${s}:`,n.indent),rg(a)||(yield*Cg(a,t+2,n)));o.length>0&&(yield*Cg(Object.fromEntries(o),t+1,n))}function*Pg(e,t,n){if(eg(e))yield Ig(t,_g(e,n.delimiter),n.indent);else if(tg(e))if(ag(e))yield Ig(t,Dg(e,n.delimiter),n.indent);else{yield Ig(t,xg(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*Pg(r,t+1,n)}else ng(e)&&(yield*Ng(e,t,n))}function Fg(e,t,n){return` `.repeat(n*e)+t}function Ig(e,t,n){return Fg(e,`- `+t,n)}function Lg(e,t){let n=t(``,e,[]);return Rg(n===void 0?e:$h(n),t,[])}function Rg(e,t,n){return ng(e)?zg(e,t,n):tg(e)?Bg(e,t,n):e}function zg(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=[...n,i],o=t(i,a,e);o!==void 0&&(r[i]=Rg($h(o),t,e))}return r}function Bg(e,t,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i],o=[...n,i],s=t(String(i),a,o);if(s===void 0)continue;let c=$h(s);r.push(Rg(c,t,o))}return r}function Vg(e,t){return Array.from(Hg(e,t)).join(`
79
+ `)}function Hg(e,t){let n=$h(e),r=Ug(t);return Sg(r.replacer?Lg(n,r.replacer):n,r,0)}function Ug(e){return{indent:e?.indent??2,delimiter:e?.delimiter??Xh,keyFolding:e?.keyFolding??`off`,flattenDepth:e?.flattenDepth??1/0,replacer:e?.replacer}}function Wg(e){return typeof e==`string`?e:Vg(e)}function Gg(){let e=process.env.ZENSKAR_MCP_UI_ENABLED;return e==null||e===``?!0:!/^(0|false|no|off)$/i.test(String(e).trim())}function Kg(){let e=process.env.ZENSKAR_MCP_UI_DISABLED_TOOLS;return e?new Set(String(e).split(`,`).map(e=>e.trim()).filter(Boolean)):new Set}const qg=process.env.ZENSKAR_MCP_UI_DEBUG===`true`||process.env.MCP_DEBUG===`true`;function Jg(...e){qg&&console.error(`[ui-wrap]`,...e)}function Yg(e,t,n,r){if(!Gg())return Jg(e,`skipped: ZENSKAR_MCP_UI_ENABLED explicitly disabled`),Zg(n);let i=Fh(e);if(i.mode!==`ui`)return Jg(e,`skipped: not in registry, mode=`,i.mode),Zg(n);if(Kg().has(e))return Jg(e,`skipped: in ZENSKAR_MCP_UI_DISABLED_TOOLS`),Zg(n);let a;try{a=i.toPayload(t,r)}catch(t){return Jg(e,`toPayload threw:`,t.message),Zg(n)}let o=Xg(a);if(o<(i.threshold??0))return Jg(e,`below threshold:`,o,`<`,i.threshold),Zg(n);let s=Yh(Jh());return Jg(e,`OK shape=`,i.shape,`items=`,o,`client=`,s),s===`coding-agent`?Zg(n):s===`widget-host`?{content:[{type:`text`,text:(o<=1&&i.shape.includes(`detail`)?`Full detail rendered in widget above — user already sees every field. Do not summarize or restate. Only respond if user asks a specific question. Reference data below for follow-ups.`:`Data rendered in table widget above. Use values below for follow-up questions — do not restate rows.`)+`
80
+ `+Wg(a)}],structuredContent:a}:Zg(n)}function Xg(e){if(!e||typeof e!=`object`)return 0;for(let t of[`customers`,`invoices`,`lines`,`payments`,`credit_notes`,`contracts`,`transactions`,`rows`,`items`,`data`,`addresses`,`payment_methods`,`products`,`plans`,`entries`,`jobs`,`contacts`,`raw_metrics`,`aggregates`,`entities`])if(Array.isArray(e[t]))return e[t].length;if(Number.isFinite(e.total))return e.total;for(let t of[`customer`,`invoice`,`contract`,`credit_note`])if(e[t]&&typeof e[t]==`object`)return 1;return+!!e.html}function Zg(e){return{content:[{type:`text`,text:e}]}}const Qg=s(import.meta.url),$g=i.dirname(Qg),e_={logUsage:async()=>{}},t_=(e,t)=>({valid:!0,adjustedArgs:t,warnings:[],errors:[]}),n_=()=>({message:`Limits validation unavailable`,severity:`info`,suggestions:[]}),$={debug:(e,t)=>{if(process.env.MCP_DEBUG===`true`){let n=new Date().toISOString();console.error(`[${n}] [MCP-DEBUG] ${e}`,t?JSON.stringify(t,null,2):``)}},info:(e,t)=>{let n=new Date().toISOString();console.error(`[${n}] [MCP-INFO] ${e}`,t?JSON.stringify(t,null,2):``)},error:(e,t)=>{let n=new Date().toISOString();console.error(`[${n}] [MCP-ERROR] ${e}`,t?JSON.stringify(t,null,2):``)},warn:(e,t)=>{let n=new Date().toISOString();console.error(`[${n}] [MCP-WARN] ${e}`,t?JSON.stringify(t,null,2):``)}},r_=i.join($g,`mcp-config.json`);let i_;try{i_=JSON.parse(t.readFileSync(r_,`utf8`))}catch(e){console.error(`Failed to load MCP config:`,e.message),console.error(`Please ensure mcp-config.json exists in the project root`),process.exit(1)}const a_=new mm({name:i_.server?.name||`zenskar-api-server`,version:`1.0.0`});qh(()=>{let e=a_.server.getClientVersion();return e&&e.name?e.name:null});const o_=new Pm;function s_(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t={...e};return typeof t.timestamp==`string`&&(t.timestamp=c_(t.timestamp)),t.data&&typeof t.data==`object`&&!Array.isArray(t.data)&&(t.data={...t.data},[`DateTime64`,`DateTime`,`DateTime32`].forEach(e=>{typeof t.data[e]==`string`&&(t.data[e]=c_(t.data[e]))})),t}function c_(e){return typeof e==`string`?e.replace(`T`,` `).replace(`t`,` `).replace(/Z$/i,``).trim():e}function l_(e){if(typeof e!=`string`)return e;let t=e.trim();if(!t)return e;switch(t.toLowerCase()){case`boolean`:return`Bool`;case`string`:return`String`;case`int`:case`int64`:return`Int64`;case`float`:case`float64`:case`double`:return`Float64`;case`date`:case`date32`:return`Date32`;case`datetime`:case`datetime64`:return`DateTime64`;case`uuid`:return`UUID`;default:return t}}function u_(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t={...e};if(t.customer_id&&=l_(t.customer_id),t.timestamp&&=l_(t.timestamp),t.data&&typeof t.data==`object`&&!Array.isArray(t.data)){let e={};Object.entries(t.data).forEach(([t,n])=>{e[t]=l_(n)}),t.data=e}return t}function d_(e){return e?Array.isArray(e)?e:Array.isArray(e.results)?e.results:e.api_response===void 0?[]:d_(e.api_response):[]}function f_(e){return!e||typeof e!=`string`?`Uncategorized`:e.trim()||`Uncategorized`}function p_(e){let t=Number(e);return Number.isFinite(t)?t/100:null}function m_(e,t){let n=f_(t);return e===`getBalanceSheet`&&n===`Liabilities`?`Liabilities & Equity`:n}function h_(e,t){return(e===`getBalanceSheet`?{Assets:1,Liabilities:2,Equity:3}:{Income:1,Revenue:1,"Cost of Goods Sold":2,Expense:3,Expenses:3,"Other Income":4,"Other Expense":5,"Other Expenses":5})[t]||999}function g_(e){return`${e?.interval_start||`unknown_start`}__${e?.interval_end||`unknown_end`}`}function __(e){return Object.values(e).sort((e,t)=>String(e.interval_start).localeCompare(String(t.interval_start)))}function v_(e,t,n){let r=new Map,i=new Map;t.forEach(t=>{let a=m_(e,t.account_category),o=g_(t),s=r.get(o)||{key:o,interval_start:t.interval_start||null,interval_end:t.interval_end||null};r.set(o,s),i.has(a)||i.set(a,{category:a,accounts:new Map,totals_by_period:{},total_balance:0,total_debits:0,total_credits:0});let c=i.get(a),l=t.account_id||`unknown_account`,u=n.get(l)||{};c.accounts.has(l)||c.accounts.set(l,{account_id:l,account_name:t.account_name||u.name||l,account_description:t.account_description||u.description||null,account_category:a,parent_path:t.account_parent_path||u.parent_path||null,balance_normality:t.balance_normality||u.balance_normality||null,periods:{},total_balance:0,total_debits:0,total_credits:0});let d=c.accounts.get(l);d.periods[o]={interval_start:t.interval_start||null,interval_end:t.interval_end||null,balance:t.balance??0,display_balance:p_(t.balance??0),debits:t.debits??0,display_debits:p_(t.debits??0),credits:t.credits??0,display_credits:p_(t.credits??0)},d.total_balance+=Number(t.balance||0),d.total_debits+=Number(t.debits||0),d.total_credits+=Number(t.credits||0);let f=c.totals_by_period[o]||{interval_start:t.interval_start||null,interval_end:t.interval_end||null,balance:0,debits:0,credits:0,display_balance:0,display_debits:0,display_credits:0};f.balance+=Number(t.balance||0),f.debits+=Number(t.debits||0),f.credits+=Number(t.credits||0),f.display_balance=p_(f.balance),f.display_debits=p_(f.debits),f.display_credits=p_(f.credits),c.totals_by_period[o]=f,c.total_balance+=Number(t.balance||0),c.total_debits+=Number(t.debits||0),c.total_credits+=Number(t.credits||0)});let a=Array.from(i.values()).sort((t,n)=>{let r=h_(e,t.category)-h_(e,n.category);return r===0?t.category.localeCompare(n.category):r}).map(e=>({category:e.category,accounts:Array.from(e.accounts.values()).sort((e,t)=>e.account_name.localeCompare(t.account_name)).map(e=>({...e,periods:__(e.periods)})),totals_by_period:__(e.totals_by_period),total_balance:e.total_balance,display_total_balance:p_(e.total_balance),total_debits:e.total_debits,display_total_debits:p_(e.total_debits),total_credits:e.total_credits,display_total_credits:p_(e.total_credits)}));return{report_type:e===`getBalanceSheet`?`balance_sheet`:`income_statement`,periods:Array.from(r.values()).sort((e,t)=>String(e.interval_start).localeCompare(String(t.interval_start))),sections:a}}function y_(e){if(!e)return``;let t=e.account_category||``;return t===`Liabilities`?`Liabilities & Equity`:t}function b_(e){let t=[...e].map(e=>({...e,account_category:y_(e)})).sort((e,t)=>{let n=y_(e).localeCompare(y_(t));return n===0?String(e.name||``).localeCompare(String(t.name||``)):n}),n=new Map;t.forEach(e=>{let t=y_(e)||`Uncategorized`;n.has(t)||n.set(t,[]),n.get(t).push(e)}),[`Assets`,`Liabilities & Equity`,`Equity`,`Income`,`Expenses`].forEach(e=>{n.has(e)||n.set(e,[])});let r=Array.from(n.entries()).sort((e,t)=>e[0].localeCompare(t[0])).map(([e,t])=>({id:e,name:e,description:e,account_category:e,is_parent:!0,parent_path:null,children:t.map(t=>({...t,parent_path:t.parent_path||e}))})),i=r.find(e=>e.name===`Liabilities & Equity`);return i&&(i.children.some(e=>e.name===`Equity`)||(i.children.push({id:`Equity`,name:`Equity`,description:`Equity`,account_category:`Liabilities & Equity`,balance_normality:`credit`,is_parent:!0,parent_path:`Liabilities & Equity`,custom_data:{default_account:!1},children:[]}),i.children.push({id:`Equity:Retained Earnings`,name:`Retained Earnings`,description:`Retained Earnings`,account_category:`Liabilities & Equity`,balance_normality:`credit`,is_parent:!1,parent_path:`Equity`,custom_data:{default_account:!1}}))),r}function x_(e){if(!e||!Array.isArray(e.results))return e;let t=e.results.reduce((e,t)=>{let n=t.status||`unknown`;return e[n]=(e[n]||0)+1,e},{});return{...e,summary:{total_count:e.total_count??e.results.length,returned_count:e.results.length,page_status_counts:t,has_more:!!e.next,note:e.next?`Showing ${e.results.length} jobs from the current page. Use the cursor to continue through the remaining jobs.`:`Showing ${e.results.length} jobs from the current page.`}}}function S_(e){if(!e||!Array.isArray(e.results))return e;let t=[...e.results].sort((e,t)=>{let n=f_(e.account_category),r=f_(t.account_category),i=n.localeCompare(r);return i===0?String(e.name||``).localeCompare(String(t.name||``)):i}),n=t.reduce((e,t)=>{let n=f_(t.account_category);return e[n]=e[n]||[],e[n].push(t),e},{});return{...e,results:t,grouped_view:n}}async function C_(e,t){let n=await fetch(e,{method:`GET`,headers:t}),r=await n.text();if(!n.ok)throw Error(`Supplemental fetch failed: ${n.status} ${n.statusText}\nResponse: ${r}`);try{return JSON.parse(r)}catch{throw Error(`Supplemental fetch returned non-JSON response: ${r}`)}}async function w_(e,t,n){let r=e.rawMetricId,i=await C_(`${n}/rawmetric/${encodeURIComponent(r)}`,t);if(!i?.api_slug)throw Error(`Unable to resolve api_slug for raw metric ${r}`);let a={...t,apiversion:`20240301`},o={limit:e.limit??20,offset:e.offset??0,order_by:e.order_by??[{column:`timestamp`,type:`DESC`}],aggregate_operation:e.aggregate_operation??null,customer_mapping:null,end_date_mapping:null,start_date_mapping:null,table_name:`raw_metric_${i.api_slug}`,visual_query:{groups:[{filters:Array.isArray(e.filters)?e.filters:[],logic:`AND`}],logic:`AND`}},s=await fetch(`${n}/aggregate/visualquery/preview`,{method:`POST`,headers:a,body:JSON.stringify(o)}),c=await s.text();if(!s.ok)throw Error(`API request failed: ${s.status} ${s.statusText}\nResponse: ${c}`);try{return JSON.parse(c)}catch{return c}}async function T_(e,t,n,r){if(!t||!Array.isArray(t.results))return t;try{let i=d_(await C_(`${r}/accounting_new/chart_of_accounts`,n)),a=new Map(i.filter(e=>e&&e.id).map(e=>[e.id,e])),o=t.results.map(t=>{let n=a.get(t.account_id)||{};return{...t,account_name:n.name||t.account_id||null,account_description:n.description||null,account_category:m_(e,n.account_category),account_parent_path:n.parent_path||null,balance_normality:n.balance_normality||null,display_balance:p_(t.balance??0),display_debits:p_(t.debits??0),display_credits:p_(t.credits??0)}}),s=v_(e,o,a);if(e===`getBalanceSheet`){let e=new URLSearchParams;n.apiversion&&e.set(`apiversion`,n.apiversion);let t=await C_(`${r}/accounting_new/income_statement/v2`,n),i=Array.isArray(t?.results)?t.results:[],a={};i.forEach(e=>{let t=g_(e),n=a[t]||{interval_start:e.interval_start||null,interval_end:e.interval_end||null,balance:0,debits:0,credits:0};n.balance+=Number(e.balance||0),n.debits+=Number(e.debits||0),n.credits+=Number(e.credits||0),a[t]=n});let o=__(Object.fromEntries(Object.entries(a).map(([e,t])=>[e,{...t,display_balance:p_(t.balance),display_debits:p_(t.debits),display_credits:p_(t.credits)}]))),c={account_id:`Equity:Retained Earnings`,account_name:`Retained Earnings (Derived)`,account_description:`Derived from the companion income statement for MCP presentation.`,account_category:`Liabilities & Equity`,parent_path:`Equity`,balance_normality:`credit`,periods:o,total_balance:o.reduce((e,t)=>e+Number(t.balance||0),0),display_total_balance:p_(o.reduce((e,t)=>e+Number(t.balance||0),0)),total_debits:o.reduce((e,t)=>e+Number(t.debits||0),0),display_total_debits:p_(o.reduce((e,t)=>e+Number(t.debits||0),0)),total_credits:o.reduce((e,t)=>e+Number(t.credits||0),0),display_total_credits:p_(o.reduce((e,t)=>e+Number(t.credits||0),0))},l=s.sections.find(e=>e.category===`Liabilities & Equity`);l||(l={category:`Liabilities & Equity`,accounts:[],totals_by_period:[],total_balance:0,display_total_balance:0,total_debits:0,display_total_debits:0,total_credits:0,display_total_credits:0},s.sections.push(l)),l.accounts.push(c)}return{...t,results:o,statement_view:s}}catch(n){return $.warn(`[${e}] Failed to enrich accounting report output; returning raw report`,{error:n.message}),t}}function E_(e){let t={};return e.forEach(e=>{let n;n=e.type===`integer`||e.type===`number`?R():e.type===`boolean`?$s():e.type===`object`?U(rc()):e.type===`array`?B(rc()):e.type===`datetime`?H([I(),R()]):I(),e.default!==void 0&&(n=n.default(e.default)),e.required||(n=n.optional()),e.description&&(n=n.describe(e.description)),t[e.name]=n}),t.__userContext=V({userId:I().optional(),authorization:I().optional(),organization:I().optional(),apiKey:I().optional(),headers:V({}).optional(),approval:V({approved:$s(),token:I().optional(),modifiedArguments:U(rc()).optional(),originalArguments:U(rc()).optional(),toolName:I().optional()}).optional()}).optional().describe(`Internal user context for multi-tenant authentication and approval workflow`),t}async function D_(e,t){let n=Date.now();if(e.name===`getCurrentDateTime`){let e=new Date;return{currentDate:e.toISOString().split(`T`)[0],currentDateTime:e.toISOString(),timestamp:e.getTime(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,humanReadable:e.toLocaleString()}}$.debug(`[${e.name}] Raw args received:`,{argKeys:Object.keys(t),argValues:JSON.stringify(t,null,2)});let r=t.__userContext,i={...t};delete i.__userContext,$.debug(`[${e.name}] User context received:`,r?{hasUserId:!!r.userId,hasAuthorization:!!r.authorization,hasOrganization:!!r.organization,authPrefix:r.authorization?r.authorization.substring(0,20)+`...`:`none`}:`NO USER CONTEXT`);let a=e.requestTemplate?.url||`/`,o=e.requestTemplate?.method||`GET`,s=a.startsWith(`http://`)||a.startsWith(`https://`);$.debug(`[${e.name}] Executing ${o} request with args:`,JSON.stringify(i,null,2)),r&&$.debug(`[${e.name}] Using user context:`,{hasApiKey:!!r.apiKey,hasOrganization:!!r.organization,userId:r.userId}),e.args&&e.args.forEach(e=>{e.position===`path`&&i[e.name]!==void 0&&(a=a.replace(`{${e.name}}`,encodeURIComponent(i[e.name])))});let c=new URLSearchParams;e.args&&e.args.forEach(e=>{e.position===`query`&&i[e.name]!==void 0&&i[e.name]!==null&&i[e.name]!==``&&(typeof i[e.name]==`boolean`?c.append(e.name,i[e.name].toString()):Array.isArray(i[e.name])?i[e.name].forEach(t=>{c.append(e.name,t)}):c.append(e.name,i[e.name]))}),Object.keys(i).forEach(t=>{if(!c.has(t)&&i[t]!==void 0&&i[t]!==null&&i[t]!==``){let n=e.args?.some(e=>e.position===`path`&&e.name===t),r=e.args?.some(e=>e.position===`body`&&e.name===t);!n&&!r&&(typeof i[t]==`boolean`?c.append(t,i[t].toString()):Array.isArray(i[t])?i[t].forEach(e=>{c.append(t,e)}):c.append(t,i[t]))}}),c.toString()&&(a+=`?`+c.toString());let l=null;if(o!==`GET`&&o!==`DELETE`&&e.args){let t=e=>{if(typeof e==`number`)return Number.isFinite(e)?Math.floor(e):e;if(typeof e==`string`){let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):e}return e},n={};if(e.args.forEach(r=>{if(r.position===`body`&&i[r.name]!==void 0){if(r.type===`datetime`){n[r.name]=t(i[r.name]);return}if(e.name===`ingestRawMetricEvent`&&r.name===`event`){let e=s_(i[r.name]);e&&typeof e==`object`&&!Array.isArray(e)?Object.entries(e).forEach(([e,t])=>{t!==void 0&&(n[e]=t)}):n[r.name]=e}else n[r.name]=i[r.name]}}),e.name===`createCustomer`||e.name===`updateCustomer`){let t=(t,r)=>{let i={[`${t}line1`]:`line1`,[`${t}line2`]:`line2`,[`${t}line3`]:`line3`,[`${t}city`]:`city`,[`${t}state`]:`state`,[`${t}zipCode`]:`zipCode`,[`${t}country`]:`country`,[`${t}country_code`]:`country_code`},a={},o=!1;Object.entries(i).forEach(([e,t])=>{n[e]!==void 0&&(a[t]=n[e],delete n[e],o=!0)}),o&&(n[r]=a,$.debug(`[${e.name}] Transformed flat ${t}* fields into ${r} object`))};t(`address_`,`address`),t(`ship_to_`,`ship_to_address`)}if(e.name===`createBusinessEntity`&&((t,r)=>{let i={[`${t}line1`]:`line1`,[`${t}line2`]:`line2`,[`${t}line3`]:`line3`,[`${t}city`]:`city`,[`${t}state`]:`state`,[`${t}zipCode`]:`zipCode`,[`${t}country`]:`country`},a={},o=!1;Object.entries(i).forEach(([e,t])=>{n[e]!==void 0&&(a[t]=n[e],delete n[e],o=!0)}),o&&(n[r]=a,$.debug(`[${e.name}] Transformed flat ${t}* fields into ${r} object`))})(`address_`,`address`),e.name===`getInvoicePreviewHtml`&&!i.orgId){let e=r?.organization||process.env.ZENSKAR_ORGANIZATION;e&&(i.orgId=e)}if(e.name===`extractContractFromRaw`&&!n.organization_id){let t=r?.organization||process.env.ZENSKAR_ORGANIZATION;t&&(n.organization_id=t,$.debug(`[${e.name}] Auto-populated organization_id: ${t}`))}e.name===`createRawMetric`&&(n.connector||=i.connector||`push_to_zenskar`,n.api_type||=i.api_type||`PUSH`,n.dataschema||={customer_id:`string`,timestamp:`timestamp`,data:{usage_amount:`decimal`,feature_id:`string`}},n.dataschema&&=u_(n.dataschema),n.column_order=[`timestamp`]),Object.keys(n).length>0?l=JSON.stringify(n):(o===`PATCH`||o===`POST`||o===`PUT`)&&(l=`{}`)}let u={"Content-Type":`application/json`,"User-Agent":`Zenskar-MCP-Server/1.0.0`,apiversion:`20230501`},d=r?.organization||process.env.ZENSKAR_ORGANIZATION,f=r?.authorization||r?.headers?.authorization||r?.headers?.Authorization||process.env.ZENSKAR_AUTH_TOKEN,p=r?.apiKey||r?.headers?.[`x-api-key`]||process.env.ZENSKAR_API_KEY||process.env.ZENSKAR_AUTH_TOKEN;if(d)u.organisation=d;else throw $.error(`[${e.name}] SECURITY ERROR: No organization ID provided`),Error(`Organization ID is required for API access. Set ZENSKAR_ORGANIZATION env var or provide in user context.`);if(f&&f.startsWith(`eyJ`))u.Authorization=f.startsWith(`Bearer `)?f:`Bearer ${f}`;else if(p)u[`x-api-key`]=p;else throw $.error(`[${e.name}] SECURITY ERROR: No authorization provided`),Error(`Authorization is required. Set ZENSKAR_AUTH_TOKEN (JWT) or ZENSKAR_API_KEY env var.`);if(r?.headers){let e=new Set(Object.keys(u).map(e=>e.toLowerCase())),t=new Set([`__proto__`,`prototype`,`constructor`]);Object.keys(r.headers).forEach(n=>{t.has(n)||Object.prototype.hasOwnProperty.call(r.headers,n)&&r.headers[n]&&!e.has(n.toLowerCase())&&(u[n]=r.headers[n])})}$.debug(`[${e.name}] Using headers:`,{hasOrganization:!!u.organisation,hasAuthorization:!!u.Authorization,hasApiKey:!!u[`x-api-key`],source:r?.organization?`userContext`:`env`}),e.requestTemplate?.headers&&(Array.isArray(e.requestTemplate.headers)?e.requestTemplate.headers.forEach(e=>{u[e.key]=e.value}):Object.keys(e.requestTemplate.headers).forEach(t=>{u[t]=e.requestTemplate.headers[t]}));let m;if(s)m=a,$.debug(`[${e.name}] Using absolute URL: ${m}`);else{let t=process.env.ZENSKAR_API_BASE_URL||`https://api.zenskar.com`;m=t+a,$.debug(`[${e.name}] Using relative URL with base: ${t} + ${a} = ${m}`)}$.debug(`[${e.name}] Making ${o} request to: ${m}`),$.info(`[${e.name}] MULTI-TENANT SECURITY CHECK - Headers being sent:`,{organization:u.organisation||`MISSING`,hasAuth:!!u.Authorization,authPrefix:u.Authorization?u.Authorization.substring(0,30)+`...`:`NONE`,allHeaders:JSON.stringify(u,null,2)});try{if(e.name===`getRawMetricLogs`){let t=await w_(i,u,process.env.ZENSKAR_API_BASE_URL||`https://api.zenskar.com`);return $.debug(`[${e.name}] Successfully processed frontend-style usage-event logs`),t}let t=await fetch(m,{method:o,headers:u,body:l}),r=await t.text(),a=Date.now()-n;if($.info(`[${e.name}] Response received in ${a}ms - Status: ${t.status}, Size: ${r.length} chars`),$.info(`[${e.name}] Raw response body:`,r),!t.ok){$.error(`[${e.name}] API Error Response:`,r);let n=`API request failed: ${t.status} ${t.statusText}\nResponse: ${r}`;throw Error(n)}let s;try{s=JSON.parse(r)}catch{$.debug(`[${e.name}] Failed to parse JSON response, returning as text`),s=r}if(e.name===`getInvoicePreviewHtml`)if(typeof s==`string`)try{let e=Buffer.from(s,`base64`).toString(`utf8`);s=e.includes(`<`)?{html:e}:{html:s}}catch{s={html:s}}else s={html:``};if(e.name===`getBalanceSheet`||e.name===`getIncomeStatement`){let t=process.env.ZENSKAR_API_BASE_URL||`https://api.zenskar.com`;s=await T_(e.name,s,u,t)}return e.name===`listJobs`&&(s=x_(s)),e.name===`listAccounts`&&(s=S_(s)),e.name===`getChartOfAccounts`&&Array.isArray(s)&&(s={raw_accounts:s,chart_view:b_(s)}),e.responseTemplate?.prependBody&&(s={template_info:e.responseTemplate.prependBody,api_response:s}),$.debug(`[${e.name}] Successfully processed response`),s}catch(t){throw $.error(`[${e.name}] Network error:`,t),Error(`Network error: ${t.message}`)}}const O_=300*1e3,k_=process.env.APPROVAL_HMAC_SECRET,A_=!!k_,j_=new Map,M_=new Map;function N_(e){if(e==null)return e;if(typeof structuredClone==`function`)try{return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}function P_(e){let t=e?N_(e):{};return delete t.__userContext,t}function F_(t){return e.createHmac(`sha256`,k_).update(t).digest(`base64url`)}function I_(t,n){let r=Date.now(),i=r+O_,a=P_(n);if(A_){let n={toolName:t,args:a,issuedAt:r,expiresAt:i,nonce:e.randomBytes(12).toString(`base64url`)},o=Buffer.from(JSON.stringify(n),`utf8`).toString(`base64url`);return`v1.${o}.${F_(o)}`}let o=Mm();return j_.set(o,{toolName:t,issuedAt:r,expiresAt:i,args:a}),o}function L_(t,n){if(!t||typeof t!=`string`)return null;if(A_){let r=t.split(`.`);if(r.length!==3)return null;let[i,a,o]=r;if(i!==`v1`)return null;let s=F_(a),c=Buffer.from(o,`base64url`),l=Buffer.from(s,`base64url`);if(c.length!==l.length||!e.timingSafeEqual(c,l))return null;let u;try{u=JSON.parse(Buffer.from(a,`base64url`).toString(`utf8`))}catch{return null}return u.toolName!==n||typeof u.expiresAt!=`number`||u.expiresAt<Date.now()||M_.has(t)?null:(M_.set(t,u.expiresAt),u)}let r=j_.get(t);return!r||(j_.delete(t),r.toolName!==n)||r.expiresAt<Date.now()?null:r}setInterval(()=>{let e=Date.now();for(let[t,n]of j_)n.expiresAt<e&&j_.delete(t);for(let[t,n]of M_)n<e&&M_.delete(t)},6e4).unref();function R_(e,t){return(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0)(e.modifiedArguments)?{args:e.modifiedArguments,source:`modifiedArguments`}:{args:t.args,source:`tokenSnapshot`}}function z_(e,t){let n=e.__userContext;Object.keys(e).forEach(t=>{t!==`__userContext`&&delete e[t]}),Object.assign(e,t),e.__userContext=n}function B_(e,t){if(!e.needsApproval)return!1;let n=t.__userContext,r=n&&n.approval;if(r&&r.approved===!0){let n=L_(r.token,e.name);if(n){let{args:i,source:a}=R_(r,n);return $.info(`[${e.name}] Approval token verified; arg source=${a}`),z_(t,i),$.info(`[${e.name}] Restored arguments for approved execution:`,Object.keys(i)),!1}$.warn(`[${e.name}] Approval received without valid token (got: ${r.token?`expired/mismatched`:`missing`}); requiring re-approval`)}return typeof e.needsApproval==`function`?e.needsApproval(t):e.needsApproval===!0}function V_(e,t){t.__userContext;let n={...t};delete n.__userContext;let r=I_(e.name,t);return{type:`approval_required`,toolName:e.name,toolDescription:e.description,arguments:n,approvalToken:r,approvalTokenExpiresInSeconds:Math.floor(O_/1e3),approvalConfig:e.approvalConfig||{title:`Approve ${e.name}`,description:`This action requires your approval: ${e.description}`,warningText:`Please review the parameters carefully before proceeding.`,confirmText:`Approve`,cancelText:`Cancel`},fields:(e.args||[]).map(t=>({name:t.name,label:t.description||t.name,type:U_(t.type),required:t.required||!1,value:n[t.name],sensitive:e.approvalConfig?.sensitiveFields?.includes(t.name)||!1}))}}function H_(e,t){let n=[];if(e===`createProductPricing`){let e=t.pricing_data;!e||typeof e!=`object`?n.push(`'pricing_data' is required and must be an object containing 'pricing_type' and 'currency'.`):(e.pricing_type||n.push(`'pricing_data.pricing_type' is required (e.g. 'per_unit', 'flat_fee', 'tiered', 'volume', 'percent', 'package').`),e.currency||n.push(`'pricing_data.currency' is required (ISO 4217, e.g. 'USD').`));let r=t.quantity;!r||typeof r!=`object`?n.push(`'quantity' is required and must be an object: {type:'fixed'|'metered', quantity?, unit?, aggregate_id?}. Without it the UI shows 0 for billing_metric.`):(r.type!==`fixed`&&r.type!==`metered`&&n.push(`'quantity.type' must be exactly 'fixed' or 'metered'.`),r.type===`fixed`&&(r.quantity==null||!r.unit)&&n.push(`'quantity.type'='fixed' requires both 'quantity' (number) and 'unit' (label string).`),r.type===`metered`&&!r.aggregate_id&&n.push(`'quantity.type'='metered' requires 'aggregate_id' (UUID of the billable metric).`));let i=t.billing_period;!i||typeof i!=`object`?n.push(`'billing_period' is required and must be an object: {cadence:'P1M'|'P3M'|'P1Y'|..., offset:'P0D'|...}. Without it the UI renders 'Undefined- Every Undefined Undefined'.`):(i.cadence||n.push(`'billing_period.cadence' is required (ISO-8601 duration: 'P1M'=monthly, 'P3M'=quarterly, 'P1Y'=yearly).`),i.offset||n.push(`'billing_period.offset' is required (ISO-8601 duration, 'P0D' for no offset).`))}if(e===`createPlan`){(!t.schedule||typeof t.schedule!=`object`||!t.schedule.duration)&&n.push(`'schedule' is required and must include 'duration' (ISO-8601, e.g. 'P1Y').`),t.status||n.push(`'status' is required: 'draft' | 'active' | 'archived'.`);let e=t.phases;!Array.isArray(e)||e.length===0?n.push(`'phases' must be a non-empty array. A plan with no phases is unusable in PlansV2 — include at least one phase with name, schedule, order, and either features or pricings.`):e.forEach((e,t)=>{if(!e||typeof e!=`object`){n.push(`'phases[${t}]' must be an object.`);return}e.name||n.push(`'phases[${t}].name' is required.`),(!e.schedule||!e.schedule.duration)&&n.push(`'phases[${t}].schedule.duration' is required (ISO-8601).`),typeof e.order!=`number`&&n.push(`'phases[${t}].order' is required (integer, 0-indexed).`),!e.features&&(!Array.isArray(e.pricings)||e.pricings.length===0)&&n.push(`'phases[${t}]' has neither 'features' nor non-empty 'pricings' — phase will be empty in the UI.`)})}if(e===`generateInvoice`){let e=e=>{if(typeof e==`number`)return Number.isInteger(e)?e:null;if(typeof e==`string`){let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):null}return null},r=e(t.from_date),i=e(t.to_date);r===null&&n.push(`'from_date' must be either an integer UNIX timestamp (seconds) or an ISO-8601 datetime string. Copy from getContractBillingCycles.start_date.`),i===null&&n.push(`'to_date' must be either an integer UNIX timestamp (seconds) or an ISO-8601 datetime string. Copy from getContractBillingCycles.end_date.`),r!==null&&i!==null&&i<=r&&n.push(`'to_date' must be strictly greater than 'from_date'.`),e(t.bill_for_date)===null&&n.push(`'bill_for_date' is REQUIRED (UNIX seconds or ISO-8601 string). Without it the API returns a $0 invoice. Copy from getContractBillingCycles.bill_for_date — do NOT compute.`),(!Number.isInteger(t.billing_cycle_start_day)||t.billing_cycle_start_day<1||t.billing_cycle_start_day>31)&&n.push(`'billing_cycle_start_day' is REQUIRED and must be an integer 1-31. Copy from getContractBillingCycles.billing_cycle_start_day.`)}return e===`pauseContract`&&(t.start_date||n.push(`'start_date' is required (ISO 8601).`),t.unpause_extension_policy||n.push(`'unpause_extension_policy' is required: 'extend' or 'overlap'.`)),{valid:n.length===0,errors:n}}function U_(e){switch(e){case`string`:return`text`;case`integer`:case`number`:return`number`;case`boolean`:return`checkbox`;default:return`text`}}Vh(a_),i_.tools&&i_.tools.length>0&&i_.tools.forEach(e=>{$.info(`Registering tool: ${e.name}`);let t=E_(e.args||[]),n=Fh(e.name),r=n.mode===`ui`?(()=>{let e=zm(n.shape);return{"openai/outputTemplate":e,"ui/resourceUri":e,ui:{resourceUri:e}}})():void 0;a_.registerTool(e.name,{title:e.name,description:e.description,inputSchema:t,...r?{_meta:r}:{}},async t=>{let n=Date.now(),r=`success`,i=null,a=0,o=0,s=null,c=null;try{$.debug(`[${e.name}] Tool execution started`),$.info(`[${e.name}] Raw args received:`,{argKeys:Object.keys(t),hasUserContextInArgs:!!t.__userContext,userContextInArgs:t.__userContext,approvedInArgs:t.__userContext?.approved});let l=H_(e.name,t);if(!l.valid){$.error(`[${e.name}] Tool execution blocked due to invalid arguments (pre-approval):`,l.errors),r=`blocked`,i=`invalid_args: ${l.errors.join(`; `)}`;let t={type:`invalid_arguments`,toolName:e.name,errors:l.errors};return{content:[{type:`text`,text:JSON.stringify(t,null,2)},{type:`text`,text:`ACTION_NOT_EXECUTED — INVALID_ARGUMENTS\n\nTool '${e.name}' was NOT executed because the supplied arguments are invalid or incomplete:\n\n`+l.errors.map((e,t)=>`${t+1}. ${e}`).join(`
79
81
  `)+`
80
82
 
81
- Fix the arguments and call again. Do NOT report success to the user.`}],isError:!0}}let u=Fg(e,t),d=t.__userContext;if($.info(`[${e.name}] Approval check:`,{needsApproval:u,hasUserContext:!!d,userContextKeys:d?Object.keys(d):[],hasApprovalBlock:!!(d&&d.approval),hasToken:!!(d&&d.approval&&d.approval.token)}),u){$.info(`[${e.name}] Tool requires approval, generating approval request`);let n=Ig(e,t);return{content:[{type:`text`,text:JSON.stringify(n,null,2)},{type:`text`,text:`ACTION_NOT_EXECUTED — APPROVAL_REQUIRED\n\nTool '${e.name}' was NOT executed. The host must render an approval dialog from the JSON payload above and re-invoke this tool with __userContext.approval = {approved: true, token: '<approvalToken from payload>'} to actually perform the action. The token is single-use and expires in ${Math.floor(Cg/1e3)}s. Do NOT fabricate the token. Do NOT report success to the user; surface the dialog instead.`}],isApprovalRequired:!0,approvalRequest:n}}let f=Lg(e.name,t);if(!f.valid)return $.error(`[${e.name}] Approved arguments failed validation:`,f.errors),r=`blocked`,i=`invalid_args_post_approval: ${f.errors.join(`; `)}`,{content:[{type:`text`,text:JSON.stringify({type:`invalid_arguments`,toolName:e.name,errors:f.errors},null,2)},{type:`text`,text:`ACTION_NOT_EXECUTED — INVALID_ARGUMENTS
83
+ Fix the arguments and call again. Do NOT report success to the user.`}],isError:!0}}let u=B_(e,t),d=t.__userContext;if($.info(`[${e.name}] Approval check:`,{needsApproval:u,hasUserContext:!!d,userContextKeys:d?Object.keys(d):[],hasApprovalBlock:!!(d&&d.approval),hasToken:!!(d&&d.approval&&d.approval.token)}),u){$.info(`[${e.name}] Tool requires approval, generating approval request`);let n=V_(e,t);return{content:[{type:`text`,text:JSON.stringify(n,null,2)},{type:`text`,text:`ACTION_NOT_EXECUTED — APPROVAL_REQUIRED\n\nTool '${e.name}' was NOT executed. The host must render an approval dialog from the JSON payload above and re-invoke this tool with __userContext.approval = {approved: true, token: '<approvalToken from payload>'} to actually perform the action. The token is single-use and expires in ${Math.floor(O_/1e3)}s. Do NOT fabricate the token. Do NOT report success to the user; surface the dialog instead.`}],isApprovalRequired:!0,approvalRequest:n}}let f=H_(e.name,t);if(!f.valid)return $.error(`[${e.name}] Approved arguments failed validation:`,f.errors),r=`blocked`,i=`invalid_args_post_approval: ${f.errors.join(`; `)}`,{content:[{type:`text`,text:JSON.stringify({type:`invalid_arguments`,toolName:e.name,errors:f.errors},null,2)},{type:`text`,text:`ACTION_NOT_EXECUTED — INVALID_ARGUMENTS
82
84
 
83
85
  Approved arguments failed validation. The user-edited values from the approval dialog do not satisfy the tool schema:
84
86
 
85
87
  `+f.errors.map((e,t)=>`${t+1}. ${e}`).join(`
86
88
  `)+`
87
89
 
88
- Re-issue the call with corrected arguments; a new approval gate will be required.`}],isError:!0};let p=d?.userId||`unknown`,m=d?.chatId||null,h=JSON.stringify(t);a=Math.ceil(h.length/4);let g=Xh(e.name,t);if(!g.valid){e.name,$.error(`[${e.name}] Tool execution blocked due to limits:`,g.errors),r=`blocked`,i=g.errors.join(`; `),o=200;try{await Yh.logUsage({userId:p,chatId:m,tool:e.name,requestTokens:a,responseTokens:o,totalTokens:a+o,status:r,reason:i,limitRequested:t.limit,limitApplied:null})}catch(t){$.error(`[${e.name}] Failed to log token usage:`,t)}return{content:[{type:`text`,text:`I'm sorry, but this request is too large to process efficiently. To get better results, please try:
90
+ Re-issue the call with corrected arguments; a new approval gate will be required.`}],isError:!0};let p=d?.userId||`unknown`,m=d?.chatId||null,h=JSON.stringify(t);a=Math.ceil(h.length/4);let g=t_(e.name,t);if(!g.valid){e.name,$.error(`[${e.name}] Tool execution blocked due to limits:`,g.errors),r=`blocked`,i=g.errors.join(`; `),o=200;try{await e_.logUsage({userId:p,chatId:m,tool:e.name,requestTokens:a,responseTokens:o,totalTokens:a+o,status:r,reason:i,limitRequested:t.limit,limitApplied:null})}catch(t){$.error(`[${e.name}] Failed to log token usage:`,t)}return{content:[{type:`text`,text:`I'm sorry, but this request is too large to process efficiently. To get better results, please try:
89
91
 
90
92
  • Using smaller numbers when asking for lists (try 10-20 items instead of larger amounts)
91
93
  • Being more specific with your search criteria
92
94
  • Breaking your request into smaller parts
93
95
 
94
- For example, instead of asking for all customers, try asking for "customers created this month" or "customers from a specific region."`}],isError:!0}}let _=g.adjustedArgs;t.limit&&_.limit&&t.limit!==_.limit&&(s=t.limit,c=_.limit);let v=Zh(e.name,_);$.info(`[${e.name}] Token usage assessment:`,{estimatedTokens:v.message,severity:v.severity,suggestions:v.suggestions,originalArgs:JSON.stringify(t),adjustedArgs:JSON.stringify(_)});let ee=await Sg(e,_),y=tg.processResponse(ee,e.name),b=Date.now()-n;$.info(`[${e.name}] Tool execution completed in ${b}ms`);let x=typeof y==`string`?y:JSON.stringify(y,null,2);(g.warnings.length>0||v.severity===`warning`)&&(r=`truncated`,i=`Response optimized due to size limits`,x+=`
96
+ For example, instead of asking for all customers, try asking for "customers created this month" or "customers from a specific region."`}],isError:!0}}let _=g.adjustedArgs;t.limit&&_.limit&&t.limit!==_.limit&&(s=t.limit,c=_.limit);let v=n_(e.name,_);$.info(`[${e.name}] Token usage assessment:`,{estimatedTokens:v.message,severity:v.severity,suggestions:v.suggestions,originalArgs:JSON.stringify(t),adjustedArgs:JSON.stringify(_)});let y=await D_(e,_),b=o_.processResponse(y,e.name),x=Date.now()-n;$.info(`[${e.name}] Tool execution completed in ${x}ms`);let S=typeof b==`string`?b:JSON.stringify(b,null,2);(g.warnings.length>0||v.severity===`warning`)&&(r=`truncated`,i=`Response optimized due to size limits`,S+=`
95
97
 
96
98
  ---
97
99
  **📋 Response Summary:**
@@ -101,8 +103,8 @@ Your request returned a large amount of data, so I've shown you a summary with t
101
103
  • Data from a particular time period
102
104
  • Filtered results based on status or category
103
105
 
104
- This helps ensure faster and more focused results.`),o=Math.ceil(x.length/4);try{await Yh.logUsage({userId:p,chatId:m,tool:e.name,requestTokens:a,responseTokens:o,totalTokens:a+o,status:r,reason:i,limitRequested:s,limitApplied:c})}catch(t){$.error(`[${e.name}] Failed to log token usage:`,t)}return Wh(e.name,ee,x,_)}catch(r){let i=Date.now()-n;$.error(`[${e.name}] Tool execution failed after ${i}ms:`,r);let l=t.__userContext,u=l?.userId||`unknown`,d=l?.chatId||null,f=`Error executing ${e.name}: ${r.message}\n\nThis might be due to:\n- Invalid parameters\n- API rate limiting\n- Network connectivity issues\n- Authentication problems\n- Token usage limits exceeded\n\nPlease check the parameters and try again with smaller limits if needed.`;o=Math.ceil(f.length/4);try{await Yh.logUsage({userId:u,chatId:d,tool:e.name,requestTokens:a,responseTokens:o,totalTokens:a+o,status:`blocked`,reason:`Execution failed: ${r.message}`,limitRequested:s,limitApplied:c})}catch(t){$.error(`[${e.name}] Failed to log token usage:`,t)}return{content:[{type:`text`,text:f}],isError:!0}}})});async function zg(){let e=new Dm;await eg.connect(e),console.error(`Zenskar Intelligent MCP Server running on stdio`),console.error(`Loaded ${$h.tools?.length||0} tools from config`),console.error(`Response optimization: Advanced processor with config-driven optimizations enabled`),$h.tools?.length>0&&(console.error(`
105
- Available tools:`),$h.tools.forEach(e=>{console.error(` • ${e.name}: ${e.description}`)})),console.error(`
106
+ This helps ensure faster and more focused results.`),o=Math.ceil(S.length/4);try{await e_.logUsage({userId:p,chatId:m,tool:e.name,requestTokens:a,responseTokens:o,totalTokens:a+o,status:r,reason:i,limitRequested:s,limitApplied:c})}catch(t){$.error(`[${e.name}] Failed to log token usage:`,t)}return Yg(e.name,y,S,_)}catch(r){let i=Date.now()-n;$.error(`[${e.name}] Tool execution failed after ${i}ms:`,r);let l=t.__userContext,u=l?.userId||`unknown`,d=l?.chatId||null,f=`Error executing ${e.name}: ${r.message}\n\nThis might be due to:\n- Invalid parameters\n- API rate limiting\n- Network connectivity issues\n- Authentication problems\n- Token usage limits exceeded\n\nPlease check the parameters and try again with smaller limits if needed.`;o=Math.ceil(f.length/4);try{await e_.logUsage({userId:u,chatId:d,tool:e.name,requestTokens:a,responseTokens:o,totalTokens:a+o,status:`blocked`,reason:`Execution failed: ${r.message}`,limitRequested:s,limitApplied:c})}catch(t){$.error(`[${e.name}] Failed to log token usage:`,t)}return{content:[{type:`text`,text:f}],isError:!0}}})});async function W_(){let e=new Dm;await a_.connect(e),console.error(`Zenskar Intelligent MCP Server running on stdio`),console.error(`Loaded ${i_.tools?.length||0} tools from config`),console.error(`Response optimization: Advanced processor with config-driven optimizations enabled`),i_.tools?.length>0&&(console.error(`
107
+ Available tools:`),i_.tools.forEach(e=>{console.error(` • ${e.name}: ${e.description}`)})),console.error(`
106
108
  Server ready to handle requests`)}process.on(`SIGINT`,()=>{console.error(`
107
109
  Received SIGINT, shutting down gracefully...`),process.exit(0)}),process.on(`SIGTERM`,()=>{console.error(`
108
- Received SIGTERM, shutting down gracefully...`),process.exit(0)}),zg().catch(e=>{console.error(`Server failed to start:`,e),process.exit(1)});export{};
110
+ Received SIGTERM, shutting down gracefully...`),process.exit(0)}),W_().catch(e=>{console.error(`Server failed to start:`,e),process.exit(1)});export{};