@aicloud360/360-aidrive 0.8.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +101 -0
- package/README.md.bak +172 -0
- package/build/cli.js +2 -0
- package/build/index.js +2 -0
- package/package.json +118 -0
- package/tools/auto-backup-monitor/README.md +208 -0
- package/tools/auto-backup-monitor/server.mjs +866 -0
package/build/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import e from"dotenv";import t from"fs";import r from"path";import{fileURLToPath as n,URL as i}from"url";import a from"node:process";import s from"pino";import o from"crypto";import{promises as c}from"dns";import{homedir as u}from"os";import{spawn as l}from"child_process";import d from"fs/promises";import f from"express";import h from"iconv-lite";import{randomUUID as p}from"node:crypto";var m,v;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(m||(m={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(v||(v={}));const y=m.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),g=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:null===e?y.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?y.promise:"undefined"!=typeof Map&&e instanceof Map?y.map:"undefined"!=typeof Set&&e instanceof Set?y.set:"undefined"!=typeof Date&&e instanceof Date?y.date:y.object;default:return y.unknown}},w=m.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"]);class b 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]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={i:[]},n=e=>{for(const i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(n);else if("invalid_return_type"===i.code)n(i.returnTypeError);else if("invalid_arguments"===i.code)n(i.argumentsError);else if(0===i.path.length)r.i.push(t(i));else{let e=r,n=0;for(;n<i.path.length;){const r=i.path[n];n===i.path.length-1?(e[r]=e[r]||{i:[]},e[r].i.push(t(i))):e[r]=e[r]||{i:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof b))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,m.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const n of this.issues)if(n.path.length>0){const r=n.path[0];t[r]=t[r]||[],t[r].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}b.create=e=>new b(e);const E=(e,t)=>{let r;switch(e.code){case w.invalid_type:r=e.received===y.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case w.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,m.jsonStringifyReplacer)}`;break;case w.unrecognized_keys:r=`Unrecognized key(s) in object: ${m.joinValues(e.keys,", ")}`;break;case w.invalid_union:r="Invalid input";break;case w.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${m.joinValues(e.options)}`;break;case w.invalid_enum_value:r=`Invalid enum value. Expected ${m.joinValues(e.options)}, received '${e.received}'`;break;case w.invalid_arguments:r="Invalid function arguments";break;case w.invalid_return_type:r="Invalid function return type";break;case w.invalid_date:r="Invalid date";break;case w.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:m.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case w.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`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 w.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case w.custom:r="Invalid input";break;case w.invalid_intersection_types:r="Intersection results could not be merged";break;case w.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case w.not_finite:r="Number must be finite";break;default:r=t.defaultError,m.assertNever(e)}return{message:r}};let x=E;function $(e,t){const r=(e=>{const{data:t,path:r,errorMaps:n,issueData:i}=e,a=[...r,...i.path||[]],s={...i,path:a};if(void 0!==i.message)return{...i,path:a,message:i.message};let o="";const c=n.filter(e=>!!e).slice().reverse();for(const e of c)o=e(s,{data:t,defaultError:o}).message;return{...i,path:a,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,x,x===E?void 0:E].filter(e=>!!e)});e.common.issues.push(r)}class P{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return _;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,n=await e.value;r.push({key:t,value:n})}return P.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:i}=n;if("aborted"===t.status)return _;if("aborted"===i.status)return _;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===t.value||void 0===i.value&&!n.alwaysSet||(r[t.value]=i.value)}return{status:e.value,value:r}}}const _=Object.freeze({status:"aborted"}),S=e=>({status:"dirty",value:e}),F=e=>({status:"valid",value:e}),k=e=>"aborted"===e.status,A=e=>"dirty"===e.status,j=e=>"valid"===e.status,O=e=>"undefined"!=typeof Promise&&e instanceof Promise;var I;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(I||(I={}));class N{constructor(e,t,r,n){this.o=[],this.parent=e,this.data=t,this.u=r,this.l=n}get path(){return this.o.length||(Array.isArray(this.l)?this.o.push(...this.u,...this.l):this.o.push(...this.u,this.l)),this.o}}const D=(e,t)=>{if(j(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this.h)return this.h;const t=new b(e.common.issues);return this.h=t,this.h}}};function T(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:i};return{errorMap:(t,i)=>{const{message:a}=e;return"invalid_enum_value"===t.code?{message:a??i.defaultError}:void 0===i.data?{message:a??n??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:a??r??i.defaultError}},description:i}}class C{get description(){return this.p.description}m(e){return g(e.data)}v(e,t){return t||{common:e.parent.common,data:e.data,parsedType:g(e.data),schemaErrorMap:this.p.errorMap,path:e.path,parent:e.parent}}$(e){return{status:new P,ctx:{common:e.parent.common,data:e.data,parsedType:g(e.data),schemaErrorMap:this.p.errorMap,path:e.path,parent:e.parent}}}P(e){const t=this._(e);if(O(t))throw new Error("Synchronous parse encountered promise.");return t}S(e){const t=this._(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this.p.errorMap,parent:null,data:e,parsedType:g(e)},n=this.P({data:e,path:r.path,parent:r});return D(r,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this.p.errorMap,parent:null,data:e,parsedType:g(e)};if(!this["~standard"].async)try{const r=this.P({data:e,path:[],parent:t});return j(r)?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this.S({data:e,path:[],parent:t}).then(e=>j(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this.p.errorMap,parent:null,data:e,parsedType:g(e)},n=this._({data:e,path:r.path,parent:r}),i=await(O(n)?n:Promise.resolve(n));return D(r,i)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this.F((t,n)=>{const i=e(t),a=()=>n.addIssue({code:w.custom,...r(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(a(),!1)):!!i||(a(),!1)})}refinement(e,t){return this.F((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1))}F(e){return new Re({schema:this,typeName:Je.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this.F(e)}constructor(e){this.spa=this.safeParseAsync,this.p=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 Me.create(this,this.p)}nullable(){return qe.create(this,this.p)}nullish(){return this.nullable().optional()}array(){return we.create(this)}promise(){return Ce.create(this,this.p)}or(e){return xe.create([this,e],this.p)}and(e){return Se.create(this,e,this.p)}transform(e){return new Re({...T(this.p),schema:this,typeName:Je.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ze({...T(this.p),innerType:this,defaultValue:t,typeName:Je.ZodDefault})}brand(){return new Ze({typeName:Je.ZodBranded,type:this,...T(this.p)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ue({...T(this.p),innerType:this,catchValue:t,typeName:Je.ZodCatch})}describe(e){return new(0,this.constructor)({...this.p,description:e})}pipe(e){return Ve.create(this,e)}readonly(){return Be.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const R=/^c[^\s-]{8,}$/i,M=/^[0-9a-z]+$/,q=/^[0-9A-HJKMNP-TV-Z]{26}$/i,z=/^[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,U=/^[a-z0-9_-]{21}$/i,L=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Z=/^[-+]?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)?)??$/,V=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let B;const J=/^(?:(?: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])$/,H=/^(?:(?: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])$/,K=/^(([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]))$/,G=/^(([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])$/,Y=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,W=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Q="((\\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])))",X=new RegExp(`^${Q}$`);function ee(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function te(e){return new RegExp(`^${ee(e)}$`)}function re(e){let t=`${Q}T${ee(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function ne(e,t){return!("v4"!==t&&t||!J.test(e))||!("v6"!==t&&t||!K.test(e))}function ie(e,t){if(!L.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return"object"==typeof i&&null!==i&&((!("typ"in i)||"JWT"===i?.typ)&&(!!i.alg&&(!t||i.alg===t)))}catch{return!1}}function ae(e,t){return!("v4"!==t&&t||!H.test(e))||!("v6"!==t&&t||!G.test(e))}class se extends C{_(e){this.p.coerce&&(e.data=String(e.data));if(this.m(e)!==y.string){const t=this.v(e);return $(t,{code:w.invalid_type,expected:y.string,received:t.parsedType}),_}const t=new P;let r;for(const n of this.p.checks)if("min"===n.kind)e.data.length<n.value&&(r=this.v(e,r),$(r,{code:w.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("max"===n.kind)e.data.length>n.value&&(r=this.v(e,r),$(r,{code:w.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const i=e.data.length>n.value,a=e.data.length<n.value;(i||a)&&(r=this.v(e,r),i?$(r,{code:w.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):a&&$(r,{code:w.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)V.test(e.data)||(r=this.v(e,r),$(r,{validation:"email",code:w.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.kind)B||(B=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),B.test(e.data)||(r=this.v(e,r),$(r,{validation:"emoji",code:w.invalid_string,message:n.message}),t.dirty());else if("uuid"===n.kind)z.test(e.data)||(r=this.v(e,r),$(r,{validation:"uuid",code:w.invalid_string,message:n.message}),t.dirty());else if("nanoid"===n.kind)U.test(e.data)||(r=this.v(e,r),$(r,{validation:"nanoid",code:w.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)R.test(e.data)||(r=this.v(e,r),$(r,{validation:"cuid",code:w.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)M.test(e.data)||(r=this.v(e,r),$(r,{validation:"cuid2",code:w.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)q.test(e.data)||(r=this.v(e,r),$(r,{validation:"ulid",code:w.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch{r=this.v(e,r),$(r,{validation:"url",code:w.invalid_string,message:n.message}),t.dirty()}else if("regex"===n.kind){n.regex.lastIndex=0;n.regex.test(e.data)||(r=this.v(e,r),$(r,{validation:"regex",code:w.invalid_string,message:n.message}),t.dirty())}else if("trim"===n.kind)e.data=e.data.trim();else if("includes"===n.kind)e.data.includes(n.value,n.position)||(r=this.v(e,r),$(r,{code:w.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),t.dirty());else if("toLowerCase"===n.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===n.kind)e.data=e.data.toUpperCase();else if("startsWith"===n.kind)e.data.startsWith(n.value)||(r=this.v(e,r),$(r,{code:w.invalid_string,validation:{startsWith:n.value},message:n.message}),t.dirty());else if("endsWith"===n.kind)e.data.endsWith(n.value)||(r=this.v(e,r),$(r,{code:w.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){re(n).test(e.data)||(r=this.v(e,r),$(r,{code:w.invalid_string,validation:"datetime",message:n.message}),t.dirty())}else if("date"===n.kind){X.test(e.data)||(r=this.v(e,r),$(r,{code:w.invalid_string,validation:"date",message:n.message}),t.dirty())}else if("time"===n.kind){te(n).test(e.data)||(r=this.v(e,r),$(r,{code:w.invalid_string,validation:"time",message:n.message}),t.dirty())}else"duration"===n.kind?Z.test(e.data)||(r=this.v(e,r),$(r,{validation:"duration",code:w.invalid_string,message:n.message}),t.dirty()):"ip"===n.kind?ne(e.data,n.version)||(r=this.v(e,r),$(r,{validation:"ip",code:w.invalid_string,message:n.message}),t.dirty()):"jwt"===n.kind?ie(e.data,n.alg)||(r=this.v(e,r),$(r,{validation:"jwt",code:w.invalid_string,message:n.message}),t.dirty()):"cidr"===n.kind?ae(e.data,n.version)||(r=this.v(e,r),$(r,{validation:"cidr",code:w.invalid_string,message:n.message}),t.dirty()):"base64"===n.kind?Y.test(e.data)||(r=this.v(e,r),$(r,{validation:"base64",code:w.invalid_string,message:n.message}),t.dirty()):"base64url"===n.kind?W.test(e.data)||(r=this.v(e,r),$(r,{validation:"base64url",code:w.invalid_string,message:n.message}),t.dirty()):m.assertNever(n);return{status:t.value,value:e.data}}k(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:w.invalid_string,...I.errToObj(r)})}A(e){return new se({...this.p,checks:[...this.p.checks,e]})}email(e){return this.A({kind:"email",...I.errToObj(e)})}url(e){return this.A({kind:"url",...I.errToObj(e)})}emoji(e){return this.A({kind:"emoji",...I.errToObj(e)})}uuid(e){return this.A({kind:"uuid",...I.errToObj(e)})}nanoid(e){return this.A({kind:"nanoid",...I.errToObj(e)})}cuid(e){return this.A({kind:"cuid",...I.errToObj(e)})}cuid2(e){return this.A({kind:"cuid2",...I.errToObj(e)})}ulid(e){return this.A({kind:"ulid",...I.errToObj(e)})}base64(e){return this.A({kind:"base64",...I.errToObj(e)})}base64url(e){return this.A({kind:"base64url",...I.errToObj(e)})}jwt(e){return this.A({kind:"jwt",...I.errToObj(e)})}ip(e){return this.A({kind:"ip",...I.errToObj(e)})}cidr(e){return this.A({kind:"cidr",...I.errToObj(e)})}datetime(e){return this.A("string"==typeof e?{kind:"datetime",precision:null,offset:!1,local:!1,message:e}:{kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...I.errToObj(e?.message)})}date(e){return this.A({kind:"date",message:e})}time(e){return this.A("string"==typeof e?{kind:"time",precision:null,message:e}:{kind:"time",precision:void 0===e?.precision?null:e?.precision,...I.errToObj(e?.message)})}duration(e){return this.A({kind:"duration",...I.errToObj(e)})}regex(e,t){return this.A({kind:"regex",regex:e,...I.errToObj(t)})}includes(e,t){return this.A({kind:"includes",value:e,position:t?.position,...I.errToObj(t?.message)})}startsWith(e,t){return this.A({kind:"startsWith",value:e,...I.errToObj(t)})}endsWith(e,t){return this.A({kind:"endsWith",value:e,...I.errToObj(t)})}min(e,t){return this.A({kind:"min",value:e,...I.errToObj(t)})}max(e,t){return this.A({kind:"max",value:e,...I.errToObj(t)})}length(e,t){return this.A({kind:"length",value:e,...I.errToObj(t)})}nonempty(e){return this.min(1,I.errToObj(e))}trim(){return new se({...this.p,checks:[...this.p.checks,{kind:"trim"}]})}toLowerCase(){return new se({...this.p,checks:[...this.p.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new se({...this.p,checks:[...this.p.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this.p.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this.p.checks.find(e=>"date"===e.kind)}get isTime(){return!!this.p.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this.p.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this.p.checks.find(e=>"email"===e.kind)}get isURL(){return!!this.p.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this.p.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this.p.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this.p.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this.p.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this.p.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this.p.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this.p.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this.p.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this.p.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this.p.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this.p.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this.p.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function oe(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}se.create=e=>new se({checks:[],typeName:Je.ZodString,coerce:e?.coerce??!1,...T(e)});class ce extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_(e){this.p.coerce&&(e.data=Number(e.data));if(this.m(e)!==y.number){const t=this.v(e);return $(t,{code:w.invalid_type,expected:y.number,received:t.parsedType}),_}let t;const r=new P;for(const n of this.p.checks)if("int"===n.kind)m.isInteger(e.data)||(t=this.v(e,t),$(t,{code:w.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty());else if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this.v(e,t),$(t,{code:w.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this.v(e,t),$(t,{code:w.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==oe(e.data,n.value)&&(t=this.v(e,t),$(t,{code:w.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this.v(e,t),$(t,{code:w.not_finite,message:n.message}),r.dirty()):m.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,I.toString(t))}gt(e,t){return this.setLimit("min",e,!1,I.toString(t))}lte(e,t){return this.setLimit("max",e,!0,I.toString(t))}lt(e,t){return this.setLimit("max",e,!1,I.toString(t))}setLimit(e,t,r,n){return new ce({...this.p,checks:[...this.p.checks,{kind:e,value:t,inclusive:r,message:I.toString(n)}]})}A(e){return new ce({...this.p,checks:[...this.p.checks,e]})}int(e){return this.A({kind:"int",message:I.toString(e)})}positive(e){return this.A({kind:"min",value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this.A({kind:"max",value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this.A({kind:"max",value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this.A({kind:"min",value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this.A({kind:"multipleOf",value:e,message:I.toString(t)})}finite(e){return this.A({kind:"finite",message:I.toString(e)})}safe(e){return this.A({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(e)}).A({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString(e)})}get minValue(){let e=null;for(const t of this.p.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this.p.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this.p.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&m.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this.p.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ce.create=e=>new ce({checks:[],typeName:Je.ZodNumber,coerce:e?.coerce||!1,...T(e)});class ue extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_(e){if(this.p.coerce)try{e.data=BigInt(e.data)}catch{return this.j(e)}if(this.m(e)!==y.bigint)return this.j(e);let t;const r=new P;for(const n of this.p.checks)if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this.v(e,t),$(t,{code:w.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this.v(e,t),$(t,{code:w.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this.v(e,t),$(t,{code:w.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):m.assertNever(n);return{status:r.value,value:e.data}}j(e){const t=this.v(e);return $(t,{code:w.invalid_type,expected:y.bigint,received:t.parsedType}),_}gte(e,t){return this.setLimit("min",e,!0,I.toString(t))}gt(e,t){return this.setLimit("min",e,!1,I.toString(t))}lte(e,t){return this.setLimit("max",e,!0,I.toString(t))}lt(e,t){return this.setLimit("max",e,!1,I.toString(t))}setLimit(e,t,r,n){return new ue({...this.p,checks:[...this.p.checks,{kind:e,value:t,inclusive:r,message:I.toString(n)}]})}A(e){return new ue({...this.p,checks:[...this.p.checks,e]})}positive(e){return this.A({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString(e)})}negative(e){return this.A({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this.A({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this.A({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,t){return this.A({kind:"multipleOf",value:e,message:I.toString(t)})}get minValue(){let e=null;for(const t of this.p.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this.p.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}ue.create=e=>new ue({checks:[],typeName:Je.ZodBigInt,coerce:e?.coerce??!1,...T(e)});class le extends C{_(e){this.p.coerce&&(e.data=Boolean(e.data));if(this.m(e)!==y.boolean){const t=this.v(e);return $(t,{code:w.invalid_type,expected:y.boolean,received:t.parsedType}),_}return F(e.data)}}le.create=e=>new le({typeName:Je.ZodBoolean,coerce:e?.coerce||!1,...T(e)});class de extends C{_(e){this.p.coerce&&(e.data=new Date(e.data));if(this.m(e)!==y.date){const t=this.v(e);return $(t,{code:w.invalid_type,expected:y.date,received:t.parsedType}),_}if(Number.isNaN(e.data.getTime())){return $(this.v(e),{code:w.invalid_date}),_}const t=new P;let r;for(const n of this.p.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this.v(e,r),$(r,{code:w.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this.v(e,r),$(r,{code:w.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):m.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}A(e){return new de({...this.p,checks:[...this.p.checks,e]})}min(e,t){return this.A({kind:"min",value:e.getTime(),message:I.toString(t)})}max(e,t){return this.A({kind:"max",value:e.getTime(),message:I.toString(t)})}get minDate(){let e=null;for(const t of this.p.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this.p.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}de.create=e=>new de({checks:[],coerce:e?.coerce||!1,typeName:Je.ZodDate,...T(e)});class fe extends C{_(e){if(this.m(e)!==y.symbol){const t=this.v(e);return $(t,{code:w.invalid_type,expected:y.symbol,received:t.parsedType}),_}return F(e.data)}}fe.create=e=>new fe({typeName:Je.ZodSymbol,...T(e)});class he extends C{_(e){if(this.m(e)!==y.undefined){const t=this.v(e);return $(t,{code:w.invalid_type,expected:y.undefined,received:t.parsedType}),_}return F(e.data)}}he.create=e=>new he({typeName:Je.ZodUndefined,...T(e)});class pe extends C{_(e){if(this.m(e)!==y.null){const t=this.v(e);return $(t,{code:w.invalid_type,expected:y.null,received:t.parsedType}),_}return F(e.data)}}pe.create=e=>new pe({typeName:Je.ZodNull,...T(e)});class me extends C{constructor(){super(...arguments),this.O=!0}_(e){return F(e.data)}}me.create=e=>new me({typeName:Je.ZodAny,...T(e)});class ve extends C{constructor(){super(...arguments),this.I=!0}_(e){return F(e.data)}}ve.create=e=>new ve({typeName:Je.ZodUnknown,...T(e)});class ye extends C{_(e){const t=this.v(e);return $(t,{code:w.invalid_type,expected:y.never,received:t.parsedType}),_}}ye.create=e=>new ye({typeName:Je.ZodNever,...T(e)});class ge extends C{_(e){if(this.m(e)!==y.undefined){const t=this.v(e);return $(t,{code:w.invalid_type,expected:y.void,received:t.parsedType}),_}return F(e.data)}}ge.create=e=>new ge({typeName:Je.ZodVoid,...T(e)});class we extends C{_(e){const{ctx:t,status:r}=this.$(e),n=this.p;if(t.parsedType!==y.array)return $(t,{code:w.invalid_type,expected:y.array,received:t.parsedType}),_;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,i=t.data.length<n.exactLength.value;(e||i)&&($(t,{code:e?w.too_big:w.too_small,minimum:i?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&($(t,{code:w.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&($(t,{code:w.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>n.type.S(new N(t,e,t.path,r)))).then(e=>P.mergeArray(r,e));const i=[...t.data].map((e,r)=>n.type.P(new N(t,e,t.path,r)));return P.mergeArray(r,i)}get element(){return this.p.type}min(e,t){return new we({...this.p,minLength:{value:e,message:I.toString(t)}})}max(e,t){return new we({...this.p,maxLength:{value:e,message:I.toString(t)}})}length(e,t){return new we({...this.p,exactLength:{value:e,message:I.toString(t)}})}nonempty(e){return this.min(1,e)}}function be(e){if(e instanceof Ee){const t={};for(const r in e.shape){t[r]=Me.create(be(e.shape[r]))}return new Ee({...e.p,shape:()=>t})}return e instanceof we?new we({...e.p,type:be(e.element)}):e instanceof Me?Me.create(be(e.unwrap())):e instanceof qe?qe.create(be(e.unwrap())):e instanceof Fe?Fe.create(e.items.map(e=>be(e))):e}we.create=(e,t)=>new we({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Je.ZodArray,...T(t)});class Ee extends C{constructor(){super(...arguments),this.N=null,this.nonstrict=this.passthrough,this.augment=this.extend}D(){if(null!==this.N)return this.N;const e=this.p.shape(),t=m.objectKeys(e);return this.N={shape:e,keys:t},this.N}_(e){if(this.m(e)!==y.object){const t=this.v(e);return $(t,{code:w.invalid_type,expected:y.object,received:t.parsedType}),_}const{status:t,ctx:r}=this.$(e),{shape:n,keys:i}=this.D(),a=[];if(!(this.p.catchall instanceof ye&&"strip"===this.p.unknownKeys))for(const e in r.data)i.includes(e)||a.push(e);const s=[];for(const e of i){s.push({key:{status:"valid",value:e},value:n[e]._(new N(r,r.data[e],r.path,e)),alwaysSet:e in r.data})}if(this.p.catchall instanceof ye){const e=this.p.unknownKeys;if("passthrough"===e)for(const e of a)s.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)a.length>0&&($(r,{code:w.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this.p.catchall;for(const t of a){s.push({key:{status:"valid",value:t},value:e._(new N(r,r.data[t],r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of s){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e}).then(e=>P.mergeObjectSync(t,e)):P.mergeObjectSync(t,s)}get shape(){return this.p.shape()}strict(e){return new Ee({...this.p,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{const n=this.p.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:I.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new Ee({...this.p,unknownKeys:"strip"})}passthrough(){return new Ee({...this.p,unknownKeys:"passthrough"})}extend(e){return new Ee({...this.p,shape:()=>({...this.p.shape(),...e})})}merge(e){return new Ee({unknownKeys:e.p.unknownKeys,catchall:e.p.catchall,shape:()=>({...this.p.shape(),...e.p.shape()}),typeName:Je.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Ee({...this.p,catchall:e})}pick(e){const t={};for(const r of m.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new Ee({...this.p,shape:()=>t})}omit(e){const t={};for(const r of m.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new Ee({...this.p,shape:()=>t})}deepPartial(){return be(this)}partial(e){const t={};for(const r of m.objectKeys(this.shape)){const n=this.shape[r];t[r]=e&&!e[r]?n:n.optional()}return new Ee({...this.p,shape:()=>t})}required(e){const t={};for(const r of m.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Me;)e=e.p.innerType;t[r]=e}return new Ee({...this.p,shape:()=>t})}keyof(){return Ne(m.objectKeys(this.shape))}}Ee.create=(e,t)=>new Ee({shape:()=>e,unknownKeys:"strip",catchall:ye.create(),typeName:Je.ZodObject,...T(t)}),Ee.strictCreate=(e,t)=>new Ee({shape:()=>e,unknownKeys:"strict",catchall:ye.create(),typeName:Je.ZodObject,...T(t)}),Ee.lazycreate=(e,t)=>new Ee({shape:e,unknownKeys:"strip",catchall:ye.create(),typeName:Je.ZodObject,...T(t)});class xe extends C{_(e){const{ctx:t}=this.$(e),r=this.p.options;if(t.common.async)return Promise.all(r.map(async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e.S({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map(e=>new b(e.ctx.common.issues));return $(t,{code:w.invalid_union,unionErrors:r}),_});{let e;const n=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},a=i.P({data:t.data,path:t.path,parent:r});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const i=n.map(e=>new b(e));return $(t,{code:w.invalid_union,unionErrors:i}),_}}get options(){return this.p.options}}xe.create=(e,t)=>new xe({options:e,typeName:Je.ZodUnion,...T(t)});const $e=e=>e instanceof Oe?$e(e.schema):e instanceof Re?$e(e.innerType()):e instanceof Ie?[e.value]:e instanceof De?e.options:e instanceof Te?m.objectValues(e.enum):e instanceof ze?$e(e.p.innerType):e instanceof he?[void 0]:e instanceof pe?[null]:e instanceof Me?[void 0,...$e(e.unwrap())]:e instanceof qe?[null,...$e(e.unwrap())]:e instanceof Ze||e instanceof Be?$e(e.unwrap()):e instanceof Ue?$e(e.p.innerType):[];class Pe extends C{_(e){const{ctx:t}=this.$(e);if(t.parsedType!==y.object)return $(t,{code:w.invalid_type,expected:y.object,received:t.parsedType}),_;const r=this.discriminator,n=this.optionsMap.get(t.data[r]);return n?t.common.async?n.S({data:t.data,path:t.path,parent:t}):n.P({data:t.data,path:t.path,parent:t}):($(t,{code:w.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),_)}get discriminator(){return this.p.discriminator}get options(){return this.p.options}get optionsMap(){return this.p.optionsMap}static create(e,t,r){const n=new Map;for(const r of t){const t=$e(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of t){if(n.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,r)}}return new Pe({typeName:Je.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...T(r)})}}function _e(e,t){const r=g(e),n=g(t);if(e===t)return{valid:!0,data:e};if(r===y.object&&n===y.object){const r=m.objectKeys(t),n=m.objectKeys(e).filter(e=>-1!==r.indexOf(e)),i={...e,...t};for(const r of n){const n=_e(e[r],t[r]);if(!n.valid)return{valid:!1};i[r]=n.data}return{valid:!0,data:i}}if(r===y.array&&n===y.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const i=_e(e[n],t[n]);if(!i.valid)return{valid:!1};r.push(i.data)}return{valid:!0,data:r}}return r===y.date&&n===y.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class Se extends C{_(e){const{status:t,ctx:r}=this.$(e),n=(e,n)=>{if(k(e)||k(n))return _;const i=_e(e.value,n.value);return i.valid?((A(e)||A(n))&&t.dirty(),{status:t.value,value:i.data}):($(r,{code:w.invalid_intersection_types}),_)};return r.common.async?Promise.all([this.p.left.S({data:r.data,path:r.path,parent:r}),this.p.right.S({data:r.data,path:r.path,parent:r})]).then(([e,t])=>n(e,t)):n(this.p.left.P({data:r.data,path:r.path,parent:r}),this.p.right.P({data:r.data,path:r.path,parent:r}))}}Se.create=(e,t,r)=>new Se({left:e,right:t,typeName:Je.ZodIntersection,...T(r)});class Fe extends C{_(e){const{status:t,ctx:r}=this.$(e);if(r.parsedType!==y.array)return $(r,{code:w.invalid_type,expected:y.array,received:r.parsedType}),_;if(r.data.length<this.p.items.length)return $(r,{code:w.too_small,minimum:this.p.items.length,inclusive:!0,exact:!1,type:"array"}),_;!this.p.rest&&r.data.length>this.p.items.length&&($(r,{code:w.too_big,maximum:this.p.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map((e,t)=>{const n=this.p.items[t]||this.p.rest;return n?n._(new N(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(n).then(e=>P.mergeArray(t,e)):P.mergeArray(t,n)}get items(){return this.p.items}rest(e){return new Fe({...this.p,rest:e})}}Fe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Fe({items:e,typeName:Je.ZodTuple,rest:null,...T(t)})};class ke extends C{get keySchema(){return this.p.keyType}get valueSchema(){return this.p.valueType}_(e){const{status:t,ctx:r}=this.$(e);if(r.parsedType!==y.object)return $(r,{code:w.invalid_type,expected:y.object,received:r.parsedType}),_;const n=[],i=this.p.keyType,a=this.p.valueType;for(const e in r.data)n.push({key:i._(new N(r,e,r.path,e)),value:a._(new N(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?P.mergeObjectAsync(t,n):P.mergeObjectSync(t,n)}get element(){return this.p.valueType}static create(e,t,r){return new ke(t instanceof C?{keyType:e,valueType:t,typeName:Je.ZodRecord,...T(r)}:{keyType:se.create(),valueType:e,typeName:Je.ZodRecord,...T(t)})}}class Ae extends C{get keySchema(){return this.p.keyType}get valueSchema(){return this.p.valueType}_(e){const{status:t,ctx:r}=this.$(e);if(r.parsedType!==y.map)return $(r,{code:w.invalid_type,expected:y.map,received:r.parsedType}),_;const n=this.p.keyType,i=this.p.valueType,a=[...r.data.entries()].map(([e,t],a)=>({key:n._(new N(r,e,r.path,[a,"key"])),value:i._(new N(r,t,r.path,[a,"value"]))}));if(r.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const r of a){const n=await r.key,i=await r.value;if("aborted"===n.status||"aborted"===i.status)return _;"dirty"!==n.status&&"dirty"!==i.status||t.dirty(),e.set(n.value,i.value)}return{status:t.value,value:e}})}{const e=new Map;for(const r of a){const n=r.key,i=r.value;if("aborted"===n.status||"aborted"===i.status)return _;"dirty"!==n.status&&"dirty"!==i.status||t.dirty(),e.set(n.value,i.value)}return{status:t.value,value:e}}}}Ae.create=(e,t,r)=>new Ae({valueType:t,keyType:e,typeName:Je.ZodMap,...T(r)});class je extends C{_(e){const{status:t,ctx:r}=this.$(e);if(r.parsedType!==y.set)return $(r,{code:w.invalid_type,expected:y.set,received:r.parsedType}),_;const n=this.p;null!==n.minSize&&r.data.size<n.minSize.value&&($(r,{code:w.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&($(r,{code:w.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const i=this.p.valueType;function a(e){const r=new Set;for(const n of e){if("aborted"===n.status)return _;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const s=[...r.data.values()].map((e,t)=>i._(new N(r,e,r.path,t)));return r.common.async?Promise.all(s).then(e=>a(e)):a(s)}min(e,t){return new je({...this.p,minSize:{value:e,message:I.toString(t)}})}max(e,t){return new je({...this.p,maxSize:{value:e,message:I.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}je.create=(e,t)=>new je({valueType:e,minSize:null,maxSize:null,typeName:Je.ZodSet,...T(t)});class Oe extends C{get schema(){return this.p.getter()}_(e){const{ctx:t}=this.$(e);return this.p.getter()._({data:t.data,path:t.path,parent:t})}}Oe.create=(e,t)=>new Oe({getter:e,typeName:Je.ZodLazy,...T(t)});class Ie extends C{_(e){if(e.data!==this.p.value){const t=this.v(e);return $(t,{received:t.data,code:w.invalid_literal,expected:this.p.value}),_}return{status:"valid",value:e.data}}get value(){return this.p.value}}function Ne(e,t){return new De({values:e,typeName:Je.ZodEnum,...T(t)})}Ie.create=(e,t)=>new Ie({value:e,typeName:Je.ZodLiteral,...T(t)});class De extends C{_(e){if("string"!=typeof e.data){const t=this.v(e);return $(t,{expected:m.joinValues(this.p.values),received:t.parsedType,code:w.invalid_type}),_}if(this.T||(this.T=new Set(this.p.values)),!this.T.has(e.data)){const t=this.v(e);return $(t,{received:t.data,code:w.invalid_enum_value,options:this.p.values}),_}return F(e.data)}get options(){return this.p.values}get enum(){const e={};for(const t of this.p.values)e[t]=t;return e}get Values(){const e={};for(const t of this.p.values)e[t]=t;return e}get Enum(){const e={};for(const t of this.p.values)e[t]=t;return e}extract(e,t=this.p){return De.create(e,{...this.p,...t})}exclude(e,t=this.p){return De.create(this.options.filter(t=>!e.includes(t)),{...this.p,...t})}}De.create=Ne;class Te extends C{_(e){const t=m.getValidEnumValues(this.p.values),r=this.v(e);if(r.parsedType!==y.string&&r.parsedType!==y.number){const e=m.objectValues(t);return $(r,{expected:m.joinValues(e),received:r.parsedType,code:w.invalid_type}),_}if(this.T||(this.T=new Set(m.getValidEnumValues(this.p.values))),!this.T.has(e.data)){const e=m.objectValues(t);return $(r,{received:r.data,code:w.invalid_enum_value,options:e}),_}return F(e.data)}get enum(){return this.p.values}}Te.create=(e,t)=>new Te({values:e,typeName:Je.ZodNativeEnum,...T(t)});class Ce extends C{unwrap(){return this.p.type}_(e){const{ctx:t}=this.$(e);if(t.parsedType!==y.promise&&!1===t.common.async)return $(t,{code:w.invalid_type,expected:y.promise,received:t.parsedType}),_;const r=t.parsedType===y.promise?t.data:Promise.resolve(t.data);return F(r.then(e=>this.p.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ce.create=(e,t)=>new Ce({type:e,typeName:Je.ZodPromise,...T(t)});class Re extends C{innerType(){return this.p.schema}sourceType(){return this.p.schema.p.typeName===Je.ZodEffects?this.p.schema.sourceType():this.p.schema}_(e){const{status:t,ctx:r}=this.$(e),n=this.p.effect||null,i={addIssue:e=>{$(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===n.type){const e=n.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return _;const n=await this.p.schema.S({data:e,path:r.path,parent:r});return"aborted"===n.status?_:"dirty"===n.status||"dirty"===t.value?S(n.value):n});{if("aborted"===t.value)return _;const n=this.p.schema.P({data:e,path:r.path,parent:r});return"aborted"===n.status?_:"dirty"===n.status||"dirty"===t.value?S(n.value):n}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this.p.schema.P({data:r.data,path:r.path,parent:r});return"aborted"===n.status?_:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this.p.schema.S({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?_:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))))}if("transform"===n.type){if(!1===r.common.async){const e=this.p.schema.P({data:r.data,path:r.path,parent:r});if(!j(e))return _;const a=n.transform(e.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}return this.p.schema.S({data:r.data,path:r.path,parent:r}).then(e=>j(e)?Promise.resolve(n.transform(e.value,i)).then(e=>({status:t.value,value:e})):_)}m.assertNever(n)}}Re.create=(e,t,r)=>new Re({schema:e,typeName:Je.ZodEffects,effect:t,...T(r)}),Re.createWithPreprocess=(e,t,r)=>new Re({schema:t,effect:{type:"preprocess",transform:e},typeName:Je.ZodEffects,...T(r)});class Me extends C{_(e){return this.m(e)===y.undefined?F(void 0):this.p.innerType._(e)}unwrap(){return this.p.innerType}}Me.create=(e,t)=>new Me({innerType:e,typeName:Je.ZodOptional,...T(t)});class qe extends C{_(e){return this.m(e)===y.null?F(null):this.p.innerType._(e)}unwrap(){return this.p.innerType}}qe.create=(e,t)=>new qe({innerType:e,typeName:Je.ZodNullable,...T(t)});class ze extends C{_(e){const{ctx:t}=this.$(e);let r=t.data;return t.parsedType===y.undefined&&(r=this.p.defaultValue()),this.p.innerType._({data:r,path:t.path,parent:t})}removeDefault(){return this.p.innerType}}ze.create=(e,t)=>new ze({innerType:e,typeName:Je.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...T(t)});class Ue extends C{_(e){const{ctx:t}=this.$(e),r={...t,common:{...t.common,issues:[]}},n=this.p.innerType._({data:r.data,path:r.path,parent:{...r}});return O(n)?n.then(e=>({status:"valid",value:"valid"===e.status?e.value:this.p.catchValue({get error(){return new b(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===n.status?n.value:this.p.catchValue({get error(){return new b(r.common.issues)},input:r.data})}}removeCatch(){return this.p.innerType}}Ue.create=(e,t)=>new Ue({innerType:e,typeName:Je.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...T(t)});class Le extends C{_(e){if(this.m(e)!==y.nan){const t=this.v(e);return $(t,{code:w.invalid_type,expected:y.nan,received:t.parsedType}),_}return{status:"valid",value:e.data}}}Le.create=e=>new Le({typeName:Je.ZodNaN,...T(e)});class Ze extends C{_(e){const{ctx:t}=this.$(e);return this.p.type._({data:t.data,path:t.path,parent:t})}unwrap(){return this.p.type}}class Ve extends C{_(e){const{status:t,ctx:r}=this.$(e);if(r.common.async){return(async()=>{const e=await this.p.in.S({data:r.data,path:r.path,parent:r});return"aborted"===e.status?_:"dirty"===e.status?(t.dirty(),S(e.value)):this.p.out.S({data:e.value,path:r.path,parent:r})})()}{const e=this.p.in.P({data:r.data,path:r.path,parent:r});return"aborted"===e.status?_:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this.p.out.P({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Ve({in:e,out:t,typeName:Je.ZodPipeline})}}class Be extends C{_(e){const t=this.p.innerType._(e),r=e=>(j(e)&&(e.value=Object.freeze(e.value)),e);return O(t)?t.then(e=>r(e)):r(t)}unwrap(){return this.p.innerType}}var Je;Be.create=(e,t)=>new Be({innerType:e,typeName:Je.ZodReadonly,...T(t)}),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"}(Je||(Je={}));const He=se.create,Ke=ce.create,Ge=le.create,Ye=ve.create,We=we.create,Qe=Ee.create,Xe=xe.create,et=Pe.create,tt=ke.create,rt=Ie.create,nt=De.create,it=Me.create,at="2025-06-18",st=[at,"2025-03-26","2024-11-05","2024-10-07"],ot="2.0",ct=Xe([He(),Ke().int()]),ut=He(),lt=Qe({progressToken:it(ct)}).passthrough(),dt=Qe({C:it(lt)}).passthrough(),ft=Qe({method:He(),params:it(dt)}),ht=Qe({C:it(Qe({}).passthrough())}).passthrough(),pt=Qe({method:He(),params:it(ht)}),mt=Qe({C:it(Qe({}).passthrough())}).passthrough(),vt=Xe([He(),Ke().int()]),yt=Qe({jsonrpc:rt(ot),id:vt}).merge(ft).strict(),gt=e=>yt.safeParse(e).success,wt=Qe({jsonrpc:rt(ot)}).merge(pt).strict(),bt=Qe({jsonrpc:rt(ot),id:vt,result:mt}).strict(),Et=e=>bt.safeParse(e).success;var xt;!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"}(xt||(xt={}));const $t=Qe({jsonrpc:rt(ot),id:vt,error:Qe({code:Ke().int(),message:He(),data:it(Ye())})}).strict(),Pt=e=>$t.safeParse(e).success,_t=Xe([yt,wt,bt,$t]),St=mt.strict(),Ft=pt.extend({method:rt("notifications/cancelled"),params:ht.extend({requestId:vt,reason:He().optional()})}),kt=Qe({name:He(),title:it(He())}).passthrough(),At=kt.extend({version:He()}),jt=Qe({experimental:it(Qe({}).passthrough()),sampling:it(Qe({}).passthrough()),elicitation:it(Qe({}).passthrough()),roots:it(Qe({listChanged:it(Ge())}).passthrough())}).passthrough(),Ot=ft.extend({method:rt("initialize"),params:dt.extend({protocolVersion:He(),capabilities:jt,clientInfo:At})}),It=e=>Ot.safeParse(e).success,Nt=Qe({experimental:it(Qe({}).passthrough()),logging:it(Qe({}).passthrough()),completions:it(Qe({}).passthrough()),prompts:it(Qe({listChanged:it(Ge())}).passthrough()),resources:it(Qe({subscribe:it(Ge()),listChanged:it(Ge())}).passthrough()),tools:it(Qe({listChanged:it(Ge())}).passthrough())}).passthrough(),Dt=mt.extend({protocolVersion:He(),capabilities:Nt,serverInfo:At,instructions:it(He())}),Tt=pt.extend({method:rt("notifications/initialized")}),Ct=ft.extend({method:rt("ping")}),Rt=Qe({progress:Ke(),total:it(Ke()),message:it(He())}).passthrough(),Mt=pt.extend({method:rt("notifications/progress"),params:ht.merge(Rt).extend({progressToken:ct})}),qt=ft.extend({params:dt.extend({cursor:it(ut)}).optional()}),zt=mt.extend({nextCursor:it(ut)}),Ut=Qe({uri:He(),mimeType:it(He()),C:it(Qe({}).passthrough())}).passthrough(),Lt=Ut.extend({text:He()}),Zt=Ut.extend({blob:He().base64()}),Vt=kt.extend({uri:He(),description:it(He()),mimeType:it(He()),C:it(Qe({}).passthrough())}),Bt=kt.extend({uriTemplate:He(),description:it(He()),mimeType:it(He()),C:it(Qe({}).passthrough())}),Jt=qt.extend({method:rt("resources/list")}),Ht=zt.extend({resources:We(Vt)}),Kt=qt.extend({method:rt("resources/templates/list")}),Gt=zt.extend({resourceTemplates:We(Bt)}),Yt=ft.extend({method:rt("resources/read"),params:dt.extend({uri:He()})}),Wt=mt.extend({contents:We(Xe([Lt,Zt]))}),Qt=pt.extend({method:rt("notifications/resources/list_changed")}),Xt=ft.extend({method:rt("resources/subscribe"),params:dt.extend({uri:He()})}),er=ft.extend({method:rt("resources/unsubscribe"),params:dt.extend({uri:He()})}),tr=pt.extend({method:rt("notifications/resources/updated"),params:ht.extend({uri:He()})}),rr=Qe({name:He(),description:it(He()),required:it(Ge())}).passthrough(),nr=kt.extend({description:it(He()),arguments:it(We(rr)),C:it(Qe({}).passthrough())}),ir=qt.extend({method:rt("prompts/list")}),ar=zt.extend({prompts:We(nr)}),sr=ft.extend({method:rt("prompts/get"),params:dt.extend({name:He(),arguments:it(tt(He()))})}),or=Qe({type:rt("text"),text:He(),C:it(Qe({}).passthrough())}).passthrough(),cr=Qe({type:rt("image"),data:He().base64(),mimeType:He(),C:it(Qe({}).passthrough())}).passthrough(),ur=Qe({type:rt("audio"),data:He().base64(),mimeType:He(),C:it(Qe({}).passthrough())}).passthrough(),lr=Qe({type:rt("resource"),resource:Xe([Lt,Zt]),C:it(Qe({}).passthrough())}).passthrough(),dr=Xe([or,cr,ur,Vt.extend({type:rt("resource_link")}),lr]),fr=Qe({role:nt(["user","assistant"]),content:dr}).passthrough(),hr=mt.extend({description:it(He()),messages:We(fr)}),pr=pt.extend({method:rt("notifications/prompts/list_changed")}),mr=Qe({title:it(He()),readOnlyHint:it(Ge()),destructiveHint:it(Ge()),idempotentHint:it(Ge()),openWorldHint:it(Ge())}).passthrough(),vr=kt.extend({description:it(He()),inputSchema:Qe({type:rt("object"),properties:it(Qe({}).passthrough()),required:it(We(He()))}).passthrough(),outputSchema:it(Qe({type:rt("object"),properties:it(Qe({}).passthrough()),required:it(We(He()))}).passthrough()),annotations:it(mr),C:it(Qe({}).passthrough())}),yr=qt.extend({method:rt("tools/list")}),gr=zt.extend({tools:We(vr)}),wr=mt.extend({content:We(dr).default([]),structuredContent:Qe({}).passthrough().optional(),isError:it(Ge())});wr.or(mt.extend({toolResult:Ye()}));const br=ft.extend({method:rt("tools/call"),params:dt.extend({name:He(),arguments:it(tt(Ye()))})}),Er=pt.extend({method:rt("notifications/tools/list_changed")}),xr=nt(["debug","info","notice","warning","error","critical","alert","emergency"]),$r=ft.extend({method:rt("logging/setLevel"),params:dt.extend({level:xr})}),Pr=pt.extend({method:rt("notifications/message"),params:ht.extend({level:xr,logger:it(He()),data:Ye()})}),_r=Qe({name:He().optional()}).passthrough(),Sr=Qe({hints:it(We(_r)),costPriority:it(Ke().min(0).max(1)),speedPriority:it(Ke().min(0).max(1)),intelligencePriority:it(Ke().min(0).max(1))}).passthrough(),Fr=Qe({role:nt(["user","assistant"]),content:Xe([or,cr,ur])}).passthrough(),kr=ft.extend({method:rt("sampling/createMessage"),params:dt.extend({messages:We(Fr),systemPrompt:it(He()),includeContext:it(nt(["none","thisServer","allServers"])),temperature:it(Ke()),maxTokens:Ke().int(),stopSequences:it(We(He())),metadata:it(Qe({}).passthrough()),modelPreferences:it(Sr)})}),Ar=mt.extend({model:He(),stopReason:it(nt(["endTurn","stopSequence","maxTokens"]).or(He())),role:nt(["user","assistant"]),content:et("type",[or,cr,ur])}),jr=Xe([Qe({type:rt("boolean"),title:it(He()),description:it(He()),default:it(Ge())}).passthrough(),Qe({type:rt("string"),title:it(He()),description:it(He()),minLength:it(Ke()),maxLength:it(Ke()),format:it(nt(["email","uri","date","date-time"]))}).passthrough(),Qe({type:nt(["number","integer"]),title:it(He()),description:it(He()),minimum:it(Ke()),maximum:it(Ke())}).passthrough(),Qe({type:rt("string"),title:it(He()),description:it(He()),enum:We(He()),enumNames:it(We(He()))}).passthrough()]),Or=ft.extend({method:rt("elicitation/create"),params:dt.extend({message:He(),requestedSchema:Qe({type:rt("object"),properties:tt(He(),jr),required:it(We(He()))}).passthrough()})}),Ir=mt.extend({action:nt(["accept","decline","cancel"]),content:it(tt(He(),Ye()))}),Nr=Qe({type:rt("ref/resource"),uri:He()}).passthrough(),Dr=Qe({type:rt("ref/prompt"),name:He()}).passthrough(),Tr=ft.extend({method:rt("completion/complete"),params:dt.extend({ref:Xe([Dr,Nr]),argument:Qe({name:He(),value:He()}).passthrough(),context:it(Qe({arguments:it(tt(He(),He()))}))})}),Cr=mt.extend({completion:Qe({values:We(He()).max(100),total:it(Ke().int()),hasMore:it(Ge())}).passthrough()}),Rr=Qe({uri:He().startsWith("file://"),name:it(He()),C:it(Qe({}).passthrough())}).passthrough(),Mr=ft.extend({method:rt("roots/list")}),qr=mt.extend({roots:We(Rr)}),zr=pt.extend({method:rt("notifications/roots/list_changed")});Xe([Ct,Ot,Tr,$r,sr,ir,Jt,Kt,Yt,Xt,er,br,yr]),Xe([Ft,Mt,Tt,zr]),Xe([St,Ar,Ir,qr]),Xe([Ct,kr,Or,Mr]),Xe([Ft,Mt,Pr,tr,Qt,Er,pr]),Xe([St,Dt,Cr,hr,ar,Ht,Gt,Wt,wr,gr]);class Ur extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}}class Lr{append(e){this.R=this.R?Buffer.concat([this.R,e]):e}readMessage(){if(!this.R)return null;const e=this.R.indexOf("\n");if(-1===e)return null;const t=this.R.toString("utf8",0,e).replace(/\r$/,"");return this.R=this.R.subarray(e+1),function(e){return _t.parse(JSON.parse(e))}(t)}clear(){this.R=void 0}}class Zr{constructor(e=a.stdin,t=a.stdout){this.M=e,this.U=t,this.L=new Lr,this.Z=!1,this.V=e=>{this.L.append(e),this.processReadBuffer()},this.B=e=>{var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}}async start(){if(this.Z)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this.Z=!0,this.M.on("data",this.V),this.M.on("error",this.B)}processReadBuffer(){for(var e,t;;)try{const t=this.L.readMessage();if(null===t)break;null===(e=this.onmessage)||void 0===e||e.call(this,t)}catch(e){null===(t=this.onerror)||void 0===t||t.call(this,e)}}async close(){var e;this.M.off("data",this.V),this.M.off("error",this.B);0===this.M.listenerCount("data")&&this.M.pause(),this.L.clear(),null===(e=this.onclose)||void 0===e||e.call(this)}send(e){return new Promise(t=>{const r=function(e){return JSON.stringify(e)+"\n"}(e);this.U.write(r)?t():this.U.once("drain",t)})}}class Vr{constructor(e){this.J=e,this.H=0,this.K=new Map,this.G=new Map,this.Y=new Map,this.W=new Map,this.X=new Map,this.ee=new Map,this.setNotificationHandler(Ft,e=>{const t=this.G.get(e.params.requestId);null==t||t.abort(e.params.reason)}),this.setNotificationHandler(Mt,e=>{this.te(e)}),this.setRequestHandler(Ct,e=>({}))}re(e,t,r,n,i=!1){this.ee.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:i,onTimeout:n})}ne(e){const t=this.ee.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this.ee.delete(e),new Ur(xt.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}ie(e){const t=this.ee.get(e);t&&(clearTimeout(t.timeoutId),this.ee.delete(e))}async connect(e){var t,r,n;this.ae=e;const i=null===(t=this.transport)||void 0===t?void 0:t.onclose;this.ae.onclose=()=>{null==i||i(),this.se()};const a=null===(r=this.transport)||void 0===r?void 0:r.onerror;this.ae.onerror=e=>{null==a||a(e),this.B(e)};const s=null===(n=this.ae)||void 0===n?void 0:n.onmessage;this.ae.onmessage=(e,t)=>{null==s||s(e,t),Et(e)||Pt(e)?this.oe(e):gt(e)?this.ce(e,t):wt.safeParse(e).success?this.ue(e):this.B(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this.ae.start()}se(){var e;const t=this.W;this.W=new Map,this.X.clear(),this.ae=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const r=new Ur(xt.ConnectionClosed,"Connection closed");for(const e of t.values())e(r)}B(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}ue(e){var t;const r=null!==(t=this.Y.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==r&&Promise.resolve().then(()=>r(e)).catch(e=>this.B(new Error(`Uncaught error in notification handler: ${e}`)))}ce(e,t){var r,n,i,a;const s=null!==(r=this.K.get(e.method))&&void 0!==r?r:this.fallbackRequestHandler;if(void 0===s)return void(null===(n=this.ae)||void 0===n||n.send({jsonrpc:"2.0",id:e.id,error:{code:xt.MethodNotFound,message:"Method not found"}}).catch(e=>this.B(new Error(`Failed to send an error response: ${e}`))));const o=new AbortController;this.G.set(e.id,o);const c={signal:o.signal,sessionId:null===(i=this.ae)||void 0===i?void 0:i.sessionId,C:null===(a=e.params)||void 0===a?void 0:a.C,sendNotification:t=>this.notification(t,{relatedRequestId:e.id}),sendRequest:(t,r,n)=>this.request(t,r,{...n,relatedRequestId:e.id}),authInfo:null==t?void 0:t.authInfo,requestId:e.id,requestInfo:null==t?void 0:t.requestInfo};Promise.resolve().then(()=>s(e,c)).then(t=>{var r;if(!o.signal.aborted)return null===(r=this.ae)||void 0===r?void 0:r.send({result:t,jsonrpc:"2.0",id:e.id})},t=>{var r,n;if(!o.signal.aborted)return null===(r=this.ae)||void 0===r?void 0:r.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:xt.InternalError,message:null!==(n=t.message)&&void 0!==n?n:"Internal error"}})}).catch(e=>this.B(new Error(`Failed to send response: ${e}`))).finally(()=>{this.G.delete(e.id)})}te(e){const{progressToken:t,...r}=e.params,n=Number(t),i=this.X.get(n);if(!i)return void this.B(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const a=this.W.get(n),s=this.ee.get(n);if(s&&a&&s.resetTimeoutOnProgress)try{this.ne(n)}catch(e){return void a(e)}i(r)}oe(e){const t=Number(e.id),r=this.W.get(t);if(void 0!==r)if(this.W.delete(t),this.X.delete(t),this.ie(t),Et(e))r(e);else{r(new Ur(e.error.code,e.error.message,e.error.data))}else this.B(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`))}get transport(){return this.ae}async close(){var e;await(null===(e=this.ae)||void 0===e?void 0:e.close())}request(e,t,r){const{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}=null!=r?r:{};return new Promise((s,o)=>{var c,u,l,d,f,h;if(!this.ae)return void o(new Error("Not connected"));!0===(null===(c=this.J)||void 0===c?void 0:c.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(u=null==r?void 0:r.signal)||void 0===u||u.throwIfAborted();const p=this.H++,m={...e,jsonrpc:"2.0",id:p};(null==r?void 0:r.onprogress)&&(this.X.set(p,r.onprogress),m.params={...e.params,C:{...(null===(l=e.params)||void 0===l?void 0:l.C)||{},progressToken:p}});const v=e=>{var t;this.W.delete(p),this.X.delete(p),this.ie(p),null===(t=this.ae)||void 0===t||t.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(e)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(e=>this.B(new Error(`Failed to send cancellation: ${e}`))),o(e)};this.W.set(p,e=>{var n;if(!(null===(n=null==r?void 0:r.signal)||void 0===n?void 0:n.aborted)){if(e instanceof Error)return o(e);try{const r=t.parse(e.result);s(r)}catch(e){o(e)}}}),null===(d=null==r?void 0:r.signal)||void 0===d||d.addEventListener("abort",()=>{var e;v(null===(e=null==r?void 0:r.signal)||void 0===e?void 0:e.reason)});const y=null!==(f=null==r?void 0:r.timeout)&&void 0!==f?f:6e4;this.re(p,y,null==r?void 0:r.maxTotalTimeout,()=>v(new Ur(xt.RequestTimeout,"Request timed out",{timeout:y})),null!==(h=null==r?void 0:r.resetTimeoutOnProgress)&&void 0!==h&&h),this.ae.send(m,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this.ie(p),o(e)})})}async notification(e,t){if(!this.ae)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r={...e,jsonrpc:"2.0"};await this.ae.send(r,t)}setRequestHandler(e,t){const r=e.shape.method.value;this.assertRequestHandlerCapability(r),this.K.set(r,(r,n)=>Promise.resolve(t(e.parse(r),n)))}removeRequestHandler(e){this.K.delete(e)}assertCanSetRequestHandler(e){if(this.K.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this.Y.set(e.shape.method.value,r=>Promise.resolve(t(e.parse(r))))}removeNotificationHandler(e){this.Y.delete(e)}}var Br="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Jr(e){return e&&e.le&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Hr={exports:{}};!function(e){function t(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];if(t.length>1){t[0]=t[0].slice(0,-1);for(var n=t.length-1,i=1;i<n;++i)t[i]=t[i].slice(1,-1);return t[n]=t[n].slice(1),t.join("")}return t[0]}function r(e){return"(?:"+e+")"}function n(e){return void 0===e?"undefined":null===e?"null":Object.prototype.toString.call(e).split(" ").pop().split("]").shift().toLowerCase()}function i(e){return e.toUpperCase()}function a(e){return null!=e?e instanceof Array?e:"number"!=typeof e.length||e.split||e.setInterval||e.call?[e]:Array.prototype.slice.call(e):[]}function s(e,t){var r=e;if(t)for(var n in t)r[n]=t[n];return r}function o(e){var n="[A-Za-z]",i="[0-9]",a=t(i,"[A-Fa-f]"),s=r(r("%[EFef]"+a+"%"+a+a+"%"+a+a)+"|"+r("%[89A-Fa-f]"+a+"%"+a+a)+"|"+r("%"+a+a)),o="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",c=t("[\\:\\/\\?\\#\\[\\]\\@]",o),u=e?"[\\uE000-\\uF8FF]":"[]",l=t(n,i,"[\\-\\.\\_\\~]",e?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]");r(n+t(n,i,"[\\+\\-\\.]")+"*"),r(r(s+"|"+t(l,o,"[\\:]"))+"*");var d=r(r("25[0-5]")+"|"+r("2[0-4]"+i)+"|"+r("1"+i+i)+"|"+r("0?[1-9]"+i)+"|0?0?"+i),f=r(d+"\\."+d+"\\."+d+"\\."+d),h=r(a+"{1,4}"),p=r(r(h+"\\:"+h)+"|"+f),m=r(r(h+"\\:")+"{6}"+p),v=r("\\:\\:"+r(h+"\\:")+"{5}"+p),y=r(r(h)+"?\\:\\:"+r(h+"\\:")+"{4}"+p),g=r(r(r(h+"\\:")+"{0,1}"+h)+"?\\:\\:"+r(h+"\\:")+"{3}"+p),w=r(r(r(h+"\\:")+"{0,2}"+h)+"?\\:\\:"+r(h+"\\:")+"{2}"+p),b=r(r(r(h+"\\:")+"{0,3}"+h)+"?\\:\\:"+h+"\\:"+p),E=r(r(r(h+"\\:")+"{0,4}"+h)+"?\\:\\:"+p),x=r(r(r(h+"\\:")+"{0,5}"+h)+"?\\:\\:"+h),$=r(r(r(h+"\\:")+"{0,6}"+h)+"?\\:\\:"),P=r([m,v,y,g,w,b,E,x,$].join("|")),_=r(r(l+"|"+s)+"+");r("[vV]"+a+"+\\."+t(l,o,"[\\:]")+"+"),r(r(s+"|"+t(l,o))+"*");var S=r(s+"|"+t(l,o,"[\\:\\@]"));return r(r(s+"|"+t(l,o,"[\\@]"))+"+"),r(r(S+"|"+t("[\\/\\?]",u))+"*"),{NOT_SCHEME:new RegExp(t("[^]",n,i,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(t("[^\\%\\:]",l,o),"g"),NOT_HOST:new RegExp(t("[^\\%\\[\\]\\:]",l,o),"g"),NOT_PATH:new RegExp(t("[^\\%\\/\\:\\@]",l,o),"g"),NOT_PATH_NOSCHEME:new RegExp(t("[^\\%\\/\\@]",l,o),"g"),NOT_QUERY:new RegExp(t("[^\\%]",l,o,"[\\:\\@\\/\\?]",u),"g"),NOT_FRAGMENT:new RegExp(t("[^\\%]",l,o,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(t("[^]",l,o),"g"),UNRESERVED:new RegExp(l,"g"),OTHER_CHARS:new RegExp(t("[^\\%]",l,c),"g"),PCT_ENCODED:new RegExp(s,"g"),IPV4ADDRESS:new RegExp("^("+f+")$"),IPV6ADDRESS:new RegExp("^\\[?("+P+")"+r(r("\\%25|\\%(?!"+a+"{2})")+"("+_+")")+"?\\]?$")}}var c=o(!1),u=o(!0),l=function(){function e(e,t){var r=[],n=!0,i=!1,a=void 0;try{for(var s,o=e[Symbol.iterator]();!(n=(s=o.next()).done)&&(r.push(s.value),!t||r.length!==t);n=!0);}catch(e){i=!0,a=e}finally{try{!n&&o.return&&o.return()}finally{if(i)throw a}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),d=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)},f=2147483647,h=36,p=1,m=26,v=38,y=700,g=72,w=128,b="-",E=/^xn--/,x=/[^\0-\x7E]/,$=/[\x2E\u3002\uFF0E\uFF61]/g,P={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},_=h-p,S=Math.floor,F=String.fromCharCode;function k(e){throw new RangeError(P[e])}function A(e,t){for(var r=[],n=e.length;n--;)r[n]=t(e[n]);return r}function j(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+A((e=e.replace($,".")).split("."),t).join(".")}function O(e){for(var t=[],r=0,n=e.length;r<n;){var i=e.charCodeAt(r++);if(i>=55296&&i<=56319&&r<n){var a=e.charCodeAt(r++);56320==(64512&a)?t.push(((1023&i)<<10)+(1023&a)+65536):(t.push(i),r--)}else t.push(i)}return t}var I=function(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:h},N=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},D=function(e,t,r){var n=0;for(e=r?S(e/y):e>>1,e+=S(e/t);e>_*m>>1;n+=h)e=S(e/_);return S(n+(_+1)*e/(e+v))},T=function(e){var t=[],r=e.length,n=0,i=w,a=g,s=e.lastIndexOf(b);s<0&&(s=0);for(var o=0;o<s;++o)e.charCodeAt(o)>=128&&k("not-basic"),t.push(e.charCodeAt(o));for(var c=s>0?s+1:0;c<r;){for(var u=n,l=1,d=h;;d+=h){c>=r&&k("invalid-input");var v=I(e.charCodeAt(c++));(v>=h||v>S((f-n)/l))&&k("overflow"),n+=v*l;var y=d<=a?p:d>=a+m?m:d-a;if(v<y)break;var E=h-y;l>S(f/E)&&k("overflow"),l*=E}var x=t.length+1;a=D(n-u,x,0==u),S(n/x)>f-i&&k("overflow"),i+=S(n/x),n%=x,t.splice(n++,0,i)}return String.fromCodePoint.apply(String,t)},C=function(e){var t=[],r=(e=O(e)).length,n=w,i=0,a=g,s=!0,o=!1,c=void 0;try{for(var u,l=e[Symbol.iterator]();!(s=(u=l.next()).done);s=!0){var d=u.value;d<128&&t.push(F(d))}}catch(e){o=!0,c=e}finally{try{!s&&l.return&&l.return()}finally{if(o)throw c}}var v=t.length,y=v;for(v&&t.push(b);y<r;){var E=f,x=!0,$=!1,P=void 0;try{for(var _,A=e[Symbol.iterator]();!(x=(_=A.next()).done);x=!0){var j=_.value;j>=n&&j<E&&(E=j)}}catch(e){$=!0,P=e}finally{try{!x&&A.return&&A.return()}finally{if($)throw P}}var I=y+1;E-n>S((f-i)/I)&&k("overflow"),i+=(E-n)*I,n=E;var T=!0,C=!1,R=void 0;try{for(var M,q=e[Symbol.iterator]();!(T=(M=q.next()).done);T=!0){var z=M.value;if(z<n&&++i>f&&k("overflow"),z==n){for(var U=i,L=h;;L+=h){var Z=L<=a?p:L>=a+m?m:L-a;if(U<Z)break;var V=U-Z,B=h-Z;t.push(F(N(Z+V%B,0))),U=S(V/B)}t.push(F(N(U,0))),a=D(i,I,y==v),i=0,++y}}}catch(e){C=!0,R=e}finally{try{!T&&q.return&&q.return()}finally{if(C)throw R}}++i,++n}return t.join("")},R=function(e){return j(e,function(e){return E.test(e)?T(e.slice(4).toLowerCase()):e})},M=function(e){return j(e,function(e){return x.test(e)?"xn--"+C(e):e})},q={version:"2.1.0",ucs2:{decode:O,encode:function(e){return String.fromCodePoint.apply(String,d(e))}},decode:T,encode:C,toASCII:M,toUnicode:R},z={};function U(e){var t=e.charCodeAt(0);return t<16?"%0"+t.toString(16).toUpperCase():t<128?"%"+t.toString(16).toUpperCase():t<2048?"%"+(t>>6|192).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase():"%"+(t>>12|224).toString(16).toUpperCase()+"%"+(t>>6&63|128).toString(16).toUpperCase()+"%"+(63&t|128).toString(16).toUpperCase()}function L(e){for(var t="",r=0,n=e.length;r<n;){var i=parseInt(e.substr(r+1,2),16);if(i<128)t+=String.fromCharCode(i),r+=3;else if(i>=194&&i<224){if(n-r>=6){var a=parseInt(e.substr(r+4,2),16);t+=String.fromCharCode((31&i)<<6|63&a)}else t+=e.substr(r,6);r+=6}else if(i>=224){if(n-r>=9){var s=parseInt(e.substr(r+4,2),16),o=parseInt(e.substr(r+7,2),16);t+=String.fromCharCode((15&i)<<12|(63&s)<<6|63&o)}else t+=e.substr(r,9);r+=9}else t+=e.substr(r,3),r+=3}return t}function Z(e,t){function r(e){var r=L(e);return r.match(t.UNRESERVED)?r:e}return e.scheme&&(e.scheme=String(e.scheme).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_SCHEME,"")),void 0!==e.userinfo&&(e.userinfo=String(e.userinfo).replace(t.PCT_ENCODED,r).replace(t.NOT_USERINFO,U).replace(t.PCT_ENCODED,i)),void 0!==e.host&&(e.host=String(e.host).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_HOST,U).replace(t.PCT_ENCODED,i)),void 0!==e.path&&(e.path=String(e.path).replace(t.PCT_ENCODED,r).replace(e.scheme?t.NOT_PATH:t.NOT_PATH_NOSCHEME,U).replace(t.PCT_ENCODED,i)),void 0!==e.query&&(e.query=String(e.query).replace(t.PCT_ENCODED,r).replace(t.NOT_QUERY,U).replace(t.PCT_ENCODED,i)),void 0!==e.fragment&&(e.fragment=String(e.fragment).replace(t.PCT_ENCODED,r).replace(t.NOT_FRAGMENT,U).replace(t.PCT_ENCODED,i)),e}function V(e){return e.replace(/^0*(.*)/,"$1")||"0"}function B(e,t){var r=e.match(t.IPV4ADDRESS)||[],n=l(r,2)[1];return n?n.split(".").map(V).join("."):e}function J(e,t){var r=e.match(t.IPV6ADDRESS)||[],n=l(r,3),i=n[1],a=n[2];if(i){for(var s=i.toLowerCase().split("::").reverse(),o=l(s,2),c=o[0],u=o[1],d=u?u.split(":").map(V):[],f=c.split(":").map(V),h=t.IPV4ADDRESS.test(f[f.length-1]),p=h?7:8,m=f.length-p,v=Array(p),y=0;y<p;++y)v[y]=d[y]||f[m+y]||"";h&&(v[p-1]=B(v[p-1],t));var g=v.reduce(function(e,t,r){if(!t||"0"===t){var n=e[e.length-1];n&&n.index+n.length===r?n.length++:e.push({index:r,length:1})}return e},[]).sort(function(e,t){return t.length-e.length})[0],w=void 0;if(g&&g.length>1){var b=v.slice(0,g.index),E=v.slice(g.index+g.length);w=b.join(":")+"::"+E.join(":")}else w=v.join(":");return a&&(w+="%"+a),w}return e}var H=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,K=void 0==="".match(/(){0}/)[1];function G(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r={},n=!1!==t.iri?u:c;"suffix"===t.reference&&(e=(t.scheme?t.scheme+":":"")+"//"+e);var i=e.match(H);if(i){K?(r.scheme=i[1],r.userinfo=i[3],r.host=i[4],r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=i[7],r.fragment=i[8],isNaN(r.port)&&(r.port=i[5])):(r.scheme=i[1]||void 0,r.userinfo=-1!==e.indexOf("@")?i[3]:void 0,r.host=-1!==e.indexOf("//")?i[4]:void 0,r.port=parseInt(i[5],10),r.path=i[6]||"",r.query=-1!==e.indexOf("?")?i[7]:void 0,r.fragment=-1!==e.indexOf("#")?i[8]:void 0,isNaN(r.port)&&(r.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?i[4]:void 0)),r.host&&(r.host=J(B(r.host,n),n)),r.reference=void 0!==r.scheme||void 0!==r.userinfo||void 0!==r.host||void 0!==r.port||r.path||void 0!==r.query?void 0===r.scheme?"relative":void 0===r.fragment?"absolute":"uri":"same-document",t.reference&&"suffix"!==t.reference&&t.reference!==r.reference&&(r.error=r.error||"URI is not a "+t.reference+" reference.");var a=z[(t.scheme||r.scheme||"").toLowerCase()];if(t.unicodeSupport||a&&a.unicodeSupport)Z(r,n);else{if(r.host&&(t.domainHost||a&&a.domainHost))try{r.host=q.toASCII(r.host.replace(n.PCT_ENCODED,L).toLowerCase())}catch(e){r.error=r.error||"Host's domain name can not be converted to ASCII via punycode: "+e}Z(r,c)}a&&a.parse&&a.parse(r,t)}else r.error=r.error||"URI can not be parsed.";return r}function Y(e,t){var r=!1!==t.iri?u:c,n=[];return void 0!==e.userinfo&&(n.push(e.userinfo),n.push("@")),void 0!==e.host&&n.push(J(B(String(e.host),r),r).replace(r.IPV6ADDRESS,function(e,t,r){return"["+t+(r?"%25"+r:"")+"]"})),"number"!=typeof e.port&&"string"!=typeof e.port||(n.push(":"),n.push(String(e.port))),n.length?n.join(""):void 0}var W=/^\.\.?\//,Q=/^\/\.(\/|$)/,X=/^\/\.\.(\/|$)/,ee=/^\/?(?:.|\n)*?(?=\/|$)/;function te(e){for(var t=[];e.length;)if(e.match(W))e=e.replace(W,"");else if(e.match(Q))e=e.replace(Q,"/");else if(e.match(X))e=e.replace(X,"/"),t.pop();else if("."===e||".."===e)e="";else{var r=e.match(ee);if(!r)throw new Error("Unexpected dot segment condition");var n=r[0];e=e.slice(n.length),t.push(n)}return t.join("")}function re(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.iri?u:c,n=[],i=z[(t.scheme||e.scheme||"").toLowerCase()];if(i&&i.serialize&&i.serialize(e,t),e.host)if(r.IPV6ADDRESS.test(e.host));else if(t.domainHost||i&&i.domainHost)try{e.host=t.iri?q.toUnicode(e.host):q.toASCII(e.host.replace(r.PCT_ENCODED,L).toLowerCase())}catch(r){e.error=e.error||"Host's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+r}Z(e,r),"suffix"!==t.reference&&e.scheme&&(n.push(e.scheme),n.push(":"));var a=Y(e,t);if(void 0!==a&&("suffix"!==t.reference&&n.push("//"),n.push(a),e.path&&"/"!==e.path.charAt(0)&&n.push("/")),void 0!==e.path){var s=e.path;t.absolutePath||i&&i.absolutePath||(s=te(s)),void 0===a&&(s=s.replace(/^\/\//,"/%2F")),n.push(s)}return void 0!==e.query&&(n.push("?"),n.push(e.query)),void 0!==e.fragment&&(n.push("#"),n.push(e.fragment)),n.join("")}function ne(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={};return arguments[3]||(e=G(re(e,r),r),t=G(re(t,r),r)),!(r=r||{}).tolerant&&t.scheme?(n.scheme=t.scheme,n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=te(t.path||""),n.query=t.query):(void 0!==t.userinfo||void 0!==t.host||void 0!==t.port?(n.userinfo=t.userinfo,n.host=t.host,n.port=t.port,n.path=te(t.path||""),n.query=t.query):(t.path?("/"===t.path.charAt(0)?n.path=te(t.path):(n.path=void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:t.path:"/"+t.path,n.path=te(n.path)),n.query=t.query):(n.path=e.path,n.query=void 0!==t.query?t.query:e.query),n.userinfo=e.userinfo,n.host=e.host,n.port=e.port),n.scheme=e.scheme),n.fragment=t.fragment,n}function ie(e,t,r){var n=s({scheme:"null"},r);return re(ne(G(e,n),G(t,n),n,!0),n)}function ae(e,t){return"string"==typeof e?e=re(G(e,t),t):"object"===n(e)&&(e=G(re(e,t),t)),e}function se(e,t,r){return"string"==typeof e?e=re(G(e,r),r):"object"===n(e)&&(e=re(e,r)),"string"==typeof t?t=re(G(t,r),r):"object"===n(t)&&(t=re(t,r)),e===t}function oe(e,t){return e&&e.toString().replace(t&&t.iri?u.ESCAPE:c.ESCAPE,U)}function ce(e,t){return e&&e.toString().replace(t&&t.iri?u.PCT_ENCODED:c.PCT_ENCODED,L)}var ue={scheme:"http",domainHost:!0,parse:function(e,t){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e},serialize:function(e,t){var r="https"===String(e.scheme).toLowerCase();return e.port!==(r?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}},le={scheme:"https",domainHost:ue.domainHost,parse:ue.parse,serialize:ue.serialize};function de(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}var fe={scheme:"ws",domainHost:!0,parse:function(e,t){var r=e;return r.secure=de(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r},serialize:function(e,t){if(e.port!==(de(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){var r=e.resourceName.split("?"),n=l(r,2),i=n[0],a=n[1];e.path=i&&"/"!==i?i:void 0,e.query=a,e.resourceName=void 0}return e.fragment=void 0,e}},he={scheme:"wss",domainHost:fe.domainHost,parse:fe.parse,serialize:fe.serialize},pe={},me="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",ve="[0-9A-Fa-f]",ye=r(r("%[EFef]"+ve+"%"+ve+ve+"%"+ve+ve)+"|"+r("%[89A-Fa-f]"+ve+"%"+ve+ve)+"|"+r("%"+ve+ve)),ge="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",we=t("[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",'[\\"\\\\]'),be="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",Ee=new RegExp(me,"g"),xe=new RegExp(ye,"g"),$e=new RegExp(t("[^]",ge,"[\\.]",'[\\"]',we),"g"),Pe=new RegExp(t("[^]",me,be),"g"),_e=Pe;function Se(e){var t=L(e);return t.match(Ee)?t:e}var Fe={scheme:"mailto",parse:function(e,t){var r=e,n=r.to=r.path?r.path.split(","):[];if(r.path=void 0,r.query){for(var i=!1,a={},s=r.query.split("&"),o=0,c=s.length;o<c;++o){var u=s[o].split("=");switch(u[0]){case"to":for(var l=u[1].split(","),d=0,f=l.length;d<f;++d)n.push(l[d]);break;case"subject":r.subject=ce(u[1],t);break;case"body":r.body=ce(u[1],t);break;default:i=!0,a[ce(u[0],t)]=ce(u[1],t)}}i&&(r.headers=a)}r.query=void 0;for(var h=0,p=n.length;h<p;++h){var m=n[h].split("@");if(m[0]=ce(m[0]),t.unicodeSupport)m[1]=ce(m[1],t).toLowerCase();else try{m[1]=q.toASCII(ce(m[1],t).toLowerCase())}catch(e){r.error=r.error||"Email address's domain name can not be converted to ASCII via punycode: "+e}n[h]=m.join("@")}return r},serialize:function(e,t){var r=e,n=a(e.to);if(n){for(var s=0,o=n.length;s<o;++s){var c=String(n[s]),u=c.lastIndexOf("@"),l=c.slice(0,u).replace(xe,Se).replace(xe,i).replace($e,U),d=c.slice(u+1);try{d=t.iri?q.toUnicode(d):q.toASCII(ce(d,t).toLowerCase())}catch(e){r.error=r.error||"Email address's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+e}n[s]=l+"@"+d}r.path=n.join(",")}var f=e.headers=e.headers||{};e.subject&&(f.subject=e.subject),e.body&&(f.body=e.body);var h=[];for(var p in f)f[p]!==pe[p]&&h.push(p.replace(xe,Se).replace(xe,i).replace(Pe,U)+"="+f[p].replace(xe,Se).replace(xe,i).replace(_e,U));return h.length&&(r.query=h.join("&")),r}},ke=/^([^\:]+)\:(.*)/,Ae={scheme:"urn",parse:function(e,t){var r=e.path&&e.path.match(ke),n=e;if(r){var i=t.scheme||n.scheme||"urn",a=r[1].toLowerCase(),s=r[2],o=z[i+":"+(t.nid||a)];n.nid=a,n.nss=s,n.path=void 0,o&&(n=o.parse(n,t))}else n.error=n.error||"URN can not be parsed.";return n},serialize:function(e,t){var r=e.nid,n=z[(t.scheme||e.scheme||"urn")+":"+(t.nid||r)];n&&(e=n.serialize(e,t));var i=e;return i.path=(r||t.nid)+":"+e.nss,i}},je=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,Oe={scheme:"urn:uuid",parse:function(e,t){var r=e;return r.uuid=r.nss,r.nss=void 0,t.tolerant||r.uuid&&r.uuid.match(je)||(r.error=r.error||"UUID is not valid."),r},serialize:function(e,t){var r=e;return r.nss=(e.uuid||"").toLowerCase(),r}};z[ue.scheme]=ue,z[le.scheme]=le,z[fe.scheme]=fe,z[he.scheme]=he,z[Fe.scheme]=Fe,z[Ae.scheme]=Ae,z[Oe.scheme]=Oe,e.SCHEMES=z,e.pctEncChar=U,e.pctDecChars=L,e.parse=G,e.removeDotSegments=te,e.serialize=re,e.resolveComponents=ne,e.resolve=ie,e.normalize=ae,e.equal=se,e.escapeComponent=oe,e.unescapeComponent=ce,Object.defineProperty(e,"le",{value:!0})}(Hr.exports);var Kr=Hr.exports,Gr=function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){if(t.constructor!==r.constructor)return!1;var n,i,a;if(Array.isArray(t)){if((n=t.length)!=r.length)return!1;for(i=n;0!==i--;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if((n=(a=Object.keys(t)).length)!==Object.keys(r).length)return!1;for(i=n;0!==i--;)if(!Object.prototype.hasOwnProperty.call(r,a[i]))return!1;for(i=n;0!==i--;){var s=a[i];if(!e(t[s],r[s]))return!1}return!0}return t!=t&&r!=r},Yr={copy:function(e,t){for(var r in t=t||{},e)t[r]=e[r];return t},checkDataType:Wr,checkDataTypes:function(e,t,r){if(1===e.length)return Wr(e[0],t,r,!0);var n="",i=Xr(e);for(var a in i.array&&i.object&&(n=i.null?"(":"(!"+t+" || ",n+="typeof "+t+' !== "object")',delete i.null,delete i.array,delete i.object),i.number&&delete i.integer,i)n+=(n?" && ":"")+Wr(a,t,r,!0);return n},coerceToTypes:function(e,t){if(Array.isArray(t)){for(var r=[],n=0;n<t.length;n++){var i=t[n];(Qr[i]||"array"===e&&"array"===i)&&(r[r.length]=i)}if(r.length)return r}else{if(Qr[t])return[t];if("array"===e&&"array"===t)return["array"]}},toHash:Xr,getProperty:rn,escapeQuotes:nn,equal:Gr,ucs2length:function(e){for(var t,r=0,n=e.length,i=0;i<n;)r++,(t=e.charCodeAt(i++))>=55296&&t<=56319&&i<n&&56320==(64512&(t=e.charCodeAt(i)))&&i++;return r},varOccurences:function(e,t){var r=e.match(new RegExp(t+="[^0-9]","g"));return r?r.length:0},varReplace:function(e,t,r){return t+="([^0-9])",r=r.replace(/\$/g,"$$$$"),e.replace(new RegExp(t,"g"),r+"$1")},schemaHasRules:function(e,t){if("boolean"==typeof e)return!e;for(var r in e)if(t[r])return!0},schemaHasRulesExcept:function(e,t,r){if("boolean"==typeof e)return!e&&"not"!=r;for(var n in e)if(n!=r&&t[n])return!0},schemaUnknownRules:function(e,t){if("boolean"==typeof e)return;for(var r in e)if(!t[r])return r},toQuotedString:an,getPathExpr:function(e,t,r,n){var i=r?"'/' + "+t+(n?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):n?"'[' + "+t+" + ']'":"'[\\'' + "+t+" + '\\']'";return cn(e,i)},getPath:function(e,t,r){var n=an(r?"/"+un(t):rn(t));return cn(e,n)},getData:function(e,t,r){var n,i,a,s;if(""===e)return"rootData";if("/"==e[0]){if(!sn.test(e))throw new Error("Invalid JSON-pointer: "+e);i=e,a="rootData"}else{if(!(s=e.match(on)))throw new Error("Invalid JSON-pointer: "+e);if(n=+s[1],"#"==(i=s[2])){if(n>=t)throw new Error("Cannot access property/index "+n+" levels up, current level is "+t);return r[t-n]}if(n>t)throw new Error("Cannot access data "+n+" levels up, current level is "+t);if(a="data"+(t-n||""),!i)return a}for(var o=a,c=i.split("/"),u=0;u<c.length;u++){var l=c[u];l&&(o+=" && "+(a+=rn(ln(l))))}return o},unescapeFragment:function(e){return ln(decodeURIComponent(e))},unescapeJsonPointer:ln,escapeFragment:function(e){return encodeURIComponent(un(e))},escapeJsonPointer:un};function Wr(e,t,r,n){var i=n?" !== ":" === ",a=n?" || ":" && ",s=n?"!":"",o=n?"":"!";switch(e){case"null":return t+i+"null";case"array":return s+"Array.isArray("+t+")";case"object":return"("+s+t+a+"typeof "+t+i+'"object"'+a+o+"Array.isArray("+t+"))";case"integer":return"(typeof "+t+i+'"number"'+a+o+"("+t+" % 1)"+a+t+i+t+(r?a+s+"isFinite("+t+")":"")+")";case"number":return"(typeof "+t+i+'"'+e+'"'+(r?a+s+"isFinite("+t+")":"")+")";default:return"typeof "+t+i+'"'+e+'"'}}var Qr=Xr(["string","number","integer","boolean","null"]);function Xr(e){for(var t={},r=0;r<e.length;r++)t[e[r]]=!0;return t}var en=/^[a-z$_][a-z$_0-9]*$/i,tn=/'|\\/g;function rn(e){return"number"==typeof e?"["+e+"]":en.test(e)?"."+e:"['"+nn(e)+"']"}function nn(e){return e.replace(tn,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function an(e){return"'"+nn(e)+"'"}var sn=/^\/(?:[^~]|~0|~1)*$/,on=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function cn(e,t){return'""'==e?t:(e+" + "+t).replace(/([^\\])' \+ '/g,"$1")}function un(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ln(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}var dn=Yr,fn=function(e){dn.copy(e,this)};var hn={exports:{}},pn=hn.exports=function(e,t,r){"function"==typeof t&&(r=t,t={}),mn(t,"function"==typeof(r=t.cb||r)?r:r.pre||function(){},r.post||function(){},e,"",e)};function mn(e,t,r,n,i,a,s,o,c,u){if(n&&"object"==typeof n&&!Array.isArray(n)){for(var l in t(n,i,a,s,o,c,u),n){var d=n[l];if(Array.isArray(d)){if(l in pn.arrayKeywords)for(var f=0;f<d.length;f++)mn(e,t,r,d[f],i+"/"+l+"/"+f,a,i,l,n,f)}else if(l in pn.propsKeywords){if(d&&"object"==typeof d)for(var h in d)mn(e,t,r,d[h],i+"/"+l+"/"+vn(h),a,i,l,n,h)}else(l in pn.keywords||e.allKeys&&!(l in pn.skipKeywords))&&mn(e,t,r,d,i+"/"+l,a,i,l,n)}r(n,i,a,s,o,c,u)}}function vn(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}pn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},pn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},pn.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},pn.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};var yn=Kr,gn=Gr,wn=Yr,bn=fn,En=hn.exports,xn=$n;function $n(e,t,r){var n=this.de[r];if("string"==typeof n){if(!this.de[n])return $n.call(this,e,t,n);n=this.de[n]}if((n=n||this.fe[r])instanceof bn)return An(n.schema,this.he.inlineRefs)?n.schema:n.validate||this.pe(n);var i,a,s,o=Pn.call(this,t,r);return o&&(i=o.schema,t=o.root,s=o.baseId),i instanceof bn?a=i.validate||e.call(this,i.schema,t,void 0,s):void 0!==i&&(a=An(i,this.he.inlineRefs)?i:e.call(this,i,t,void 0,s)),a}function Pn(e,t){var r=yn.parse(t),n=Nn(r),i=In(this.me(e.schema));if(0===Object.keys(e.schema).length||n!==i){var a=Tn(n),s=this.de[a];if("string"==typeof s)return _n.call(this,e,s,r);if(s instanceof bn)s.validate||this.pe(s),e=s;else{if(!((s=this.fe[a])instanceof bn))return;if(s.validate||this.pe(s),a==Tn(t))return{schema:s,root:e,baseId:i};e=s}if(!e.schema)return;i=In(this.me(e.schema))}return Fn.call(this,r,i,e.schema,e)}function _n(e,t,r){var n=Pn.call(this,e,t);if(n){var i=n.schema,a=n.baseId;e=n.root;var s=this.me(i);return s&&(a=Cn(a,s)),Fn.call(this,r,a,i,e)}}$n.normalizeId=Tn,$n.fullPath=In,$n.url=Cn,$n.ids=function(e){var t=Tn(this.me(e)),r={"":t},n={"":In(t,!1)},i={},a=this;return En(e,{allKeys:!0},function(e,t,s,o,c,u,l){if(""!==t){var d=a.me(e),f=r[o],h=n[o]+"/"+c;if(void 0!==l&&(h+="/"+("number"==typeof l?l:wn.escapeFragment(l))),"string"==typeof d){d=f=Tn(f?yn.resolve(f,d):d);var p=a.de[d];if("string"==typeof p&&(p=a.de[p]),p&&p.schema){if(!gn(e,p.schema))throw new Error('id "'+d+'" resolves to more than one schema')}else if(d!=Tn(h))if("#"==d[0]){if(i[d]&&!gn(e,i[d]))throw new Error('id "'+d+'" resolves to more than one schema');i[d]=e}else a.de[d]=h}r[t]=f,n[t]=h}}),i},$n.inlineRef=An,$n.schema=Pn;var Sn=wn.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function Fn(e,t,r,n){if(e.fragment=e.fragment||"","/"==e.fragment.slice(0,1)){for(var i=e.fragment.split("/"),a=1;a<i.length;a++){var s=i[a];if(s){if(void 0===(r=r[s=wn.unescapeFragment(s)]))break;var o;if(!Sn[s]&&((o=this.me(r))&&(t=Cn(t,o)),r.$ref)){var c=Cn(t,r.$ref),u=Pn.call(this,n,c);u&&(r=u.schema,n=u.root,t=u.baseId)}}}return void 0!==r&&r!==n.schema?{schema:r,root:n,baseId:t}:void 0}}var kn=wn.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function An(e,t){return!1!==t&&(void 0===t||!0===t?jn(e):t?On(e)<=t:void 0)}function jn(e){var t;if(Array.isArray(e)){for(var r=0;r<e.length;r++)if("object"==typeof(t=e[r])&&!jn(t))return!1}else for(var n in e){if("$ref"==n)return!1;if("object"==typeof(t=e[n])&&!jn(t))return!1}return!0}function On(e){var t,r=0;if(Array.isArray(e)){for(var n=0;n<e.length;n++)if("object"==typeof(t=e[n])&&(r+=On(t)),r==1/0)return 1/0}else for(var i in e){if("$ref"==i)return 1/0;if(kn[i])r++;else if("object"==typeof(t=e[i])&&(r+=On(t)+1),r==1/0)return 1/0}return r}function In(e,t){return!1!==t&&(e=Tn(e)),Nn(yn.parse(e))}function Nn(e){return yn.serialize(e).split("#")[0]+"#"}var Dn=/#\/?$/;function Tn(e){return e?e.replace(Dn,""):""}function Cn(e,t){return t=Tn(t),yn.resolve(e,t)}var Rn=xn,Mn={Validation:zn(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:zn(qn)};function qn(e,t,r){this.message=r||qn.message(e,t),this.missingRef=Rn.url(e,t),this.missingSchema=Rn.normalizeId(Rn.fullPath(this.missingRef))}function zn(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e,e}qn.message=function(e,t){return"can't resolve reference "+t+" from id "+e};var Un=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var r,n="boolean"==typeof t.cycles&&t.cycles,i=t.cmp&&(r=t.cmp,function(e){return function(t,n){return r({key:t,value:e[t]},{key:n,value:e[n]})}}),a=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var r,s;if(Array.isArray(t)){for(s="[",r=0;r<t.length;r++)r&&(s+=","),s+=e(t[r])||"null";return s+"]"}if(null===t)return"null";if(-1!==a.indexOf(t)){if(n)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var o=a.push(t)-1,c=Object.keys(t).sort(i&&i(t));for(s="",r=0;r<c.length;r++){var u=c[r],l=e(t[u]);l&&(s&&(s+=","),s+=JSON.stringify(u)+":"+l)}return a.splice(o,1),"{"+s+"}"}}(e)},Ln=function(e,t,r){var n="",i=!0===e.schema.$async,a=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),s=e.self.me(e.schema);if(e.opts.strictKeywords){var o=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(o){var c="unknown keyword: "+o;if("log"!==e.opts.strictKeywords)throw new Error(c);e.logger.warn(c)}}if(e.isTop&&(n+=" var validate = ",i&&(e.async=!0,n+="async "),n+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",s&&(e.opts.sourceCode||e.opts.processCode)&&(n+=" /*# sourceURL="+s+" */ ")),"boolean"==typeof e.schema||!a&&!e.schema.$ref){var u=e.level,l=e.dataLevel,d=e.schema[t="false schema"],f=e.schemaPath+e.util.getProperty(t),h=e.errSchemaPath+"/"+t,p=!e.opts.allErrors,m="data"+(l||""),v="valid"+u;if(!1===e.schema){e.isTop?p=!0:n+=" var "+v+" = false; ",(G=G||[]).push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: {} ",!1!==e.opts.messages&&(n+=" , message: 'boolean schema is false' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),n+=" } "):n+=" {} ";var y=n;n=G.pop(),n+=!e.compositeRule&&p?e.async?" throw new ValidationError(["+y+"]); ":" validate.errors = ["+y+"]; return false; ":" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else n+=e.isTop?i?" return data; ":" validate.errors = null; return true; ":" var "+v+" = true; ";return e.isTop&&(n+=" }; return validate; "),n}if(e.isTop){var g=e.isTop;u=e.level=0,l=e.dataLevel=0,m="data";if(e.rootId=e.resolve.fullPath(e.self.me(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],void 0!==e.schema.default&&e.opts.useDefaults&&e.opts.strictDefaults){var w="default is ignored in the schema root";if("log"!==e.opts.strictDefaults)throw new Error(w);e.logger.warn(w)}n+=" var vErrors = null; ",n+=" var errors = 0; ",n+=" if (rootData === undefined) rootData = data; "}else{u=e.level,m="data"+((l=e.dataLevel)||"");if(s&&(e.baseId=e.resolve.url(e.baseId,s)),i&&!e.async)throw new Error("async schema in sync schema");n+=" var errs_"+u+" = errors;"}v="valid"+u,p=!e.opts.allErrors;var b="",E="",x=e.schema.type,$=Array.isArray(x);if(x&&e.opts.nullable&&!0===e.schema.nullable&&($?-1==x.indexOf("null")&&(x=x.concat("null")):"null"!=x&&(x=[x,"null"],$=!0)),$&&1==x.length&&(x=x[0],$=!1),e.schema.$ref&&a){if("fail"==e.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');!0!==e.opts.extendRefs&&(a=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(n+=" "+e.RULES.all.$comment.code(e,"$comment")),x){if(e.opts.coerceTypes)var P=e.util.coerceToTypes(e.opts.coerceTypes,x);var _=e.RULES.types[x];if(P||$||!0===_||_&&!Y(_)){f=e.schemaPath+".type",h=e.errSchemaPath+"/type",f=e.schemaPath+".type",h=e.errSchemaPath+"/type";if(n+=" if ("+e.util[$?"checkDataTypes":"checkDataType"](x,m,e.opts.strictNumbers,!0)+") { ",P){var S="dataType"+u,F="coerced"+u;n+=" var "+S+" = typeof "+m+"; var "+F+" = undefined; ","array"==e.opts.coerceTypes&&(n+=" if ("+S+" == 'object' && Array.isArray("+m+") && "+m+".length == 1) { "+m+" = "+m+"[0]; "+S+" = typeof "+m+"; if ("+e.util.checkDataType(e.schema.type,m,e.opts.strictNumbers)+") "+F+" = "+m+"; } "),n+=" if ("+F+" !== undefined) ; ";var k=P;if(k)for(var A,j=-1,O=k.length-1;j<O;)"string"==(A=k[j+=1])?n+=" else if ("+S+" == 'number' || "+S+" == 'boolean') "+F+" = '' + "+m+"; else if ("+m+" === null) "+F+" = ''; ":"number"==A||"integer"==A?(n+=" else if ("+S+" == 'boolean' || "+m+" === null || ("+S+" == 'string' && "+m+" && "+m+" == +"+m+" ","integer"==A&&(n+=" && !("+m+" % 1)"),n+=")) "+F+" = +"+m+"; "):"boolean"==A?n+=" else if ("+m+" === 'false' || "+m+" === 0 || "+m+" === null) "+F+" = false; else if ("+m+" === 'true' || "+m+" === 1) "+F+" = true; ":"null"==A?n+=" else if ("+m+" === '' || "+m+" === 0 || "+m+" === false) "+F+" = null; ":"array"==e.opts.coerceTypes&&"array"==A&&(n+=" else if ("+S+" == 'string' || "+S+" == 'number' || "+S+" == 'boolean' || "+m+" == null) "+F+" = ["+m+"]; ");(G=G||[]).push(n+=" else { "),n="",!1!==e.createErrors?(n+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",n+=$?""+x.join(","):""+x,n+="' } ",!1!==e.opts.messages&&(n+=" , message: 'should be ",n+=$?""+x.join(","):""+x,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),n+=" } "):n+=" {} ";y=n;n=G.pop(),n+=!e.compositeRule&&p?e.async?" throw new ValidationError(["+y+"]); ":" validate.errors = ["+y+"]; return false; ":" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } if ("+F+" !== undefined) { ";var I=l?"data"+(l-1||""):"parentData";n+=" "+m+" = "+F+"; ",l||(n+="if ("+I+" !== undefined)"),n+=" "+I+"["+(l?e.dataPathArr[l]:"parentDataProperty")+"] = "+F+"; } "}else{(G=G||[]).push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",n+=$?""+x.join(","):""+x,n+="' } ",!1!==e.opts.messages&&(n+=" , message: 'should be ",n+=$?""+x.join(","):""+x,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),n+=" } "):n+=" {} ";y=n;n=G.pop(),n+=!e.compositeRule&&p?e.async?" throw new ValidationError(["+y+"]); ":" validate.errors = ["+y+"]; return false; ":" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}n+=" } "}}if(e.schema.$ref&&!a)n+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",p&&(n+=" } if (errors === ",n+=g?"0":"errs_"+u,n+=") { ",E+="}");else{var N=e.RULES;if(N)for(var D=-1,T=N.length-1;D<T;)if(Y(_=N[D+=1])){if(_.type&&(n+=" if ("+e.util.checkDataType(_.type,m,e.opts.strictNumbers)+") { "),e.opts.useDefaults)if("object"==_.type&&e.schema.properties){d=e.schema.properties;var C=Object.keys(d);if(C)for(var R,M=-1,q=C.length-1;M<q;){if(void 0!==(L=d[R=C[M+=1]]).default){var z=m+e.util.getProperty(R);if(e.compositeRule){if(e.opts.strictDefaults){w="default is ignored for: "+z;if("log"!==e.opts.strictDefaults)throw new Error(w);e.logger.warn(w)}}else n+=" if ("+z+" === undefined ","empty"==e.opts.useDefaults&&(n+=" || "+z+" === null || "+z+" === '' "),n+=" ) "+z+" = ",n+="shared"==e.opts.useDefaults?" "+e.useDefault(L.default)+" ":" "+JSON.stringify(L.default)+" ",n+="; "}}}else if("array"==_.type&&Array.isArray(e.schema.items)){var U=e.schema.items;if(U){j=-1;for(var L,Z=U.length-1;j<Z;)if(void 0!==(L=U[j+=1]).default){z=m+"["+j+"]";if(e.compositeRule){if(e.opts.strictDefaults){w="default is ignored for: "+z;if("log"!==e.opts.strictDefaults)throw new Error(w);e.logger.warn(w)}}else n+=" if ("+z+" === undefined ","empty"==e.opts.useDefaults&&(n+=" || "+z+" === null || "+z+" === '' "),n+=" ) "+z+" = ",n+="shared"==e.opts.useDefaults?" "+e.useDefault(L.default)+" ":" "+JSON.stringify(L.default)+" ",n+="; "}}}var V=_.rules;if(V)for(var B,J=-1,H=V.length-1;J<H;)if(W(B=V[J+=1])){var K=B.code(e,B.keyword,_.type);K&&(n+=" "+K+" ",p&&(b+="}"))}if(p&&(n+=" "+b+" ",b=""),_.type&&(n+=" } ",x&&x===_.type&&!P)){var G;f=e.schemaPath+".type",h=e.errSchemaPath+"/type";(G=G||[]).push(n+=" else { "),n="",!1!==e.createErrors?(n+=" { keyword: 'type' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",n+=$?""+x.join(","):""+x,n+="' } ",!1!==e.opts.messages&&(n+=" , message: 'should be ",n+=$?""+x.join(","):""+x,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),n+=" } "):n+=" {} ";y=n;n=G.pop(),n+=!e.compositeRule&&p?e.async?" throw new ValidationError(["+y+"]); ":" validate.errors = ["+y+"]; return false; ":" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } "}p&&(n+=" if (errors === ",n+=g?"0":"errs_"+u,n+=") { ",E+="}")}}function Y(e){for(var t=e.rules,r=0;r<t.length;r++)if(W(t[r]))return!0}function W(t){return void 0!==e.schema[t.keyword]||t.implements&&function(t){for(var r=t.implements,n=0;n<r.length;n++)if(void 0!==e.schema[r[n]])return!0}(t)}return p&&(n+=" "+E+" "),g?(i?(n+=" if (errors === 0) return data; ",n+=" else throw new ValidationError(vErrors); "):(n+=" validate.errors = vErrors; ",n+=" return errors === 0; "),n+=" }; return validate;"):n+=" var "+v+" = errors === errs_"+u+";",n},Zn=xn,Vn=Yr,Bn=Mn,Jn=Un,Hn=Ln,Kn=Vn.ucs2length,Gn=Gr,Yn=Bn.Validation,Wn=function e(t,r,n,i){var a=this,s=this.he,o=[void 0],c={},u=[],l={},d=[],f={},h=[];function p(e,t){return"var pattern"+e+" = "+(s.regExp?"regExp":"new RegExp")+"("+Vn.toQuotedString(t[e])+");"}var m=Qn.call(this,t,r=r||{schema:t,refVal:o,refs:c},i),v=this.ve[m.index];if(m.compiling)return v.callValidate=function e(){var t=v.validate,r=t.apply(this,arguments);return e.errors=t.errors,r};var y=this.ye,g=this.RULES;try{var w=E(t,r,n,i);v.validate=w;var b=v.callValidate;return b&&(b.schema=w.schema,b.errors=null,b.refs=w.refs,b.refVal=w.refVal,b.root=w.root,b.$async=w.$async,s.sourceCode&&(b.source=w.source)),w}finally{Xn.call(this,t,r,i)}function E(t,n,i,l){var f=!n||n&&n.schema==t;if(n.schema!=r.schema)return e.call(a,t,n,i,l);var m,v=!0===t.$async,w=Hn({isTop:!0,schema:t,isRoot:f,baseId:l,root:n,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:Bn.MissingRef,RULES:g,validate:Hn,util:Vn,resolve:Zn,resolveRef:x,usePattern:_,useDefault:S,useCustomRule:F,opts:s,formats:y,logger:a.logger,self:a});w=ii(o,ri)+ii(u,p)+ii(d,ti)+ii(h,ni)+w,s.processCode&&(w=s.processCode(w,t));try{m=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError","regExp",w)(a,g,y,r,o,d,h,Gn,Kn,Yn,s.regExp),o[0]=m}catch(e){throw a.logger.error("Error compiling schema, function code:",w),e}return m.schema=t,m.errors=null,m.refs=c,m.refVal=o,m.root=f?m:n,v&&(m.$async=!0),!0===s.sourceCode&&(m.source={code:w,patterns:u,defaults:d}),m}function x(t,i,u){i=Zn.url(t,i);var l,d,f=c[i];if(void 0!==f)return P(l=o[f],d="refVal["+f+"]");if(!u&&r.refs){var h=r.refs[i];if(void 0!==h)return P(l=r.refVal[h],d=$(i,l))}d=$(i);var p=Zn.call(a,E,r,i);if(void 0===p){var m=n&&n[i];m&&(p=Zn.inlineRef(m,s.inlineRefs)?m:e.call(a,m,r,n,t))}if(void 0!==p)return function(e,t){var r=c[e];o[r]=t}(i,p),P(p,d);!function(e){delete c[e]}(i)}function $(e,t){var r=o.length;return o[r]=t,c[e]=r,"refVal"+r}function P(e,t){return"object"==typeof e||"boolean"==typeof e?{code:t,schema:e,inline:!0}:{code:t,$async:e&&!!e.$async}}function _(e){var t=l[e];return void 0===t&&(t=l[e]=u.length,u[t]=e),"pattern"+t}function S(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return Vn.toQuotedString(e);case"object":if(null===e)return"null";var t=Jn(e),r=f[t];return void 0===r&&(r=f[t]=d.length,d[r]=e),"default"+r}}function F(e,t,r,n){if(!1!==a.he.validateSchema){var i=e.definition.dependencies;if(i&&!i.every(function(e){return Object.prototype.hasOwnProperty.call(r,e)}))throw new Error("parent schema must have all required keywords: "+i.join(","));var o=e.definition.validateSchema;if(o)if(!o(t)){var c="keyword schema is invalid: "+a.errorsText(o.errors);if("log"!=a.he.validateSchema)throw new Error(c);a.logger.error(c)}}var u,l=e.definition.compile,d=e.definition.inline,f=e.definition.macro;if(l)u=l.call(a,t,r,n);else if(f)u=f.call(a,t,r,n),!1!==s.validateSchema&&a.validateSchema(u,!0);else if(d)u=d.call(a,n,e.keyword,t,r);else if(!(u=e.definition.validate))return;if(void 0===u)throw new Error('custom keyword "'+e.keyword+'"failed to compile');var p=h.length;return h[p]=u,{code:"customRule"+p,validate:u}}};function Qn(e,t,r){var n=ei.call(this,e,t,r);return n>=0?{index:n,compiling:!0}:(this.ve[n=this.ve.length]={schema:e,root:t,baseId:r},{index:n,compiling:!1})}function Xn(e,t,r){var n=ei.call(this,e,t,r);n>=0&&this.ve.splice(n,1)}function ei(e,t,r){for(var n=0;n<this.ve.length;n++){var i=this.ve[n];if(i.schema==e&&i.root==t&&i.baseId==r)return n}return-1}function ti(e){return"var default"+e+" = defaults["+e+"];"}function ri(e,t){return void 0===t[e]?"":"var refVal"+e+" = refVal["+e+"];"}function ni(e){return"var customRule"+e+" = customRules["+e+"];"}function ii(e,t){if(!e.length)return"";for(var r="",n=0;n<e.length;n++)r+=t(n,e);return r}var ai={exports:{}},si=ai.exports=function(){this.T={}};si.prototype.put=function(e,t){this.T[e]=t},si.prototype.get=function(e){return this.T[e]},si.prototype.del=function(e){delete this.T[e]},si.prototype.clear=function(){this.T={}};var oi=ai.exports,ci=Yr,ui=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,li=[0,31,28,31,30,31,30,31,31,30,31,30,31],di=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,fi=/^(?=.{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,hi=/^(?:[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,pi=/^(?:(?:[^\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,mi=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,vi=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,yi=/^(?:\/(?:[^~/]|~0|~1)*)*$/,gi=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,wi=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,bi=Ei;function Ei(e){return ci.copy(Ei[e="full"==e?"full":"fast"])}function xi(e){var t=e.match(ui);if(!t)return!1;var r=+t[2],n=+t[3];return r>=1&&r<=12&&n>=1&&n<=(2==r&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(+t[1])?29:li[r])}function $i(e,t){var r=e.match(di);if(!r)return!1;var n=r[1],i=r[2],a=r[3];return(n<=23&&i<=59&&a<=59||23==n&&59==i&&60==a)&&(!t||r[5])}Ei.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\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,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":pi,url:mi,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,hostname:fi,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:Fi,uuid:vi,"json-pointer":yi,"json-pointer-uri-fragment":gi,"relative-json-pointer":wi},Ei.full={date:xi,time:$i,"date-time":function(e){var t=e.split(Pi);return 2==t.length&&xi(t[0])&&$i(t[1],!0)},uri:function(e){return _i.test(e)&&hi.test(e)},"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":pi,url:mi,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:fi,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:Fi,uuid:vi,"json-pointer":yi,"json-pointer-uri-fragment":gi,"relative-json-pointer":wi};var Pi=/t|\s/i;var _i=/\/|:/;var Si=/[^\\]\\Z/;function Fi(e){if(Si.test(e))return!1;try{return!0}catch(e){return!1}}var ki=function(e,t,r){var n,i=" ",a=e.level,s=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(s||""),f=e.opts.$data&&o&&o.$data;f?(i+=" var schema"+a+" = "+e.util.getData(o.$data,s,e.dataPathArr)+"; ",n="schema"+a):n=o;var h="maximum"==t,p=h?"exclusiveMaximum":"exclusiveMinimum",m=e.schema[p],v=e.opts.$data&&m&&m.$data,y=h?"<":">",g=h?">":"<",w=void 0;if(!f&&"number"!=typeof o&&void 0!==o)throw new Error(t+" must be number");if(!v&&void 0!==m&&"number"!=typeof m&&"boolean"!=typeof m)throw new Error(p+" must be number or boolean");if(v){var b=e.util.getData(m.$data,s,e.dataPathArr),E="exclusive"+a,x="exclType"+a,$="exclIsNumber"+a,P="' + "+(F="op"+a)+" + '";i+=" var schemaExcl"+a+" = "+b+"; ";var _;w=p;(_=_||[]).push(i+=" var "+E+"; var "+x+" = typeof "+(b="schemaExcl"+a)+"; if ("+x+" != 'boolean' && "+x+" != 'undefined' && "+x+" != 'number') { "),i="",!1!==e.createErrors?(i+=" { keyword: '"+(w||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",!1!==e.opts.messages&&(i+=" , message: '"+p+" should be boolean' "),e.opts.verbose&&(i+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var S=i;i=_.pop(),i+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+S+"]); ":" validate.errors = ["+S+"]; return false; ":" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } else if ( ",f&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),i+=" "+x+" == 'number' ? ( ("+E+" = "+n+" === undefined || "+b+" "+y+"= "+n+") ? "+d+" "+g+"= "+b+" : "+d+" "+g+" "+n+" ) : ( ("+E+" = "+b+" === true) ? "+d+" "+g+"= "+n+" : "+d+" "+g+" "+n+" ) || "+d+" !== "+d+") { var op"+a+" = "+E+" ? '"+y+"' : '"+y+"='; ",void 0===o&&(w=p,u=e.errSchemaPath+"/"+p,n=b,f=v)}else{P=y;if(($="number"==typeof m)&&f){var F="'"+P+"'";i+=" if ( ",f&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),i+=" ( "+n+" === undefined || "+m+" "+y+"= "+n+" ? "+d+" "+g+"= "+m+" : "+d+" "+g+" "+n+" ) || "+d+" !== "+d+") { "}else{$&&void 0===o?(E=!0,w=p,u=e.errSchemaPath+"/"+p,n=m,g+="="):($&&(n=Math[h?"min":"max"](m,o)),m===(!$||n)?(E=!0,w=p,u=e.errSchemaPath+"/"+p,g+="="):(E=!1,P+="="));F="'"+P+"'";i+=" if ( ",f&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),i+=" "+d+" "+g+" "+n+" || "+d+" !== "+d+") { "}}w=w||t,(_=_||[]).push(i),i="",!1!==e.createErrors?(i+=" { keyword: '"+(w||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { comparison: "+F+", limit: "+n+", exclusive: "+E+" } ",!1!==e.opts.messages&&(i+=" , message: 'should be "+P+" ",i+=f?"' + "+n:n+"'"),e.opts.verbose&&(i+=" , schema: ",i+=f?"validate.schema"+c:""+o,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";S=i;return i=_.pop(),i+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+S+"]); ":" validate.errors = ["+S+"]; return false; ":" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",l&&(i+=" else { "),i},Ai=function(e,t,r){var n,i=" ",a=e.level,s=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(s||""),f=e.opts.$data&&o&&o.$data;if(f?(i+=" var schema"+a+" = "+e.util.getData(o.$data,s,e.dataPathArr)+"; ",n="schema"+a):n=o,!f&&"number"!=typeof o)throw new Error(t+" must be number");i+="if ( ",f&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'number') || ");var h=t,p=p||[];p.push(i+=" "+d+".length "+("maxItems"==t?">":"<")+" "+n+") { "),i="",!1!==e.createErrors?(i+=" { keyword: '"+(h||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+n+" } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT have ",i+="maxItems"==t?"more":"fewer",i+=" than ",i+=f?"' + "+n+" + '":""+o,i+=" items' "),e.opts.verbose&&(i+=" , schema: ",i+=f?"validate.schema"+c:""+o,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var m=i;return i=p.pop(),i+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+m+"]); ":" validate.errors = ["+m+"]; return false; ":" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i},ji=function(e,t,r){var n,i=" ",a=e.level,s=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(s||""),f=e.opts.$data&&o&&o.$data;if(f?(i+=" var schema"+a+" = "+e.util.getData(o.$data,s,e.dataPathArr)+"; ",n="schema"+a):n=o,!f&&"number"!=typeof o)throw new Error(t+" must be number");i+="if ( ",f&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'number') || "),i+=!1===e.opts.unicode?" "+d+".length ":" ucs2length("+d+") ";var h=t,p=p||[];p.push(i+=" "+("maxLength"==t?">":"<")+" "+n+") { "),i="",!1!==e.createErrors?(i+=" { keyword: '"+(h||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+n+" } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT be ",i+="maxLength"==t?"longer":"shorter",i+=" than ",i+=f?"' + "+n+" + '":""+o,i+=" characters' "),e.opts.verbose&&(i+=" , schema: ",i+=f?"validate.schema"+c:""+o,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var m=i;return i=p.pop(),i+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+m+"]); ":" validate.errors = ["+m+"]; return false; ":" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i},Oi=function(e,t,r){var n,i=" ",a=e.level,s=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(s||""),f=e.opts.$data&&o&&o.$data;if(f?(i+=" var schema"+a+" = "+e.util.getData(o.$data,s,e.dataPathArr)+"; ",n="schema"+a):n=o,!f&&"number"!=typeof o)throw new Error(t+" must be number");i+="if ( ",f&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'number') || ");var h=t,p=p||[];p.push(i+=" Object.keys("+d+").length "+("maxProperties"==t?">":"<")+" "+n+") { "),i="",!1!==e.createErrors?(i+=" { keyword: '"+(h||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+n+" } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT have ",i+="maxProperties"==t?"more":"fewer",i+=" than ",i+=f?"' + "+n+" + '":""+o,i+=" properties' "),e.opts.verbose&&(i+=" , schema: ",i+=f?"validate.schema"+c:""+o,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var m=i;return i=p.pop(),i+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+m+"]); ":" validate.errors = ["+m+"]; return false; ":" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i},Ii={$ref:function(e,t,r){var n,i,a=" ",s=e.dataLevel,o=e.schema[t],c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(s||""),d="valid"+e.level;if("#"==o||"#/"==o)e.isRoot?(n=e.async,i="validate"):(n=!0===e.root.schema.$async,i="root.refVal[0]");else{var f=e.resolveRef(e.baseId,o,e.isRoot);if(void 0===f){var h=e.MissingRefError.message(e.baseId,o);if("fail"==e.opts.missingRefs){e.logger.error(h),(y=y||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { ref: '"+e.util.escapeQuotes(o)+"' } ",!1!==e.opts.messages&&(a+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(o)+"' "),e.opts.verbose&&(a+=" , schema: "+e.util.toQuotedString(o)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),a+=" } "):a+=" {} ";var p=a;a=y.pop(),a+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+p+"]); ":" validate.errors = ["+p+"]; return false; ":" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(a+=" if (false) { ")}else{if("ignore"!=e.opts.missingRefs)throw new e.MissingRefError(e.baseId,o,h);e.logger.warn(h),u&&(a+=" if (true) { ")}}else if(f.inline){var m=e.util.copy(e);m.level++;var v="valid"+m.level;m.schema=f.schema,m.schemaPath="",m.errSchemaPath=o,a+=" "+e.validate(m).replace(/validate\.schema/g,f.code)+" ",u&&(a+=" if ("+v+") { ")}else n=!0===f.$async||e.async&&!1!==f.$async,i=f.code}if(i){var y;(y=y||[]).push(a),a="",a+=e.opts.passContext?" "+i+".call(this, ":" "+i+"( ",a+=" "+l+", (dataPath || '')",'""'!=e.errorPath&&(a+=" + "+e.errorPath);var g=a+=" , "+(s?"data"+(s-1||""):"parentData")+" , "+(s?e.dataPathArr[s]:"parentDataProperty")+", rootData) ";if(a=y.pop(),n){if(!e.async)throw new Error("async schema referenced by sync schema");u&&(a+=" var "+d+"; "),a+=" try { await "+g+"; ",u&&(a+=" "+d+" = true; "),a+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",u&&(a+=" "+d+" = false; "),a+=" } ",u&&(a+=" if ("+d+") { ")}else a+=" if (!"+g+") { if (vErrors === null) vErrors = "+i+".errors; else vErrors = vErrors.concat("+i+".errors); errors = vErrors.length; } ",u&&(a+=" else { ")}return a},allOf:function(e,t,r){var n=" ",i=e.schema[t],a=e.schemaPath+e.util.getProperty(t),s=e.errSchemaPath+"/"+t,o=!e.opts.allErrors,c=e.util.copy(e),u="";c.level++;var l="valid"+c.level,d=c.baseId,f=!0,h=i;if(h)for(var p,m=-1,v=h.length-1;m<v;)p=h[m+=1],(e.opts.strictKeywords?"object"==typeof p&&Object.keys(p).length>0||!1===p:e.util.schemaHasRules(p,e.RULES.all))&&(f=!1,c.schema=p,c.schemaPath=a+"["+m+"]",c.errSchemaPath=s+"/"+m,n+=" "+e.validate(c)+" ",c.baseId=d,o&&(n+=" if ("+l+") { ",u+="}"));return o&&(n+=f?" if (true) { ":" "+u.slice(0,-1)+" "),n},anyOf:function(e,t,r){var n=" ",i=e.level,a=e.dataLevel,s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(a||""),d="valid"+i,f="errs__"+i,h=e.util.copy(e),p="";h.level++;var m="valid"+h.level,v=s.every(function(t){return e.opts.strictKeywords?"object"==typeof t&&Object.keys(t).length>0||!1===t:e.util.schemaHasRules(t,e.RULES.all)});if(v){var y=h.baseId;n+=" var "+f+" = errors; var "+d+" = false; ";var g=e.compositeRule;e.compositeRule=h.compositeRule=!0;var w=s;if(w)for(var b,E=-1,x=w.length-1;E<x;)b=w[E+=1],h.schema=b,h.schemaPath=o+"["+E+"]",h.errSchemaPath=c+"/"+E,n+=" "+e.validate(h)+" ",h.baseId=y,n+=" "+d+" = "+d+" || "+m+"; if (!"+d+") { ",p+="}";e.compositeRule=h.compositeRule=g,n+=" "+p+" if (!"+d+") { var err = ",!1!==e.createErrors?(n+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(n+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(n+=e.async?" throw new ValidationError(vErrors); ":" validate.errors = vErrors; return false; "),n+=" } else { errors = "+f+"; if (vErrors !== null) { if ("+f+") vErrors.length = "+f+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else u&&(n+=" if (true) { ");return n},$comment:function(e,t,r){var n=" ",i=e.errSchemaPath+"/"+t,a=e.util.toQuotedString(e.schema[t]);return!0===e.opts.$comment?n+=" console.log("+a+");":"function"==typeof e.opts.$comment&&(n+=" self._opts.$comment("+a+", "+e.util.toQuotedString(i)+", validate.root.schema);"),n},const:function(e,t,r){var n=" ",i=e.level,a=e.dataLevel,s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(a||""),d="valid"+i,f=e.opts.$data&&s&&s.$data;f&&(n+=" var schema"+i+" = "+e.util.getData(s.$data,a,e.dataPathArr)+"; "),f||(n+=" var schema"+i+" = validate.schema"+o+";");var h=h||[];h.push(n+="var "+d+" = equal("+l+", schema"+i+"); if (!"+d+") { "),n="",!1!==e.createErrors?(n+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValue: schema"+i+" } ",!1!==e.opts.messages&&(n+=" , message: 'should be equal to constant' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var p=n;return n=h.pop(),n+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+p+"]); ":" validate.errors = ["+p+"]; return false; ":" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",u&&(n+=" else { "),n},contains:function(e,t,r){var n=" ",i=e.level,a=e.dataLevel,s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(a||""),d="valid"+i,f="errs__"+i,h=e.util.copy(e);h.level++;var p="valid"+h.level,m="i"+i,v=h.dataLevel=e.dataLevel+1,y="data"+v,g=e.baseId,w=e.opts.strictKeywords?"object"==typeof s&&Object.keys(s).length>0||!1===s:e.util.schemaHasRules(s,e.RULES.all);if(n+="var "+f+" = errors;var "+d+";",w){var b=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.schema=s,h.schemaPath=o,h.errSchemaPath=c,n+=" var "+p+" = false; for (var "+m+" = 0; "+m+" < "+l+".length; "+m+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers,!0);var E=l+"["+m+"]";h.dataPathArr[v]=m;var x=e.validate(h);h.baseId=g,e.util.varOccurences(x,y)<2?n+=" "+e.util.varReplace(x,y,E)+" ":n+=" var "+y+" = "+E+"; "+x+" ",n+=" if ("+p+") break; } ",e.compositeRule=h.compositeRule=b,n+=" if (!"+p+") {"}else n+=" if ("+l+".length == 0) {";var $=$||[];$.push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(n+=" , message: 'should contain a valid item' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var P=n;return n=$.pop(),n+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+P+"]); ":" validate.errors = ["+P+"]; return false; ":" var err = "+P+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { ",w&&(n+=" errors = "+f+"; if (vErrors !== null) { if ("+f+") vErrors.length = "+f+"; else vErrors = null; } "),e.opts.allErrors&&(n+=" } "),n},dependencies:function(e,t,r){var n=" ",i=e.level,a=e.dataLevel,s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(a||""),d="errs__"+i,f=e.util.copy(e),h="";f.level++;var p="valid"+f.level,m={},v={},y=e.opts.ownProperties;for(E in s)if("__proto__"!=E){var g=s[E],w=Array.isArray(g)?v:m;w[E]=g}n+="var "+d+" = errors;";var b=e.errorPath;for(var E in n+="var missing"+i+";",v)if((w=v[E]).length){if(n+=" if ( "+l+e.util.getProperty(E)+" !== undefined ",y&&(n+=" && Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(E)+"') "),u){n+=" && ( ";var x=w;if(x)for(var $=-1,P=x.length-1;$<P;){j=x[$+=1],$&&(n+=" || "),n+=" ( ( "+(D=l+(N=e.util.getProperty(j)))+" === undefined ",y&&(n+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(j)+"') "),n+=") && (missing"+i+" = "+e.util.toQuotedString(e.opts.jsonPointers?j:N)+") ) "}n+=")) { ";var _="missing"+i,S="' + "+_+" + '";e.opts.ge&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(b,_,!0):b+" + "+_);var F=F||[];F.push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(E)+"', missingProperty: '"+S+"', depsCount: "+w.length+", deps: '"+e.util.escapeQuotes(1==w.length?w[0]:w.join(", "))+"' } ",!1!==e.opts.messages&&(n+=" , message: 'should have ",n+=1==w.length?"property "+e.util.escapeQuotes(w[0]):"properties "+e.util.escapeQuotes(w.join(", ")),n+=" when property "+e.util.escapeQuotes(E)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var k=n;n=F.pop(),n+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+k+"]); ":" validate.errors = ["+k+"]; return false; ":" var err = "+k+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{n+=" ) { ";var A=w;if(A)for(var j,O=-1,I=A.length-1;O<I;){j=A[O+=1];var N=e.util.getProperty(j),D=(S=e.util.escapeQuotes(j),l+N);e.opts.ge&&(e.errorPath=e.util.getPath(b,j,e.opts.jsonPointers)),n+=" if ( "+D+" === undefined ",y&&(n+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(j)+"') "),n+=") { var err = ",!1!==e.createErrors?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(E)+"', missingProperty: '"+S+"', depsCount: "+w.length+", deps: '"+e.util.escapeQuotes(1==w.length?w[0]:w.join(", "))+"' } ",!1!==e.opts.messages&&(n+=" , message: 'should have ",n+=1==w.length?"property "+e.util.escapeQuotes(w[0]):"properties "+e.util.escapeQuotes(w.join(", ")),n+=" when property "+e.util.escapeQuotes(E)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}n+=" } ",u&&(h+="}",n+=" else { ")}e.errorPath=b;var T=f.baseId;for(var E in m){g=m[E];(e.opts.strictKeywords?"object"==typeof g&&Object.keys(g).length>0||!1===g:e.util.schemaHasRules(g,e.RULES.all))&&(n+=" "+p+" = true; if ( "+l+e.util.getProperty(E)+" !== undefined ",y&&(n+=" && Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(E)+"') "),n+=") { ",f.schema=g,f.schemaPath=o+e.util.getProperty(E),f.errSchemaPath=c+"/"+e.util.escapeFragment(E),n+=" "+e.validate(f)+" ",f.baseId=T,n+=" } ",u&&(n+=" if ("+p+") { ",h+="}"))}return u&&(n+=" "+h+" if ("+d+" == errors) {"),n},enum:function(e,t,r){var n=" ",i=e.level,a=e.dataLevel,s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(a||""),d="valid"+i,f=e.opts.$data&&s&&s.$data;f&&(n+=" var schema"+i+" = "+e.util.getData(s.$data,a,e.dataPathArr)+"; ");var h="i"+i,p="schema"+i;f||(n+=" var "+p+" = validate.schema"+o+";"),n+="var "+d+";",f&&(n+=" if (schema"+i+" === undefined) "+d+" = true; else if (!Array.isArray(schema"+i+")) "+d+" = false; else {"),n+=d+" = false;for (var "+h+"=0; "+h+"<"+p+".length; "+h+"++) if (equal("+l+", "+p+"["+h+"])) { "+d+" = true; break; }",f&&(n+=" } ");var m=m||[];m.push(n+=" if (!"+d+") { "),n="",!1!==e.createErrors?(n+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValues: schema"+i+" } ",!1!==e.opts.messages&&(n+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var v=n;return n=m.pop(),n+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+v+"]); ":" validate.errors = ["+v+"]; return false; ":" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",u&&(n+=" else { "),n},format:function(e,t,r){var n=" ",i=e.level,a=e.dataLevel,s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(a||"");if(!1===e.opts.format)return u&&(n+=" if (true) { "),n;var d,f=e.opts.$data&&s&&s.$data;f?(n+=" var schema"+i+" = "+e.util.getData(s.$data,a,e.dataPathArr)+"; ",d="schema"+i):d=s;var h=e.opts.unknownFormats,p=Array.isArray(h);if(f){n+=" var "+(m="format"+i)+" = formats["+d+"]; var "+(v="isObject"+i)+" = typeof "+m+" == 'object' && !("+m+" instanceof RegExp) && "+m+".validate; var "+(y="formatType"+i)+" = "+v+" && "+m+".type || 'string'; if ("+v+") { ",e.async&&(n+=" var async"+i+" = "+m+".async; "),n+=" "+m+" = "+m+".validate; } if ( ",f&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'string') || "),n+=" (","ignore"!=h&&(n+=" ("+d+" && !"+m+" ",p&&(n+=" && self._opts.unknownFormats.indexOf("+d+") == -1 "),n+=") || "),n+=" ("+m+" && "+y+" == '"+r+"' && !(typeof "+m+" == 'function' ? ",n+=e.async?" (async"+i+" ? await "+m+"("+l+") : "+m+"("+l+")) ":" "+m+"("+l+") ",n+=" : "+m+".test("+l+"))))) {"}else{var m;if(!(m=e.formats[s])){if("ignore"==h)return e.logger.warn('unknown format "'+s+'" ignored in schema at path "'+e.errSchemaPath+'"'),u&&(n+=" if (true) { "),n;if(p&&h.indexOf(s)>=0)return u&&(n+=" if (true) { "),n;throw new Error('unknown format "'+s+'" is used in schema at path "'+e.errSchemaPath+'"')}var v,y=(v="object"==typeof m&&!(m instanceof RegExp)&&m.validate)&&m.type||"string";if(v){var g=!0===m.async;m=m.validate}if(y!=r)return u&&(n+=" if (true) { "),n;if(g){if(!e.async)throw new Error("async format in sync schema");n+=" if (!(await "+(w="formats"+e.util.getProperty(s)+".validate")+"("+l+"))) { "}else{n+=" if (! ";var w="formats"+e.util.getProperty(s);v&&(w+=".validate"),n+="function"==typeof m?" "+w+"("+l+") ":" "+w+".test("+l+") ",n+=") { "}}var b=b||[];b.push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { format: ",n+=f?""+d:""+e.util.toQuotedString(s),n+=" } ",!1!==e.opts.messages&&(n+=" , message: 'should match format \"",n+=f?"' + "+d+" + '":""+e.util.escapeQuotes(s),n+="\"' "),e.opts.verbose&&(n+=" , schema: ",n+=f?"validate.schema"+o:""+e.util.toQuotedString(s),n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var E=n;return n=b.pop(),n+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+E+"]); ":" validate.errors = ["+E+"]; return false; ":" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",u&&(n+=" else { "),n},if:function(e,t,r){var n=" ",i=e.level,a=e.dataLevel,s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(a||""),d="valid"+i,f="errs__"+i,h=e.util.copy(e);h.level++;var p="valid"+h.level,m=e.schema.then,v=e.schema.else,y=void 0!==m&&(e.opts.strictKeywords?"object"==typeof m&&Object.keys(m).length>0||!1===m:e.util.schemaHasRules(m,e.RULES.all)),g=void 0!==v&&(e.opts.strictKeywords?"object"==typeof v&&Object.keys(v).length>0||!1===v:e.util.schemaHasRules(v,e.RULES.all)),w=h.baseId;if(y||g){var b;h.createErrors=!1,h.schema=s,h.schemaPath=o,h.errSchemaPath=c,n+=" var "+f+" = errors; var "+d+" = true; ";var E=e.compositeRule;e.compositeRule=h.compositeRule=!0,n+=" "+e.validate(h)+" ",h.baseId=w,h.createErrors=!0,n+=" errors = "+f+"; if (vErrors !== null) { if ("+f+") vErrors.length = "+f+"; else vErrors = null; } ",e.compositeRule=h.compositeRule=E,y?(n+=" if ("+p+") { ",h.schema=e.schema.then,h.schemaPath=e.schemaPath+".then",h.errSchemaPath=e.errSchemaPath+"/then",n+=" "+e.validate(h)+" ",h.baseId=w,n+=" "+d+" = "+p+"; ",y&&g?n+=" var "+(b="ifClause"+i)+" = 'then'; ":b="'then'",n+=" } ",g&&(n+=" else { ")):n+=" if (!"+p+") { ",g&&(h.schema=e.schema.else,h.schemaPath=e.schemaPath+".else",h.errSchemaPath=e.errSchemaPath+"/else",n+=" "+e.validate(h)+" ",h.baseId=w,n+=" "+d+" = "+p+"; ",y&&g?n+=" var "+(b="ifClause"+i)+" = 'else'; ":b="'else'",n+=" } "),n+=" if (!"+d+") { var err = ",!1!==e.createErrors?(n+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { failingKeyword: "+b+" } ",!1!==e.opts.messages&&(n+=" , message: 'should match \"' + "+b+" + '\" schema' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(n+=e.async?" throw new ValidationError(vErrors); ":" validate.errors = vErrors; return false; "),n+=" } ",u&&(n+=" else { ")}else u&&(n+=" if (true) { ");return n},items:function(e,t,r){var n=" ",i=e.level,a=e.dataLevel,s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(a||""),d="valid"+i,f="errs__"+i,h=e.util.copy(e),p="";h.level++;var m="valid"+h.level,v="i"+i,y=h.dataLevel=e.dataLevel+1,g="data"+y,w=e.baseId;if(n+="var "+f+" = errors;var "+d+";",Array.isArray(s)){var b=e.schema.additionalItems;if(!1===b){n+=" "+d+" = "+l+".length <= "+s.length+"; ";var E=c;c=e.errSchemaPath+"/additionalItems";var x=x||[];x.push(n+=" if (!"+d+") { "),n="",!1!==e.createErrors?(n+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+s.length+" } ",!1!==e.opts.messages&&(n+=" , message: 'should NOT have more than "+s.length+" items' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var $=n;n=x.pop(),n+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+$+"]); ":" validate.errors = ["+$+"]; return false; ":" var err = "+$+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",c=E,u&&(p+="}",n+=" else { ")}var P=s;if(P)for(var _,S=-1,F=P.length-1;S<F;)if(_=P[S+=1],e.opts.strictKeywords?"object"==typeof _&&Object.keys(_).length>0||!1===_:e.util.schemaHasRules(_,e.RULES.all)){n+=" "+m+" = true; if ("+l+".length > "+S+") { ";var k=l+"["+S+"]";h.schema=_,h.schemaPath=o+"["+S+"]",h.errSchemaPath=c+"/"+S,h.errorPath=e.util.getPathExpr(e.errorPath,S,e.opts.jsonPointers,!0),h.dataPathArr[y]=S;var A=e.validate(h);h.baseId=w,e.util.varOccurences(A,g)<2?n+=" "+e.util.varReplace(A,g,k)+" ":n+=" var "+g+" = "+k+"; "+A+" ",n+=" } ",u&&(n+=" if ("+m+") { ",p+="}")}if("object"==typeof b&&(e.opts.strictKeywords?"object"==typeof b&&Object.keys(b).length>0||!1===b:e.util.schemaHasRules(b,e.RULES.all))){h.schema=b,h.schemaPath=e.schemaPath+".additionalItems",h.errSchemaPath=e.errSchemaPath+"/additionalItems",n+=" "+m+" = true; if ("+l+".length > "+s.length+") { for (var "+v+" = "+s.length+"; "+v+" < "+l+".length; "+v+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);k=l+"["+v+"]";h.dataPathArr[y]=v;A=e.validate(h);h.baseId=w,e.util.varOccurences(A,g)<2?n+=" "+e.util.varReplace(A,g,k)+" ":n+=" var "+g+" = "+k+"; "+A+" ",u&&(n+=" if (!"+m+") break; "),n+=" } } ",u&&(n+=" if ("+m+") { ",p+="}")}}else if(e.opts.strictKeywords?"object"==typeof s&&Object.keys(s).length>0||!1===s:e.util.schemaHasRules(s,e.RULES.all)){h.schema=s,h.schemaPath=o,h.errSchemaPath=c,n+=" for (var "+v+" = 0; "+v+" < "+l+".length; "+v+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);k=l+"["+v+"]";h.dataPathArr[y]=v;A=e.validate(h);h.baseId=w,e.util.varOccurences(A,g)<2?n+=" "+e.util.varReplace(A,g,k)+" ":n+=" var "+g+" = "+k+"; "+A+" ",u&&(n+=" if (!"+m+") break; "),n+=" }"}return u&&(n+=" "+p+" if ("+f+" == errors) {"),n},maximum:ki,minimum:ki,maxItems:Ai,minItems:Ai,maxLength:ji,minLength:ji,maxProperties:Oi,minProperties:Oi,multipleOf:function(e,t,r){var n,i=" ",a=e.level,s=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(s||""),f=e.opts.$data&&o&&o.$data;if(f?(i+=" var schema"+a+" = "+e.util.getData(o.$data,s,e.dataPathArr)+"; ",n="schema"+a):n=o,!f&&"number"!=typeof o)throw new Error(t+" must be number");i+="var division"+a+";if (",f&&(i+=" "+n+" !== undefined && ( typeof "+n+" != 'number' || "),i+=" (division"+a+" = "+d+" / "+n+", ",i+=e.opts.multipleOfPrecision?" Math.abs(Math.round(division"+a+") - division"+a+") > 1e-"+e.opts.multipleOfPrecision+" ":" division"+a+" !== parseInt(division"+a+") ",i+=" ) ",f&&(i+=" ) ");var h=h||[];h.push(i+=" ) { "),i="",!1!==e.createErrors?(i+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { multipleOf: "+n+" } ",!1!==e.opts.messages&&(i+=" , message: 'should be multiple of ",i+=f?"' + "+n:n+"'"),e.opts.verbose&&(i+=" , schema: ",i+=f?"validate.schema"+c:""+o,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var p=i;return i=h.pop(),i+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+p+"]); ":" validate.errors = ["+p+"]; return false; ":" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i},not:function(e,t,r){var n=" ",i=e.level,a=e.dataLevel,s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(a||""),d="errs__"+i,f=e.util.copy(e);f.level++;var h="valid"+f.level;if(e.opts.strictKeywords?"object"==typeof s&&Object.keys(s).length>0||!1===s:e.util.schemaHasRules(s,e.RULES.all)){f.schema=s,f.schemaPath=o,f.errSchemaPath=c,n+=" var "+d+" = errors; ";var p,m=e.compositeRule;e.compositeRule=f.compositeRule=!0,f.createErrors=!1,f.opts.allErrors&&(p=f.opts.allErrors,f.opts.allErrors=!1),n+=" "+e.validate(f)+" ",f.createErrors=!0,p&&(f.opts.allErrors=p),e.compositeRule=f.compositeRule=m;var v=v||[];v.push(n+=" if ("+h+") { "),n="",!1!==e.createErrors?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var y=n;n=v.pop(),n+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+y+"]); ":" validate.errors = ["+y+"]; return false; ":" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else n+=" var err = ",!1!==e.createErrors?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(n+=" if (false) { ");return n},oneOf:function(e,t,r){var n=" ",i=e.level,a=e.dataLevel,s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(a||""),d="valid"+i,f="errs__"+i,h=e.util.copy(e),p="";h.level++;var m="valid"+h.level,v=h.baseId,y="prevValid"+i,g="passingSchemas"+i;n+="var "+f+" = errors , "+y+" = false , "+d+" = false , "+g+" = null; ";var w=e.compositeRule;e.compositeRule=h.compositeRule=!0;var b=s;if(b)for(var E,x=-1,$=b.length-1;x<$;)E=b[x+=1],(e.opts.strictKeywords?"object"==typeof E&&Object.keys(E).length>0||!1===E:e.util.schemaHasRules(E,e.RULES.all))?(h.schema=E,h.schemaPath=o+"["+x+"]",h.errSchemaPath=c+"/"+x,n+=" "+e.validate(h)+" ",h.baseId=v):n+=" var "+m+" = true; ",x&&(n+=" if ("+m+" && "+y+") { "+d+" = false; "+g+" = ["+g+", "+x+"]; } else { ",p+="}"),n+=" if ("+m+") { "+d+" = "+y+" = true; "+g+" = "+x+"; }";return e.compositeRule=h.compositeRule=w,n+=p+"if (!"+d+") { var err = ",!1!==e.createErrors?(n+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { passingSchemas: "+g+" } ",!1!==e.opts.messages&&(n+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(n+=e.async?" throw new ValidationError(vErrors); ":" validate.errors = vErrors; return false; "),n+="} else { errors = "+f+"; if (vErrors !== null) { if ("+f+") vErrors.length = "+f+"; else vErrors = null; }",e.opts.allErrors&&(n+=" } "),n},pattern:function(e,t,r){var n,i=" ",a=e.level,s=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(s||""),f="valid"+a,h=e.opts.$data&&o&&o.$data;(h?(i+=" var schema"+a+" = "+e.util.getData(o.$data,s,e.dataPathArr)+"; ",n="schema"+a):n=o,h)?(i+=" var "+f+" = true; try { "+f+" = "+(e.opts.regExp?"regExp":"new RegExp")+"("+n+").test("+d+"); } catch(e) { "+f+" = false; } if ( ",h&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'string') || "),i+=" !"+f+") {"):(i+=" if ( ",h&&(i+=" ("+n+" !== undefined && typeof "+n+" != 'string') || "),i+=" !"+e.usePattern(o)+".test("+d+") ) {");var p=p||[];p.push(i),i="",!1!==e.createErrors?(i+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { pattern: ",i+=h?""+n:""+e.util.toQuotedString(o),i+=" } ",!1!==e.opts.messages&&(i+=" , message: 'should match pattern \"",i+=h?"' + "+n+" + '":""+e.util.escapeQuotes(o),i+="\"' "),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+e.util.toQuotedString(o),i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var m=i;return i=p.pop(),i+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+m+"]); ":" validate.errors = ["+m+"]; return false; ":" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+="} ",l&&(i+=" else { "),i},properties:function(e,t,r){var n=" ",i=e.level,a=e.dataLevel,s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(a||""),d="errs__"+i,f=e.util.copy(e),h="";f.level++;var p="valid"+f.level,m="key"+i,v="idx"+i,y=f.dataLevel=e.dataLevel+1,g="data"+y,w="dataProperties"+i,b=Object.keys(s||{}).filter(N),E=e.schema.patternProperties||{},x=Object.keys(E).filter(N),$=e.schema.additionalProperties,P=b.length||x.length,_=!1===$,S="object"==typeof $&&Object.keys($).length,F=e.opts.removeAdditional,k=_||S||F,A=e.opts.ownProperties,j=e.baseId,O=e.schema.required;if(O&&(!e.opts.$data||!O.$data)&&O.length<e.opts.loopRequired)var I=e.util.toHash(O);function N(e){return"__proto__"!==e}if(n+="var "+d+" = errors;var "+p+" = true;",A&&(n+=" var "+w+" = undefined;"),k){if(n+=A?" "+w+" = "+w+" || Object.keys("+l+"); for (var "+v+"=0; "+v+"<"+w+".length; "+v+"++) { var "+m+" = "+w+"["+v+"]; ":" for (var "+m+" in "+l+") { ",P){if(n+=" var isAdditional"+i+" = !(false ",b.length)if(b.length>8)n+=" || validate.schema"+o+".hasOwnProperty("+m+") ";else{var D=b;if(D)for(var T=-1,C=D.length-1;T<C;)G=D[T+=1],n+=" || "+m+" == "+e.util.toQuotedString(G)+" "}if(x.length){var R=x;if(R)for(var M=-1,q=R.length-1;M<q;)ae=R[M+=1],n+=" || "+e.usePattern(ae)+".test("+m+") "}n+=" ); if (isAdditional"+i+") { "}if("all"==F)n+=" delete "+l+"["+m+"]; ";else{var z=e.errorPath,U="' + "+m+" + '";if(e.opts.ge&&(e.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers)),_)if(F)n+=" delete "+l+"["+m+"]; ";else{var L=c;c=e.errSchemaPath+"/additionalProperties",(re=re||[]).push(n+=" "+p+" = false; "),n="",!1!==e.createErrors?(n+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { additionalProperty: '"+U+"' } ",!1!==e.opts.messages&&(n+=" , message: '",n+=e.opts.ge?"is an invalid additional property":"should NOT have additional properties",n+="' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var Z=n;n=re.pop(),n+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+Z+"]); ":" validate.errors = ["+Z+"]; return false; ":" var err = "+Z+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=L,u&&(n+=" break; ")}else if(S)if("failing"==F){n+=" var "+d+" = errors; ";var V=e.compositeRule;e.compositeRule=f.compositeRule=!0,f.schema=$,f.schemaPath=e.schemaPath+".additionalProperties",f.errSchemaPath=e.errSchemaPath+"/additionalProperties",f.errorPath=e.opts.ge?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var B=l+"["+m+"]";f.dataPathArr[y]=m;var J=e.validate(f);f.baseId=j,e.util.varOccurences(J,g)<2?n+=" "+e.util.varReplace(J,g,B)+" ":n+=" var "+g+" = "+B+"; "+J+" ",n+=" if (!"+p+") { errors = "+d+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+l+"["+m+"]; } ",e.compositeRule=f.compositeRule=V}else{f.schema=$,f.schemaPath=e.schemaPath+".additionalProperties",f.errSchemaPath=e.errSchemaPath+"/additionalProperties",f.errorPath=e.opts.ge?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);B=l+"["+m+"]";f.dataPathArr[y]=m;J=e.validate(f);f.baseId=j,e.util.varOccurences(J,g)<2?n+=" "+e.util.varReplace(J,g,B)+" ":n+=" var "+g+" = "+B+"; "+J+" ",u&&(n+=" if (!"+p+") break; ")}e.errorPath=z}P&&(n+=" } "),n+=" } ",u&&(n+=" if ("+p+") { ",h+="}")}var H=e.opts.useDefaults&&!e.compositeRule;if(b.length){var K=b;if(K)for(var G,Y=-1,W=K.length-1;Y<W;){var Q=s[G=K[Y+=1]];if(e.opts.strictKeywords?"object"==typeof Q&&Object.keys(Q).length>0||!1===Q:e.util.schemaHasRules(Q,e.RULES.all)){var X=e.util.getProperty(G),ee=(B=l+X,H&&void 0!==Q.default);f.schema=Q,f.schemaPath=o+X,f.errSchemaPath=c+"/"+e.util.escapeFragment(G),f.errorPath=e.util.getPath(e.errorPath,G,e.opts.jsonPointers),f.dataPathArr[y]=e.util.toQuotedString(G);J=e.validate(f);if(f.baseId=j,e.util.varOccurences(J,g)<2){J=e.util.varReplace(J,g,B);var te=B}else{te=g;n+=" var "+g+" = "+B+"; "}if(ee)n+=" "+J+" ";else{if(I&&I[G]){n+=" if ( "+te+" === undefined ",A&&(n+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(G)+"') "),n+=") { "+p+" = false; ";z=e.errorPath,L=c;var re,ne=e.util.escapeQuotes(G);e.opts.ge&&(e.errorPath=e.util.getPath(z,G,e.opts.jsonPointers)),c=e.errSchemaPath+"/required",(re=re||[]).push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+ne+"' } ",!1!==e.opts.messages&&(n+=" , message: '",n+=e.opts.ge?"is a required property":"should have required property \\'"+ne+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";Z=n;n=re.pop(),n+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+Z+"]); ":" validate.errors = ["+Z+"]; return false; ":" var err = "+Z+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=L,e.errorPath=z,n+=" } else { "}else u?(n+=" if ( "+te+" === undefined ",A&&(n+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(G)+"') "),n+=") { "+p+" = true; } else { "):(n+=" if ("+te+" !== undefined ",A&&(n+=" && Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(G)+"') "),n+=" ) { ");n+=" "+J+" } "}}u&&(n+=" if ("+p+") { ",h+="}")}}if(x.length){var ie=x;if(ie)for(var ae,se=-1,oe=ie.length-1;se<oe;){Q=E[ae=ie[se+=1]];if(e.opts.strictKeywords?"object"==typeof Q&&Object.keys(Q).length>0||!1===Q:e.util.schemaHasRules(Q,e.RULES.all)){f.schema=Q,f.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(ae),f.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(ae),n+=A?" "+w+" = "+w+" || Object.keys("+l+"); for (var "+v+"=0; "+v+"<"+w+".length; "+v+"++) { var "+m+" = "+w+"["+v+"]; ":" for (var "+m+" in "+l+") { ",n+=" if ("+e.usePattern(ae)+".test("+m+")) { ",f.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);B=l+"["+m+"]";f.dataPathArr[y]=m;J=e.validate(f);f.baseId=j,e.util.varOccurences(J,g)<2?n+=" "+e.util.varReplace(J,g,B)+" ":n+=" var "+g+" = "+B+"; "+J+" ",u&&(n+=" if (!"+p+") break; "),n+=" } ",u&&(n+=" else "+p+" = true; "),n+=" } ",u&&(n+=" if ("+p+") { ",h+="}")}}}return u&&(n+=" "+h+" if ("+d+" == errors) {"),n},propertyNames:function(e,t,r){var n=" ",i=e.level,a=e.dataLevel,s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(a||""),d="errs__"+i,f=e.util.copy(e);f.level++;var h="valid"+f.level;if(n+="var "+d+" = errors;",e.opts.strictKeywords?"object"==typeof s&&Object.keys(s).length>0||!1===s:e.util.schemaHasRules(s,e.RULES.all)){f.schema=s,f.schemaPath=o,f.errSchemaPath=c;var p="key"+i,m="idx"+i,v="i"+i,y="' + "+p+" + '",g="data"+(f.dataLevel=e.dataLevel+1),w="dataProperties"+i,b=e.opts.ownProperties,E=e.baseId;b&&(n+=" var "+w+" = undefined; "),n+=b?" "+w+" = "+w+" || Object.keys("+l+"); for (var "+m+"=0; "+m+"<"+w+".length; "+m+"++) { var "+p+" = "+w+"["+m+"]; ":" for (var "+p+" in "+l+") { ",n+=" var startErrs"+i+" = errors; ";var x=p,$=e.compositeRule;e.compositeRule=f.compositeRule=!0;var P=e.validate(f);f.baseId=E,e.util.varOccurences(P,g)<2?n+=" "+e.util.varReplace(P,g,x)+" ":n+=" var "+g+" = "+x+"; "+P+" ",e.compositeRule=f.compositeRule=$,n+=" if (!"+h+") { for (var "+v+"=startErrs"+i+"; "+v+"<errors; "+v+"++) { vErrors["+v+"].propertyName = "+p+"; } var err = ",!1!==e.createErrors?(n+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { propertyName: '"+y+"' } ",!1!==e.opts.messages&&(n+=" , message: 'property name \\'"+y+"\\' is invalid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(n+=e.async?" throw new ValidationError(vErrors); ":" validate.errors = vErrors; return false; "),u&&(n+=" break; "),n+=" } }"}return u&&(n+=" if ("+d+" == errors) {"),n},required:function(e,t,r){var n=" ",i=e.level,a=e.dataLevel,s=e.schema[t],o=e.schemaPath+e.util.getProperty(t),c=e.errSchemaPath+"/"+t,u=!e.opts.allErrors,l="data"+(a||""),d="valid"+i,f=e.opts.$data&&s&&s.$data;f&&(n+=" var schema"+i+" = "+e.util.getData(s.$data,a,e.dataPathArr)+"; ");var h="schema"+i;if(!f)if(s.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var p=[],m=s;if(m)for(var v,y=-1,g=m.length-1;y<g;){v=m[y+=1];var w=e.schema.properties[v];w&&(e.opts.strictKeywords?"object"==typeof w&&Object.keys(w).length>0||!1===w:e.util.schemaHasRules(w,e.RULES.all))||(p[p.length]=v)}}else p=s;if(f||p.length){var b=e.errorPath,E=f||p.length>=e.opts.loopRequired,x=e.opts.ownProperties;if(u)if(n+=" var missing"+i+"; ",E){f||(n+=" var "+h+" = validate.schema"+o+"; ");var $="' + "+(A="schema"+i+"["+(S="i"+i)+"]")+" + '";e.opts.ge&&(e.errorPath=e.util.getPathExpr(b,A,e.opts.jsonPointers)),n+=" var "+d+" = true; ",f&&(n+=" if (schema"+i+" === undefined) "+d+" = true; else if (!Array.isArray(schema"+i+")) "+d+" = false; else {"),n+=" for (var "+S+" = 0; "+S+" < "+h+".length; "+S+"++) { "+d+" = "+l+"["+h+"["+S+"]] !== undefined ",x&&(n+=" && Object.prototype.hasOwnProperty.call("+l+", "+h+"["+S+"]) "),n+="; if (!"+d+") break; } ",f&&(n+=" } "),(k=k||[]).push(n+=" if (!"+d+") { "),n="",!1!==e.createErrors?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+$+"' } ",!1!==e.opts.messages&&(n+=" , message: '",n+=e.opts.ge?"is a required property":"should have required property \\'"+$+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";var P=n;n=k.pop(),n+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+P+"]); ":" validate.errors = ["+P+"]; return false; ":" var err = "+P+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else{n+=" if ( ";var _=p;if(_)for(var S=-1,F=_.length-1;S<F;){O=_[S+=1],S&&(n+=" || "),n+=" ( ( "+(T=l+(D=e.util.getProperty(O)))+" === undefined ",x&&(n+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(O)+"') "),n+=") && (missing"+i+" = "+e.util.toQuotedString(e.opts.jsonPointers?O:D)+") ) "}n+=") { ";var k;$="' + "+(A="missing"+i)+" + '";e.opts.ge&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(b,A,!0):b+" + "+A),(k=k||[]).push(n),n="",!1!==e.createErrors?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+$+"' } ",!1!==e.opts.messages&&(n+=" , message: '",n+=e.opts.ge?"is a required property":"should have required property \\'"+$+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ";P=n;n=k.pop(),n+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+P+"]); ":" validate.errors = ["+P+"]; return false; ":" var err = "+P+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else if(E){f||(n+=" var "+h+" = validate.schema"+o+"; ");var A;$="' + "+(A="schema"+i+"["+(S="i"+i)+"]")+" + '";e.opts.ge&&(e.errorPath=e.util.getPathExpr(b,A,e.opts.jsonPointers)),f&&(n+=" if ("+h+" && !Array.isArray("+h+")) { var err = ",!1!==e.createErrors?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+$+"' } ",!1!==e.opts.messages&&(n+=" , message: '",n+=e.opts.ge?"is a required property":"should have required property \\'"+$+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+h+" !== undefined) { "),n+=" for (var "+S+" = 0; "+S+" < "+h+".length; "+S+"++) { if ("+l+"["+h+"["+S+"]] === undefined ",x&&(n+=" || ! Object.prototype.hasOwnProperty.call("+l+", "+h+"["+S+"]) "),n+=") { var err = ",!1!==e.createErrors?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+$+"' } ",!1!==e.opts.messages&&(n+=" , message: '",n+=e.opts.ge?"is a required property":"should have required property \\'"+$+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",f&&(n+=" } ")}else{var j=p;if(j)for(var O,I=-1,N=j.length-1;I<N;){O=j[I+=1];var D=e.util.getProperty(O),T=($=e.util.escapeQuotes(O),l+D);e.opts.ge&&(e.errorPath=e.util.getPath(b,O,e.opts.jsonPointers)),n+=" if ( "+T+" === undefined ",x&&(n+=" || ! Object.prototype.hasOwnProperty.call("+l+", '"+e.util.escapeQuotes(O)+"') "),n+=") { var err = ",!1!==e.createErrors?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+$+"' } ",!1!==e.opts.messages&&(n+=" , message: '",n+=e.opts.ge?"is a required property":"should have required property \\'"+$+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+o+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+l+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=b}else u&&(n+=" if (true) {");return n},uniqueItems:function(e,t,r){var n,i=" ",a=e.level,s=e.dataLevel,o=e.schema[t],c=e.schemaPath+e.util.getProperty(t),u=e.errSchemaPath+"/"+t,l=!e.opts.allErrors,d="data"+(s||""),f="valid"+a,h=e.opts.$data&&o&&o.$data;if(h?(i+=" var schema"+a+" = "+e.util.getData(o.$data,s,e.dataPathArr)+"; ",n="schema"+a):n=o,(o||h)&&!1!==e.opts.uniqueItems){h&&(i+=" var "+f+"; if ("+n+" === false || "+n+" === undefined) "+f+" = true; else if (typeof "+n+" != 'boolean') "+f+" = false; else { "),i+=" var i = "+d+".length , "+f+" = true , j; if (i > 1) { ";var p=e.schema.items&&e.schema.items.type,m=Array.isArray(p);if(!p||"object"==p||"array"==p||m&&(p.indexOf("object")>=0||p.indexOf("array")>=0))i+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+d+"[i], "+d+"[j])) { "+f+" = false; break outer; } } } ";else i+=" var itemIndices = {}, item; for (;i--;) { var item = "+d+"[i]; ",i+=" if ("+e.util["checkDataType"+(m?"s":"")](p,"item",e.opts.strictNumbers,!0)+") continue; ",m&&(i+=" if (typeof item == 'string') item = '\"' + item; "),i+=" if (typeof itemIndices[item] == 'number') { "+f+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ";i+=" } ",h&&(i+=" } ");var v=v||[];v.push(i+=" if (!"+f+") { "),i="",!1!==e.createErrors?(i+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(i+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(i+=" , schema: ",i+=h?"validate.schema"+c:""+o,i+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),i+=" } "):i+=" {} ";var y=i;i=v.pop(),i+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+y+"]); ":" validate.errors = ["+y+"]; return false; ":" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i+=" } ",l&&(i+=" else { ")}else l&&(i+=" if (true) { ");return i},validate:Ln},Ni=Ii,Di=Yr.toHash,Ti=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"],Ci=Mn.MissingRef,Ri=function e(t,r,n){var i=this;if("function"!=typeof this.he.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof r&&(n=r,r=void 0);var a=s(t).then(function(){var e=i.we(t,void 0,r);return e.validate||o(e)});n&&a.then(function(e){n(null,e)},n);return a;function s(t){var r=t.$schema;return r&&!i.getSchema(r)?e.call(i,{$ref:r},!0):Promise.resolve()}function o(e){try{return i.pe(e)}catch(t){if(t instanceof Ci)return function(t){var n=t.missingSchema;if(u(n))throw new Error("Schema "+n+" is loaded but "+t.missingRef+" cannot be resolved");var a=i.be[n];a||(a=i.be[n]=i.he.loadSchema(n)).then(c,c);return a.then(function(e){if(!u(n))return s(e).then(function(){u(n)||i.addSchema(e,n,void 0,r)})}).then(function(){return o(e)});function c(){delete i.be[n]}function u(e){return i.de[e]||i.fe[e]}}(t);throw t}}};const Mi={$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};var qi=/^[a-z_$][a-z0-9_$-]*$/i,zi=function(e,t,r){var n,i,a=" ",s=e.level,o=e.dataLevel,c=e.schema[t],u=e.schemaPath+e.util.getProperty(t),l=e.errSchemaPath+"/"+t,d=!e.opts.allErrors,f="data"+(o||""),h="valid"+s,p="errs__"+s,m=e.opts.$data&&c&&c.$data;m?(a+=" var schema"+s+" = "+e.util.getData(c.$data,o,e.dataPathArr)+"; ",i="schema"+s):i=c;var v,y,g,w,b,E=this,x="definition"+s,$=E.definition,P="";if(m&&$.$data){var _=$.validateSchema;a+=" var "+x+" = RULES.custom['"+t+"'].definition; var "+(b="keywordValidate"+s)+" = "+x+".validate;"}else{if(!(w=e.useCustomRule(E,c,e.schema,e)))return;i="validate.schema"+u,b=w.code,v=$.compile,y=$.inline,g=$.macro}var S=b+".errors",F="i"+s,k="ruleErr"+s,A=$.async;if(A&&!e.async)throw new Error("async keyword in sync schema");if(y||g||(a+=S+" = null;"),a+="var "+p+" = errors;var "+h+";",m&&$.$data&&(P+="}",a+=" if ("+i+" === undefined) { "+h+" = true; } else { ",_&&(P+="}",a+=" "+h+" = "+x+".validateSchema("+i+"); if ("+h+") { ")),y)a+=$.statements?" "+w.validate+" ":" "+h+" = "+w.validate+"; ";else if(g){var j=e.util.copy(e);P="";j.level++;var O="valid"+j.level;j.schema=w.validate,j.schemaPath="";var I=e.compositeRule;e.compositeRule=j.compositeRule=!0;var N=e.validate(j).replace(/validate\.schema/g,b);e.compositeRule=j.compositeRule=I,a+=" "+N}else{(R=R||[]).push(a),a="",a+=" "+b+".call( ",a+=e.opts.passContext?"this":"self",a+=v||!1===$.schema?" , "+f+" ":" , "+i+" , "+f+" , validate.schema"+e.schemaPath+" ",a+=" , (dataPath || '')",'""'!=e.errorPath&&(a+=" + "+e.errorPath);var D=o?"data"+(o-1||""):"parentData",T=o?e.dataPathArr[o]:"parentDataProperty",C=a+=" , "+D+" , "+T+" , rootData ) ";a=R.pop(),!1===$.errors?(a+=" "+h+" = ",A&&(a+="await "),a+=C+"; "):a+=A?" var "+(S="customErrors"+s)+" = null; try { "+h+" = await "+C+"; } catch (e) { "+h+" = false; if (e instanceof ValidationError) "+S+" = e.errors; else throw e; } ":" "+S+" = null; "+h+" = "+C+"; "}if($.modifying&&(a+=" if ("+D+") "+f+" = "+D+"["+T+"];"),a+=""+P,$.valid)d&&(a+=" if (true) { ");else{var R;a+=" if ( ",void 0===$.valid?(a+=" !",a+=g?""+O:""+h):a+=" "+!$.valid+" ",n=E.keyword,(R=R||[]).push(a+=") { "),(R=R||[]).push(a=""),a="",!1!==e.createErrors?(a+=" { keyword: '"+(n||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { keyword: '"+E.keyword+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should pass \""+E.keyword+"\" keyword validation' "),e.opts.verbose&&(a+=" , schema: validate.schema"+u+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),a+=" } "):a+=" {} ";var M=a;a=R.pop();var q=a+=!e.compositeRule&&d?e.async?" throw new ValidationError(["+M+"]); ":" validate.errors = ["+M+"]; return false; ":" var err = "+M+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";a=R.pop(),y?$.errors?"full"!=$.errors&&(a+=" for (var "+F+"="+p+"; "+F+"<errors; "+F+"++) { var "+k+" = vErrors["+F+"]; if ("+k+".dataPath === undefined) "+k+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+k+".schemaPath === undefined) { "+k+'.schemaPath = "'+l+'"; } ',e.opts.verbose&&(a+=" "+k+".schema = "+i+"; "+k+".data = "+f+"; "),a+=" } "):!1===$.errors?a+=" "+q+" ":(a+=" if ("+p+" == errors) { "+q+" } else { for (var "+F+"="+p+"; "+F+"<errors; "+F+"++) { var "+k+" = vErrors["+F+"]; if ("+k+".dataPath === undefined) "+k+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+k+".schemaPath === undefined) { "+k+'.schemaPath = "'+l+'"; } ',e.opts.verbose&&(a+=" "+k+".schema = "+i+"; "+k+".data = "+f+"; "),a+=" } } "):g?(a+=" var err = ",!1!==e.createErrors?(a+=" { keyword: '"+(n||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { keyword: '"+E.keyword+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should pass \""+E.keyword+"\" keyword validation' "),e.opts.verbose&&(a+=" , schema: validate.schema"+u+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(a+=e.async?" throw new ValidationError(vErrors); ":" validate.errors = vErrors; return false; ")):!1===$.errors?a+=" "+q+" ":(a+=" if (Array.isArray("+S+")) { if (vErrors === null) vErrors = "+S+"; else vErrors = vErrors.concat("+S+"); errors = vErrors.length; for (var "+F+"="+p+"; "+F+"<errors; "+F+"++) { var "+k+" = vErrors["+F+"]; if ("+k+".dataPath === undefined) "+k+".dataPath = (dataPath || '') + "+e.errorPath+"; "+k+'.schemaPath = "'+l+'"; ',e.opts.verbose&&(a+=" "+k+".schema = "+i+"; "+k+".data = "+f+"; "),a+=" } } else { "+q+" } "),a+=" } ",d&&(a+=" else { ")}return a},Ui={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:Mi.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:Mi.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}},Li={add:function(e,t){var r=this.RULES;if(r.keywords[e])throw new Error("Keyword "+e+" is already defined");if(!qi.test(e))throw new Error("Keyword "+e+" is not a valid identifier");if(t){this.validateKeyword(t,!0);var n=t.type;if(Array.isArray(n))for(var i=0;i<n.length;i++)s(e,n[i],t);else s(e,n,t);var a=t.metaSchema;a&&(t.$data&&this.he.$data&&(a={anyOf:[a,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),t.validateSchema=this.compile(a,!0))}function s(e,t,n){for(var i,a=0;a<r.length;a++){var s=r[a];if(s.type==t){i=s;break}}i||r.push(i={type:t,rules:[]});var o={keyword:e,definition:n,custom:!0,code:zi,implements:n.implements};i.rules.push(o),r.custom[e]=o}return r.keywords[e]=r.all[e]=!0,this},get:function(e){var t=this.RULES.custom[e];return t?t.definition:this.RULES.keywords[e]||!1},remove:function(e){var t=this.RULES;delete t.keywords[e],delete t.all[e],delete t.custom[e];for(var r=0;r<t.length;r++)for(var n=t[r].rules,i=0;i<n.length;i++)if(n[i].keyword==e){n.splice(i,1);break}return this},validate:function e(t,r){e.errors=null;var n=this.Ee=this.Ee||this.compile(Ui,!0);if(n(t))return!0;if(e.errors=n.errors,r)throw new Error("custom keyword definition is invalid: "+this.errorsText(n.errors));return!1}};const Zi={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var Vi=Wn,Bi=xn,Ji=oi,Hi=fn,Ki=Un,Gi=bi,Yi=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],t=["type","$comment"];return e.all=Di(t),e.types=Di(["number","integer","string","array","object","boolean","null"]),e.forEach(function(r){r.rules=r.rules.map(function(r){var n;if("object"==typeof r){var i=Object.keys(r)[0];n=r[i],r=i,n.forEach(function(r){t.push(r),e.all[r]=!0})}return t.push(r),e.all[r]={keyword:r,code:Ni[r],implements:n}}),e.all.$comment={keyword:"$comment",code:Ni.$comment},r.type&&(e.types[r.type]=r)}),e.keywords=Di(t.concat(["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"])),e.custom={},e},Wi=function(e,t){for(var r=0;r<t.length;r++){e=JSON.parse(JSON.stringify(e));var n,i=t[r].split("/"),a=e;for(n=1;n<i.length;n++)a=a[i[n]];for(n=0;n<Ti.length;n++){var s=Ti[n],o=a[s];o&&(a[s]={anyOf:[o,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return e},Qi=Yr,Xi=aa;aa.prototype.validate=function(e,t){var r;if("string"==typeof e){if(!(r=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var n=this.we(e);r=n.validate||this.pe(n)}var i=r(t);!0!==r.$async&&(this.errors=r.errors);return i},aa.prototype.compile=function(e,t){var r=this.we(e,void 0,t);return r.validate||this.pe(r)},aa.prototype.addSchema=function(e,t,r,n){if(Array.isArray(e)){for(var i=0;i<e.length;i++)this.addSchema(e[i],void 0,r,n);return this}var a=this.me(e);if(void 0!==a&&"string"!=typeof a)throw new Error("schema id must be string");return da(this,t=Bi.normalizeId(t||a)),this.fe[t]=this.we(e,r,n,!0),this},aa.prototype.addMetaSchema=function(e,t,r){return this.addSchema(e,t,r,!0),this},aa.prototype.validateSchema=function(e,t){var r=e.$schema;if(void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(r=r||this.he.defaultMeta||function(e){var t=e.he.meta;return e.he.defaultMeta="object"==typeof t?e.me(t)||t:e.getSchema(ra)?ra:void 0,e.he.defaultMeta}(this),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var n=this.validate(r,e);if(!n&&t){var i="schema is invalid: "+this.errorsText();if("log"!=this.he.validateSchema)throw new Error(i);this.logger.error(i)}return n},aa.prototype.getSchema=function(e){var t=sa(this,e);switch(typeof t){case"object":return t.validate||this.pe(t);case"string":return this.getSchema(t);case"undefined":return function(e,t){var r=Bi.schema.call(e,{schema:{}},t);if(r){var n=r.schema,i=r.root,a=r.baseId,s=Vi.call(e,n,i,void 0,a);return e.xe[t]=new Hi({ref:t,fragment:!0,schema:n,root:i,baseId:a,validate:s}),s}}(this,e)}},aa.prototype.removeSchema=function(e){if(e instanceof RegExp)return oa(this,this.fe,e),oa(this,this.de,e),this;switch(typeof e){case"undefined":return oa(this,this.fe),oa(this,this.de),this.T.clear(),this;case"string":var t=sa(this,e);return t&&this.T.del(t.cacheKey),delete this.fe[e],delete this.de[e],this;case"object":var r=this.he.serialize,n=r?r(e):e;this.T.del(n);var i=this.me(e);i&&(i=Bi.normalizeId(i),delete this.fe[i],delete this.de[i])}return this},aa.prototype.addFormat=function(e,t){"string"==typeof t&&(t=new RegExp(t));return this.ye[e]=t,this},aa.prototype.errorsText=function(e,t){if(!(e=e||this.errors))return"No errors";for(var r=void 0===(t=t||{}).separator?", ":t.separator,n=void 0===t.dataVar?"data":t.dataVar,i="",a=0;a<e.length;a++){var s=e[a];s&&(i+=n+s.dataPath+" "+s.message+r)}return i.slice(0,-r.length)},aa.prototype.we=function(e,t,r,n){if("object"!=typeof e&&"boolean"!=typeof e)throw new Error("schema should be object or boolean");var i=this.he.serialize,a=i?i(e):e,s=this.T.get(a);if(s)return s;n=n||!1!==this.he.addUsedSchema;var o=Bi.normalizeId(this.me(e));o&&n&&da(this,o);var c,u=!1!==this.he.validateSchema&&!t;u&&!(c=o&&o==Bi.normalizeId(e.$schema))&&this.validateSchema(e,!0);var l=Bi.ids.call(this,e),d=new Hi({id:o,schema:e,localRefs:l,cacheKey:a,meta:r});"#"!=o[0]&&n&&(this.de[o]=d);this.T.put(a,d),u&&c&&this.validateSchema(e,!0);return d},aa.prototype.pe=function(e,t){if(e.compiling)return e.validate=i,i.schema=e.schema,i.errors=null,i.root=t||i,!0===e.schema.$async&&(i.$async=!0),i;var r,n;e.compiling=!0,e.meta&&(r=this.he,this.he=this.$e);try{n=Vi.call(this,e.schema,t,e.localRefs)}catch(t){throw delete e.validate,t}finally{e.compiling=!1,e.meta&&(this.he=r)}return e.validate=n,e.refs=n.refs,e.refVal=n.refVal,e.root=n.root,n;function i(){var t=e.validate,r=t.apply(this,arguments);return i.errors=t.errors,r}},aa.prototype.compileAsync=Ri;var ea=Li;aa.prototype.addKeyword=ea.add,aa.prototype.getKeyword=ea.get,aa.prototype.removeKeyword=ea.remove,aa.prototype.validateKeyword=ea.validate;var ta=Mn;aa.ValidationError=ta.Validation,aa.MissingRefError=ta.MissingRef,aa.$dataMetaSchema=Wi;var ra="http://json-schema.org/draft-07/schema",na=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],ia=["/properties"];function aa(e){if(!(this instanceof aa))return new aa(e);e=this.he=Qi.copy(e)||{},function(e){var t=e.he.logger;if(!1===t)e.logger={log:fa,warn:fa,error:fa};else{if(void 0===t&&(t=console),!("object"==typeof t&&t.log&&t.warn&&t.error))throw new Error("logger must implement log, warn and error methods");e.logger=t}}(this),this.fe={},this.de={},this.xe={},this.ye=Gi(e.format),this.T=e.cache||new Ji,this.be={},this.ve=[],this.RULES=Yi(),this.me=function(e){switch(e.schemaId){case"auto":return la;case"id":return ca;default:return ua}}(e),e.loopRequired=e.loopRequired||1/0,"property"==e.errorDataPath&&(e.ge=!0),void 0===e.serialize&&(e.serialize=Ki),this.$e=function(e){for(var t=Qi.copy(e.he),r=0;r<na.length;r++)delete t[na[r]];return t}(this),e.formats&&function(e){for(var t in e.he.formats){e.addFormat(t,e.he.formats[t])}}(this),e.keywords&&function(e){for(var t in e.he.keywords){e.addKeyword(t,e.he.keywords[t])}}(this),function(e){var t;e.he.$data&&e.addMetaSchema(t=Zi,t.$id,!0);if(!1===e.he.meta)return;var r=Mi;e.he.$data&&(r=Wi(r,ia));e.addMetaSchema(r,ra,!0),e.de["http://json-schema.org/schema"]=ra}(this),"object"==typeof e.meta&&this.addMetaSchema(e.meta),e.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),function(e){var t=e.he.schemas;if(!t)return;if(Array.isArray(t))e.addSchema(t);else for(var r in t)e.addSchema(t[r],r)}(this)}function sa(e,t){return t=Bi.normalizeId(t),e.fe[t]||e.de[t]||e.xe[t]}function oa(e,t,r){for(var n in t){var i=t[n];i.meta||r&&!r.test(n)||(e.T.del(i.cacheKey),delete t[n])}}function ca(e){return e.$id&&this.logger.warn("schema $id ignored",e.$id),e.id}function ua(e){return e.id&&this.logger.warn("schema id ignored",e.id),e.$id}function la(e){if(e.$id&&e.id&&e.$id!=e.id)throw new Error("schema $id is different from id");return e.$id||e.id}function da(e,t){if(e.fe[t]||e.de[t])throw new Error('schema with key or id "'+t+'" already exists')}function fa(){}const ha=Jr(Xi);class pa extends Vr{constructor(e,t){var r;super(t),this.Pe=e,this._e=null!==(r=null==t?void 0:t.capabilities)&&void 0!==r?r:{},this.Se=null==t?void 0:t.instructions,this.setRequestHandler(Ot,e=>this.Fe(e)),this.setNotificationHandler(Tt,()=>{var e;return null===(e=this.oninitialized)||void 0===e?void 0:e.call(this)})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");var t;this._e=(t=this._e,Object.entries(e).reduce((e,[t,r])=>(e[t]=r&&"object"==typeof r&&e[t]?{...e[t],...r}:r,e),{...t}))}assertCapabilityForMethod(e){var t,r,n;switch(e){case"sampling/createMessage":if(!(null===(t=this.ke)||void 0===t?void 0:t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(null===(r=this.ke)||void 0===r?void 0:r.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(null===(n=this.ke)||void 0===n?void 0:n.roots))throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._e.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._e.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._e.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._e.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._e.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._e.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._e.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._e.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._e.tools)throw new Error(`Server does not support tools (required for ${e})`)}}async Fe(e){const t=e.params.protocolVersion;this.ke=e.params.capabilities,this.Ae=e.params.clientInfo;return{protocolVersion:st.includes(t)?t:at,capabilities:this.getCapabilities(),serverInfo:this.Pe,...this.Se&&{instructions:this.Se}}}getClientCapabilities(){return this.ke}getClientVersion(){return this.Ae}getCapabilities(){return this._e}async ping(){return this.request({method:"ping"},St)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},Ar,t)}async elicitInput(e,t){const r=await this.request({method:"elicitation/create",params:e},Ir,t);if("accept"===r.action&&r.content)try{const t=new ha,n=t.compile(e.requestedSchema);if(!n(r.content))throw new Ur(xt.InvalidParams,`Elicitation response content does not match requested schema: ${t.errorsText(n.errors)}`)}catch(e){if(e instanceof Ur)throw e;throw new Ur(xt.InternalError,`Error validating elicitation response: ${e}`)}return r}async listRoots(e,t){return this.request({method:"roots/list",params:e},qr,t)}async sendLoggingMessage(e){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 ma=Symbol("Let zodToJsonSchema decide on which parser to use"),va={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"},ya=e=>{const t=(e=>"string"==typeof e?{...va,name:e}:{...va,...e})(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,r])=>[r.p,{def:r.p,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function ga(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function wa(e,t,r,n,i){e[t]=r,ga(e,t,n,i)}const ba=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function Ea(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?ba(t,e.currentPath):t.join("/")}}function xa(e,t){return Ga(e.type.p,t)}function $a(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((r,n)=>$a(e,t,r))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Pa(e,t)}}const Pa=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const n of e.checks)switch(n.kind){case"min":wa(r,"minimum",n.value,n.message,t);break;case"max":wa(r,"maximum",n.value,n.message,t)}return r};let _a;const Sa=/^[cC][^\s-]{8,}$/,Fa=/^[0-9a-z]+$/,ka=/^[0-9A-HJKMNP-TV-Z]{26}$/,Aa=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,ja=()=>(void 0===_a&&(_a=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),_a),Oa=/^(?:(?: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])$/,Ia=/^(([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])$/,Na=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Da=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ta=/^[a-zA-Z0-9_-]{21}$/,Ca=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function Ra(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":wa(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":wa(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":za(r,"email",n.message,t);break;case"format:idn-email":za(r,"idn-email",n.message,t);break;case"pattern:zod":Ua(r,Aa,n.message,t)}break;case"url":za(r,"uri",n.message,t);break;case"uuid":za(r,"uuid",n.message,t);break;case"regex":Ua(r,n.regex,n.message,t);break;case"cuid":Ua(r,Sa,n.message,t);break;case"cuid2":Ua(r,Fa,n.message,t);break;case"startsWith":Ua(r,RegExp(`^${Ma(n.value,t)}`),n.message,t);break;case"endsWith":Ua(r,RegExp(`${Ma(n.value,t)}$`),n.message,t);break;case"datetime":za(r,"date-time",n.message,t);break;case"date":za(r,"date",n.message,t);break;case"time":za(r,"time",n.message,t);break;case"duration":za(r,"duration",n.message,t);break;case"length":wa(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t),wa(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":Ua(r,RegExp(Ma(n.value,t)),n.message,t);break;case"ip":"v6"!==n.version&&za(r,"ipv4",n.message,t),"v4"!==n.version&&za(r,"ipv6",n.message,t);break;case"base64url":Ua(r,Da,n.message,t);break;case"jwt":Ua(r,Ca,n.message,t);break;case"cidr":"v6"!==n.version&&Ua(r,Oa,n.message,t),"v4"!==n.version&&Ua(r,Ia,n.message,t);break;case"emoji":Ua(r,ja(),n.message,t);break;case"ulid":Ua(r,ka,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":za(r,"binary",n.message,t);break;case"contentEncoding:base64":wa(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":Ua(r,Na,n.message,t)}break;case"nanoid":Ua(r,Ta,n.message,t)}return r}function Ma(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)qa.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}const qa=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function za(e,t,r,n){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):wa(e,"format",t,r,n)}function Ua(e,t,r,n){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:La(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):wa(e,"pattern",La(t,n),r,n)}function La(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),n=e.flags.includes("m"),i=e.flags.includes("s"),a=r?e.source.toLowerCase():e.source;let s="",o=!1,c=!1,u=!1;for(let e=0;e<a.length;e++)if(o)s+=a[e],o=!1;else{if(r)if(c){if(a[e].match(/[a-z]/)){u?(s+=a[e],s+=`${a[e-2]}-${a[e]}`.toUpperCase(),u=!1):"-"===a[e+1]&&a[e+2]?.match(/[a-z]/)?(s+=a[e],u=!0):s+=`${a[e]}${a[e].toUpperCase()}`;continue}}else if(a[e].match(/[a-z]/)){s+=`[${a[e]}${a[e].toUpperCase()}]`;continue}if(n){if("^"===a[e]){s+="(^|(?<=[\r\n]))";continue}if("$"===a[e]){s+="($|(?=[\r\n]))";continue}}i&&"."===a[e]?s+=c?`${a[e]}\r\n`:`[${a[e]}\r\n]`:(s+=a[e],"\\"===a[e]?o=!0:c&&"]"===a[e]?c=!1:c||"["!==a[e]||(c=!0))}return s}function Za(e,t){if("openApi3"===t.target&&e.keyType?.p.typeName===Je.ZodEnum)return{type:"object",required:e.keyType.p.values,properties:e.keyType.p.values.reduce((r,n)=>({...r,[n]:Ga(e.valueType.p,{...t,currentPath:[...t.currentPath,"properties",n]})??Ea(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Ga(e.valueType.p,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?.p.typeName===Je.ZodString&&e.keyType.p.checks?.length){const{type:n,...i}=Ra(e.keyType.p,t);return{...r,propertyNames:i}}if(e.keyType?.p.typeName===Je.ZodEnum)return{...r,propertyNames:{enum:e.keyType.p.values}};if(e.keyType?.p.typeName===Je.ZodBranded&&e.keyType.p.type.p.typeName===Je.ZodString&&e.keyType.p.type.p.checks?.length){const{type:n,...i}=xa(e.keyType.p,t);return{...r,propertyNames:i}}return r}const Va={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const Ba=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,r)=>Ga(e.p,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return r.length?{anyOf:r}:void 0};function Ja(e,t){const r="openAi"===t.target,n={type:"object",properties:{}},i=[],a=e.shape();for(const e in a){let s=a[e];if(void 0===s||void 0===s.p)continue;let o=Ha(s);o&&r&&("ZodOptional"===s.p.typeName&&(s=s.p.innerType),s.isNullable()||(s=s.nullable()),o=!1);const c=Ga(s.p,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==c&&(n.properties[e]=c,o||i.push(e))}i.length&&(n.required=i);const s=function(e,t){if("ZodNever"!==e.catchall.p.typeName)return Ga(e.catchall.p,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==s&&(n.additionalProperties=s),n}function Ha(e){try{return e.isOptional()}catch{return!0}}const Ka=(e,t,r)=>{switch(t){case Je.ZodString:return Ra(e,r);case Je.ZodNumber:return function(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",ga(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?wa(r,n.inclusive?"minimum":"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),wa(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?wa(r,n.inclusive?"maximum":"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),wa(r,"maximum",n.value,n.message,t));break;case"multipleOf":wa(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case Je.ZodObject:return Ja(e,r);case Je.ZodBigInt:return function(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?wa(r,n.inclusive?"minimum":"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),wa(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?wa(r,n.inclusive?"maximum":"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),wa(r,"maximum",n.value,n.message,t));break;case"multipleOf":wa(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case Je.ZodBoolean:return{type:"boolean"};case Je.ZodDate:return $a(e,r);case Je.ZodUndefined:return function(e){return{not:Ea(e)}}(r);case Je.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case Je.ZodArray:return function(e,t){const r={type:"array"};return e.type?.p&&e.type?.p?.typeName!==Je.ZodAny&&(r.items=Ga(e.type.p,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&wa(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&wa(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(wa(r,"minItems",e.exactLength.value,e.exactLength.message,t),wa(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case Je.ZodUnion:case Je.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return Ba(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(e=>e.p.typeName in Va&&(!e.p.checks||!e.p.checks.length))){const e=r.reduce((e,t)=>{const r=Va[t.p.typeName];return r&&!e.includes(r)?[...e,r]:e},[]);return{type:e.length>1?e:e[0]}}if(r.every(e=>"ZodLiteral"===e.p.typeName&&!e.description)){const e=r.reduce((e,t)=>{const r=typeof t.p.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t.p.value)return[...e,"null"];default:return e}},[]);if(e.length===r.length){const t=e.filter((e,t,r)=>r.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:r.reduce((e,t)=>e.includes(t.p.value)?e:[...e,t.p.value],[])}}}else if(r.every(e=>"ZodEnum"===e.p.typeName))return{type:"string",enum:r.reduce((e,t)=>[...e,...t.p.values.filter(t=>!e.includes(t))],[])};return Ba(e,t)}(e,r);case Je.ZodIntersection:return function(e,t){const r=[Ga(e.left.p,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Ga(e.right.p,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e);let n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const i=[];return r.forEach(e=>{if((e=>(!("type"in e)||"string"!==e.type)&&"allOf"in e)(e))i.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...n}=e;t=n}else n=void 0;i.push(t)}}),i.length?{allOf:i,...n}:void 0}(e,r);case Je.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,r)=>Ga(e.p,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:Ga(e.rest.p,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,r)=>Ga(e.p,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,r);case Je.ZodRecord:return Za(e,r);case Je.ZodLiteral:return function(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}(e,r);case Je.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case Je.ZodNativeEnum:return function(e){const t=e.values,r=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),n=Array.from(new Set(r.map(e=>typeof e)));return{type:1===n.length?"string"===n[0]?"string":"number":["string","number"],enum:r}}(e);case Je.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType.p.typeName)&&(!e.innerType.p.checks||!e.innerType.p.checks.length))return"openApi3"===t.target?{type:Va[e.innerType.p.typeName],nullable:!0}:{type:[Va[e.innerType.p.typeName],"null"]};if("openApi3"===t.target){const r=Ga(e.innerType.p,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=Ga(e.innerType.p,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case Je.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Ga(e.innerType.p,t);const r=Ga(e.innerType.p,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ea(t)},r]}:Ea(t)})(e,r);case Je.ZodMap:return function(e,t){return"record"===t.mapStrategy?Za(e,t):{type:"array",maxItems:125,items:{type:"array",items:[Ga(e.keyType.p,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ea(t),Ga(e.valueType.p,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ea(t)],minItems:2,maxItems:2}}}(e,r);case Je.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:Ga(e.valueType.p,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&wa(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&wa(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case Je.ZodLazy:return()=>e.getter().p;case Je.ZodPromise:return function(e,t){return Ga(e.type.p,t)}(e,r);case Je.ZodNaN:case Je.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:Ea({...e,currentPath:[...e.currentPath,"not"]})}}(r);case Je.ZodEffects:return function(e,t){return"input"===t.effectStrategy?Ga(e.schema.p,t):Ea(t)}(e,r);case Je.ZodAny:return Ea(r);case Je.ZodUnknown:return function(e){return Ea(e)}(r);case Je.ZodDefault:return function(e,t){return{...Ga(e.innerType.p,t),default:e.defaultValue()}}(e,r);case Je.ZodBranded:return xa(e,r);case Je.ZodReadonly:case Je.ZodCatch:return((e,t)=>Ga(e.innerType.p,t))(e,r);case Je.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return Ga(e.in.p,t);if("output"===t.pipeStrategy)return Ga(e.out.p,t);const r=Ga(e.in.p,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,Ga(e.out.p,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter(e=>void 0!==e)}})(e,r);default:return}};function Ga(e,t,r=!1){const n=t.seen.get(e);if(t.override){const i=t.override?.(e,t,n,r);if(i!==ma)return i}if(n&&!r){const e=Ya(n,t);if(void 0!==e)return e}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const a=Ka(e,e.typeName,t),s="function"==typeof a?Ga(a(),t):a;if(s&&Wa(e,t,s),t.postProcess){const r=t.postProcess(s,e,t);return i.jsonSchema=s,r}return i.jsonSchema=s,s}const Ya=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:ba(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((e,r)=>t.currentPath[r]===e)||"seen"===t.$refStrategy?Ea(t):void 0}},Wa=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),Qa=(e,t)=>{const r=ya(t);let n="object"==typeof t&&t.definitions?Object.entries(t.definitions).reduce((e,[t,n])=>({...e,[t]:Ga(n.p,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0)??Ea(r)}),{}):void 0;const i="string"==typeof t?t:"title"===t?.nameStrategy?void 0:t?.name,a=Ga(e.p,void 0===i?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??Ea(r),s="object"==typeof t&&void 0!==t.name&&"title"===t.nameStrategy?t.name:void 0;void 0!==s&&(a.title=s),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===r.$refStrategy?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const o=void 0===i?n?{...a,[r.definitionPath]:n}:a:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:a}};return"jsonSchema7"===r.target?o.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==r.target&&"openAi"!==r.target||(o.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type)),o};var Xa;!function(e){e.Completable="McpCompletable"}(Xa||(Xa={}));class es extends C{_(e){const{ctx:t}=this.$(e);return this.p.type._({data:t.data,path:t.path,parent:t})}unwrap(){return this.p.type}}function ts(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:i};return{errorMap:(t,i)=>{var a,s;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:i.defaultError}:void 0===i.data?{message:null!==(a=null!=o?o:n)&&void 0!==a?a:i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:null!==(s=null!=o?o:r)&&void 0!==s?s:i.defaultError}},description:i}}es.create=(e,t)=>new es({type:e,typeName:Xa.Completable,complete:t.complete,...ts(t)});class rs{constructor(e,t){this.je={},this.Oe={},this.Ie={},this.Ne={},this.De=!1,this.Te=!1,this.Ce=!1,this.Re=!1,this.server=new pa(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this.De||(this.server.assertCanSetRequestHandler(yr.shape.method.value),this.server.assertCanSetRequestHandler(br.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(yr,()=>({tools:Object.entries(this.Ie).filter(([,e])=>e.enabled).map(([e,t])=>{const r={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?Qa(t.inputSchema,{strictUnions:!0}):ns,annotations:t.annotations};return t.outputSchema&&(r.outputSchema=Qa(t.outputSchema,{strictUnions:!0})),r})})),this.server.setRequestHandler(br,async(e,t)=>{const r=this.Ie[e.params.name];if(!r)throw new Ur(xt.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Ur(xt.InvalidParams,`Tool ${e.params.name} disabled`);let n;if(r.inputSchema){const i=await r.inputSchema.safeParseAsync(e.params.arguments);if(!i.success)throw new Ur(xt.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${i.error.message}`);const a=i.data,s=r.callback;try{n=await Promise.resolve(s(a,t))}catch(e){n={content:[{type:"text",text:e instanceof Error?e.message:String(e)}],isError:!0}}}else{const e=r.callback;try{n=await Promise.resolve(e(t))}catch(e){n={content:[{type:"text",text:e instanceof Error?e.message:String(e)}],isError:!0}}}if(r.outputSchema&&!n.isError){if(!n.structuredContent)throw new Ur(xt.InvalidParams,`Tool ${e.params.name} has an output schema but no structured content was provided`);const t=await r.outputSchema.safeParseAsync(n.structuredContent);if(!t.success)throw new Ur(xt.InvalidParams,`Invalid structured content for tool ${e.params.name}: ${t.error.message}`)}return n}),this.De=!0)}setCompletionRequestHandler(){this.Te||(this.server.assertCanSetRequestHandler(Tr.shape.method.value),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Tr,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new Ur(xt.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this.Te=!0)}async handlePromptCompletion(e,t){const r=this.Ne[t.name];if(!r)throw new Ur(xt.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new Ur(xt.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return os;const n=r.argsSchema.shape[e.params.argument.name];if(!(n instanceof es))return os;const i=n.p;return ss(await i.complete(e.params.argument.value,e.params.context))}async handleResourceCompletion(e,t){const r=Object.values(this.Oe).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this.je[t.uri])return os;throw new Ur(xt.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return os;return ss(await n(e.params.argument.value,e.params.context))}setResourceRequestHandlers(){this.Ce||(this.server.assertCanSetRequestHandler(Jt.shape.method.value),this.server.assertCanSetRequestHandler(Kt.shape.method.value),this.server.assertCanSetRequestHandler(Yt.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Jt,async(e,t)=>{const r=Object.entries(this.je).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),n=[];for(const e of Object.values(this.Oe)){if(!e.resourceTemplate.listCallback)continue;const r=await e.resourceTemplate.listCallback(t);for(const t of r.resources)n.push({...e.metadata,...t})}return{resources:[...r,...n]}}),this.server.setRequestHandler(Kt,async()=>({resourceTemplates:Object.entries(this.Oe).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(Yt,async(e,t)=>{const r=new URL(e.params.uri),n=this.je[r.toString()];if(n){if(!n.enabled)throw new Ur(xt.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(const e of Object.values(this.Oe)){const n=e.resourceTemplate.uriTemplate.match(r.toString());if(n)return e.readCallback(r,n,t)}throw new Ur(xt.InvalidParams,`Resource ${r} not found`)}),this.setCompletionRequestHandler(),this.Ce=!0)}setPromptRequestHandlers(){this.Re||(this.server.assertCanSetRequestHandler(ir.shape.method.value),this.server.assertCanSetRequestHandler(sr.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ir,()=>({prompts:Object.entries(this.Ne).filter(([,e])=>e.enabled).map(([e,t])=>{return{name:e,title:t.title,description:t.description,arguments:t.argsSchema?(r=t.argsSchema,Object.entries(r.shape).map(([e,t])=>({name:e,description:t.description,required:!t.isOptional()}))):void 0};var r})})),this.server.setRequestHandler(sr,async(e,t)=>{const r=this.Ne[e.params.name];if(!r)throw new Ur(xt.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Ur(xt.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){const n=await r.argsSchema.safeParseAsync(e.params.arguments);if(!n.success)throw new Ur(xt.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${n.error.message}`);const i=n.data,a=r.callback;return await Promise.resolve(a(i,t))}{const e=r.callback;return await Promise.resolve(e(t))}}),this.setCompletionRequestHandler(),this.Re=!0)}resource(e,t,...r){let n;"object"==typeof r[0]&&(n=r.shift());const i=r[0];if("string"==typeof t){if(this.je[t])throw new Error(`Resource ${t} is already registered`);const r=this.Me(e,void 0,t,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}{if(this.Oe[e])throw new Error(`Resource template ${e} is already registered`);const r=this.qe(e,void 0,t,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}}registerResource(e,t,r,n){if("string"==typeof t){if(this.je[t])throw new Error(`Resource ${t} is already registered`);const i=this.Me(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this.Oe[e])throw new Error(`Resource template ${e} is already registered`);const i=this.qe(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}Me(e,t,r,n,i){const a={name:e,title:t,metadata:n,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==r&&(delete this.je[r],e.uri&&(this.je[e.uri]=a)),void 0!==e.name&&(a.name=e.name),void 0!==e.title&&(a.title=e.title),void 0!==e.metadata&&(a.metadata=e.metadata),void 0!==e.callback&&(a.readCallback=e.callback),void 0!==e.enabled&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this.je[r]=a,a}qe(e,t,r,n,i){const a={resourceTemplate:r,title:t,metadata:n,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this.Oe[e],t.name&&(this.Oe[t.name]=a)),void 0!==t.title&&(a.title=t.title),void 0!==t.template&&(a.resourceTemplate=t.template),void 0!==t.metadata&&(a.metadata=t.metadata),void 0!==t.callback&&(a.readCallback=t.callback),void 0!==t.enabled&&(a.enabled=t.enabled),this.sendResourceListChanged()}};return this.Oe[e]=a,a}ze(e,t,r,n,i){const a={title:t,description:r,argsSchema:void 0===n?void 0:Qe(n),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this.Ne[e],t.name&&(this.Ne[t.name]=a)),void 0!==t.title&&(a.title=t.title),void 0!==t.description&&(a.description=t.description),void 0!==t.argsSchema&&(a.argsSchema=Qe(t.argsSchema)),void 0!==t.callback&&(a.callback=t.callback),void 0!==t.enabled&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this.Ne[e]=a,a}Ue(e,t,r,n,i,a,s){const o={title:t,description:r,inputSchema:void 0===n?void 0:Qe(n),outputSchema:void 0===i?void 0:Qe(i),annotations:a,callback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this.Ie[e],t.name&&(this.Ie[t.name]=o)),void 0!==t.title&&(o.title=t.title),void 0!==t.description&&(o.description=t.description),void 0!==t.paramsSchema&&(o.inputSchema=Qe(t.paramsSchema)),void 0!==t.callback&&(o.callback=t.callback),void 0!==t.annotations&&(o.annotations=t.annotations),void 0!==t.enabled&&(o.enabled=t.enabled),this.sendToolListChanged()}};return this.Ie[e]=o,this.setToolRequestHandlers(),this.sendToolListChanged(),o}tool(e,...t){if(this.Ie[e])throw new Error(`Tool ${e} is already registered`);let r,n,i;if("string"==typeof t[0]&&(r=t.shift()),t.length>1){const e=t[0];is(e)?(n=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!is(t[0])&&(i=t.shift())):"object"==typeof e&&null!==e&&(i=t.shift())}return this.Ue(e,void 0,r,n,void 0,i,t[0])}registerTool(e,t,r){if(this.Ie[e])throw new Error(`Tool ${e} is already registered`);const{title:n,description:i,inputSchema:a,outputSchema:s,annotations:o}=t;return this.Ue(e,n,i,a,s,o,r)}prompt(e,...t){if(this.Ne[e])throw new Error(`Prompt ${e} is already registered`);let r,n;"string"==typeof t[0]&&(r=t.shift()),t.length>1&&(n=t.shift());const i=this.ze(e,void 0,r,n,t[0]);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,t,r){if(this.Ne[e])throw new Error(`Prompt ${e} is already registered`);const{title:n,description:i,argsSchema:a}=t,s=this.ze(e,n,i,a,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return void 0!==this.server.transport}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}const ns={type:"object",properties:{}};function is(e){if("object"!=typeof e||null===e)return!1;return 0===Object.keys(e).length||Object.values(e).some(as)}function as(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function ss(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const os={completion:{values:[],hasMore:!1}},cs=(e,t)=>{const r=t.server?.transport||t.transport;if(r?.httpContext){const t=r.httpContext;return"function"==typeof t?t(e)||{}:t||{}}return{}},us=e=>(e=>{if(!e)return e;const t=e.startsWith("::ffff:")?e.slice(7):e;return"::1"===t?"127.0.0.1":t})(((e.headers["x-forwarded-for"]||"").split(",")[0]||e.socket?.remoteAddress||"").trim()),ls=e=>({apiKey:(e.headers["x-api-key"]||e.headers.authorization||"").toString().replace("Bearer ","")||e.query.api_key||e.body&&e.body.api_key,ecsEnv:(e.headers["x-ecs-env"]||e.headers["ecs-env"]||"").toString()||e.query.ecs_env||e.body&&e.body.ecs_env,subChannel:(e.headers["x-sub-channel"]||e.headers["sub-channel"]||"").toString()||e.query.sub_channel||e.body&&e.body.sub_channel||"open",conversation_id:(e.headers["x-conversation_id"]||e.headers.conversation_id||e.headers.mcpsession||"").toString()||e.query.conversation_id||e.body&&e.body.conversation_id,q:(e.headers["x-q"]||e.headers.q||"").toString()||e.query.q||e.body&&e.body.q,t:(e.headers["x-t"]||e.headers.t||"").toString()||e.query.t||e.body&&e.body.t}),ds="production"===process.env.NODE_ENV,fs="true"===process.env.LOG_TO_FILE,hs=process.env.LOG_FILE_PATH||"/data/logs/ecs-mcp/app.log",ps=(process.env.LOG_TIME_FORMAT||"epoch").toLowerCase();function ms(){const e=new Date,t=new Intl.DateTimeFormat("en-CA",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(e).reduce((e,t)=>("literal"!==t.type&&(e[t.type]=t.value),e),{}),r=String(e.getMilliseconds()).padStart(3,"0");return`,"time":"${`${t.year}-${t.month}-${t.day}T${t.hour}:${t.minute}:${t.second}.${r}+08:00`}"`}let vs;if(fs)vs=s.destination({dest:hs,minLength:512,sync:!1});else{const e=process.env.LOG_STDERR,t="string"==typeof e&&e.length>0,r=Array.isArray(process.argv)?process.argv.slice(2):[],n=r.includes("--stdio")||r.includes("--all"),i=t?"true"===e.toLowerCase():n;vs=s.destination({fd:i?2:1,minLength:256,sync:!0})}const ys=s({level:process.env.LOG_LEVEL||(ds?"info":"debug"),base:{service:process.env.APP_NAME||"ecs-mcp",version:process.env.APP_VERSION||"0.0.0",log_type:"app"},formatters:{level:(e,t)=>({level:e,level_number:t})},redact:{paths:["req.headers.authorization","authInfo.token","authInfo.access_token","req.body.params.arguments.access_token","req.body.params.arguments.token"],censor:"***"},timestamp:"iso"===ps?s.stdTimeFunctions.isoTime:"epoch"===ps?s.stdTimeFunctions.epochTime:"beijing"===ps||"cst"===ps||"asia/shanghai"===ps?ms:s.stdTimeFunctions.isoTime},vs);function gs(){try{vs?.flushSync?.()}catch{}try{vs?.end?.()}catch{}}function ws(e){return ys.child(e)}function bs(e){try{return null==e?0:"string"==typeof e?e.length:"object"==typeof e?JSON.stringify(e).length:String(e).length}catch{return-1}}function Es(e){if(!e||"object"!=typeof e)return{size:bs(e)};const t=Object.keys(e),r={keys:t,size:0},n="true"===(process.env.TOOL_LOG_ACTUAL_VALUES||"true").toLowerCase(),i=Number(process.env.TOOL_LOG_MAX_VALUE_LENGTH||"200");for(const a of t){if(/token|secret|password|authorization|access_token/i.test(a)){r[a]="***";continue}const t=e[a],s=bs(t);if(n&&s>0&&s<=i&&null!=t)if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)r[a]=t;else try{const e=JSON.stringify(t);r[a]=e.length<=i?t:s}catch{r[a]=s}else r[a]=s}return r.size=bs(e),r}function xs(e,t,r,n){const i="false"!==(process.env.TOOL_LOG_ENABLED??"true").toLowerCase(),a=Math.max(0,Math.min(1,Number(process.env.TOOL_LOG_SAMPLE_RATE??"1"))),s=n?.sampleRate??a;return async(...a)=>{const[o,c]=a,u=1===a.length?o:c,l=1===a.length?void 0:o,d=Date.now(),f=cs(u,e)||{},h=f.conversation_id;let p;try{const e=n?.apiMethod;p="function"==typeof e?e(l,u):e}catch{}const m=ys.child({tool:t,api_method:p,conversation_id:h,client_ip:(e=>{if(!e)return e;const t=e.startsWith("::ffff:")?e.slice(7):e;return"::1"===t?"127.0.0.1":t})(f.client_ip),channel:f?.authInfo?.subChannel});try{u.Le=m}catch{}const v=Math.random()<s;i&&v&&m.info({args_summary:Es(l)},"tool start");try{const e=1===a.length?await r(u):await r(l,u),t=Date.now()-d;if(i&&v){const r=Array.isArray(e?.content)?{content_len:e.content.length}:{size:bs(e)};m.info({consume:t,result:r},"tool done")}return e}catch(e){const t=Date.now()-d;throw m.error({consume:t,errno:-1,errmsg:e?.message},"tool error"),e}}}process.on("uncaughtException",e=>{ys.error({err:e},"uncaught exception"),gs(),process.exit(1)}),process.on("unhandledRejection",e=>{ys.error({err:e},"unhandled rejection"),gs(),process.exit(1)}),process.on("SIGINT",()=>{gs(),process.exit(0)}),process.on("SIGTERM",()=>{gs(),process.exit(0)}),process.on("beforeExit",()=>{gs()});const $s={test:"https://qaopen.eyun.360.cn/intf.php",hgtest:"https://hg-openapi.eyun.360.cn/intf.php",prod:"https://openapi.eyun.360.cn/intf.php"};function Ps(e){const t=e||process.env.ECS_ENV||"prod";return{request_url:$s[t]||$s.prod,client_env:t}}const _s="注意:如问题中未明确指定,请勿再自行调用其他无关工具。";function Ss(e,t="e7b24b112a44fdd9ee93bdf998c6ca0e"){const r=Object.keys(e).sort().map(t=>{const r=function(e){return encodeURIComponent(e).replace(/%20/g,"+").replace(/[!'()*~]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}(e[t]);return`${t}=${r}`});let n=r.join("&");return n+=t,function(e){return o.createHash("md5").update(e,"utf8").digest("hex")}(n)}class Fs extends Error{traceId;apiErrno;constructor(e,t){super(e),this.name="ApiError",this.traceId=t?.traceId,this.apiErrno=t?.apiErrno}}function ks(e){if(!e||"object"!=typeof e)return;const t=e.trace_id??e.traceId;return"string"==typeof t&&t.length>0?t:void 0}async function As(e,t){const r=function(e){let t="",r="",n="",i="",a="";e&&(e.apiKey&&(t=e.apiKey),e.subChannel&&(r=e.subChannel),e.q&&(n=e.q),e.t&&(i=e.t),e.clientSrc&&(a=e.clientSrc)),t||(t=process.env.API_KEY||""),r||(r=process.env.SUB_CHANNEL||"open"),a||(a=process.env.CLIENT_SRC||"default");const{client_env:s}=Ps(e?.ecsEnv);return{apiKey:t,clientEnv:s,clientSrc:a,subChannel:r,q:n,t:i}}(t);if(!r.apiKey&&!r.q&&!r.t)throw new Error("未配置API_KEY环境变量");try{const{request_url:n}=Ps(t?.ecsEnv),i=r.subChannel,a=new URL(n);let s={};const o=e.extraParams;o&&"file-upload-stdio"===o.toolName?(s.method=o.method,s.client_env=o.clientEnv,s.client_src=o.clientSrc,s.qid=o.qid,s.grant_type=o.grantType,s.sub_channel=i):(s.method="Oauth.getAccessTokenByApiKeyOrQT",s.client_env=r.clientEnv,s.client_src=r.clientSrc,s.grant_type="authorization_code",s.sub_channel=i,r.apiKey&&(s.api_key=r.apiKey)),Object.entries(s).forEach(([e,t])=>{a.searchParams.append(e,t)});const c={Accept:"application/json"};r.apiKey&&(c.api_key=r.apiKey),r.q&&(c.q=r.q),r.t&&(c.t=r.t);const u=await fetch(a.toString(),{method:"GET",headers:c});if(!u.ok)throw new Error(`鉴权请求失败,状态码: ${u.status}`);const l=await u.json(),d=ks(l);if(0!==l.errno)throw ys.debug({trace_id:d,errno:l.errno,msg:"oauth response"},"oauth response error"),new Fs(`鉴权请求返回错误: ${l.errmsg}`,{traceId:d,apiErrno:l.errno});ys.debug({trace_id:d,errno:0},"oauth response");const{access_token:f,qid:h,token:p}=l.data;return{access_token:f,qid:h,token:p,sub_channel:i}}catch(e){throw ys.error({err:e},"获取鉴权信息失败"),e}}async function js(e={},t){ys.debug({transportAuthInfo:t?{hasApiKey:!!t.apiKey,apiKey:t.apiKey||"",subChannel:t.subChannel,ecsEnv:t.ecsEnv,q:t.q||"",t:t.t||""}:void 0},"getAuthInfo");const r=await As(e,t);if(e.extraParams&&"file-upload-stdio"===e.extraParams.toolName)return r.qid=e.extraParams.qid,r;const n=Ss(function(e,t,r={}){const n={};if(e.access_token&&(n.access_token=String(e.access_token)),t&&(n.method=String(t)),e.qid&&(n.qid=String(e.qid)),r)for(const[e,t]of Object.entries(r))null!=t&&(n[String(e)]=String(t));return{...n}}({access_token:r.access_token,qid:r.qid},e.method||"",e.extraParams));return r.sign=n,r}class Os{apiKey;ecsEnv;subChannel;timeout;retries;retryDelay;constructor(e){this.apiKey=e.apiKey,this.ecsEnv=e.ecsEnv||"prod",this.subChannel=e.subChannel||"open",this.timeout=e.timeout||3e4,this.retries=e.retries||0,this.retryDelay=e.retryDelay||1e3}getTransportAuthInfo(){return{apiKey:this.apiKey,ecsEnv:this.ecsEnv,subChannel:this.subChannel}}logApiResponse(e,t){if(!e)return;const r=ks(t),n=t&&"object"==typeof t&&"errno"in t?t.errno:void 0;ys.debug({apiMethod:e,trace_id:r,errno:"number"==typeof n?n:void 0},"api response")}throwIfApiError(e,t="API请求失败"){if(!e||"object"!=typeof e)return;if("number"!=typeof e.errno||0===e.errno)return;const r=ks(e);throw new Fs(e.errmsg||t,{traceId:r,apiErrno:e.errno})}async getAuth(e={}){const t=this.getTransportAuthInfo(),r=await js(e,t);return r.request_url=Ps(this.ecsEnv).request_url,r}isRetryable(e){return"AbortError"===e.name||("ECONNRESET"===e.code||"ETIMEDOUT"===e.code||"ECONNREFUSED"===e.code||!!e.message?.includes("状态码: 5"))}async fetchWithRetry(e,t=0){const{url:r,init:n}=e(),i=new AbortController,a=setTimeout(()=>i.abort(),this.timeout),s={...n,signal:i.signal};try{const e=await fetch(r,s);if(clearTimeout(a),!e.ok)throw new Error(`API 请求失败,状态码: ${e.status}`);const t=await e.text();try{return JSON.parse(t)}catch{throw new Error(`无法解析API响应: ${t.substring(0,100)}...`)}}catch(r){if(clearTimeout(a),t<this.retries&&this.isRetryable(r)){const n=this.retryDelay*Math.pow(2,t);return ys.debug({attempt:t+1,delay:n,error:r.message},"请求失败,准备重试"),await new Promise(e=>setTimeout(e,n)),this.fetchWithRetry(e,t+1)}if("AbortError"===r.name)throw new Error(`请求超时 (${this.timeout}ms)`);throw r}}async apiGet(e,t){const r=t.method,n=await this.fetchWithRetry(()=>{const r=new URL(e.request_url||"");return Object.entries(t).forEach(([e,t])=>{r.searchParams.append(e,String(t))}),{url:r.toString(),init:{method:"GET",headers:{"Access-Token":e.access_token||""}}}});return this.logApiResponse(r,n),n}async apiPost(e,t,r={}){const n=t.method,i=await this.fetchWithRetry(()=>{const n=new URL(e.request_url||"");Object.entries(t).forEach(([e,t])=>{n.searchParams.append(e,String(t))});const i=new URLSearchParams;return Object.entries(r).forEach(([e,t])=>{i.append(e,String(t))}),{url:n.toString(),init:{method:"POST",headers:{"Access-Token":e.access_token||"","Content-Type":"application/x-www-form-urlencoded"},body:i}}});return this.logApiResponse(n,i),i}buildBaseParams(e,t){return{method:t,access_token:e.access_token||"",qid:e.qid||"",sign:e.sign||"",sub_channel:e.sub_channel}}get logger(){return ys}}class Is extends Os{async list(e={}){const{path:t="/",page:r=0,page_size:n=50}=e;let i=t||"/";"/"!==i&&(i.startsWith("/")||(i="/"+i),i.endsWith("/")||(i+="/"));const a={path:i,page:r,page_size:n},s=await this.getAuth({method:"File.getList",extraParams:a}),o={...this.buildBaseParams(s,"File.getList")};for(const[e,t]of Object.entries(a))"access_token"!==e&&(o[e]=String(t));return await this.apiGet(s,o)}async mkdir(e){const t={fname:e},r=await this.getAuth({method:"File.mkdir",extraParams:t}),n=this.buildBaseParams(r,"File.mkdir");return await this.apiPost(r,{},{...n,fname:e})}}const Ns=["http:","https:"],Ds=/[\\@]/,Ts=[/^127\./,/^10\./,/^11\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^224\./,/^0\./,/^255\./,/^::1$/,/^fe80::/i,/^fc00::/i,/^fd00::/i,/^localhost$/i,/\.local$/i,/\.lan$/i,/\.internal$/i,/\.intranet$/i,/\.corp$/i,/\.home$/i],Cs=[22,23,25,53,135,139,445,1433,1521,3306,3389,5432,6379,9200,11211,27017];async function Rs(e,t=5e3){const r=function(e){if(!e||"string"!=typeof e)return{isValid:!1,error:"URL不能为空"};try{const r=e.trim();if(Ds.test(r))return{isValid:!1,error:"URL包含不安全的字符"};const n=new URL(r);if(!Ns.includes(n.protocol))return{isValid:!1,error:"不支持的协议,只支持 http/https"};const i=n.hostname.toLowerCase();if(!i)return{isValid:!1,error:"主机名不能为空"};for(const e of Ts)if(e.test(i))return{isValid:!1,error:"禁止访问受限地址"};if(Ms(i)&&!qs(i))return{isValid:!1,error:"禁止访问受限IP地址"};if(n.port){const e=parseInt(n.port,10);if(Cs.includes(e))return{isValid:!1,error:"禁止访问受限端口"}}return t=n.pathname,[/\.\./,/%2e%2e/i,/%252e%252e/i,/\/etc\//i,/\/proc\//i,/\/sys\//i,/\/dev\//i].some(e=>e.test(t))?{isValid:!1,error:"路径包含不安全的内容"}:{isValid:!0,normalizedUrl:n.toString(),originalHostname:i}}catch(e){return{isValid:!1,error:"URL格式无效"}}var t}(e);if(!r.isValid)return r;try{const n=new URL(e).hostname.toLowerCase();if(Ms(n))return{...r,resolvedIP:n,originalHostname:n,needsHostHeader:!1};let i=[];try{const e=c.lookup(n,{all:!0}),r=new Promise((e,r)=>{setTimeout(()=>r(new Error("DNS解析超时")),t)});i=(await Promise.race([e,r])).map(e=>e.address)}catch(e){return{isValid:!1,error:"域名解析失败"}}for(const e of i){for(const t of Ts)if(t.test(e))return{isValid:!1,error:"域名解析到受限IP地址"};if(!qs(e))return{isValid:!1,error:"域名解析到受限IP地址"}}return{isValid:!0,normalizedUrl:r.normalizedUrl,resolvedIP:i[0],resolvedIPs:i,originalHostname:n,needsHostHeader:!1}}catch(e){return{isValid:!1,error:"URL验证过程中发生错误"}}}function Ms(e){if(/^(\d{1,3}\.){3}\d{1,3}$/.test(e)){return e.split(".").every(e=>{const t=parseInt(e,10);return t>=0&&t<=255})}return/^([0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}$/i.test(e)}function qs(e){for(const t of Ts)if(t.test(e))return!1;return!0}class zs extends Os{normalizeUploadResult(e){return{id:e?.id,name:e?.name||e?.uploadRes?.name,path:e?.uploadRes?.name,fid:e?.fid,size:e?.size||e?.uploadRes?.count_size,uploadRes:e?.uploadRes?{nid:e.uploadRes.nid,qid:e.uploadRes.qid,name:e.uploadRes.name,count_size:e.uploadRes.count_size,file_hash:e.uploadRes.file_hash,create_time:e.uploadRes.create_time,modify_time:e.uploadRes.modify_time}:void 0}}normalizeRemoteDir(e){let t=String(e||"").trim();if(!t)throw new Error("远端目录不能为空");return t.startsWith("/")||(t="/"+t),t.endsWith("/")||(t+="/"),t}toPosixRelativePath(e){return e.split(r.sep).join(r.posix.sep)}getMissingUploadPath(e){const t=e?.message||"",n="文件不存在: ";if(t.startsWith(n))return r.resolve(t.slice(7).trim())}async getSysConfig(){const e=await this.getAuth({method:"Oauth.getSysConfig"}),t=this.buildBaseParams(e,"Oauth.getSysConfig"),r=await this.apiGet(e,t);return this.throwIfApiError(r,"获取系统云控配置失败"),r}async search(e){const{key:t="",file_category:r=-1,page:n=1,page_size:i=20}=e;if(!t&&-1===r)throw new Error("必须提供搜索关键词(key)或指定文件类型(file_category)");const a={file_category:r,key:t,page:n,page_size:i},s=await this.getAuth({method:"File.searchList",extraParams:a}),o=this.buildBaseParams(s,"File.searchList"),c={};for(const[e,t]of Object.entries(a))"access_token"!==e&&(c[e]=String(t));return await this.apiPost(s,o,c)}async share(e){const t=await this.getAuth({method:"Share.preShare"}),r=this.buildBaseParams(t,"Share.preShare");return await this.apiPost(t,{},{...r,paths:e})}async getDownloadUrl(e){const{nid:t,fpath:r}=e;if(void 0===t&&!r)throw new Error("必须提供nid或fpath中的一个参数");const n={};void 0!==t?n.nid=t:r&&(n.fpath=r);const i=await this.getAuth({method:"MCP.getDownLoadUrl",extraParams:n}),a={...this.buildBaseParams(i,"MCP.getDownLoadUrl")};return void 0!==t?a.nid=String(t):r&&(a.fpath=r),await this.apiPost(i,{},a)}async getNodeInfoByNid(e){const{nid:t,ks_ext:r=0}=e;if(!t)throw new Error("nid 不能为空");if(0!==r&&1!==r)throw new Error("ks_ext 仅支持 0 或 1");const n={nid:t},i=await this.getAuth({method:"File.getNodeInfoByNid",extraParams:n}),a=this.buildBaseParams(i,"File.getNodeInfoByNid");return await this.apiGet(i,{...a,nid:t,ks_ext:String(r)})}async save(e){const{url:t,content:r,upload_path:n,file_name:i,is_rename:a=1}=e;if(!t&&!r||t&&r)throw new Error("url 与 content 互斥,必须且只能传一个");if(0!==a&&1!==a)throw new Error("is_rename 仅支持 0 或 1");if(t){if(t.includes("|"))throw new Error("MCP.saveFile 仅支持单个下载 URL,请勿使用英文竖线(|)连接多个地址;请对每个 URL 分别执行保存");const e=await Rs(t.trim(),5e3);if(!e.isValid)throw new Error(`URL安全验证失败: ${e.error}`)}const s=await this.getAuth({method:"MCP.saveFile"}),o=this.buildBaseParams(s,"MCP.saveFile"),c={};n&&(c.upload_path=n),t?c.url=t:r&&(c.content=r),i&&(c.file_name=i),c.is_rename=String(a);const u=await this.apiPost(s,o,c);if(u&&0===u.errno){const e=Array.isArray(u.data)?u.data:u.data?[u.data]:[];if(0===e.length)throw new Error("保存文件失败: 未获取到任何任务信息");const t=[],r=[];for(const n of e){const e=n.task_id;if(e)try{t.push(await this.pollTaskStatus(s,e))}catch(t){r.push(`任务 ${e} 失败: ${t.message}`)}else r.push(`URL ${n.url||"未知"} 未获取到任务ID`)}if(0===t.length&&r.length>0)throw new Error(`文件保存失败: ${r.join("; ")}`);return 1===t.length?t[0]:{errno:0,errmsg:r.length>0?`部分任务失败: ${r.join("; ")}`:"",data:{tasks:t,is_multi:!0}}}throw new Fs(u?.errmsg||"API请求失败",{traceId:ks(u),apiErrno:"number"==typeof u?.errno?u.errno:void 0})}async appendContent(e){const{path:t,content:r}=e;if(!t||!t.startsWith("/"))throw new Error("path 必须以 / 开头");if("string"!=typeof r||0===r.length)throw new Error("content 不能为空");const n={path:t,content:r},i=await this.getAuth({method:"File.appendContent",extraParams:n}),a=this.buildBaseParams(i,"File.appendContent");return await this.apiPost(i,{},{...a,path:t,content:r})}async detectFileExists(e){const{path:t,files:r}=e;if(!t||!t.startsWith("/"))throw new Error("path 必须以 / 开头");if(!Array.isArray(r)||0===r.length)throw new Error("files 不能为空");for(const e of r){if(!e?.fname||"string"!=typeof e.fname)throw new Error("files[].fname 必须为非空字符串");if(!Number.isFinite(e.fsize)||e.fsize<0)throw new Error("files[].fsize 必须为大于等于 0 的数字")}const n=JSON.stringify(r),i={path:t,data:n},a=await this.getAuth({method:"Sync.detectFileExists",extraParams:i}),s=this.buildBaseParams(a,"Sync.detectFileExists");return await this.apiGet(a,{...s,path:t,data:n})}async queryTaskStatus(e,t){const r={method:"MCP.query",qid:e.qid||"",access_token:e.access_token||"",sign:e.sign||""};return await this.apiPost(e,r,{task_id:t})}async pollTaskStatus(e,t,r=1e3,n=120){let i,a=0;for(;a<n;){if(a++,i=await this.queryTaskStatus(e,t),0!==i.errno)throw new Fs(i.errmsg||"查询任务状态失败",{traceId:ks(i),apiErrno:i.errno});const n=i.data?.status;if(2===n)return i;if(3===n)throw new Fs(i.data?.error||"文件保存失败",{traceId:ks(i),apiErrno:"number"==typeof i.errno?i.errno:void 0});await new Promise(e=>setTimeout(e,r))}return i}async upload(e){const{filePaths:r,uploadPath:n="/",is_rename:i}=e,a=void 0!==i?String(i):void 0;if(!r||0===r.length)throw new Error("filePaths 为必填参数且不能为空");if(void 0!==i&&0!==i&&1!==i)throw new Error("is_rename 仅支持 0 或 1");for(const e of r)if(!t.existsSync(e))throw new Error(`文件不存在: ${e}`);const s=await this.getAuth({});let o;try{const e=await import("@aicloud360/sec-sdk-node");o=e.UploadNode}catch{throw new Error("请先安装 @aicloud360/sec-sdk-node: npm install @aicloud360/sec-sdk-node")}const c={qid:s.qid||"0",token:s.token||"",access_token:s.access_token||"",env:this.ecsEnv,path:n,is_rename:a,preventAutoTokenRefresh:!1,retryForTokenError:!0,tokenRefreshCallback:async()=>{this.logger.info("SDK 触发 token 刷新");const e=await this.getAuth({});return{token:e.token,access_token:e.access_token}}};return new Promise((e,t)=>{const i=Date.now(),s=[],u=[],l=[],d=new o(c,{success:e=>{s.push(this.normalizeUploadResult(e))},progress:()=>{},error:(e,t)=>{const r=t?.errmsg||t?.message||JSON.stringify(t);u.push({fileName:e?.name||"未知文件",error:r})},duplicateList:e=>{l.push(...e.map(e=>({name:e.name,nid:e.nid,size:e.count_size,path:e.path||n})))},complete:()=>{if(u.length>0&&0===s.length){const e=new Error(`所有文件上传失败: ${u.map(e=>`${e.fileName}: ${e.error}`).join("; ")}`);return e.uploadErrors=u,e.primaryUploadError=u[0]?.error,void t(e)}e({uploadResults:s,uploadErrors:u,duplicateFiles:l,totalTime:((Date.now()-i)/1e3).toFixed(2),fileCount:s.length,totalFileCount:r.length})}});void 0!==a&&d.on("filequeue",(e,t)=>{t&&"object"==typeof t&&(t.is_rename=a,t.file&&"object"==typeof t.file&&(t.file.is_rename=a))}),d.addWaitFile(r)})}async uploadTree(e){const{rootDir:n,filePaths:i,uploadRoot:a,is_rename:s}=e,o=Date.now();if(!n)throw new Error("rootDir 为必填参数");if(!i||0===i.length)throw new Error("filePaths 为必填参数且不能为空");const c=r.resolve(n),u=this.normalizeRemoteDir(a),l=new Map;for(const e of i){const t=r.resolve(e),n=this.toPosixRelativePath(r.relative(c,t));if(!n||".."===n||n.startsWith("../")||r.posix.isAbsolute(n))throw new Error(`文件不在 rootDir 下: ${t}`);const i=r.posix.dirname(n),a="."===i?u:this.normalizeRemoteDir(r.posix.join(u,i)),s=l.get(a)||[];s.push({absolutePath:t,relativePath:n}),l.set(a,s)}const d=[],f=[],h=[];for(const[e,n]of l){let i=[...n];for(;i.length>0;){const n=[];for(const r of i)t.existsSync(r.absolutePath)?n.push(r):f.push({absolutePath:r.absolutePath,relativePath:r.relativePath,remoteDir:e,error:`文件不存在: ${r.absolutePath}`});if(i=n,0===i.length)break;let a;try{a=await this.upload({filePaths:i.map(e=>e.absolutePath),uploadPath:e,is_rename:s})}catch(t){const n=this.getMissingUploadPath(t);if(n){const r=i.findIndex(e=>e.absolutePath===n);if(r>=0){const[n]=i.splice(r,1);f.push({absolutePath:n.absolutePath,relativePath:n.relativePath,remoteDir:e,error:t.message});continue}}const a=t;if(Array.isArray(a.uploadErrors)&&a.uploadErrors.length>0)for(const t of a.uploadErrors){const n=i.find(e=>r.basename(e.absolutePath)===t.fileName);f.push({absolutePath:n?.absolutePath||t.fileName,relativePath:n?.relativePath||t.fileName,remoteDir:e,error:t.error})}else for(const r of i)f.push({absolutePath:r.absolutePath,relativePath:r.relativePath,remoteDir:e,error:t?.message||"上传失败"});break}h.push(...a.duplicateFiles);const o=[...i];for(const t of a.uploadResults){const n=r.basename(String(t?.name||t?.uploadRes?.name||"")),i=o.findIndex(e=>r.basename(e.absolutePath)===n),a=i>=0?o.splice(i,1)[0]:o.shift();a&&d.push({absolutePath:a.absolutePath,relativePath:a.relativePath,remoteDir:e,uploadResult:t})}for(const t of a.uploadErrors){const n=i.find(e=>r.basename(e.absolutePath)===t.fileName);f.push({absolutePath:n?.absolutePath||t.fileName,relativePath:n?.relativePath||t.fileName,remoteDir:e,error:t.error})}break}}return{uploadResults:d,uploadErrors:f,duplicateFiles:h,totalTime:((Date.now()-o)/1e3).toFixed(2),fileCount:d.length,totalFileCount:i.length}}async download(e){const{nid:t,auto:n=!0,downloadDir:i,forceForeground:a=!1}=e,s=i||r.join(u(),".mcp-downloads"),o=await this.getDownloadUrl({nid:String(t)});if(!o)throw new Fs("API请求失败");this.throwIfApiError(o);const c=o.data?.downloadUrl||"";if(!c)throw new Fs("未能获取到文件下载链接",{traceId:ks(o)});const l=r.basename(String(o.data?.fname||"downloaded_file")),f=Number(o.data?.size||0),h=f>0?f/1048576:0,p=h>0?`${h.toFixed(2)} MB`:"未知大小";if(!n)return{downloadUrl:c,filename:l,fileSize:p,downloadPath:""};await d.mkdir(s,{recursive:!0});const m=r.join(s,l);return h>10&&!a?(this.spawnBackgroundDownload(c,m),{downloadUrl:c,filename:l,fileSize:p,downloadPath:m,background:!0}):(await this.downloadWithCurl(c,m),{downloadUrl:c,filename:l,fileSize:p,downloadPath:m})}extractFileInfoFromUrl(e){try{const t=new URL(e);let n="downloaded_file";const i=t.searchParams.get("fname");if(i?n=r.basename(decodeURIComponent(i)):t.pathname&&t.pathname.length>1&&(n=r.basename(t.pathname)),n=n.replace(/[\x00/]/g,"_"),n&&"."!==n||(n="downloaded_file"),n.length>200){const e=r.extname(n);n=r.basename(n,e).substring(0,200-e.length)+e}const a=t.searchParams.get("fsize");return{filename:n,sizeMB:a?parseInt(a,10)/1048576:0}}catch{return{filename:"downloaded_file",sizeMB:0}}}downloadWithCurl(e,t,r=3e5){return new Promise((n,i)=>{const a=l("curl",["-L","-s","-A","yunpan_mcp_server",e,"-o",t]),s=setTimeout(()=>{a.kill(),i(new Error("下载超时"))},r);a.on("close",e=>{clearTimeout(s),0===e?n():i(new Error(`下载失败,curl 退出码: ${e}`))}),a.on("error",e=>{clearTimeout(s),i(e)})})}spawnBackgroundDownload(e,t){l("curl",["-L","-s","-A","yunpan_mcp_server",e,"-o",t],{detached:!0,stdio:"ignore"}).unref()}}class Us extends Os{async move(e){const{src_name:t,new_name:r}=e,n={src_name:t,new_name:r},i=await this.getAuth({method:"File.move",extraParams:n}),a=this.buildBaseParams(i,"File.move");return await this.apiPost(i,{},{...a,src_name:t,new_name:r})}async rename(e){const{src_name:t,new_name:r}=e,n={src_name:t,new_name:r},i=await this.getAuth({method:"File.rename",extraParams:n}),a=this.buildBaseParams(i,"File.rename");return await this.apiPost(i,{},{...a,src_name:t,new_name:r})}async delete(e){const t=await this.getAuth({method:"File.delete"}),r=this.buildBaseParams(t,"File.delete");return await this.apiPost(t,{},{...r,fname:e})}async transOrCopy(e){const{src_name:t,new_path:r,is_delete:n,is_replace:i=0,src_ks_id:a,new_ks_id:s}=e;if(0!==n&&1!==n)throw new Error("is_delete 仅支持 0 或 1");if(0!==i&&1!==i)throw new Error("is_replace 仅支持 0 或 1");const o={src_name:t,new_path:r,is_delete:n},c=await this.getAuth({method:"File.transOrCopy",extraParams:o}),u={...this.buildBaseParams(c,"File.transOrCopy"),src_name:t,new_path:r,is_delete:String(n),is_replace:String(i)};return a&&(u.src_ks_id=a),s&&(u.new_ks_id=s),await this.apiPost(c,{},u)}async countOriginSize(e){const{path:t}=e;if(!t||!t.startsWith("/"))throw new Error("path 必须以 / 开头");const r={path:t},n=await this.getAuth({method:"File.countFileOriginSize",extraParams:r}),i=this.buildBaseParams(n,"File.countFileOriginSize");return await this.apiPost(n,{},{...i,path:t})}async clearDir(e){const{fname:t}=e;if(!t)throw new Error("fname 不能为空");if(t.includes("|"))throw new Error("File.clearDir 仅支持单个目录路径,勿用英文竖线(|)拼接;竖线会被服务端视为路径非法字符(errno:3022)。请对每个目录分别调用");const r=await this.getAuth({method:"File.clearDir"}),n=this.buildBaseParams(r,"File.clearDir");return await this.apiPost(r,{},{...n,fname:t})}async config(e){const{path:t,command:r,type:n,key:i,value:a,content:s}=e;if(!t||!t.startsWith("/"))throw new Error("path 必须以 / 开头");const o="yml"===n?"yaml":n,c={path:t,command:r,type:o},u=await this.getAuth({method:"MCP.config",extraParams:c}),l={...this.buildBaseParams(u,"MCP.config"),path:t,command:r,type:o};return void 0!==i&&(l.key=i),void 0!==a&&(l.value=a),void 0!==s&&(l.content=s),await this.apiPost(u,{},l)}}class Ls extends Os{async info(){const e=await this.getAuth({}),t=this.buildBaseParams(e,"User.getUserDetail");return t.sign="",await this.apiGet(e,t)}}function Zs(){const e=new Date;return`${e.getFullYear()}${String(e.getMonth()+1).padStart(2,"0")}${String(e.getDate()).padStart(2,"0")}`}function Vs(e,t=2){if(0===e)return"0 Bytes";if(!e||e<0)return"未知大小";const r=t<0?0:t,n=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,n)).toFixed(r))+" "+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][n]}function Bs(e){!function(e){e.tool("file-list","获取云盘指定路径下的文件和文件夹列表,支持分页查询。返回文件名、大小、创建时间、修改时间等详细信息。",{page:Ke().optional().default(0).describe("页码,默认从0开始。"),page_size:Ke().optional().default(50).describe("每页显示的条目数,默认50条。"),path:He().optional().default("/").describe("云盘路径,必须以/开头和结尾,如 /folder/subfolder/,根目录为 /")},xs(e,"file-list",async({page:t,page_size:r,path:n},i)=>{const a=cs(i,e).authInfo;try{const e=new Is({apiKey:a?.apiKey||process.env.API_KEY||"",ecsEnv:a?.ecsEnv,subChannel:a?.subChannel}),i=await e.list({path:n,page:t,page_size:r});return{content:[{type:"text",text:JSON.stringify(i,null,2)}]}}catch(e){return ys.error({err:e},"获取文件列表出错"),{content:[{type:"text",text:`获取文件列表出错: ${e.message||"未知错误"}`}],isError:!0}}},{apiMethod:"File.getList"}))}(e),function(e){e.tool("file-search","在云盘中根据关键词搜索文件和文件夹,支持按文件类型筛选和分页查询。返回符合条件的文件详细信息。",{file_category:Ke().optional().default(-1).describe("文件类型筛选:-1(全部)、0(其他)、1(图片)、2(文档)、3(音乐)、4(视频)"),key:He().optional().default("").describe("搜索关键词,当file_category 不为 -1 时,可以为空,否则必填"),page:Ke().optional().default(1).describe("页码,从1开始"),page_size:Ke().optional().default(20).describe("每页显示的条目数,默认20条,最大100条")},xs(e,"file-search",async({file_category:t,key:r,page:n,page_size:i},a)=>{const s=cs(a,e).authInfo;try{const e=new zs({apiKey:s?.apiKey||process.env.API_KEY||"",ecsEnv:s?.ecsEnv,subChannel:s?.subChannel}),a=await e.search({file_category:t,key:r,page:n,page_size:i});return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}catch(e){return ys.error({err:e},"搜索文件时发生错误"),{content:[{type:"text",text:`搜索文件时发生错误: ${e.message}`}]}}},{apiMethod:"File.searchList"}))}(e);const t=process.argv.slice(2);t.includes("--sse")||t.includes("--http")||(function(e){e.tool("file-download-stdio","获取云盘中指定文件的下载链接并支持直接下载文件。可以指定下载目录,默认下载到用户主目录的 .mcp-downloads 文件夹中。",{nid:He().describe("文件的唯一标识ID,可通过文件列表或搜索获取"),auto:Ge().optional().describe("是否直接下载文件,默认为 true"),downloadDir:He().optional().describe("指定下载目录,必须有读写权限,默认为用户主目录下的 .mcp-downloads 文件夹")},xs(e,"file-download-stdio",async({nid:t,auto:r=!0,downloadDir:n},i)=>{const a=cs(i,e).authInfo;try{const e=new zs({apiKey:a?.apiKey||process.env.API_KEY||"",ecsEnv:a?.ecsEnv,subChannel:a?.subChannel}),i=await e.download({nid:t,auto:r,downloadDir:n});return r?i.background?{content:[{type:"text",text:`🚀 正在下载中,请稍后在"${i.downloadPath}"查看\n📁 文件名:${i.filename}\n🔗 下载链接:${i.downloadUrl}\n📦 文件大小:${i.fileSize}`},{type:"text",text:_s}]}:{content:[{type:"text",text:`✅ 文件下载完成!\n📁 文件名:${i.filename}\n💾 保存路径:${i.downloadPath}\n🔗 下载链接:${i.downloadUrl}\n📦 文件大小:${i.fileSize}`},{type:"text",text:_s}]}:{content:[{type:"text",text:`文件下载地址:${i.downloadUrl}\n📦 文件大小:${i.fileSize}`},{type:"text",text:_s}]}}catch(e){return ys.error({err:e},"下载文件出错"),{content:[{type:"text",text:`获取文件下载链接时发生错误: ${e.message}`},{type:"text",text:_s}]}}},{apiMethod:"Sync.getVerifiedDownLoadUrl"}))}(e),function(e){e.tool("file-upload-stdio","将本地文件上传到云盘指定路径。支持批量上传多个文件。",{filePaths:We(He()).describe("本地文件路径数组,例如:['/本地/文件1.txt', '/本地/文件2.jpg']"),uploadPath:He().optional().default("/").describe("云盘上传目标路径,默认为根目录'/'")},xs(e,"file-upload-stdio",async({filePaths:t,uploadPath:r},n)=>{const i=cs(n,e).authInfo;try{const e=new zs({apiKey:i?.apiKey||process.env.API_KEY||"",ecsEnv:i?.ecsEnv,subChannel:i?.subChannel}),n=await e.upload({filePaths:t,uploadPath:r}),a=[`总计上传文件数: ${n.fileCount}/${n.totalFileCount}`,`总上传耗时: ${n.totalTime}秒`,`上传路径: ${r}`].join("\n"),s=n.uploadResults.map((e,t)=>{const r=e.uploadRes?.name||e.name||"未知",n=e.fid||e.uploadRes?.nid||"未知",i=e.uploadRes?.count_size?function(e){return e<1024?e+" B":e<1048576?(e/1024).toFixed(2)+" KB":e<1073741824?(e/1048576).toFixed(2)+" MB":(e/1073741824).toFixed(2)+" GB"}(parseInt(e.uploadRes.count_size)):"未知";return`文件 ${t+1}: ${r} (ID: ${n}, 大小: ${i})`}).join("\n");let o="";n.duplicateFiles.length>0&&(o="\n\n检测到以下文件已存在(重名文件):\n"+n.duplicateFiles.map((e,t)=>`${t+1}. ${e.name} (路径: ${e.path})`).join("\n"));let c="";return n.uploadErrors.length>0&&(c="\n\n以下文件上传失败:\n"+n.uploadErrors.map((e,t)=>`${t+1}. ${e.fileName}: ${e.error}`).join("\n")),{content:[{type:"text",text:`文件上传完成!\n\n${a}\n\n${s}${o}${c}`},{type:"text",text:_s}]}}catch(e){return ys.error({err:e},"上传文件出错"),{content:[{type:"text",text:`上传文件时发生错误: ${e.message}`},{type:"text",text:_s}]}}},{apiMethod:"SDK.UploadNode"}))}(e)),function(e){e.tool("make-dir","在云盘中创建新文件夹,支持指定路径。",{fname:He().describe("要创建的文件夹完整路径,例如:/新文件夹/ 或 /文档/子文件夹/")},xs(e,"make-dir",async({fname:t},r)=>{const n=cs(r,e).authInfo;try{const e=new Is({apiKey:n?.apiKey||process.env.API_KEY||"",ecsEnv:n?.ecsEnv,subChannel:n?.subChannel}),r=await e.mkdir(t);if(r&&0===r.errno)return{content:[{type:"text",text:`文件夹"${t}"创建成功!\n文件夹ID: ${(r.data||{}).nid||""}`}]};throw new Error(r?.errmsg||"API请求失败")}catch(e){return ys.error({err:e},"创建文件夹出错"),{content:[{type:"text",text:`创建文件夹时发生错误: ${e.message}`}]}}},{apiMethod:"File.mkdir"}))}(e),function(e){e.tool("file-move","移动云盘中的文件或文件夹到指定位置。支持批量移动多个文件。",{src_name:He().describe("源文件或文件夹路径,多个文件用竖线(|)分隔,例如:/文件1.txt|/文件2.txt"),new_name:He().describe("目标文件夹路径,例如:/目标文件夹/")},xs(e,"file-move",async({src_name:t,new_name:r},n)=>{const i=cs(n,e).authInfo;try{const e=new Us({apiKey:i?.apiKey||process.env.API_KEY||"",ecsEnv:i?.ecsEnv,subChannel:i?.subChannel}),n=await e.move({src_name:t,new_name:r});if(n&&0===n.errno){const e=t.split("|").length;return{content:[{type:"text",text:`成功将${e}${e>1?"些文件":"个文件"}移动到"${r}"!`},{type:"text",text:_s}]}}throw new Error(n?.errmsg||"API请求失败")}catch(e){return ys.error({err:e},"移动文件出错"),{content:[{type:"text",text:`移动文件时发生错误: ${e.message}`},{type:"text",text:_s}]}}},{apiMethod:"File.move"}))}(e),function(e){e.tool("file-rename","重命名云盘中的文件或文件夹。",{src_name:He().describe("原文件或文件夹的完整路径,例如:/我的知识库/111.doc 或 /我的知识库/"),new_name:He().describe("新的名称(仅文件名或文件夹名,不含父路径)。文件夹名需以/结尾,例如:222.doc 或 我的知识库/")},xs(e,"file-rename",async({src_name:t,new_name:r},n)=>{const i=cs(n,e).authInfo;try{const e=new Us({apiKey:i?.apiKey||process.env.API_KEY||"",ecsEnv:i?.ecsEnv,subChannel:i?.subChannel}),n=await e.rename({src_name:t,new_name:r});if(n&&0===n.errno){const e=t.endsWith("/")?"文件夹":"文件",n=t.split("/").filter(e=>""!==e);return{content:[{type:"text",text:`成功将${e}"${n.length>0?n[n.length-1]:t}"重命名为"${r}"!`},{type:"text",text:_s}]}}throw new Error(n?.errmsg||"API请求失败")}catch(e){return ys.error({err:e},"重命名文件出错"),{content:[{type:"text",text:`重命名文件时发生错误: ${e.message}`},{type:"text",text:_s}]}}},{apiMethod:"File.rename"}))}(e),function(e){e.tool("file-share","生成云盘文件的分享链接。支持批量生成多个文件的分享链接。",{paths:He().describe("要分享的文件全路径,多个文件用竖线(|)隔开,例如:/文件1.txt|/文件夹2/文件2.txt")},xs(e,"file-share",async({paths:t},r)=>{const n=cs(r,e).authInfo;try{const e=new zs({apiKey:n?.apiKey||process.env.API_KEY||"",ecsEnv:n?.ecsEnv,subChannel:n?.subChannel}),r=await e.share(t);if(r&&0===r.errno&&r.data&&r.data.share){const e=r.data.share;return{content:[{type:"text",text:`分享链接生成成功!\n链接: ${e.url}\n提取码: ${e.password||"无"}\n短链: ${e.shorturl}\n二维码: ${e.qrcode}`},{type:"text",text:_s}],shareInfo:e}}throw new Error(r?.errmsg||"API请求失败")}catch(e){return ys.error({err:e},"生成分享链接出错"),{content:[{type:"text",text:`生成分享链接时发生错误: ${e.message}`},{type:"text",text:_s}]}}},{apiMethod:"Share.preShare"}))}(e),function(e){e.tool("user-info","获取360AI云盘用户详细信息。",xs(e,"user-info",async t=>{const r=cs(t,e).authInfo;try{const e=new Ls({apiKey:r?.apiKey||process.env.API_KEY||"",ecsEnv:r?.ecsEnv,subChannel:r?.subChannel}),t=await e.info();if(t&&0===t.errno&&t.data){const e=t.data;return{content:[{type:"text",text:`用户信息获取成功!\n${[`昵称: ${e.name}`,`会员: ${e.is_vip?"是":"否"}${e.vip_desc?"("+e.vip_desc+")":""}`,`总空间: ${(parseInt(e.total_size)/1073741824).toFixed(2)} GB`,`已用空间: ${(parseInt(e.used_size)/1073741824).toFixed(2)} GB`,`剩余空间: ${(e.available_size/1073741824).toFixed(2)} GB`,`会员剩余天数: ${e.expire_day}天`,`会员到期时间: ${e.expire?new Date(1e3*parseInt(e.expire)).toLocaleString():"未知"}`].join("\n")}`}],userInfo:e}}throw new Error(t?.errmsg||"API请求失败")}catch(e){return ys.error({err:e},"获取用户信息出错"),{content:[{type:"text",text:`获取用户信息时发生错误: ${e.message}`}]}}},{apiMethod:"User.getUserDetail"}))}(e),function(e){e.tool("file-save","通过URL或文本内容保存文件到云盘",{url:He().optional().describe("单个文件下载地址;与 content 互斥且二选一;勿用竖线拼接多个 URL(OpenAPI 不支持,请分多次调用)"),content:He().optional().describe("文件内容(建议为 MD 文本);与 url 互斥且二选一,必须且只能传其中一个;需传用户指定的完整内容,不能省略任何部分"),upload_path:He().default(`/AI为我下载/${Zs()}/`).describe("云盘存储路径,必须以 / 开头和结尾。如不指定,默认为 '/AI为我下载/YYYYMMDD/'(YYYYMMDD 为当天日期)。").refine(e=>e.endsWith("/"),{message:"路径必须以/结尾"}).refine(e=>e.startsWith("/"),{message:"路径必须以/开头"}),file_name:He().optional().describe("保存到云盘的文件名,不含路径。如不填写此参数代表自动解析。"),is_rename:Ke().optional().default(1).describe("同名文件处理策略:0 代表直接替换原文件;1 代表如果 upload_path 这个目录下有同名文件,会自动重命名。默认为 1。")},xs(e,"file-save",async(t,r)=>{const n=["url","content","upload_path","file_name","is_rename"],i=Object.keys(t||{}).filter(e=>!n.includes(e));if(i.length>0)return{content:[{type:"text",text:`❌ 参数错误: 仅允许参数 ${n.join(", ")};检测到不支持的参数: ${i.join(", ")}`}]};const{url:a,content:s,upload_path:o,file_name:c,is_rename:u}=t||{};if(!a&&!s||a&&s)return{content:[{type:"text",text:"❌ 参数错误: url 与 content 互斥,必须且只能传一个"}]};if(a&&a.includes("|"))return{content:[{type:"text",text:"❌ 参数错误: url 仅支持单个下载地址,不支持用 | 连接多个 URL;请对每个 URL 分别调用 file-save"}]};const l=cs(r,e).authInfo;try{const e=new zs({apiKey:l?.apiKey||process.env.API_KEY||"",ecsEnv:l?.ecsEnv,subChannel:l?.subChannel}),t=await e.save({url:a,content:s,upload_path:o,file_name:c,is_rename:u});if(!0===t.data?.is_multi){const e=t.data?.tasks||[],r=[];let n=`✅ 批量文件保存完成!(共 ${e.length} 个任务)\n\n`;for(let t=0;t<e.length;t++){const i=e[t],a=i?.data,s=a?.task_id||"",o={taskId:s};n+=`── 任务 ${t+1} ──\n`,n+=`🆔 任务ID: ${s}\n`,a&&(o.path=a.file_path,o.nid=a.nid,o.size=a.file_size,o.qid=a.qid,a.file_path&&(n+=`📂 云盘路径: ${a.file_path}\n`),a.file_size&&(n+=`📦 文件大小: ${Vs(a.file_size)}\n`)),r.push(o),n+="\n"}return t.errmsg&&(n+=`⚠️ ${t.errmsg}\n`),{content:[{type:"text",name:"x-save-result-json",text:JSON.stringify({status:"success",files:r})},{type:"text",name:"x-save-result-display",text:n}]}}const r=t.data,n=r?.task_id||t.data?.task_id||"";let i="✅ 文件保存成功!\n\n";i+=`🆔 任务ID: ${n}\n`;const d={taskId:n};if(r){const e=r.qid,t=r.file_path,n=r.nid,a=r.file_size;if(d.path=t,d.nid=n,d.size=a,d.qid=e,t&&(i+=`📂 云盘路径: ${t}\n`),a&&(i+=`📦 文件大小: ${Vs(a)}\n`),t&&n&&e){const r=t.substring(0,t.lastIndexOf("/")+1),a=`https://www.yunpan.com/file/index#/fileManage/my/file/${encodeURIComponent(r)}?focus_nid=${n}&owner_qid=${e}`;i+=`🔗 [点击查看云盘文件](${a})\n`,d.href=a}}return{content:[{type:"text",name:"x-save-result-json",text:JSON.stringify({status:"success",file:d})},{type:"text",name:"x-save-result-display",text:i}]}}catch(e){ys.error({err:e},"file-save 执行出错");const t=e.message?.includes("轮询超时");return t?{content:[{type:"text",name:"x-save-result-json",text:JSON.stringify({status:"timeout",error:e.message})},{type:"text",name:"x-save-result-display",text:"⏳ 文件保存轮询超时\n\n- 请稍后检查云盘。"}]}:{content:[{type:"text",text:`保存文件时发生错误: ${e.message}`}]}}},{apiMethod:"MCP.saveFile"}))}(e),function(e){e.tool("get-download-url","获取云盘中文件的下载链接。可以通过文件NID或路径获取。",{nid:He().optional().describe("文件nid,与fpath二选一必填"),fpath:He().optional().describe("文件路径,与nid二选一必填")},xs(e,"get-download-url",async({nid:t,fpath:r},n)=>{if(void 0===t&&!r)return{content:[{type:"text",text:"错误: 必须提供nid或fpath中的一个参数"}],isError:!0};const i=cs(n,e).authInfo;try{const e=new zs({apiKey:i?.apiKey||process.env.API_KEY||"",ecsEnv:i?.ecsEnv,subChannel:i?.subChannel}),n=await e.getDownloadUrl({nid:t,fpath:r});return{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}catch(e){return ys.error({err:e},"获取下载链接出错"),{content:[{type:"text",text:`获取下载链接时发生错误: ${e.message}`}]}}},{apiMethod:"MCP.getDownLoadUrl"}))}(e)}class Js{server;logLevel;constructor(e){this.server=new rs({...e,responseInterceptor:e=>{try{return"string"==typeof e?JSON.parse(e):e}catch(e){return ys.warn({err:e},"响应处理失败"),{error:"响应处理失败"}}}},{capabilities:{logging:{},tools:{listChanged:!0}}}),this.registerTools(),this.server.server.setRequestHandler($r,async e=>(this.logLevel=e.params.level,ys.info({level:this.logLevel},"logging level set"),{})),ys.info({name:e.name,version:e.version},"ECSMcpServer initialized")}registerTools(){Bs(this.server)}getServer(){return this.server}}const Hs={sub_channel:{envVar:"SUB_CHANNEL",aliases:["--sub_channel","--sub-channel"],description:"渠道配置"},api_key:{envVar:"API_KEY",aliases:["--api_key","--api-key"],description:"API密钥"},ecs_env:{envVar:"ECS_ENV",aliases:["--ecs_env","--ecs-env"],description:"ECS环境配置"}};function Ks(e,t){if(e.includes("=")){return{value:e.split("=")[1]||null,skipNext:!1}}return t&&!t.startsWith("--")?{value:t,skipNext:!0}:{value:null,skipNext:!1}}async function Gs(e){try{const e=function(){}.bind();console.log=(...t)=>e(...t),console.warn=(...t)=>e(...t)}catch{}!function(){const e=process.argv.slice(2);for(let t=0;t<e.length;t++){const r=e[t],n=e[t+1];if("--stdio"===r||"--http"===r||"--sse"===r||"--all"===r)continue;let i=!1;for(const[e,a]of Object.entries(Hs))if(a.aliases.some(e=>r===e||r.startsWith(e+"="))){const{value:e,skipNext:s}=Ks(r,n);e&&(process.env[a.envVar]=e),s&&t++,i=!0;break}!i&&r.startsWith("--")}for(const e of Object.values(Hs))process}();const t=new Js(e).getServer(),r=new Zr;return process.stdin.on("error",e=>{}),process.stdout.on("error",e=>{}),await t.connect(r),{server:t,transport:r}}var Ys={exports:{}};Ys.exports=function(e,t){if("string"==typeof e)return ro(e);if("number"==typeof e)return to(e,t);return null},Ys.exports.format=to,Ys.exports.parse=ro;var Ws=/\B(?=(\d{3})+(?!\d))/g,Qs=/(?:\.0*|(\.[^0]+)0+)$/,Xs={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},eo=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function to(e,t){if(!Number.isFinite(e))return null;var r=Math.abs(e),n=t&&t.thousandsSeparator||"",i=t&&t.unitSeparator||"",a=t&&void 0!==t.decimalPlaces?t.decimalPlaces:2,s=Boolean(t&&t.fixedDecimals),o=t&&t.unit||"";o&&Xs[o.toLowerCase()]||(o=r>=Xs.pb?"PB":r>=Xs.tb?"TB":r>=Xs.gb?"GB":r>=Xs.mb?"MB":r>=Xs.kb?"KB":"B");var c=(e/Xs[o.toLowerCase()]).toFixed(a);return s||(c=c.replace(Qs,"$1")),n&&(c=c.split(".").map(function(e,t){return 0===t?e.replace(Ws,n):e}).join(".")),c+i+o}function ro(e){if("number"==typeof e&&!isNaN(e))return e;if("string"!=typeof e)return null;var t,r=eo.exec(e),n="b";return r?(t=parseFloat(r[1]),n=r[4].toLowerCase()):(t=parseInt(e,10),n="b"),isNaN(t)?null:Math.floor(Xs[n]*t)}var no=Ys.exports,io={exports:{}},ao=r.relative,so=function(e){if(!e)throw new TypeError("argument namespace is required");var t=fo(yo()[1]);function r(e){lo.call(r,e)}return r.Ze=t[0],r.Ve=function(e){if(process.noDeprecation)return!0;return co(process.env.NO_DEPRECATION||"",e)}(e),r.Be=e,r.Je=function(e){if(process.traceDeprecation)return!0;return co(process.env.TRACE_DEPRECATION||"",e)}(e),r.He=Object.create(null),r.function=wo,r.property=bo,r},oo=process.cwd();function co(e,t){for(var r=e.split(/[ ,]+/),n=String(t).toLowerCase(),i=0;i<r.length;i++){var a=r[i];if(a&&("*"===a||a.toLowerCase()===n))return!0}return!1}function uo(e){var t=this.name+": "+this.namespace;this.message&&(t+=" deprecated "+this.message);for(var r=0;r<e.length;r++)t+="\n at "+e[r].toString();return t}function lo(e,t){var r=function(e,t){return("function"!=typeof e.listenerCount?e.listeners(t).length:e.listenerCount(t))>0}(process,"deprecation");if(r||!this.Ve){var n,i,a,s,o=0,c=!1,u=yo(),l=this.Ze;for(t?(s=t,(a=fo(u[1])).name=s.name,l=a[0]):a=s=fo(u[o=2]);o<u.length;o++)if((i=(n=fo(u[o]))[0])===l)c=!0;else if(i===this.Ze)l=this.Ze;else if(c)break;var d=n?s.join(":")+"__"+n.join(":"):void 0;if(void 0===d||!(d in this.He)){this.He[d]=!0;var f=e;if(f||(f=ho(a!==s&&a.name?a:s)),r){var h=Eo(this.Be,f,u.slice(o));process.emit("deprecation",h)}else{var p=(process.stderr.isTTY?mo:po).call(this,f,n,u.slice(o));process.stderr.write(p+"\n","utf8")}}}}function fo(e){var t=e.getFileName()||"<anonymous>",r=e.getLineNumber(),n=e.getColumnNumber();e.isEval()&&(t=e.getEvalOrigin()+", "+t);var i=[t,r,n];return i.callSite=e,i.name=e.getFunctionName(),i}function ho(e){var t=e.callSite,r=e.name;r||(r="<anonymous@"+vo(e)+">");var n=t.getThis(),i=n&&t.getTypeName();return"Object"===i&&(i=void 0),"Function"===i&&(i=n.name||i),i&&t.getMethodName()?i+"."+r:r}function po(e,t,r){var n=(new Date).toUTCString()+" "+this.Be+" deprecated "+e;if(this.Je){for(var i=0;i<r.length;i++)n+="\n at "+r[i].toString();return n}return t&&(n+=" at "+vo(t)),n}function mo(e,t,r){var n="[36;1m"+this.Be+"[22;39m [33;1mdeprecated[22;39m [0m"+e+"[39m";if(this.Je){for(var i=0;i<r.length;i++)n+="\n [36mat "+r[i].toString()+"[39m";return n}return t&&(n+=" [36m"+vo(t)+"[39m"),n}function vo(e){return ao(oo,e[0])+":"+e[1]+":"+e[2]}function yo(){var e=Error.stackTraceLimit,t={},r=Error.prepareStackTrace;Error.prepareStackTrace=go,Error.stackTraceLimit=Math.max(10,e),Error.captureStackTrace(t);var n=t.stack.slice(1);return Error.prepareStackTrace=r,Error.stackTraceLimit=e,n}function go(e,t){return t}function wo(e,t){if("function"!=typeof e)throw new TypeError("argument fn must be a function");var r=function(e){for(var t="",r=0;r<e;r++)t+=", arg"+r;return t.substr(2)}(e.length),n=fo(yo()[1]);return n.name=e.name,new Function("fn","log","deprecate","message","site",'"use strict"\nreturn function ('+r+") {log.call(deprecate, message, site)\nreturn fn.apply(this, arguments)\n}")(e,lo,this,t,n)}function bo(e,t,r){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new TypeError("argument obj must be object");var n=Object.getOwnPropertyDescriptor(e,t);if(!n)throw new TypeError("must call property on owner object");if(!n.configurable)throw new TypeError("property must be configurable");var i=this,a=fo(yo()[1]);a.name=t,"value"in n&&(n=function(e,t){var r=Object.getOwnPropertyDescriptor(e,t),n=r.value;return r.get=function(){return n},r.writable&&(r.set=function(e){return n=e}),delete r.value,delete r.writable,Object.defineProperty(e,t,r),r}(e,t));var s=n.get,o=n.set;"function"==typeof s&&(n.get=function(){return lo.call(i,r,a),s.apply(this,arguments)}),"function"==typeof o&&(n.set=function(){return lo.call(i,r,a),o.apply(this,arguments)}),Object.defineProperty(e,t,n)}function Eo(e,t,r){var n,i=new Error;return Object.defineProperty(i,"constructor",{value:Eo}),Object.defineProperty(i,"message",{configurable:!0,enumerable:!1,value:t,writable:!0}),Object.defineProperty(i,"name",{enumerable:!1,configurable:!0,value:"DeprecationError",writable:!0}),Object.defineProperty(i,"namespace",{configurable:!0,enumerable:!1,value:e,writable:!0}),Object.defineProperty(i,"stack",{configurable:!0,enumerable:!1,get:function(){return void 0!==n?n:n=uo.call(this,r)},set:function(e){n=e}}),i}var xo=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(e,t){return e.__proto__=t,e}:function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(e,r)||(e[r]=t[r]);return e});var $o={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},Po=So;function _o(e){if(!Object.prototype.hasOwnProperty.call(So.message,e))throw new Error("invalid status code: "+e);return So.message[e]}function So(e){if("number"==typeof e)return _o(e);if("string"!=typeof e)throw new TypeError("code must be a number or string");var t=parseInt(e,10);return isNaN(t)?function(e){var t=e.toLowerCase();if(!Object.prototype.hasOwnProperty.call(So.code,t))throw new Error('invalid status message: "'+e+'"');return So.code[t]}(e):_o(t)}So.message=$o,So.code=function(e){var t={};return Object.keys(e).forEach(function(r){var n=e[r],i=Number(r);t[n.toLowerCase()]=i}),t}($o),So.codes=function(e){return Object.keys(e).map(function(e){return Number(e)})}($o),So.redirect={300:!0,301:!0,302:!0,303:!0,305:!0,307:!0,308:!0},So.empty={204:!0,205:!0,304:!0},So.retry={502:!0,503:!0,504:!0};var Fo,ko={exports:{}},Ao={exports:{}};try{var jo=require("util");if("function"!=typeof jo.inherits)throw"";ko.exports=jo.inherits}catch(e){ko.exports=(Fo||(Fo=1,Ao.exports="function"==typeof Object.create?function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}),Ao.exports)}var Oo=ko.exports,Io=function(e){return e.split(" ").map(function(e){return e.slice(0,1).toUpperCase()+e.slice(1)}).join("").replace(/[^ _0-9a-z]/gi,"")};!function(e){var t,r=so("http-errors"),n=xo,i=Po,a=Oo,s=Io;function o(e){return Number(String(e).charAt(0)+"00")}function c(e,t){var r=Object.getOwnPropertyDescriptor(e,"name");r&&r.configurable&&(r.value=t,Object.defineProperty(e,"name",r))}function u(e){return"Error"===e.slice(-5)?e:e+"Error"}e.exports=function e(){for(var t,n,a=500,s={},c=0;c<arguments.length;c++){var u=arguments[c],l=typeof u;if("object"===l&&u instanceof Error)a=(t=u).status||t.statusCode||a;else if("number"===l&&0===c)a=u;else if("string"===l)n=u;else{if("object"!==l)throw new TypeError("argument #"+(c+1)+" unsupported type "+l);s=u}}"number"==typeof a&&(a<400||a>=600)&&r("non-error status code; use only 4xx or 5xx status codes");("number"!=typeof a||!i.message[a]&&(a<400||a>=600))&&(a=500);var d=e[a]||e[o(a)];t||(t=d?new d(n):new Error(n||i.message[a]),Error.captureStackTrace(t,e));d&&t instanceof d&&t.status===a||(t.expose=a<500,t.status=t.statusCode=a);for(var f in s)"status"!==f&&"statusCode"!==f&&(t[f]=s[f]);return t},e.exports.HttpError=function(){function e(){throw new TypeError("cannot construct abstract class")}return a(e,Error),e}(),e.exports.isHttpError=(t=e.exports.HttpError,function(e){return!(!e||"object"!=typeof e)&&(e instanceof t||e instanceof Error&&"boolean"==typeof e.expose&&"number"==typeof e.statusCode&&e.status===e.statusCode)}),function(e,t,r){t.forEach(function(t){var l,d=s(i.message[t]);switch(o(t)){case 400:l=function(e,t,r){var s=u(t);function o(e){var t=null!=e?e:i.message[r],a=new Error(t);return Error.captureStackTrace(a,o),n(a,o.prototype),Object.defineProperty(a,"message",{enumerable:!0,configurable:!0,value:t,writable:!0}),Object.defineProperty(a,"name",{enumerable:!1,configurable:!0,value:s,writable:!0}),a}return a(o,e),c(o,s),o.prototype.status=r,o.prototype.statusCode=r,o.prototype.expose=!0,o}(r,d,t);break;case 500:l=function(e,t,r){var s=u(t);function o(e){var t=null!=e?e:i.message[r],a=new Error(t);return Error.captureStackTrace(a,o),n(a,o.prototype),Object.defineProperty(a,"message",{enumerable:!0,configurable:!0,value:t,writable:!0}),Object.defineProperty(a,"name",{enumerable:!1,configurable:!0,value:s,writable:!0}),a}return a(o,e),c(o,s),o.prototype.status=r,o.prototype.statusCode=r,o.prototype.expose=!1,o}(r,d,t)}l&&(e[t]=l,e[d]=l)})}(e.exports,i.codes,e.exports.HttpError)}(io);var No=io.exports,Do=function(e){if(!e)throw new TypeError("argument stream is required");if("function"==typeof e.unpipe)return void e.unpipe();if(!function(e){for(var t=e.listeners("data"),r=0;r<t.length;r++)if("ondata"===t[r].name)return!0;return!1}(e))return;for(var t,r=e.listeners("close"),n=0;n<r.length;n++)"cleanup"!==(t=r[n]).name&&"onclose"!==t.name||t.call(e)};var To=function(){try{return require("async_hooks")}catch(e){return{}}}(),Co=no,Ro=No,Mo=h,qo=Do,zo=function(e,t,r){var n=r,i=t||{};if(void 0===e)throw new TypeError("argument stream is required");if("object"!=typeof e||null===e||"function"!=typeof e.on)throw new TypeError("argument stream must be a stream");!0!==t&&"string"!=typeof t||(i={encoding:t});"function"==typeof t&&(n=t,i={});if(void 0!==n&&"function"!=typeof n)throw new TypeError("argument callback must be a function");if(!n&&!Br.Promise)throw new TypeError("argument callback is required");var a=!0!==i.encoding?i.encoding:"utf-8",s=Co.parse(i.limit),o=null==i.length||isNaN(i.length)?null:parseInt(i.length,10);if(n)return Lo(e,a,o,s,function(e){var t;To.AsyncResource&&(t=new To.AsyncResource(e.name||"bound-anonymous-fn"));if(!t||!t.runInAsyncScope)return e;return t.runInAsyncScope.bind(t,e,null)}(n));return new Promise(function(t,r){Lo(e,a,o,s,function(e,n){if(e)return r(e);t(n)})})},Uo=/^Encoding not recognized: /;function Lo(e,t,r,n,i){var a=!1,s=!0;if(null!==n&&null!==r&&r>n)return d(Ro(413,"request entity too large",{expected:r,length:r,limit:n,type:"entity.too.large"}));var o=e.Ke;if(e.Ge||o&&(o.encoding||o.decoder))return d(Ro(500,"stream encoding should not be set",{type:"stream.encoding.set"}));if(void 0!==e.readable&&!e.readable)return d(Ro(500,"stream is not readable",{type:"stream.not.readable"}));var c,u=0;try{c=function(e){if(!e)return null;try{return Mo.getDecoder(e)}catch(t){if(!Uo.test(t.message))throw t;throw Ro(415,"specified encoding unsupported",{encoding:e,type:"encoding.unsupported"})}}(t)}catch(e){return d(e)}var l=c?"":[];function d(){for(var t=new Array(arguments.length),r=0;r<t.length;r++)t[r]=arguments[r];function n(){m(),t[0]&&function(e){qo(e),"function"==typeof e.pause&&e.pause()}(e),i.apply(null,t)}a=!0,s?process.nextTick(n):n()}function f(){a||d(Ro(400,"request aborted",{code:"ECONNABORTED",expected:r,length:r,received:u,type:"request.aborted"}))}function h(e){a||(u+=e.length,null!==n&&u>n?d(Ro(413,"request entity too large",{limit:n,received:u,type:"entity.too.large"})):c?l+=c.write(e):l.push(e))}function p(e){if(!a){if(e)return d(e);if(null!==r&&u!==r)d(Ro(400,"request size did not match content length",{expected:r,length:r,received:u,type:"request.size.invalid"}));else d(null,c?l+(c.end()||""):Buffer.concat(l))}}function m(){l=null,e.removeListener("aborted",f),e.removeListener("data",h),e.removeListener("end",p),e.removeListener("error",p),e.removeListener("close",m)}e.on("aborted",f),e.on("close",m),e.on("data",h),e.on("end",p),e.on("error",p),s=!1}const Zo=Jr(zo);var Vo={},Bo=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,Jo=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,Ho=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,Ko=/\\([\u000b\u0020-\u00ff])/g,Go=/([\\"])/g,Yo=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function Wo(e){var t=String(e);if(Ho.test(t))return t;if(t.length>0&&!Jo.test(t))throw new TypeError("invalid parameter value");return'"'+t.replace(Go,"\\$1")+'"'}function Qo(e){this.parameters=Object.create(null),this.type=e}Vo.format=function(e){if(!e||"object"!=typeof e)throw new TypeError("argument obj is required");var t=e.parameters,r=e.type;if(!r||!Yo.test(r))throw new TypeError("invalid type");var n=r;if(t&&"object"==typeof t)for(var i,a=Object.keys(t).sort(),s=0;s<a.length;s++){if(!Ho.test(i=a[s]))throw new TypeError("invalid parameter name");n+="; "+i+"="+Wo(t[i])}return n},Vo.parse=function(e){if(!e)throw new TypeError("argument string is required");var t="object"==typeof e?function(e){var t;"function"==typeof e.getHeader?t=e.getHeader("content-type"):"object"==typeof e.headers&&(t=e.headers&&e.headers["content-type"]);if("string"!=typeof t)throw new TypeError("content-type header is missing from object");return t}(e):e;if("string"!=typeof t)throw new TypeError("argument string is required to be a string");var r=t.indexOf(";"),n=-1!==r?t.slice(0,r).trim():t.trim();if(!Yo.test(n))throw new TypeError("invalid media type");var i=new Qo(n.toLowerCase());if(-1!==r){var a,s,o;for(Bo.lastIndex=r;s=Bo.exec(t);){if(s.index!==r)throw new TypeError("invalid parameter format");r+=s[0].length,a=s[1].toLowerCase(),34===(o=s[2]).charCodeAt(0)&&-1!==(o=o.slice(1,-1)).indexOf("\\")&&(o=o.replace(Ko,"$1")),i.parameters[a]=o}if(r!==t.length)throw new TypeError("invalid parameter format")}return i};class Xo{constructor(e){var t,r;this.Z=!1,this.Ye=new Map,this.We=new Map,this.Qe=new Map,this.Xe=!1,this.et=!1,this.tt="_GET_stream",this.sessionIdGenerator=e.sessionIdGenerator,this.et=null!==(t=e.enableJsonResponse)&&void 0!==t&&t,this.rt=e.eventStore,this.nt=e.onsessioninitialized,this.it=e.allowedHosts,this.st=e.allowedOrigins,this.ot=null!==(r=e.enableDnsRebindingProtection)&&void 0!==r&&r}async start(){if(this.Z)throw new Error("Transport already started");this.Z=!0}validateRequestHeaders(e){if(this.ot){if(this.it&&this.it.length>0){const t=e.headers.host;if(!t||!this.it.includes(t))return`Invalid Host header: ${t}`}if(this.st&&this.st.length>0){const t=e.headers.origin;if(!t||!this.st.includes(t))return`Invalid Origin header: ${t}`}}}async handleRequest(e,t,r){var n;const i=this.validateRequestHeaders(e);if(i)return t.writeHead(403).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:i},id:null})),void(null===(n=this.onerror)||void 0===n||n.call(this,new Error(i)));"POST"===e.method?await this.handlePostRequest(e,t,r):"GET"===e.method?await this.handleGetRequest(e,t):"DELETE"===e.method?await this.handleDeleteRequest(e,t):await this.handleUnsupportedRequest(t)}async handleGetRequest(e,t){const r=e.headers.accept;if(!(null==r?void 0:r.includes("text/event-stream")))return void t.writeHead(406).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Not Acceptable: Client must accept text/event-stream"},id:null}));if(!this.validateSession(e,t))return;if(!this.validateProtocolVersion(e,t))return;if(this.rt){const r=e.headers["last-event-id"];if(r)return void await this.replayEvents(r,t)}const n={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};void 0!==this.sessionId&&(n["mcp-session-id"]=this.sessionId),void 0===this.Ye.get(this.tt)?(t.writeHead(200,n).flushHeaders(),this.Ye.set(this.tt,t),t.on("close",()=>{this.Ye.delete(this.tt)})):t.writeHead(409).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Conflict: Only one SSE stream is allowed per session"},id:null}))}async replayEvents(e,t){var r,n;if(this.rt)try{const n={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};void 0!==this.sessionId&&(n["mcp-session-id"]=this.sessionId),t.writeHead(200,n).flushHeaders();const i=await(null===(r=this.rt)||void 0===r?void 0:r.replayEventsAfter(e,{send:async(e,r)=>{var n;this.writeSSEEvent(t,r,e)||(null===(n=this.onerror)||void 0===n||n.call(this,new Error("Failed replay events")),t.end())}}));this.Ye.set(i,t)}catch(e){null===(n=this.onerror)||void 0===n||n.call(this,e)}}writeSSEEvent(e,t,r){let n="event: message\n";return r&&(n+=`id: ${r}\n`),n+=`data: ${JSON.stringify(t)}\n\n`,e.write(n)}async handleUnsupportedRequest(e){e.writeHead(405,{Allow:"GET, POST, DELETE"}).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))}async handlePostRequest(e,t,r){var n,i,a,s,o;try{const o=e.headers.accept;if(!(null==o?void 0:o.includes("application/json"))||!o.includes("text/event-stream"))return void t.writeHead(406).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Not Acceptable: Client must accept both application/json and text/event-stream"},id:null}));const c=e.headers["content-type"];if(!c||!c.includes("application/json"))return void t.writeHead(415).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Unsupported Media Type: Content-Type must be application/json"},id:null}));const u=e.auth,l={headers:e.headers};let d,f;if(void 0!==r)d=r;else{const t=Vo.parse(c),r=await Zo(e,{limit:"4mb",encoding:null!==(n=t.parameters.charset)&&void 0!==n?n:"utf-8"});d=JSON.parse(r.toString())}f=Array.isArray(d)?d.map(e=>_t.parse(e)):[_t.parse(d)];const h=f.some(It);if(h){if(this.Xe&&void 0!==this.sessionId)return void t.writeHead(400).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32600,message:"Invalid Request: Server already initialized"},id:null}));if(f.length>1)return void t.writeHead(400).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32600,message:"Invalid Request: Only one initialization request is allowed"},id:null}));this.sessionId=null===(i=this.sessionIdGenerator)||void 0===i?void 0:i.call(this),this.Xe=!0,this.sessionId&&this.nt&&this.nt(this.sessionId)}if(!h){if(!this.validateSession(e,t))return;if(!this.validateProtocolVersion(e,t))return}const m=f.some(gt);if(m){if(m){const e=p();if(!this.et){const e={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};void 0!==this.sessionId&&(e["mcp-session-id"]=this.sessionId),t.writeHead(200,e)}for(const r of f)gt(r)&&(this.Ye.set(e,t),this.We.set(r.id,e));t.on("close",()=>{this.Ye.delete(e)});for(const e of f)null===(s=this.onmessage)||void 0===s||s.call(this,e,{authInfo:u,requestInfo:l})}}else{t.writeHead(202).end();for(const e of f)null===(a=this.onmessage)||void 0===a||a.call(this,e,{authInfo:u,requestInfo:l})}}catch(e){t.writeHead(400).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error",data:String(e)},id:null})),null===(o=this.onerror)||void 0===o||o.call(this,e)}}async handleDeleteRequest(e,t){this.validateSession(e,t)&&this.validateProtocolVersion(e,t)&&(await this.close(),t.writeHead(200).end())}validateSession(e,t){if(void 0===this.sessionIdGenerator)return!0;if(!this.Xe)return t.writeHead(400).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: Server not initialized"},id:null})),!1;const r=e.headers["mcp-session-id"];return r?Array.isArray(r)?(t.writeHead(400).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: Mcp-Session-Id header must be a single value"},id:null})),!1):r===this.sessionId||(t.writeHead(404).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32001,message:"Session not found"},id:null})),!1):(t.writeHead(400).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: Mcp-Session-Id header is required"},id:null})),!1)}validateProtocolVersion(e,t){var r;let n=null!==(r=e.headers["mcp-protocol-version"])&&void 0!==r?r:"2025-03-26";return Array.isArray(n)&&(n=n[n.length-1]),!!st.includes(n)||(t.writeHead(400).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:`Bad Request: Unsupported protocol version (supported versions: ${st.join(", ")})`},id:null})),!1)}async close(){var e;this.Ye.forEach(e=>{e.end()}),this.Ye.clear(),this.Qe.clear(),null===(e=this.onclose)||void 0===e||e.call(this)}async send(e,t){let r=null==t?void 0:t.relatedRequestId;if((Et(e)||Pt(e))&&(r=e.id),void 0===r){if(Et(e)||Pt(e))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");const t=this.Ye.get(this.tt);if(void 0===t)return;let r;return this.rt&&(r=await this.rt.storeEvent(this.tt,e)),void this.writeSSEEvent(t,e,r)}const n=this.We.get(r),i=this.Ye.get(n);if(!n)throw new Error(`No connection established for request ID: ${String(r)}`);if(!this.et){let t;this.rt&&(t=await this.rt.storeEvent(n,e)),i&&this.writeSSEEvent(i,e,t)}if(Et(e)||Pt(e)){this.Qe.set(r,e);const t=Array.from(this.We.entries()).filter(([e,t])=>this.Ye.get(t)===i).map(([e])=>e);if(t.every(e=>this.Qe.has(e))){if(!i)throw new Error(`No connection established for request ID: ${String(r)}`);if(this.et){const e={"Content-Type":"application/json"};void 0!==this.sessionId&&(e["mcp-session-id"]=this.sessionId);const r=t.map(e=>this.Qe.get(e));i.writeHead(200,e),i.end(1===r.length?JSON.stringify(r[0]):JSON.stringify(r))}else i.end();for(const e of t)this.Qe.delete(e),this.We.delete(e)}}}}class ec{constructor(e,t,r){this.ct=e,this.res=t,this.ut=p(),this.J=r||{enableDnsRebindingProtection:!1}}validateRequestHeaders(e){if(this.J.enableDnsRebindingProtection){if(this.J.allowedHosts&&this.J.allowedHosts.length>0){const t=e.headers.host;if(!t||!this.J.allowedHosts.includes(t))return`Invalid Host header: ${t}`}if(this.J.allowedOrigins&&this.J.allowedOrigins.length>0){const t=e.headers.origin;if(!t||!this.J.allowedOrigins.includes(t))return`Invalid Origin header: ${t}`}}}async start(){if(this.dt)throw new Error("SSEServerTransport already started! If using Server class, note that connect() calls start() automatically.");this.res.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"});const e=new i(this.ct,"http://localhost");e.searchParams.set("sessionId",this.ut);this.res.write(`event: endpoint\ndata: ${e.pathname+e.search+e.hash}\n\n`),this.dt=this.res,this.res.on("close",()=>{var e;this.dt=void 0,null===(e=this.onclose)||void 0===e||e.call(this)})}async handlePostMessage(e,t,r){var n,i,a,s;if(!this.dt){const e="SSE connection not established";throw t.writeHead(500).end(e),new Error(e)}const o=this.validateRequestHeaders(e);if(o)return t.writeHead(403).end(o),void(null===(n=this.onerror)||void 0===n||n.call(this,new Error(o)));const c=e.auth,u={headers:e.headers};let l;try{const t=Vo.parse(null!==(i=e.headers["content-type"])&&void 0!==i?i:"");if("application/json"!==t.type)throw new Error(`Unsupported content-type: ${t.type}`);l=null!=r?r:await Zo(e,{limit:"4mb",encoding:null!==(a=t.parameters.charset)&&void 0!==a?a:"utf-8"})}catch(e){return t.writeHead(400).end(String(e)),void(null===(s=this.onerror)||void 0===s||s.call(this,e))}try{await this.handleMessage("string"==typeof l?JSON.parse(l):l,{requestInfo:u,authInfo:c})}catch(e){return void t.writeHead(400).end(`Invalid message: ${l}`)}t.writeHead(202).end("Accepted")}async handleMessage(e,t){var r,n;let i;try{i=_t.parse(e)}catch(e){throw null===(r=this.onerror)||void 0===r||r.call(this,e),e}null===(n=this.onmessage)||void 0===n||n.call(this,i,t)}async close(){var e,t;null===(e=this.dt)||void 0===e||e.end(),this.dt=void 0,null===(t=this.onclose)||void 0===t||t.call(this)}async send(e){if(!this.dt)throw new Error("Not connected");this.dt.write(`event: message\ndata: ${JSON.stringify(e)}\n\n`)}get sessionId(){return this.ut}}function tc(e){const t={...ls(e)};return e.query&&(!t.apiKey&&e.query.apiKey&&(t.apiKey=e.query.apiKey),!t.apiKey&&e.query.API_KEY&&(t.apiKey=e.query.API_KEY)),t}class rc{config;sessions=new Map;cleanupInterval;CLEANUP_INTERVAL=3e4;SESSION_TIMEOUT=3e5;constructor(e){this.config=e,this.cleanupInterval=setInterval(()=>{this.cleanupInactiveSessions()},this.CLEANUP_INTERVAL)}async createSession(e,t){const r=new Js({name:this.config.name,version:this.config.version}).getServer(),n={sessionId:e.sessionId,mcpServer:r,transport:e,createdAt:Date.now(),lastActivity:Date.now(),isConnected:!0,authInfo:t};return await r.connect(e),this.sessions.set(n.sessionId,n),ys.info({session:n.sessionId.substring(0,8)},"创建新 SSE 会话"),n}getSession(e){const t=this.sessions.get(e);return t&&(t.lastActivity=Date.now()),t}async removeSession(e){const t=this.sessions.get(e);if(t){try{t.isConnected=!1,await t.mcpServer.close(),ys.info({session:e.substring(0,8)},"关闭 SSE 会话")}catch(t){ys.warn({session:e.substring(0,8),err:t},"关闭会话时出错")}this.sessions.delete(e),ys.info({activeSessions:this.sessions.size},"SSE 活跃会话数")}}cleanupInactiveSessions(){const e=Date.now(),t=[];for(const[r,n]of this.sessions){const i=e-n.lastActivity>this.SESSION_TIMEOUT;if(i||!n.isConnected){t.push(r);const a=i?`不活跃${Math.round((e-n.lastActivity)/1e3)}秒`:"标记为断开";ys.info({session:r.substring(0,8),reason:a},"清理会话")}}t.forEach(e=>{this.removeSession(e).catch(t=>{ys.warn({session:e.substring(0,8),err:t},"清理会话失败")})}),t.length>0&&ys.info({removed:t.length},"SSE 清理完成")}getStats(){const e=Date.now(),t=Array.from(this.sessions.values()).filter(e=>e.isConnected),r=t.filter(t=>e-t.lastActivity<6e4);return{total:this.sessions.size,active:t.length,recentlyActive:r.length,oldestSession:t.length>0?Math.min(...t.map(e=>e.createdAt)):null,sessions:Array.from(this.sessions.entries()).map(([t,r])=>({id:t.substring(0,8)+"...",isConnected:r.isConnected,createdAt:new Date(r.createdAt).toISOString(),lastActivity:new Date(r.lastActivity).toISOString(),ageMinutes:Math.round((e-r.createdAt)/6e4),inactiveSeconds:Math.round((e-r.lastActivity)/1e3)}))}}async destroy(){this.cleanupInterval&&clearInterval(this.cleanupInterval);const e=Array.from(this.sessions.keys());for(const t of e)await this.removeSession(t)}}e.config(),async function(){const e=function(){try{const e=r.dirname(n(import.meta.url)),i=r.resolve(e,"../package.json"),a=JSON.parse(t.readFileSync(i,"utf8"));return{name:a.name,version:a.version}}catch(e){return{name:"mcp-server",version:"1.0.0"}}}(),i=process.argv.slice(2);let a=!1,s=!1,o=!1;if(0===i.length||i.includes("--all")?(a=!0,s=!0,o=!0):(i.includes("--stdio")&&(a=!0),i.includes("--http")&&(s=!0),i.includes("--sse")&&(o=!0)),a)try{await Gs({name:e.name,version:e.version})}catch(e){ys.error({err:e},"启动 stdio 服务器失败")}if(s)try{const t=function(e){const t=f();t.use(f.json());const r=new Js({name:e.name,version:e.version}).getServer();return t.use((e,t,r)=>{e.authInfo=ls(e);const n=e.headers["x-request-id"]||e.headers["request-id"]||e.headers.mcpsession||e.headers.conversation_id,i=e.body?.id?String(e.body.id):void 0;e.conversation_id=n||i||`req-${Date.now()}-${Math.random().toString(36).slice(2,10)}`;const a=us(e);e.client_ip=a,e.log=ws({conversation_id:e.conversation_id,client_env:e.authInfo?.client_env,client_src:e.authInfo?.client_src,channel:e.authInfo?.channel,client_ip:a}),r()}),t.post("/mcp",async(e,t)=>{const n=Date.now(),i=e.body?.method||"unknown";e.log?.info({method:i},"MCP request start");try{const a=new Xo({sessionIdGenerator:void 0,enableJsonResponse:!0});t.on("close",()=>{a.close()}),await r.connect(a),a.httpContext=()=>({authInfo:e.authInfo,conversation_id:e.conversation_id,client_ip:e.client_ip}),await a.handleRequest(e,t,e.body);const s=Date.now()-n;e.log?.info({method:i,consume:s},"MCP request done")}catch(r){const a=Date.now()-n;e.log?.error({method:i,consume:a,errno:-32e3,errmsg:r?.message},"MCP request error"),t.status(500).json({jsonrpc:"2.0",error:{code:-32e3,message:"服务器内部错误",data:r.message},id:e.body?.id??null})}}),t.get("/mcp",async(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))}),t.delete("/mcp",async(e,t)=>{t.writeHead(405).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))}),t.get("/mcp/health",(t,r)=>{r.json({status:"ok",version:e.version,transport:"streamable-http",mode:"stateless",details:"每个请求都使用独立的会话与传输实例,处理完成即释放资源"})}),t.get("/mcp/dashboard",(t,r)=>{r.send(`\n <!DOCTYPE html>\n <html>\n <head>\n <title>MCP服务器 - ${e.name}</title>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <style>\n body { font-family: system-ui; max-width: 800px; margin: 0 auto; padding: 2rem; }\n code { background: #f0f0f0; padding: 0.2rem 0.4rem; border-radius: 3px; }\n .endpoint { margin: 1rem 0; }\n .mode-info { background: #f9f9f9; padding: 1rem; border-radius: 5px; margin: 1rem 0; }\n .stateless-info { color: #0066cc; }\n </style>\n </head>\n <body>\n <h1>MCP服务器正在运行</h1>\n <p>版本: ${e.version}</p>\n <p>传输方式: Streamable HTTP</p>\n <p>会话模式: <strong class="stateless-info">stateless</strong></p>\n \n <div class="mode-info">\n <h3>无状态模式 (Stateless) 信息</h3>\n <p>在无状态模式下:</p>\n <ul>\n <li>每个请求创建独立的MCP服务器与传输实例</li>\n <li>请求结束后立即释放资源,避免会话冲突</li>\n <li>不支持SSE会话保持与DELETE会话终止</li>\n </ul>\n </div>\n </body>\n </html>\n `)}),{app:t,start:()=>{const r=t.listen(e.port,()=>{ys.info({port:e.port,transport:"streamable-http",mode:"stateless"},"MCP server started")});process.on("SIGTERM",()=>{ys.warn("SIGTERM received, closing server..."),r.close(()=>{ys.info("HTTP server closed"),process.exit(0)})})}}}({name:e.name,version:e.version,port:5e3});t.start()}catch(e){ys.error({err:e},"启动Streamable HTTP服务器失败")}if(o)try{const t=function(e){const t=f();t.use(f.json());const r=new rc(e);return t.use((e,t,r)=>{e.authInfo=tc(e);const n=e.headers["x-request-id"]||e.headers["request-id"]||e.headers.mcpsession||e.headers.conversation_id,i=e.body?.id?String(e.body.id):void 0;e.conversation_id=n||i||`req-${Date.now()}-${Math.random().toString(36).slice(2,10)}`;const a=us(e);e.client_ip=a,e.log=ws({conversation_id:e.conversation_id,client_env:e.authInfo?.client_env,client_src:e.authInfo?.client_src,channel:e.authInfo?.channel,client_ip:a}),r()}),t.use((e,t,r)=>{t.header("Access-Control-Allow-Origin","*"),t.header("Access-Control-Allow-Methods","GET, POST, OPTIONS"),t.header("Access-Control-Allow-Headers","Content-Type, Authorization"),"OPTIONS"!==e.method?r():t.sendStatus(200)}),t.get("/sse",async(t,n)=>{try{const i=new ec(`http://localhost:${e.port}/messages`,n),a=await r.createSession(i,t.authInfo);i.httpContext=()=>({authInfo:t.authInfo,conversation_id:t.conversation_id,client_ip:t.client_ip}),n.on("close",async()=>{ys.info({session:a.sessionId.substring(0,8)},"SSE 连接关闭"),await r.removeSession(a.sessionId)}),n.on("error",async e=>{ys.error({session:a.sessionId.substring(0,8),err:e},"SSE 连接错误"),await r.removeSession(a.sessionId)})}catch(e){ys.error({err:e},"创建 SSE 连接失败"),n.status(500).send("创建SSE连接失败")}}),t.post("/messages",async(e,t)=>{const n=Date.now(),i=e.body?.method||"unknown";e.log?.info({method:i},"SSE 请求start");let a=e.query.sessionId;if(a||(a=e.headers["x-session-id"]||e.headers["session-id"]||e.headers["mcp-session-id"]),!a&&e.body&&e.body.sessionId&&(a=e.body.sessionId),!a)return void t.status(400).json({error:"缺失会话ID参数",details:"请通过URL参数(?sessionId=xxx)、请求头(X-Session-Id)或请求体(body.sessionId)提供会话ID",activeSessions:Array.from(r.sessions.keys()).map(e=>e.substring(0,8)+"...")});let s=r.getSession(a);if(!s){const e=async(e,t=2e3,n=50)=>{const i=Date.now();for(;Date.now()-i<t;){const t=r.getSession(e);if(t)return t;await new Promise(e=>setTimeout(e,n))}};s=await e(a)}if(!s){const e=Array.from(r.sessions.keys()).map(e=>e.substring(0,8)+"...");return ys.warn({session:a.substring(0,8),activeSessions:e},"未找到会话(含重试)"),void t.status(400).json({error:"未找到指定会话ID的传输实例",providedSessionId:a.substring(0,8)+"...",activeSessions:e})}if(!s.isConnected)return ys.warn({session:a.substring(0,8)},"会话已断开"),void t.status(400).json({error:"会话已断开连接"});try{const r=tc(e),o={...s.authInfo,...r};!o.apiKey&&s.authInfo?.apiKey&&(o.apiKey=s.authInfo.apiKey),!o.ecsEnv&&s.authInfo?.ecsEnv&&(o.ecsEnv=s.authInfo.ecsEnv),e.authInfo=o,s.transport.httpContext=()=>({authInfo:e.authInfo,conversation_id:e.conversation_id,client_ip:e.client_ip,requestId:e.requestId||`sse-${s.sessionId.substring(0,8)}-${Date.now()}`}),await s.transport.handlePostMessage(e,t,e.body);const c=Date.now()-n;e.log?.info({method:i,consume:c,session:a.substring(0,8)},"SSE 请求done")}catch(r){const s=Date.now()-n,o=r instanceof Error?r.message:String(r);e.log?.error({method:i,consume:s,session:a.substring(0,8),errno:-32e3,errmsg:o},"SSE 请求错误"),t.status(500).json({error:"消息处理失败",details:r instanceof Error?r.message:String(r)})}}),t.post("/cleanup-connections",async(e,t)=>{try{const e=r.getStats();ys.info({stats:e},"收到连接清理请求"),t.json({message:"连接清理请求已处理",stats:{total:e.total,active:e.active,recentlyActive:e.recentlyActive}})}catch(e){ys.error({err:e},"连接清理失败"),t.status(500).json({error:"连接清理失败"})}}),t.get("/sse/health",(t,n)=>{const i=r.getStats();n.json({status:"ok",version:e.version,transport:"SSE",pid:process.pid,uptimeSec:Math.round(process.uptime()),timestamp:(new Date).toISOString(),sessions:{total:i.total,active:i.active,recentlyActive:i.recentlyActive}})}),t.get("/sse/dashboard",(t,n)=>{const i=r.getStats();n.send(`\n <html>\n <head>\n <title>MCP服务器 - ${e.name}</title>\n <meta charset="utf-8">\n <style>\n body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 40px; }\n .stats { background: #f5f5f5; padding: 20px; border-radius: 8px; margin: 20px 0; }\n .endpoint { background: #e8f4f8; padding: 10px; border-radius: 4px; margin: 10px 0; font-family: monospace; }\n .session { background: #fff; border: 1px solid #ddd; padding: 10px; margin: 5px 0; border-radius: 4px; }\n .active { border-left: 4px solid #4CAF50; }\n .inactive { border-left: 4px solid #ff9800; }\n </style>\n </head>\n <body>\n <h1>🚀 MCP服务器正在运行</h1>\n <div class="stats">\n <h2>📊 服务器状态</h2>\n <p><strong>名称:</strong> ${e.name}</p>\n <p><strong>版本:</strong> ${e.version}</p>\n <p><strong>传输方式:</strong> SSE (Server-Sent Events)</p>\n <p><strong>运行时间:</strong> ${Math.round(process.uptime())}秒</p>\n </div>\n \n <div class="stats">\n <h2>🔗 API端点</h2>\n <div class="endpoint">SSE端点: http://localhost:${e.port}/sse</div>\n <div class="endpoint">消息端点: http://localhost:${e.port}/messages</div>\n <div class="endpoint">状态API: http://localhost:${e.port}/status</div>\n <div class="endpoint">清理连接: http://localhost:${e.port}/cleanup-connections</div>\n </div>\n\n <div class="stats">\n <h2>🔐 鉴权配置说明</h2>\n <p><strong>支持的API_KEY传递方式:</strong></p>\n <div class="endpoint">URL参数: http://localhost:${e.port}/sse?apiKey=YOUR_API_KEY</div>\n <div class="endpoint">HTTP请求头: X-API-Key: YOUR_API_KEY</div>\n <div class="endpoint">Authorization头: Authorization: Bearer YOUR_API_KEY</div>\n <div class="endpoint">环境变量: API_KEY=YOUR_API_KEY</div>\n <p><strong>可选参数:</strong></p>\n <div class="endpoint">环境配置: ?ecsEnv=prod 或 ?ecsEnv=test (默认为prod)</div>\n </div>\n\n <div class="stats">\n <h2>📈 会话统计</h2>\n <p><strong>总会话数:</strong> ${i.total}</p>\n <p><strong>活跃会话:</strong> ${i.active}</p>\n <p><strong>最近活跃:</strong> ${i.recentlyActive}</p>\n ${i.oldestSession?`<p><strong>最早会话:</strong> ${new Date(i.oldestSession).toLocaleString()}</p>`:""}\n </div>\n\n ${i.sessions.length>0?`\n <div class="stats">\n <h2>🔍 会话详情</h2>\n ${i.sessions.map(e=>`\n <div class="session ${e.isConnected?"active":"inactive"}">\n <strong>会话 ${e.id}</strong> \n ${e.isConnected?"🟢 连接中":"🔴 已断开"}<br>\n 创建时间: ${new Date(e.createdAt).toLocaleString()}<br>\n 最后活动: ${new Date(e.lastActivity).toLocaleString()}<br>\n 存活时间: ${e.ageMinutes}分钟,不活跃: ${e.inactiveSeconds}秒\n </div>\n `).join("")}\n </div>\n `:""}\n\n <script>\n // 每30秒刷新页面以更新状态\n setTimeout(() => window.location.reload(), 30000);\n <\/script>\n </body>\n </html>\n `)}),process.on("SIGTERM",async()=>{ys.warn("收到 SIGTERM 信号,开始优雅关闭..."),await r.destroy(),process.exit(0)}),process.on("SIGINT",async()=>{ys.warn("收到 SIGINT 信号,开始优雅关闭..."),await r.destroy(),process.exit(0)}),{app:t,sessionManager:r,start:()=>t.listen(e.port,()=>{ys.info({port:e.port,transport:"sse",mode:""},"MCP server started")})}}({name:e.name,version:e.version,port:5001});t.start()}catch(e){ys.error({err:e},"启动SSE服务器失败")}a||s||o||!(i.length>0)||i.includes("--all")||ys.warn("没有指定有效的服务类型启动,请使用 --stdio, --http, --sse, 或 --all。")}().catch(e=>{ys.fatal({err:e},"Fatal error in main()"),process.exit(1)});
|