zaileys 1.1.28 → 1.1.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("baileys"),t=require("events"),a=require("figlet"),s=require("node-cache"),n=require("ora"),i=require("pino"),r=require("better-sqlite3"),o=require("fs"),d=require("kysely"),c=require("mysql2"),l=require("path"),u=require("pg"),p=require("url"),h=require("qrcode"),m=require("stream"),f=require("fast-levenshtein");function g(e){return e&&e.__esModule?e:{default:e}}function y(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(a){if("default"!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}})),t.default=e,Object.freeze(t)}var v,_,w,b=g(a),x=g(s),k=g(n),C=g(i),M=g(r),I=g(c),S=g(l),N=g(h),T=y(f),A=Object.defineProperty,O=(e="")=>{try{return JSON.parse(e)}catch{return JSON.parse(JSON.stringify(e))}},E=(e={})=>{try{return JSON.stringify(e)}catch{return JSON.stringify(JSON.parse(JSON.stringify(e)))}},Z=(e="",t="")=>e?e.toLowerCase().includes(t.toLowerCase()):null,L=(e,t)=>e&&"object"==typeof e?Array.isArray(e)?e.map((e=>L(e,t))):Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e))).map((([e,a])=>[e,"object"==typeof a?L(a,t):a]))):e,j=e=>{const t={...e.fingerprint,deviceIndexes:Array.isArray(e.fingerprint.deviceIndexes)?e.fingerprint.deviceIndexes:[]},a={keyData:Array.isArray(e.keyData)?e.keyData:new Uint8Array,fingerprint:{rawId:t.rawId||0,currentIndex:t.rawId||0,deviceIndexes:t.deviceIndexes},timestamp:(s=e.timestamp,"string"==typeof s?parseInt(s,10):s)};var s;return"string"==typeof e.keyData&&(a.keyData=(e=>{let t=e.length;if(!t)return new Uint8Array(1);let a=0;for(;--t%4>1&&"="===e.charAt(t);)++a;return new Uint8Array(Math.ceil(3*e.length)/4-a).fill(0)})(e.keyData)),a},P={};((e,t)=>{for(var a in t)A(e,a,{get:t[a],enumerable:!0})})(P,{BRAND:()=>mt,DIRTY:()=>X,EMPTY_PATH:()=>B,INVALID:()=>Q,NEVER:()=>da,OK:()=>ee,ParseStatus:()=>H,Schema:()=>ce,ZodAny:()=>qe,ZodArray:()=>Ue,ZodBigInt:()=>Ze,ZodBoolean:()=>Le,ZodBranded:()=>ft,ZodCatch:()=>pt,ZodDate:()=>je,ZodDefault:()=>ut,ZodDiscriminatedUnion:()=>Ge,ZodEffects:()=>dt,ZodEnum:()=>it,ZodError:()=>z,ZodFirstPartyTypeKind:()=>wt,ZodFunction:()=>tt,ZodIntersection:()=>Ye,ZodIssueCode:()=>q,ZodLazy:()=>at,ZodLiteral:()=>st,ZodMap:()=>Xe,ZodNaN:()=>ht,ZodNativeEnum:()=>rt,ZodNever:()=>ze,ZodNull:()=>Fe,ZodNullable:()=>lt,ZodNumber:()=>Ee,ZodObject:()=>Ke,ZodOptional:()=>ct,ZodParsedType:()=>R,ZodPipeline:()=>gt,ZodPromise:()=>ot,ZodReadonly:()=>yt,ZodRecord:()=>Qe,ZodSchema:()=>ce,ZodSet:()=>et,ZodString:()=>Ae,ZodSymbol:()=>Pe,ZodTransformer:()=>dt,ZodTuple:()=>He,ZodType:()=>ce,ZodUndefined:()=>Re,ZodUnion:()=>Je,ZodUnknown:()=>$e,ZodVoid:()=>De,addIssueToContext:()=>G,any:()=>Zt,array:()=>Rt,bigint:()=>St,boolean:()=>Nt,coerce:()=>oa,custom:()=>_t,date:()=>Tt,datetimeRegex:()=>Se,defaultErrorMap:()=>D,discriminatedUnion:()=>zt,effect:()=>Xt,enum:()=>Yt,function:()=>Bt,getErrorMap:()=>K,getParsedType:()=>F,instanceof:()=>kt,intersection:()=>Dt,isAborted:()=>te,isAsync:()=>ne,isDirty:()=>ae,isValid:()=>se,late:()=>xt,lazy:()=>Gt,literal:()=>Wt,makeIssue:()=>J,map:()=>Kt,nan:()=>It,nativeEnum:()=>Ht,never:()=>jt,null:()=>Et,nullable:()=>ta,number:()=>Mt,object:()=>Ft,objectUtil:()=>w,oboolean:()=>ra,onumber:()=>ia,optional:()=>ea,ostring:()=>na,pipeline:()=>sa,preprocess:()=>aa,promise:()=>Qt,quotelessJson:()=>$,record:()=>Vt,set:()=>Jt,setErrorMap:()=>V,strictObject:()=>qt,string:()=>Ct,symbol:()=>At,transformer:()=>Xt,tuple:()=>Ut,undefined:()=>Ot,union:()=>$t,unknown:()=>Lt,util:()=>v,void:()=>Pt}),(_=v||(v={})).assertEqual=e=>{},_.assertIs=function(e){},_.assertNever=function(e){throw new Error},_.arrayToEnum=e=>{const t={};for(const a of e)t[a]=a;return t},_.getValidEnumValues=e=>{const t=_.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),a={};for(const s of t)a[s]=e[s];return _.objectValues(a)},_.objectValues=e=>_.objectKeys(e).map((function(t){return e[t]})),_.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.push(a);return t},_.find=(e,t)=>{for(const a of e)if(t(a))return a},_.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,_.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},_.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(w||(w={})).mergeShapes=(e,t)=>({...e,...t});var R=v.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),F=e=>{switch(typeof e){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(e)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(e)?R.array:null===e?R.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?R.promise:"undefined"!=typeof Map&&e instanceof Map?R.map:"undefined"!=typeof Set&&e instanceof Set?R.set:"undefined"!=typeof Date&&e instanceof Date?R.date:R.object;default:return R.unknown}},q=v.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),z=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};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},a={_errors:[]},s=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)a._errors.push(t(n));else{let e=a,s=0;for(;s<n.path.length;){const a=n.path[s];s===n.path.length-1?(e[a]=e[a]||{_errors:[]},e[a]._errors.push(t(n))):e[a]=e[a]||{_errors:[]},e=e[a],s++}}};return s(this),a}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,v.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},a=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):a.push(e(s));return{formErrors:a,fieldErrors:t}}get formErrors(){return this.flatten()}};z.create=e=>new z(e);var D=(e,t)=>{let a;switch(e.code){case q.invalid_type:a=e.received===R.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case q.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(e.expected,v.jsonStringifyReplacer)}`;break;case q.unrecognized_keys:a=`Unrecognized key(s) in object: ${v.joinValues(e.keys,", ")}`;break;case q.invalid_union:a="Invalid input";break;case q.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${v.joinValues(e.options)}`;break;case q.invalid_enum_value:a=`Invalid enum value. Expected ${v.joinValues(e.options)}, received '${e.received}'`;break;case q.invalid_arguments:a="Invalid function arguments";break;case q.invalid_return_type:a="Invalid function return type";break;case q.invalid_date:a="Invalid date";break;case q.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(a=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(a=`${a} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?a=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?a=`Invalid input: must end with "${e.validation.endsWith}"`:v.assertNever(e.validation):a="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case q.too_small:a="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?`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 q.too_big:a="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 q.custom:a="Invalid input";break;case q.invalid_intersection_types:a="Intersection results could not be merged";break;case q.not_multiple_of:a=`Number must be a multiple of ${e.multipleOf}`;break;case q.not_finite:a="Number must be finite";break;default:a=t.defaultError,v.assertNever(e)}return{message:a}},U=D;function V(e){U=e}function K(){return U}var J=e=>{const{data:t,path:a,errorMaps:s,issueData:n}=e,i=[...a,...n.path||[]],r={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const d=s.filter((e=>!!e)).slice().reverse();for(const e of d)o=e(r,{data:t,defaultError:o}).message;return{...n,path:i,message:o}},B=[];function G(e,t){const a=K(),s=J({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,a,a===D?void 0:D].filter((e=>!!e))});e.common.issues.push(s)}var W,Y,H=class e{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const a=[];for(const s of t){if("aborted"===s.status)return Q;"dirty"===s.status&&e.dirty(),a.push(s.value)}return{status:e.value,value:a}}static async mergeObjectAsync(t,a){const s=[];for(const e of a){const t=await e.key,a=await e.value;s.push({key:t,value:a})}return e.mergeObjectSync(t,s)}static mergeObjectSync(e,t){const a={};for(const s of t){const{key:t,value:n}=s;if("aborted"===t.status)return Q;if("aborted"===n.status)return Q;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!s.alwaysSet||(a[t.value]=n.value)}return{status:e.value,value:a}}},Q=Object.freeze({status:"aborted"}),X=e=>({status:"dirty",value:e}),ee=e=>({status:"valid",value:e}),te=e=>"aborted"===e.status,ae=e=>"dirty"===e.status,se=e=>"valid"===e.status,ne=e=>"undefined"!=typeof Promise&&e instanceof Promise;(Y=W||(W={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},Y.toString=e=>"string"==typeof e?e:e?.message;var ie=class{constructor(e,t,a,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=a,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},re=(e,t)=>{if(se(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._error)return this._error;const t=new z(e.common.issues);return this._error=t,this._error}}};function oe(e){if(!e)return{};const{errorMap:t,invalid_type_error:a,required_error:s,description:n}=e;if(t&&(a||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??s??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??a??n.defaultError}},description:n}}var de,ce=class{get description(){return this._def.description}_getType(e){return F(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:F(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new H,ctx:{common:e.parent.common,data:e.data,parsedType:F(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ne(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const a=this.safeParse(e,t);if(a.success)return a.data;throw a.error}safeParse(e,t){const a={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:F(e)},s=this._parseSync({data:e,path:a.path,parent:a});return re(a,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:F(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:t});return se(a)?{value:a.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((e=>se(e)?{value:e.value}:{issues:t.common.issues}))}async parseAsync(e,t){const a=await this.safeParseAsync(e,t);if(a.success)return a.data;throw a.error}async safeParseAsync(e,t){const a={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:F(e)},s=this._parse({data:e,path:a.path,parent:a}),n=await(ne(s)?s:Promise.resolve(s));return re(a,n)}refine(e,t){const a=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,s)=>{const n=e(t),i=()=>s.addIssue({code:q.custom,...a(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then((e=>!!e||(i(),!1))):!!n||(i(),!1)}))}refinement(e,t){return this._refinement(((a,s)=>!!e(a)||(s.addIssue("function"==typeof t?t(a,s):t),!1)))}_refinement(e){return new dt({schema:this,typeName:wt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return ct.create(this,this._def)}nullable(){return lt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ue.create(this)}promise(){return ot.create(this,this._def)}or(e){return Je.create([this,e],this._def)}and(e){return Ye.create(this,e,this._def)}transform(e){return new dt({...oe(this._def),schema:this,typeName:wt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ut({...oe(this._def),innerType:this,defaultValue:t,typeName:wt.ZodDefault})}brand(){return new ft({typeName:wt.ZodBranded,type:this,...oe(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new pt({...oe(this._def),innerType:this,catchValue:t,typeName:wt.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return gt.create(this,e)}readonly(){return yt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},le=/^c[^\s-]{8,}$/i,ue=/^[0-9a-z]+$/,pe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,he=/^[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,me=/^[a-z0-9_-]{21}$/i,fe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ge=/^[-+]?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)?)??$/,ye=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ve=/^(?:(?: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])$/,_e=/^(?:(?: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])$/,we=/^(([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]))$/,be=/^(([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])$/,xe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ke=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ce="((\\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])))",Me=new RegExp(`^${Ce}$`);function Ie(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 Se(e){let t=`${Ce}T${Ie(e)}`;const a=[];return a.push(e.local?"Z?":"Z"),e.offset&&a.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${a.join("|")})`,new RegExp(`^${t}$`)}function Ne(e,t){if(!fe.test(e))return!1;try{const[a]=e.split("."),s=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(a.length+(4-a.length%4)%4,"="),n=JSON.parse(atob(s));return"object"==typeof n&&null!==n&&((!("typ"in n)||"JWT"===n?.typ)&&(!!n.alg&&(!t||n.alg===t)))}catch{return!1}}function Te(e,t){return!("v4"!==t&&t||!_e.test(e))||!("v6"!==t&&t||!be.test(e))}var Ae=class e extends ce{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==R.string){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.string,received:t.parsedType}),Q}const t=new H;let a;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(a=this._getOrReturnCtx(e,a),G(a,{code:q.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("max"===i.kind)e.data.length>i.value&&(a=this._getOrReturnCtx(e,a),G(a,{code:q.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("length"===i.kind){const s=e.data.length>i.value,n=e.data.length<i.value;(s||n)&&(a=this._getOrReturnCtx(e,a),s?G(a,{code:q.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&G(a,{code:q.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)ye.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"email",code:q.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)de||(de=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),de.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"emoji",code:q.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)he.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"uuid",code:q.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)me.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"nanoid",code:q.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)le.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"cuid",code:q.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)ue.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"cuid2",code:q.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)pe.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"ulid",code:q.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a),G(a,{validation:"url",code:q.invalid_string,message:i.message}),t.dirty()}else if("regex"===i.kind){i.regex.lastIndex=0;i.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"regex",code:q.invalid_string,message:i.message}),t.dirty())}else if("trim"===i.kind)e.data=e.data.trim();else if("includes"===i.kind)e.data.includes(i.value,i.position)||(a=this._getOrReturnCtx(e,a),G(a,{code:q.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),t.dirty());else if("toLowerCase"===i.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===i.kind)e.data=e.data.toUpperCase();else if("startsWith"===i.kind)e.data.startsWith(i.value)||(a=this._getOrReturnCtx(e,a),G(a,{code:q.invalid_string,validation:{startsWith:i.value},message:i.message}),t.dirty());else if("endsWith"===i.kind)e.data.endsWith(i.value)||(a=this._getOrReturnCtx(e,a),G(a,{code:q.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){Se(i).test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{code:q.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){Me.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{code:q.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${Ie(i)}$`).test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{code:q.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?ge.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"duration",code:q.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(s=e.data,("v4"!==(n=i.version)&&n||!ve.test(s))&&("v6"!==n&&n||!we.test(s))&&(a=this._getOrReturnCtx(e,a),G(a,{validation:"ip",code:q.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?Ne(e.data,i.alg)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"jwt",code:q.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?Te(e.data,i.version)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"cidr",code:q.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?xe.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"base64",code:q.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?ke.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"base64url",code:q.invalid_string,message:i.message}),t.dirty()):v.assertNever(i);var s,n;return{status:t.value,value:e.data}}_regex(e,t,a){return this.refinement((t=>e.test(t)),{validation:t,code:q.invalid_string,...W.errToObj(a)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...W.errToObj(e)})}url(e){return this._addCheck({kind:"url",...W.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...W.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...W.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...W.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...W.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...W.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...W.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...W.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...W.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...W.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...W.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...W.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...W.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...W.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...W.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...W.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...W.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...W.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...W.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...W.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...W.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...W.errToObj(t)})}nonempty(e){return this.min(1,W.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};function Oe(e,t){const a=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=a>s?a:s;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}Ae.create=e=>new Ae({checks:[],typeName:wt.ZodString,coerce:e?.coerce??!1,...oe(e)});var Ee=class e extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==R.number){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.number,received:t.parsedType}),Q}let t;const a=new H;for(const s of this._def.checks)if("int"===s.kind)v.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),G(t,{code:q.invalid_type,expected:"integer",received:"float",message:s.message}),a.dirty());else if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:q.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:q.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty())}else"multipleOf"===s.kind?0!==Oe(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:q.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),G(t,{code:q.not_finite,message:s.message}),a.dirty()):v.assertNever(s);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,W.toString(t))}gt(e,t){return this.setLimit("min",e,!1,W.toString(t))}lte(e,t){return this.setLimit("max",e,!0,W.toString(t))}lt(e,t){return this.setLimit("max",e,!1,W.toString(t))}setLimit(t,a,s,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:a,inclusive:s,message:W.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:W.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:W.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&v.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const a of this._def.checks){if("finite"===a.kind||"int"===a.kind||"multipleOf"===a.kind)return!0;"min"===a.kind?(null===t||a.value>t)&&(t=a.value):"max"===a.kind&&(null===e||a.value<e)&&(e=a.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Ee.create=e=>new Ee({checks:[],typeName:wt.ZodNumber,coerce:e?.coerce||!1,...oe(e)});var Ze=class e extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let t;const a=new H;for(const s of this._def.checks)if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:q.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:q.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty())}else"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),G(t,{code:q.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):v.assertNever(s);return{status:a.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.bigint,received:t.parsedType}),Q}gte(e,t){return this.setLimit("min",e,!0,W.toString(t))}gt(e,t){return this.setLimit("min",e,!1,W.toString(t))}lte(e,t){return this.setLimit("max",e,!0,W.toString(t))}lt(e,t){return this.setLimit("max",e,!1,W.toString(t))}setLimit(t,a,s,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:a,inclusive:s,message:W.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};Ze.create=e=>new Ze({checks:[],typeName:wt.ZodBigInt,coerce:e?.coerce??!1,...oe(e)});var Le=class extends ce{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==R.boolean){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.boolean,received:t.parsedType}),Q}return ee(e.data)}};Le.create=e=>new Le({typeName:wt.ZodBoolean,coerce:e?.coerce||!1,...oe(e)});var je=class e extends ce{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==R.date){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.date,received:t.parsedType}),Q}if(Number.isNaN(e.data.getTime())){return G(this._getOrReturnCtx(e),{code:q.invalid_date}),Q}const t=new H;let a;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(a=this._getOrReturnCtx(e,a),G(a,{code:q.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(a=this._getOrReturnCtx(e,a),G(a,{code:q.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):v.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:W.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:W.toString(t)})}get minDate(){let e=null;for(const t of this._def.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._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}};je.create=e=>new je({checks:[],coerce:e?.coerce||!1,typeName:wt.ZodDate,...oe(e)});var Pe=class extends ce{_parse(e){if(this._getType(e)!==R.symbol){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.symbol,received:t.parsedType}),Q}return ee(e.data)}};Pe.create=e=>new Pe({typeName:wt.ZodSymbol,...oe(e)});var Re=class extends ce{_parse(e){if(this._getType(e)!==R.undefined){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.undefined,received:t.parsedType}),Q}return ee(e.data)}};Re.create=e=>new Re({typeName:wt.ZodUndefined,...oe(e)});var Fe=class extends ce{_parse(e){if(this._getType(e)!==R.null){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.null,received:t.parsedType}),Q}return ee(e.data)}};Fe.create=e=>new Fe({typeName:wt.ZodNull,...oe(e)});var qe=class extends ce{constructor(){super(...arguments),this._any=!0}_parse(e){return ee(e.data)}};qe.create=e=>new qe({typeName:wt.ZodAny,...oe(e)});var $e=class extends ce{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ee(e.data)}};$e.create=e=>new $e({typeName:wt.ZodUnknown,...oe(e)});var ze=class extends ce{_parse(e){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.never,received:t.parsedType}),Q}};ze.create=e=>new ze({typeName:wt.ZodNever,...oe(e)});var De=class extends ce{_parse(e){if(this._getType(e)!==R.undefined){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.void,received:t.parsedType}),Q}return ee(e.data)}};De.create=e=>new De({typeName:wt.ZodVoid,...oe(e)});var Ue=class e extends ce{_parse(e){const{ctx:t,status:a}=this._processInputParams(e),s=this._def;if(t.parsedType!==R.array)return G(t,{code:q.invalid_type,expected:R.array,received:t.parsedType}),Q;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(G(t,{code:e?q.too_big:q.too_small,minimum:n?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),a.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(G(t,{code:q.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),a.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(G(t,{code:q.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),a.dirty()),t.common.async)return Promise.all([...t.data].map(((e,a)=>s.type._parseAsync(new ie(t,e,t.path,a))))).then((e=>H.mergeArray(a,e)));const n=[...t.data].map(((e,a)=>s.type._parseSync(new ie(t,e,t.path,a))));return H.mergeArray(a,n)}get element(){return this._def.type}min(t,a){return new e({...this._def,minLength:{value:t,message:W.toString(a)}})}max(t,a){return new e({...this._def,maxLength:{value:t,message:W.toString(a)}})}length(t,a){return new e({...this._def,exactLength:{value:t,message:W.toString(a)}})}nonempty(e){return this.min(1,e)}};function Ve(e){if(e instanceof Ke){const t={};for(const a in e.shape){const s=e.shape[a];t[a]=ct.create(Ve(s))}return new Ke({...e._def,shape:()=>t})}return e instanceof Ue?new Ue({...e._def,type:Ve(e.element)}):e instanceof ct?ct.create(Ve(e.unwrap())):e instanceof lt?lt.create(Ve(e.unwrap())):e instanceof He?He.create(e.items.map((e=>Ve(e)))):e}Ue.create=(e,t)=>new Ue({type:e,minLength:null,maxLength:null,exactLength:null,typeName:wt.ZodArray,...oe(t)});var Ke=class e extends ce{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=v.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==R.object){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.object,received:t.parsedType}),Q}const{status:t,ctx:a}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof ze&&"strip"===this._def.unknownKeys))for(const e in a.data)n.includes(e)||i.push(e);const r=[];for(const e of n){const t=s[e],n=a.data[e];r.push({key:{status:"valid",value:e},value:t._parse(new ie(a,n,a.path,e)),alwaysSet:e in a.data})}if(this._def.catchall instanceof ze){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)r.push({key:{status:"valid",value:e},value:{status:"valid",value:a.data[e]}});else if("strict"===e)i.length>0&&(G(a,{code:q.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const s=a.data[t];r.push({key:{status:"valid",value:t},value:e._parse(new ie(a,s,a.path,t)),alwaysSet:t in a.data})}}return a.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of r){const a=await t.key,s=await t.value;e.push({key:a,value:s,alwaysSet:t.alwaysSet})}return e})).then((e=>H.mergeObjectSync(t,e))):H.mergeObjectSync(t,r)}get shape(){return this._def.shape()}strict(t){return W.errToObj,new e({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(e,a)=>{const s=this._def.errorMap?.(e,a).message??a.defaultError;return"unrecognized_keys"===e.code?{message:W.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:wt.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){const a={};for(const e of v.objectKeys(t))t[e]&&this.shape[e]&&(a[e]=this.shape[e]);return new e({...this._def,shape:()=>a})}omit(t){const a={};for(const e of v.objectKeys(this.shape))t[e]||(a[e]=this.shape[e]);return new e({...this._def,shape:()=>a})}deepPartial(){return Ve(this)}partial(t){const a={};for(const e of v.objectKeys(this.shape)){const s=this.shape[e];t&&!t[e]?a[e]=s:a[e]=s.optional()}return new e({...this._def,shape:()=>a})}required(t){const a={};for(const e of v.objectKeys(this.shape))if(t&&!t[e])a[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof ct;)t=t._def.innerType;a[e]=t}return new e({...this._def,shape:()=>a})}keyof(){return nt(v.objectKeys(this.shape))}};Ke.create=(e,t)=>new Ke({shape:()=>e,unknownKeys:"strip",catchall:ze.create(),typeName:wt.ZodObject,...oe(t)}),Ke.strictCreate=(e,t)=>new Ke({shape:()=>e,unknownKeys:"strict",catchall:ze.create(),typeName:wt.ZodObject,...oe(t)}),Ke.lazycreate=(e,t)=>new Ke({shape:e,unknownKeys:"strip",catchall:ze.create(),typeName:wt.ZodObject,...oe(t)});var Je=class extends ce{_parse(e){const{ctx:t}=this._processInputParams(e),a=this._def.options;if(t.common.async)return Promise.all(a.map((async e=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const a of e)if("dirty"===a.result.status)return t.common.issues.push(...a.ctx.common.issues),a.result;const a=e.map((e=>new z(e.ctx.common.issues)));return G(t,{code:q.invalid_union,unionErrors:a}),Q}));{let e;const s=[];for(const n of a){const a={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:a});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:a}),a.common.issues.length&&s.push(a.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map((e=>new z(e)));return G(t,{code:q.invalid_union,unionErrors:n}),Q}}get options(){return this._def.options}};Je.create=(e,t)=>new Je({options:e,typeName:wt.ZodUnion,...oe(t)});var Be=e=>e instanceof at?Be(e.schema):e instanceof dt?Be(e.innerType()):e instanceof st?[e.value]:e instanceof it?e.options:e instanceof rt?v.objectValues(e.enum):e instanceof ut?Be(e._def.innerType):e instanceof Re?[void 0]:e instanceof Fe?[null]:e instanceof ct?[void 0,...Be(e.unwrap())]:e instanceof lt?[null,...Be(e.unwrap())]:e instanceof ft||e instanceof yt?Be(e.unwrap()):e instanceof pt?Be(e._def.innerType):[],Ge=class e extends ce{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.object)return G(t,{code:q.invalid_type,expected:R.object,received:t.parsedType}),Q;const a=this.discriminator,s=t.data[a],n=this.optionsMap.get(s);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(G(t,{code:q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),Q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,a,s){const n=new Map;for(const e of a){const a=Be(e.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const s of a){if(n.has(s))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(s)}`);n.set(s,e)}}return new e({typeName:wt.ZodDiscriminatedUnion,discriminator:t,options:a,optionsMap:n,...oe(s)})}};function We(e,t){const a=F(e),s=F(t);if(e===t)return{valid:!0,data:e};if(a===R.object&&s===R.object){const a=v.objectKeys(t),s=v.objectKeys(e).filter((e=>-1!==a.indexOf(e))),n={...e,...t};for(const a of s){const s=We(e[a],t[a]);if(!s.valid)return{valid:!1};n[a]=s.data}return{valid:!0,data:n}}if(a===R.array&&s===R.array){if(e.length!==t.length)return{valid:!1};const a=[];for(let s=0;s<e.length;s++){const n=We(e[s],t[s]);if(!n.valid)return{valid:!1};a.push(n.data)}return{valid:!0,data:a}}return a===R.date&&s===R.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}var Ye=class extends ce{_parse(e){const{status:t,ctx:a}=this._processInputParams(e),s=(e,s)=>{if(te(e)||te(s))return Q;const n=We(e.value,s.value);return n.valid?((ae(e)||ae(s))&&t.dirty(),{status:t.value,value:n.data}):(G(a,{code:q.invalid_intersection_types}),Q)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then((([e,t])=>s(e,t))):s(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};Ye.create=(e,t,a)=>new Ye({left:e,right:t,typeName:wt.ZodIntersection,...oe(a)});var He=class e extends ce{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==R.array)return G(a,{code:q.invalid_type,expected:R.array,received:a.parsedType}),Q;if(a.data.length<this._def.items.length)return G(a,{code:q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q;!this._def.rest&&a.data.length>this._def.items.length&&(G(a,{code:q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...a.data].map(((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new ie(a,e,a.path,t)):null})).filter((e=>!!e));return a.common.async?Promise.all(s).then((e=>H.mergeArray(t,e))):H.mergeArray(t,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};He.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new He({items:e,typeName:wt.ZodTuple,rest:null,...oe(t)})};var Qe=class e extends ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==R.object)return G(a,{code:q.invalid_type,expected:R.object,received:a.parsedType}),Q;const s=[],n=this._def.keyType,i=this._def.valueType;for(const e in a.data)s.push({key:n._parse(new ie(a,e,a.path,e)),value:i._parse(new ie(a,a.data[e],a.path,e)),alwaysSet:e in a.data});return a.common.async?H.mergeObjectAsync(t,s):H.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(t,a,s){return new e(a instanceof ce?{keyType:t,valueType:a,typeName:wt.ZodRecord,...oe(s)}:{keyType:Ae.create(),valueType:t,typeName:wt.ZodRecord,...oe(a)})}},Xe=class extends ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==R.map)return G(a,{code:q.invalid_type,expected:R.map,received:a.parsedType}),Q;const s=this._def.keyType,n=this._def.valueType,i=[...a.data.entries()].map((([e,t],i)=>({key:s._parse(new ie(a,e,a.path,[i,"key"])),value:n._parse(new ie(a,t,a.path,[i,"value"]))})));if(a.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const a of i){const s=await a.key,n=await a.value;if("aborted"===s.status||"aborted"===n.status)return Q;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const a of i){const s=a.key,n=a.value;if("aborted"===s.status||"aborted"===n.status)return Q;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}};Xe.create=(e,t,a)=>new Xe({valueType:t,keyType:e,typeName:wt.ZodMap,...oe(a)});var et=class e extends ce{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==R.set)return G(a,{code:q.invalid_type,expected:R.set,received:a.parsedType}),Q;const s=this._def;null!==s.minSize&&a.data.size<s.minSize.value&&(G(a,{code:q.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&a.data.size>s.maxSize.value&&(G(a,{code:q.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const a=new Set;for(const s of e){if("aborted"===s.status)return Q;"dirty"===s.status&&t.dirty(),a.add(s.value)}return{status:t.value,value:a}}const r=[...a.data.values()].map(((e,t)=>n._parse(new ie(a,e,a.path,t))));return a.common.async?Promise.all(r).then((e=>i(e))):i(r)}min(t,a){return new e({...this._def,minSize:{value:t,message:W.toString(a)}})}max(t,a){return new e({...this._def,maxSize:{value:t,message:W.toString(a)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};et.create=(e,t)=>new et({valueType:e,minSize:null,maxSize:null,typeName:wt.ZodSet,...oe(t)});var tt=class e extends ce{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.function)return G(t,{code:q.invalid_type,expected:R.function,received:t.parsedType}),Q;function a(e,a){return J({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,K(),D].filter((e=>!!e)),issueData:{code:q.invalid_arguments,argumentsError:a}})}function s(e,a){return J({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,K(),D].filter((e=>!!e)),issueData:{code:q.invalid_return_type,returnTypeError:a}})}const n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof ot){const e=this;return ee((async function(...t){const r=new z([]),o=await e._def.args.parseAsync(t,n).catch((e=>{throw r.addIssue(a(t,e)),r})),d=await Reflect.apply(i,this,o);return await e._def.returns._def.type.parseAsync(d,n).catch((e=>{throw r.addIssue(s(d,e)),r}))}))}{const e=this;return ee((function(...t){const r=e._def.args.safeParse(t,n);if(!r.success)throw new z([a(t,r.error)]);const o=Reflect.apply(i,this,r.data),d=e._def.returns.safeParse(o,n);if(!d.success)throw new z([s(o,d.error)]);return d.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:He.create(t).rest($e.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,a,s){return new e({args:t||He.create([]).rest($e.create()),returns:a||$e.create(),typeName:wt.ZodFunction,...oe(s)})}},at=class extends ce{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};at.create=(e,t)=>new at({getter:e,typeName:wt.ZodLazy,...oe(t)});var st=class extends ce{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return G(t,{received:t.data,code:q.invalid_literal,expected:this._def.value}),Q}return{status:"valid",value:e.data}}get value(){return this._def.value}};function nt(e,t){return new it({values:e,typeName:wt.ZodEnum,...oe(t)})}st.create=(e,t)=>new st({value:e,typeName:wt.ZodLiteral,...oe(t)});var it=class e extends ce{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),a=this._def.values;return G(t,{expected:v.joinValues(a),received:t.parsedType,code:q.invalid_type}),Q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),a=this._def.values;return G(t,{received:t.data,code:q.invalid_enum_value,options:a}),Q}return ee(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(t,a=this._def){return e.create(t,{...this._def,...a})}exclude(t,a=this._def){return e.create(this.options.filter((e=>!t.includes(e))),{...this._def,...a})}};it.create=nt;var rt=class extends ce{_parse(e){const t=v.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==R.string&&a.parsedType!==R.number){const e=v.objectValues(t);return G(a,{expected:v.joinValues(e),received:a.parsedType,code:q.invalid_type}),Q}if(this._cache||(this._cache=new Set(v.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=v.objectValues(t);return G(a,{received:a.data,code:q.invalid_enum_value,options:e}),Q}return ee(e.data)}get enum(){return this._def.values}};rt.create=(e,t)=>new rt({values:e,typeName:wt.ZodNativeEnum,...oe(t)});var ot=class extends ce{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.promise&&!1===t.common.async)return G(t,{code:q.invalid_type,expected:R.promise,received:t.parsedType}),Q;const a=t.parsedType===R.promise?t.data:Promise.resolve(t.data);return ee(a.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}};ot.create=(e,t)=>new ot({type:e,typeName:wt.ZodPromise,...oe(t)});var dt=class extends ce{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===wt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:a}=this._processInputParams(e),s=this._def.effect||null,n={addIssue:e=>{G(a,e),e.fatal?t.abort():t.dirty()},get path(){return a.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===s.type){const e=s.transform(a.data,n);if(a.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return Q;const s=await this._def.schema._parseAsync({data:e,path:a.path,parent:a});return"aborted"===s.status?Q:"dirty"===s.status||"dirty"===t.value?X(s.value):s}));{if("aborted"===t.value)return Q;const s=this._def.schema._parseSync({data:e,path:a.path,parent:a});return"aborted"===s.status?Q:"dirty"===s.status||"dirty"===t.value?X(s.value):s}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,n);if(a.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===a.common.async){const s=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===s.status?Q:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then((a=>"aborted"===a.status?Q:("dirty"===a.status&&t.dirty(),e(a.value).then((()=>({status:t.value,value:a.value}))))))}if("transform"===s.type){if(!1===a.common.async){const e=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!se(e))return Q;const i=s.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then((e=>se(e)?Promise.resolve(s.transform(e.value,n)).then((e=>({status:t.value,value:e}))):Q))}v.assertNever(s)}};dt.create=(e,t,a)=>new dt({schema:e,typeName:wt.ZodEffects,effect:t,...oe(a)}),dt.createWithPreprocess=(e,t,a)=>new dt({schema:t,effect:{type:"preprocess",transform:e},typeName:wt.ZodEffects,...oe(a)});var ct=class extends ce{_parse(e){return this._getType(e)===R.undefined?ee(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ct.create=(e,t)=>new ct({innerType:e,typeName:wt.ZodOptional,...oe(t)});var lt=class extends ce{_parse(e){return this._getType(e)===R.null?ee(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};lt.create=(e,t)=>new lt({innerType:e,typeName:wt.ZodNullable,...oe(t)});var ut=class extends ce{_parse(e){const{ctx:t}=this._processInputParams(e);let a=t.data;return t.parsedType===R.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ut.create=(e,t)=>new ut({innerType:e,typeName:wt.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...oe(t)});var pt=class extends ce{_parse(e){const{ctx:t}=this._processInputParams(e),a={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return ne(s)?s.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new z(a.common.issues)},input:a.data})}))):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new z(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};pt.create=(e,t)=>new pt({innerType:e,typeName:wt.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...oe(t)});var ht=class extends ce{_parse(e){if(this._getType(e)!==R.nan){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.nan,received:t.parsedType}),Q}return{status:"valid",value:e.data}}};ht.create=e=>new ht({typeName:wt.ZodNaN,...oe(e)});var mt=Symbol("zod_brand"),ft=class extends ce{_parse(e){const{ctx:t}=this._processInputParams(e),a=t.data;return this._def.type._parse({data:a,path:t.path,parent:t})}unwrap(){return this._def.type}},gt=class e extends ce{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?Q:"dirty"===e.status?(t.dirty(),X(e.value)):this._def.out._parseAsync({data:e.value,path:a.path,parent:a})})()}{const e=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?Q:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:a.path,parent:a})}}static create(t,a){return new e({in:t,out:a,typeName:wt.ZodPipeline})}},yt=class extends ce{_parse(e){const t=this._def.innerType._parse(e),a=e=>(se(e)&&(e.value=Object.freeze(e.value)),e);return ne(t)?t.then((e=>a(e))):a(t)}unwrap(){return this._def.innerType}};function vt(e,t){const a="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof a?{message:a}:a}function _t(e,t={},a){return e?qe.create().superRefine(((s,n)=>{const i=e(s);if(i instanceof Promise)return i.then((e=>{if(!e){const e=vt(t,s),i=e.fatal??a??!0;n.addIssue({code:"custom",...e,fatal:i})}}));if(!i){const e=vt(t,s),i=e.fatal??a??!0;n.addIssue({code:"custom",...e,fatal:i})}})):qe.create()}yt.create=(e,t)=>new yt({innerType:e,typeName:wt.ZodReadonly,...oe(t)});var wt,bt,xt={object:Ke.lazycreate};(bt=wt||(wt={})).ZodString="ZodString",bt.ZodNumber="ZodNumber",bt.ZodNaN="ZodNaN",bt.ZodBigInt="ZodBigInt",bt.ZodBoolean="ZodBoolean",bt.ZodDate="ZodDate",bt.ZodSymbol="ZodSymbol",bt.ZodUndefined="ZodUndefined",bt.ZodNull="ZodNull",bt.ZodAny="ZodAny",bt.ZodUnknown="ZodUnknown",bt.ZodNever="ZodNever",bt.ZodVoid="ZodVoid",bt.ZodArray="ZodArray",bt.ZodObject="ZodObject",bt.ZodUnion="ZodUnion",bt.ZodDiscriminatedUnion="ZodDiscriminatedUnion",bt.ZodIntersection="ZodIntersection",bt.ZodTuple="ZodTuple",bt.ZodRecord="ZodRecord",bt.ZodMap="ZodMap",bt.ZodSet="ZodSet",bt.ZodFunction="ZodFunction",bt.ZodLazy="ZodLazy",bt.ZodLiteral="ZodLiteral",bt.ZodEnum="ZodEnum",bt.ZodEffects="ZodEffects",bt.ZodNativeEnum="ZodNativeEnum",bt.ZodOptional="ZodOptional",bt.ZodNullable="ZodNullable",bt.ZodDefault="ZodDefault",bt.ZodCatch="ZodCatch",bt.ZodPromise="ZodPromise",bt.ZodBranded="ZodBranded",bt.ZodPipeline="ZodPipeline",bt.ZodReadonly="ZodReadonly";var kt=(e,t={message:`Input not instance of ${e.name}`})=>_t((t=>t instanceof e),t),Ct=Ae.create,Mt=Ee.create,It=ht.create,St=Ze.create,Nt=Le.create,Tt=je.create,At=Pe.create,Ot=Re.create,Et=Fe.create,Zt=qe.create,Lt=$e.create,jt=ze.create,Pt=De.create,Rt=Ue.create,Ft=Ke.create,qt=Ke.strictCreate,$t=Je.create,zt=Ge.create,Dt=Ye.create,Ut=He.create,Vt=Qe.create,Kt=Xe.create,Jt=et.create,Bt=tt.create,Gt=at.create,Wt=st.create,Yt=it.create,Ht=rt.create,Qt=ot.create,Xt=dt.create,ea=ct.create,ta=lt.create,aa=dt.createWithPreprocess,sa=gt.create,na=()=>Ct().optional(),ia=()=>Mt().optional(),ra=()=>Nt().optional(),oa={string:e=>Ae.create({...e,coerce:!0}),number:e=>Ee.create({...e,coerce:!0}),boolean:e=>Le.create({...e,coerce:!0}),bigint:e=>Ze.create({...e,coerce:!0}),date:e=>je.create({...e,coerce:!0})},da=Q,ca={text:"text",conversation:"text",imageMessage:"image",contactMessage:"contact",locationMessage:"location",documentMessage:"document",audioMessage:"audio",videoMessage:"video",protocolMessage:"protocol",contactsArrayMessage:"contactsArray",highlyStructuredMessage:"highlyStructured",sendPaymentMessage:"sendPayment",liveLocationMessage:"liveLocation",requestPaymentMessage:"requestPayment",declinePaymentRequestMessage:"declinePaymentRequest",cancelPaymentRequestMessage:"cancelPaymentRequest",templateMessage:"template",stickerMessage:"sticker",groupInviteMessage:"groupInvite",templateButtonReplyMessage:"templateButtonReply",productMessage:"product",deviceSentMessage:"deviceSent",listMessage:"list",viewOnceMessage:"viewOnce",orderMessage:"order",listResponseMessage:"listResponse",ephemeralMessage:"ephemeral",invoiceMessage:"invoice",buttonsMessage:"buttons",buttonsResponseMessage:"buttonsResponse",paymentInviteMessage:"paymentInvite",interactiveMessage:"interactive",reactionMessage:"reaction",stickerSyncRmrMessage:"sticker",interactiveResponseMessage:"interactiveResponse",pollCreationMessage:"pollCreation",pollUpdateMessage:"pollUpdate",keepInChatMessage:"keepInChat",documentWithCaptionMessage:"document",requestPhoneNumberMessage:"requestPhoneNumber",viewOnceMessageV2:"viewOnce",encReactionMessage:"reaction",editedMessage:"text",viewOnceMessageV2Extension:"viewOnce",pollCreationMessageV2:"pollCreation",scheduledCallCreationMessage:"scheduledCallCreation",groupMentionedMessage:"groupMentioned",pinInChatMessage:"pinInChat",pollCreationMessageV3:"pollCreation",scheduledCallEditMessage:"scheduledCallEdit",ptvMessage:"ptv",botInvokeMessage:"botInvoke",callLogMesssage:"callLog",encCommentMessage:"encComment",bcallMessage:"bcall",lottieStickerMessage:"lottieSticker",eventMessage:"event",commentMessage:"comment",newsletterAdminInviteMessage:"text",extendedTextMessageWithParentKey:"text",extendedTextMessage:"text",placeholderMessage:"placeholder",encEventUpdateMessage:"encEventUpdate"},la={whatsapp:"0@s.whatsapp.net",meta:"13135550002@s.whatsapp.net",chatgpt:"18002428478@s.whatsapp.net",copilot:"18772241042@s.whatsapp.net",instagram:"447723442971@s.whatsapp.net",tiktok:"6285574670498@s.whatsapp.net"},ua=P.enum(["text","text","image","contact","location","document","audio","video","protocol","contactsArray","highlyStructured","sendPayment","liveLocation","requestPayment","declinePaymentRequest","cancelPaymentRequest","template","sticker","groupInvite","templateButtonReply","product","deviceSent","list","viewOnce","order","listResponse","ephemeral","invoice","buttons","buttonsResponse","paymentInvite","interactive","reaction","sticker","interactiveResponse","pollCreation","pollUpdate","keepInChat","document","requestPhoneNumber","viewOnce","reaction","text","viewOnce","pollCreation","scheduledCallCreation","groupMentioned","pinInChat","pollCreation","scheduledCallEdit","ptv","botInvoke","callLog","encComment","bcall","lottieSticker","event","comment","text","text","placeholder","encEventUpdate"]),pa=P.enum(["unknown","android","ios","desktop","web"]),ha=P.object({chatId:P.string(),channelId:P.string(),uniqueId:P.string(),receiverId:P.string(),receiverName:P.string(),roomId:P.string(),roomName:P.string(),senderId:P.string(),senderName:P.string(),senderDevice:pa,chatType:ua,timestamp:P.number(),mentions:P.string().array(),text:P.string().nullable(),links:P.string().array(),isPrefix:P.boolean(),isFromMe:P.boolean(),isTagMe:P.boolean(),isGroup:P.boolean(),isStory:P.boolean(),isViewOnce:P.boolean(),isEdited:P.boolean(),isDeleted:P.boolean(),isPinned:P.boolean(),isUnPinned:P.boolean(),isChannel:P.boolean(),isBroadcast:P.boolean(),isEphemeral:P.boolean(),isForwarded:P.boolean(),citation:P.record(P.string(),P.boolean()).nullable(),media:P.object({buffer:P.function().returns(P.instanceof(Buffer)),stream:P.function().returns(P.instanceof(m.Readable))}).passthrough().nullable(),message:P.function().returns(P.record(P.string(),P.any()))});ha.extend({replied:ha.nullable()});var ma=class{constructor(e,t,a){this.socket=e,this.client=t,this.db=a}maxReplies=0;async connection(t){this.client.stopSpinner("connection",!1),this.client.startSpinner("connection","Connecting to WhatsApp...");const{connection:a,lastDisconnect:s,qr:n}=t;if(this.client.emit("connection",{status:"connecting"}),"qr"===this.client.options?.authType&&n)return this.client.stopSpinner("reconnect",!1),console.log(),console.log(await N.default.toString(n,{type:"terminal",small:!0})),this.client.startSpinner("qr","Waiting for QR code scan..."),void this.socket?.ev.on("connection.update",(()=>this.client.stopSpinner("qr",!1)));if("close"===a){const t=s?.error?.output?.statusCode,n=t===e.DisconnectReason.restartRequired||t===e.DisconnectReason.connectionLost;if(this.client.failSpinner("connection",`[Connection Closed] [${t}]\n${s?.error?.message}\n`),401===t||405===t||500===t)return void console.error("Invalid session, please delete manually");n&&"close"==a&&(await this.client.startSpinner("reconnect","Automatically restarting..."),await this.client.initialize())}else"open"===a&&(this.client.stopSpinner("connection",!0,"Connected to WhatsApp\n"),this.client.emit("connection",{status:"open"}))}async messages(t,a){if(t?.messageStubType||t?.messageStubParameters?.length||t?.message?.protocolMessage?.peerDataOperationRequestResponseMessage||t?.message?.botInvokeMessage||!t?.key?.id||!t?.message)return null;if(this.client.options?.ignoreMe&&t?.key?.fromMe&&"status@broadcast"!=t?.key?.remoteJid&&!t?.participant)return null;this.client.options?.autoRead&&await this.socket.readMessages([t?.key]);const s=t,n=t?.message?.pinInChatMessage?.key?.id,i=1==t?.message?.pinInChatMessage?.type,r=2==t?.message?.pinInChatMessage?.type;if(n){const e=await this.db.selectFrom("messages").select("value").where("id","=",n).executeTakeFirst(),a=O(e?.value);t=a}const o=!t?.message?.protocolMessage?.editedMessage&&t?.message?.protocolMessage?.key?.id,d=!!o;if(o){const e=await this.db.selectFrom("messages").select("value").where("id","=",o).executeTakeFirst(),a=O(e?.value);t=a}const c={},l=e.getContentType(t?.message?.protocolMessage?.editedMessage||t?.message);c.chatId=t?.message?.protocolMessage?.key?.id||t?.key?.id,c.channelId="",c.uniqueId="",c.receiverId=e.jidNormalizedUser(this.socket.user?.id),c.receiverName=this.socket.user?.name||this.socket.user?.verifiedName,c.roomId=e.jidNormalizedUser(t?.key?.remoteJid);const u=await this.db.selectFrom("chats").select("value").where("id","=",c.roomId).executeTakeFirst();c.roomName=O(u?.value)?.name,c.senderId=e.jidNormalizedUser(t?.participant||t?.key?.participant||t?.key?.remoteJid);const p=await this.db.selectFrom("chats").select("value").where("id","=",c.senderId).executeTakeFirst();c.senderName=t?.pushName||t?.verifiedBizName||O(p?.value)?.name||c.receiverName,c.roomName=c.roomName||c.senderName,c.senderDevice=e.getDevice(c.chatId),c.chatType=ca[l],c.timestamp=t?.messageTimestamp?.low||t?.messageTimestamp||0,c.mentions=[],c.text=null,c.links=[],c.isPrefix=!1,c.isFromMe=t?.key?.fromMe,c.isTagMe=!1,c.isGroup=c.roomId.includes("@g.us"),c.isStory=c.roomId.includes("@broadcast"),c.isViewOnce=!1,c.isEdited=!1,c.isDeleted=d,c.isPinned=i,c.isUnPinned=r,c.isChannel=c.roomId.includes("@newsletter"),c.isBroadcast=!!t?.broadcast,c.isEphemeral=!1,c.isForwarded=!1,c.citation=null,c.media=null,c.replied=null,c.channelId=c.roomId.split("@")[0]+"-"+c.senderId.split("@")[0],c.uniqueId=c.channelId+"-"+c.chatId;const h=this.client.options?.citation;if(Object.keys(h).length){c.citation={};for(const e of Object.keys(h))c.citation[e]=h[e].includes(Number(c.senderId.split("@")[0]))||h[e].includes(Number(c.roomId.split("@")[0]))}const m=(t?.message?.protocolMessage?.editedMessage?.[l]||t?.message?.[l])?.message?.documentMessage||t?.message?.[l];"text"!=c.chatType&&(c.media={...L(m,["url","contextInfo","fileSha256","fileEncSha256","mediaKey","directPath","waveform","thumbnail","jpegThumbnail","thumbnailEncSha256","thumbnailSha256","thumbnailDirectPath","firstFrameSidecar","streamingSidecar","scansSidecar","callKey","midQualityFileSha256"]),buffer:async()=>await e.downloadMediaMessage(t,"buffer",{}),stream:async()=>await e.downloadMediaMessage(t,"stream",{})});const f=t?.message?.[l]?.contextInfo?.stanzaId;if(f&&this.maxReplies<1){this.maxReplies++;const a=await this.db.selectFrom("messages").select("value").where("id","=",f).executeTakeFirst(),s=O(a?.value);if(s)c.replied=await this.messages(s,!0);else{const a=t,s=e.getContentType(a.message?.extendedTextMessage?.contextInfo.quotedMessage);a.key.id=a.message?.extendedTextMessage?.contextInfo.stanzaId,a.message[s]=a.message?.extendedTextMessage?.contextInfo.quotedMessage[s],delete a.message?.extendedTextMessage,c.replied=await this.messages(a,!0)}}const g="string"==typeof m?m:m?.text||m?.caption||m?.name||m?.displayName||"";c.text=((e="")=>e?e.replace(/\u202E([\s\S]*?)\u202C/g,((e,t)=>Array.from(t).reverse().join(""))).replace(/[\u202A-\u202E\u202C]/g,""):null)(g)||null,c.mentions=((e="")=>{if(!e)return[];const t=new Set;for(const a of e.matchAll(/@(\d+)/g))t.add(a[1]);return[...t]})(c.text),c.links=((e="")=>e&&e.match(/(?:https?:\/\/)?[^\s<>"']+\.[^\s<>"']+/g)||[])(c.text);const y=t?.message?.[l];return c.isPrefix=!!this.client.options?.prefix&&!!c.text?.startsWith(this.client.options?.prefix),c.isTagMe=c.mentions.includes(c.receiverId.split("@")[0]),c.isEdited=Z(E(t),"editedMessage"),c.isEphemeral=Z(E(y?.contextInfo),"ephemeralSettingTimestamp"),c.isForwarded=Z(E(y?.contextInfo),"forwardingScore"),c.isViewOnce=!!y?.viewOnce,c.isPrefix&&(c.text=c.text.replace(new RegExp(`^${this.client.options?.prefix}`),"")),c.message=()=>s,a||this.client.emit("messages",c),c}async calls(e){this.client.options?.autoRejectCall&&await this.socket.rejectCall(e.id,e.from);const t={};t.callId=e.id,t.roomId=e.chatId,t.callerId=e.from,t.date=e.date,t.offline=e.offline,t.status=e.status,t.isVideo=!!e.isVideo,t.isGroup=!!e.isGroup,this.client.emit("calls",t)}},fa=async(t,a,s)=>{const n="auth";await(async(e,t)=>{await e.transaction().execute((async e=>{await e.schema.createTable("auth").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("auth_session_id_unique",["session","id"]).execute(),await e.schema.createTable("chats").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("chats_session_id_unique",["session","id"]).execute(),await e.schema.createTable("contacts").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("contacts_session_id_unique",["session","id"]).execute(),await e.schema.createTable("messages").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("messages_session_id_unique",["session","id"]).execute(),t.loadLLMSchemas&&(await e.schema.createTable("llm_messages").ifNotExists().addColumn("uniqueId","char(36)",(e=>e.notNull().primaryKey())).addColumn("channelId","char(36)").addColumn("model","char(36)").addColumn("role","varchar(20)",(e=>e.notNull())).addColumn("content","text",(e=>e.notNull())).addColumn("additional","text").addUniqueConstraint("llm_messages_id_unique",["uniqueId"]).execute(),await e.schema.createTable("llm_personalization").ifNotExists().addColumn("uniqueId","char(36)",(e=>e.notNull().primaryKey())).addColumn("senderId","char(36)").addColumn("content","text",(e=>e.notNull())).addUniqueConstraint("llm_personalization_id_unique",["uniqueId"]).execute(),await e.schema.createTable("llm_rag").ifNotExists().addColumn("metadata.id","char(36)",(e=>e.notNull().primaryKey())).addColumn("pageContent","text",(e=>e.notNull())).addUniqueConstraint("llm_rag_id_unique",["metadata.id"]).execute()),await Promise.all([e.schema.createIndex("auth_session_id_idx").ifNotExists().on("auth").columns(["session","id"]).execute(),e.schema.createIndex("chats_session_id_idx").ifNotExists().on("chats").columns(["session","id"]).execute(),e.schema.createIndex("contacts_session_id_idx").ifNotExists().on("contacts").columns(["session","id"]).execute(),e.schema.createIndex("messages_session_id_idx").ifNotExists().on("messages").columns(["session","id"]).execute(),e.schema.createIndex("llm_messages_uniqueId_idx").ifNotExists().on("llm_messages").column("uniqueId").execute(),e.schema.createIndex("llm_messages_channelId_idx").ifNotExists().on("llm_messages").column("channelId").execute(),e.schema.createIndex("llm_messages_model_idx").ifNotExists().on("llm_messages").column("model").execute(),e.schema.createIndex("llm_messages_role_idx").ifNotExists().on("llm_messages").column("role").execute(),e.schema.createIndex("llm_personalization_uniqueId_idx").ifNotExists().on("llm_personalization").column("uniqueId").execute(),e.schema.createIndex("llm_personalization_senderId_idx").ifNotExists().on("llm_personalization").column("senderId").execute(),e.schema.createIndex("llm_rag_id_idx").ifNotExists().on("llm_rag").column("metadata.id").execute(),e.schema.createIndex("llm_rag_pageContent_idx").ifNotExists().on("llm_rag").column("pageContent").execute()])}))})(t,s);const i=async e=>{for(let t=0;t<10;t++)try{return await e()}catch(e){await new Promise((e=>setTimeout(e,200)))}throw new Error("Max retries reached")},r=async s=>{const r=await i((()=>t.selectFrom(n).select(["value"]).where("id","=",s).where("session","=",a).executeTakeFirst()));if(!r?.value)return null;const o="object"==typeof r.value?JSON.stringify(r.value):r.value;return JSON.parse(o,e.BufferJSON.reviver)},o=async(s,r)=>{const o=JSON.stringify(r,e.BufferJSON.replacer);await i((()=>t.insertInto(n).values({session:a,id:s,value:o}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:o}))).execute()))},d=async e=>{await i((()=>t.deleteFrom(n).where("id","=",e).where("session","=",a).execute()))},c=await r("creds")||e.initAuthCreds();return{state:{creds:c,keys:{get:async(e,t)=>{const a={};for(const s of t){let t=await r(`${e}-${s}`);"app-state-sync-key"===e&&t&&(t=j(t)),a[s]=t}return a},set:async e=>{for(const t in e)for(const a in e[t]){const s=e[t][a],n=`${t}-${a}`;s?await o(n,s):await d(n)}}}},saveCreds:async()=>{await o("creds",c)},clear:async()=>{await(async()=>{await i((()=>t.deleteFrom(n).where("session","=",a).where("id","!=","creds").execute()))})()},removeCreds:async()=>{await(async()=>{await i((()=>t.deleteFrom(n).where("session","=",a).execute()))})()}}},ga=P.object({type:P.enum(["sqlite","postgresql","mysql"]).default("sqlite"),connection:P.object({url:P.string().default("./session/zaileys.db")}).optional().default({})}).optional().default({}),ya=P.record(P.function().returns(P.union([P.number().array(),P.promise(P.number().array())]))).optional().transform((async e=>{if(!e)return{};const t={};for(const[a,s]of Object.entries(e)){t[`is${a.charAt(0).toUpperCase()}${a.slice(1)}`]=await s()}return t})),va=P.object({prefix:P.string().optional(),ignoreMe:P.boolean().optional().default(!0),showLogs:P.boolean().optional().default(!0),autoMentions:P.boolean().optional().default(!0),autoOnline:P.boolean().optional().default(!0),autoRead:P.boolean().optional().default(!0),autoPresence:P.boolean().optional().default(!0),autoRejectCall:P.boolean().optional().default(!0),loadLLMSchemas:P.boolean().optional().default(!1),database:ga,citation:ya}),_a=P.object({authType:P.literal("pairing"),phoneNumber:P.number()}).extend(va.shape),wa=P.object({authType:P.literal("qr"),phoneNumber:P.undefined().optional()}).extend(va.shape),ba=P.discriminatedUnion("authType",[_a,wa]),xa=P.object({channelId:P.string(),uniqueId:P.string(),model:P.string().min(2).max(100).optional().nullable(),role:P.string().min(2).max(100),content:P.string().min(1).max(65e3),additional:P.string().max(2e4).optional().nullable()}),ka=P.object({uniqueId:P.string(),senderId:P.string(),content:P.string().min(1).max(5e3)}),Ca=P.object({metadata:P.object({id:P.string().default((()=>(e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";return Array.from({length:e},(()=>t[Math.floor(62*Math.random())])).join("")})(5)))}).default({}),pageContent:P.string().min(1).max(128e3)});Ca.pick({pageContent:!0});var Ma=P.union([P.string().url(),P.instanceof(Buffer).or(P.instanceof(m.Readable))]),Ia=P.union([P.string(),P.object({image:Ma,text:P.string().optional()}),P.object({video:Ma,text:P.string().optional()}),P.object({videoNote:Ma}),P.object({gif:Ma,text:P.string().optional()}),P.object({audio:Ma}),P.object({audioNote:Ma}),P.object({sticker:Ma})]),Sa=P.object({roomId:P.string(),asForwarded:P.boolean().optional(),asViewOnce:P.boolean().optional(),verifiedReply:P.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).optional(),quoted:P.function().returns(P.record(P.string(),P.any())).optional()}),Na=Sa,Ta=P.object({latitude:P.number(),longitude:P.number(),title:P.string().optional(),footer:P.string().optional()}),Aa=Sa,Oa=P.object({fullname:P.string(),nickname:P.string().optional(),organization:P.string().optional(),role:P.string().optional(),email:P.string().email().optional(),whatsAppNumber:P.number(),callNumber:P.number().optional(),voiceNumber:P.number().optional(),website:P.string().url().optional(),homeAddress:P.string().optional(),workAddress:P.string().optional(),avatar:P.string().url().optional()}),Ea=P.object({message:P.function().returns(P.record(P.string(),P.any()))}),Za=P.string(),La=P.object({message:P.function().returns(P.record(P.string(),P.any()))}),ja=P.object({action:P.enum(["pin","unpin"]),expired:P.enum(["24h","7d","30d"])}),Pa=Sa.pick({roomId:!0}),Ra=P.object({name:P.string(),answers:P.string().array(),multipleAnswers:P.boolean().optional()}),Fa=P.object({message:P.function().returns(P.record(P.string(),P.any()))}),qa=P.string(),$a=P.object({message:P.function().returns(P.record(P.string(),P.any()))}),za=P.object({callId:P.string(),callerId:P.string()}),Da=Sa.pick({roomId:!0}),Ua=P.object({expired:P.enum(["remove","8h","7d"])}),Va=P.string();P.object({type:P.enum(["group","user"]),id:P.string(),name:P.string(),bio:P.string(),avatar:P.string().url(),ephemeralDuration:P.number().optional(),isRestrict:P.boolean().optional(),isAnnounce:P.boolean().optional(),isCommunity:P.boolean().optional(),isCommunityAnnounce:P.boolean().optional(),isJoinApprovalMode:P.boolean().optional(),isMemberAddMode:P.boolean().optional(),owner:P.object({type:P.literal("user"),id:P.string()}).nullable(),roomCreatedAt:P.number().optional(),nameUpdatedAt:P.number().optional(),bioUpdatedAt:P.number().optional(),membersLength:P.number().optional(),members:P.object({type:P.enum(["user","admin","superadmin"]),id:P.string()}).array().optional()});var Ka=Sa.pick({roomId:!0}),Ja=P.enum(["typing","recording","online","offline","paused"]),Ba=class{constructor(e){this.wa=e,this.parser=new ma(e.socket,e.client,e.db)}parser;caching=new x.default({stdTTL:600,checkperiod:120,maxKeys:1e3});async sendMessage(e,t,a){let s=[];this.wa.client.options?.autoMentions&&(s=((e="")=>{if(!e)return[];const t=new Set;for(const a of e.matchAll(/@(\d+)/g))t.add(a[1]);return[...t].flatMap((e=>[`${e}@s.whatsapp.net`,`${e}@g.us`]))})(t?.text||t?.caption)),this.wa.client.options?.autoPresence&&this.wa.socket?.sendPresenceUpdate("composing",e),this.wa.client.options?.autoPresence&&(t?.audio||t?.audioNote)&&this.wa.socket?.sendPresenceUpdate("recording",e);const n=t,i={contextInfo:{isForwarded:!!n?.asForwarded}};if("function"==typeof n?.quoted){let t=n?.quoted();t.key.remoteJid=la[n?.verifiedReply]||t.key.remoteJid;const r=await(this.wa.socket?.sendMessage(e,{...n,mentions:s,...i},{quoted:t,...a}));return await this.parser.messages(r)}{const t=await(this.wa.socket?.sendMessage(e,{...n,mentions:s,...i},a));return await this.parser.messages(t)}}async text(e,t){if(e=Ia.parse(e),t=Sa.parse(t),"string"==typeof e)return await this.sendMessage(t.roomId,{text:e,...t});if("object"==typeof e){const a=Object.keys(e),s=e;if(a.includes("image")){const e="string"==typeof s.image?{url:s.image}:s.image;return await this.sendMessage(t.roomId,{caption:s?.text,image:e,viewOnce:!!t.asViewOnce,...t})}if(a.includes("video")){const e="string"==typeof s.video?{url:s.video}:s.video;return await this.sendMessage(t.roomId,{caption:s?.text,video:e,ptv:!1,viewOnce:!!t.asViewOnce,...t})}if(a.includes("videoNote")){const e="string"==typeof s.videoNote?{url:s.videoNote}:s.videoNote;return await this.sendMessage(t.roomId,{caption:s?.text,video:e,ptv:!0,...t})}if(a.includes("gif")){const e="string"==typeof s.gif?{url:s.gif}:s.gif;return await this.sendMessage(t.roomId,{caption:s?.text,video:e,gifPlayback:!0,viewOnce:!!t.asViewOnce,...t})}if(a.includes("audio")){const e="string"==typeof s.audio?{url:s.audio}:s.audio;return await this.sendMessage(t.roomId,{caption:s?.text,audio:e,viewOnce:!!t.asViewOnce,...t})}if(a.includes("audioNote")){const e="string"==typeof s.audioNote?{url:s.audioNote}:s.audioNote;return await this.sendMessage(t.roomId,{caption:s?.text,audio:e,ptt:!0,viewOnce:!!t.asViewOnce,...t})}if(a.includes("sticker")){const e="string"==typeof s.sticker?{url:s.sticker}:s.sticker;return await this.sendMessage(t.roomId,{caption:s?.text,sticker:e,...t})}}}async location(e,t){return e=Ta.parse(e),t=Na.parse(t),await this.sendMessage(t.roomId,{location:{degreesLatitude:e.latitude,degreesLongitude:e.longitude,url:e.title,address:e.footer,name:e.title},...t})}async contact(e,t){e=Oa.parse(e),t=Aa.parse(t);const a=["BEGIN:VCARD","VERSION:3.0",`N:;${e.fullname};;;`,`FN:${e.fullname}`,e.nickname?`NICKNAME:${e.nickname}`:"",e.organization||e.role?`ORG:${e.organization??""};`:"",e.role?`TITLE:${e.role}`:"",`TEL;TYPE=CELL,VOICE;waid=${e.whatsAppNumber}:+${e.whatsAppNumber}`,e.callNumber?`TEL;TYPE=WORK,VOICE:+${e.callNumber}`:"",e.voiceNumber?`TEL;TYPE=VOICE:+${e.voiceNumber}`:"",e.email?`EMAIL;TYPE=INTERNET:${e.email}`:"",e.website?`URL;TYPE=WORK:${e.website}`:"",e.homeAddress?`ADR;TYPE=HOME:;;${e.homeAddress};;;;`:"",e.workAddress?`ADR;TYPE=WORK:;;${e.workAddress};;;;`:"",e.avatar?`PHOTO;VALUE=URI;TYPE=JPEG:${e.avatar}`:"","END:VCARD"].join("\n");return await this.sendMessage(t.roomId,{contacts:{displayName:e.fullname,contacts:[{vcard:a}]},...t})}async reaction(e,t){return e=Za.parse(e),t=Ea.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{react:{text:e,key:t.message()?.key},...t})}async pin(e,t){e=ja.parse(e),t=La.parse(t);return await this.sendMessage(t.message()?.key?.remoteJid,{pin:{type:"pin"==e.action?1:0,time:{"24h":86400,"7d":604800,"30d":2592e3}[e.expired],key:t.message()?.key},...t})}async poll(e,t){return e=Ra.parse(e),t=Pa.parse(t),await this.sendMessage(t.roomId,{poll:{name:e.name,values:e.answers,selectableCount:e.multipleAnswers?1:0,toAnnouncementGroup:!0},...t})}async edit(e,t){return e=qa.parse(e),t=Fa.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{text:e,edit:t.message()?.key,...t})}async delete(e){return e=$a.parse(e),await this.sendMessage(e.message()?.key?.remoteJid,{delete:e.message()?.key})}async rejectCall(e){return e=za.parse(e),await(this.wa.socket?.rejectCall(e.callId,e.callerId))}async mute(e,t){e=Ua.parse(e),t=Da.parse(t);return await(this.wa.socket?.chatModify({mute:{remove:null,"8h":864e5,"7d":6048e5}[e.expired]},t.roomId))}async profile(t){const a=(t=Va.parse(t)).includes("@g.us"),s={};s.id=t;if(e.jidNormalizedUser(this.wa.socket?.user?.id)==t)s.name=this.wa.socket?.user?.name||this.wa.socket?.user?.verifiedName;else if(a){const e=await(this.wa.socket?.groupMetadata(t));s.type="group",s.name=e?.subject,s.bio=e?.desc,s.avatar=await(this.wa.socket?.profilePictureUrl(t)),s.ephemeralDuration=e?.ephemeralDuration,s.isRestrict=e?.restrict,s.isAnnounce=e?.announce,s.isCommunity=e?.isCommunity,s.isCommunityAnnounce=e?.isCommunityAnnounce,s.isJoinApprovalMode=e?.joinApprovalMode,s.isMemberAddMode=e?.memberAddMode,s.owner={type:"user",id:e?.owner},s.roomCreatedAt=e?.creation,s.nameUpdatedAt=e?.subjectTime,s.membersLength=e?.size,s.members=e?.participants.map((e=>({id:e.id,type:"admin"==e.admin||"superadmin"==e.admin?e.admin:"user"})))}else{const e=await(this.wa.db?.selectFrom("chats").select("value").where("id","=",t).executeTakeFirst()),a=O(e?.value),n=(await(this.wa?.socket?.fetchStatus(t)))[0]?.status;s.type="user",s.name=a?.name,s.bio=n?.status,s.avatar=await(this.wa?.socket?.profilePictureUrl(t)),s.bioUpdatedAt=new Date(n?.setAt).getTime()}return s}async presence(e,t){e=Ja.parse(e),t=Ka.parse(t);return await(this.wa.socket?.sendPresenceUpdate({typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"}[e],t.roomId))}async addCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=xa.parse(e);if(!await(this.wa.db?.insertInto("llm_messages").values(e).executeTakeFirst()))throw new Error("Failed to add completion");return e}async deleteCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_messages").where("uniqueId","=",e).executeTakeFirst()))throw new Error("Failed to delete completion");return!0}async updateCompletion(e,t){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const a=xa.partial().parse(t),s=await(this.wa.db?.updateTable("llm_messages").set(a).where("uniqueId","=",e).returningAll().executeTakeFirst());if(!s)throw new Error("Failed to update completion");return xa.parse(s)}async clearCompletions(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_messages").where("channelId","=",e).executeTakeFirst()))throw new Error("Failed to clear completions");return!0}async getCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_messages").selectAll().where("uniqueId","=",e).executeTakeFirst());return t?xa.parse(t):null}async getCompletions(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_messages").selectAll().where("channelId","=",e).execute());return t?.map((e=>xa.parse(e)))||[]}async addPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=ka.parse(e);if(!await(this.wa.db?.insertInto("llm_personalization").values(e).executeTakeFirst()))throw new Error("Failed to add completion");return e}async deletePersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_personalization").where("uniqueId","=",e).executeTakeFirst()))throw new Error("Failed to delete completion");return!0}async clearPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_personalization").where("senderId","=",e).executeTakeFirst()))throw new Error("Failed to clear completions");return!0}async getPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_personalization").selectAll().where("senderId","=",e).execute());return t?.map((e=>ka.parse(e)))||[]}async addRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=Ca.parse(e);if(!await(this.wa.db?.insertInto("llm_rag").values({pageContent:e.pageContent.toLowerCase(),"metadata.id":e.metadata?.id}).executeTakeFirst()))throw new Error("Failed to add RAG");return e}async deleteRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_rag").where(d.sql`"metadata.id"`,"=",e).executeTakeFirst()))throw new Error("Failed to delete RAG");return!0}async updateRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.updateTable("llm_rag").set({metadata:{id:e}}).where(d.sql`"metadata.id"`,"=",e).returningAll().executeTakeFirst());if(!t)throw new Error("Failed to update RAG");return Ca.parse(t)}async clearRAGs(){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_rag").executeTakeFirst()))throw new Error("Failed to clear RAGs");return!0}async getRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_rag").selectAll().where(d.sql`"metadata.id"`,"=",e).executeTakeFirst());return t?Ca.parse(t):null}async getRAGs(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas not loaded");const t=e.toLowerCase().trim(),a=this.caching.get(t);if(a)return a;const s=t.split(/\s+/).filter((e=>e.length>0));if(!s.length)return[];const n=await(this.wa.db?.selectFrom("llm_rag").select([d.sql`"metadata.id"`.as("metadata.id"),"pageContent"]).where("pageContent","!=","").limit(1e4).execute().then((e=>e.map((e=>Ca.parse({...e,metadata:{id:e["metadata.id"]}}))))).then((e=>e.filter((e=>{const t=e.pageContent.toLowerCase().split(/\s+/);return s.some((e=>t.some((t=>T.get(e,t)<=Math.max(1,Math.floor(e.length/4))))))})))));return this.caching.set(t,n),n||[]}llms={addCompletion:this.addCompletion.bind(this),deleteCompletion:this.deleteCompletion.bind(this),updateCompletion:this.updateCompletion.bind(this),clearCompletions:this.clearCompletions.bind(this),getCompletion:this.getCompletion.bind(this),getCompletions:this.getCompletions.bind(this),addPersonalization:this.addPersonalization.bind(this),deletePersonalization:this.deletePersonalization.bind(this),clearPersonalization:this.clearPersonalization.bind(this),getPersonalization:this.getPersonalization.bind(this),addRAG:this.addRAG.bind(this),deleteRAG:this.deleteRAG.bind(this),updateRAG:this.updateRAG.bind(this),clearRAGs:this.clearRAGs.bind(this),getRAG:this.getRAG.bind(this),getRAGs:this.getRAGs.bind(this)}};exports.Client=class{constructor(e){return this.props=e,this.initialize(),this.worker,new Proxy(this,{get:(e,t)=>t in e?e[t]:e.worker[t]})}options={};cache=new x.default({stdTTL:300,useClones:!1});chatId="zaileys-chats";logger=C.default({level:"silent",enabled:!1});db;socket;events=new t.EventEmitter;spinners=new Map;worker;async initialize(){console.clear(),await((e="ZAILEYS")=>new Promise((t=>{b.default(e,((e,a)=>{if(e)return t("");console.log(a),t(a||"")}))})))(),this.options=await ba.parseAsync(this.props),this.startSpinner("db","Initializing database..."),this.db=await(e=>{const{type:t,connection:a}=e.database;if("sqlite"===t){const e=a.url||"./db/zaileys.db",t=S.default.resolve(e);return o.mkdirSync(S.default.dirname(t),{recursive:!0}),o.writeFileSync(t,"",{flag:"a"}),new d.Kysely({dialect:new d.SqliteDialect({database:new M.default(t)})})}const s=new p.URL(a.url),n=s.protocol.replace(":","");if("mysql"===t)return new d.Kysely({dialect:new d.MysqlDialect({pool:I.default.createPool({host:s.hostname,user:s.username,password:s.password,database:s.pathname.replace("/",""),port:parseInt(s.port||"3306",10)})})});if("postgresql"===t)return new d.Kysely({dialect:new d.PostgresDialect({pool:new u.Pool({host:s.hostname,user:s.username,password:s.password,database:s.pathname.replace("/",""),port:parseInt(s.port||"5432",10)})})});throw new Error(`Unsupported database protocol: ${n}`)})(this.options),this.stopSpinner("db",!0,"Database initialized"),this.startSpinner("auth","Setting up auth adapter...");const{state:t,saveCreds:a}=await fa(this.db,this.chatId,this.options);this.stopSpinner("auth",!0,"Auth adapter ready"),this.startSpinner("store","Setting up store adapter...");const s=await(async(e,t,a)=>({bind:s=>{const n=new ma(s,e,t);s?.ev.on("connection.update",(async e=>{await n.connection(e)})),s?.ev.on("call",(async e=>{for(const t of e)await n.calls(t)})),s?.ev.on("messaging-history.set",(async e=>{const{chats:s,contacts:n,messages:i}=e;for(const e of s)await t.insertInto("chats").values({session:a,id:e.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute();for(const e of n)await t.insertInto("contacts").values({session:a,id:e.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute();for(const e of i){if(!e.message)return;if(e.message?.protocolMessage)return;await t.insertInto("messages").values({session:a,id:e.key.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute()}})),s?.ev.on("messages.upsert",(async({messages:e})=>{for(const s of e){if(!s.message)return;if(s.message?.protocolMessage)return;await n.messages(s),await t.insertInto("messages").values({session:a,id:s.key.id,value:JSON.stringify(s)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(s)}))).execute()}})),s?.ev.on("chats.upsert",(async e=>{for(const s of e)await t.insertInto("chats").values({session:a,id:s.id,value:JSON.stringify(s)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(s)}))).execute()})),s?.ev.on("contacts.upsert",(async e=>{for(const s of e)await t.insertInto("contacts").values({session:a,id:s.id,value:JSON.stringify(s)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(s)}))).execute()})),s?.ev.on("groups.update",(async([t])=>{const a=await(s?.groupMetadata(t.id));e.cache.set(t.id,a)})),s?.ev.on("group-participants.update",(async t=>{const a=await(s?.groupMetadata(t.id));e.cache.set(t.id,a)}))}}))(this,this.db,this.chatId);this.stopSpinner("store",!0,"Store adapter ready");const{version:n}=await e.fetchLatestBaileysVersion();if(this.socket=e.makeWASocket({version:n,logger:this.logger,markOnlineOnConnect:this.options.autoOnline,syncFullHistory:!1,defaultQueryTimeoutMs:void 0,msgRetryCounterCache:new x.default,mediaCache:new x.default({stdTTL:60}),userDevicesCache:new x.default,cachedGroupMetadata:async e=>this.cache.get(e),printQRInTerminal:!1,browser:e.Browsers.ubuntu("qr"===this.options.authType?"Zaileys Library":"Chrome"),auth:{creds:t.creds,keys:e.makeCacheableSignalKeyStore(t.keys,this.logger)},getMessage:async e=>{const t=await(this.db?.selectFrom("messages").select("value").where("id","=",e.id).executeTakeFirst());return O(t?.value)}}),"pairing"===this.options.authType&&this.options.phoneNumber&&!this.socket?.authState.creds.registered){this.startSpinner("pairing","Generating pairing code...");(await this.socket.onWhatsApp(this.options.phoneNumber.toString()+"@s.whatsapp.net"))[0].exists||(this.failSpinner("pairing","Phone is not registered on WhatsApp"),process.exit(1)),setTimeout((async()=>{try{if("pairing"===this.options?.authType){const e=await(this.socket?.requestPairingCode(this.options.phoneNumber.toString()));this.stopSpinner("pairing",!0,`Pairing code: ${e}`)}}catch{this.failSpinner("pairing","Connection failed"),process.exit(1)}}),5e3)}this.worker=new Ba({client:this,db:this.db,socket:this.socket}),this.socket?.ev.on("creds.update",a),s.bind(this.socket)}startSpinner(e,t){let a=this.spinners.get(e);return a||(a=k.default(t).start(),this.spinners.set(e,a)),a}stopSpinner(e,t,a){const s=this.spinners.get(e);s&&(t?s.succeed(a):s.stop(),this.spinners.delete(e))}failSpinner(e,t){const a=this.spinners.get(e);a&&(a.fail(t),this.spinners.delete(e))}on(e,t){this.events.on(e,t)}emit(e,...t){this.events.emit(e,...t)}};
|
|
1
|
+
"use strict";var e=require("baileys"),t=require("events"),a=require("figlet"),s=require("node-cache"),n=require("ora"),i=require("pino"),r=require("better-sqlite3"),o=require("fs"),d=require("kysely"),c=require("mysql2"),l=require("path"),u=require("pg"),p=require("url"),h=require("qrcode"),m=require("stream"),f=require("fast-levenshtein");function g(e){return e&&e.__esModule?e:{default:e}}function y(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(a){if("default"!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}})),t.default=e,Object.freeze(t)}var v,_,w,b=g(a),x=g(s),k=g(n),C=g(i),M=g(r),I=g(c),S=g(l),N=g(h),T=y(f),A=Object.defineProperty,O=(e="")=>{try{return JSON.parse(e)}catch{return JSON.parse(JSON.stringify(e))}},E=(e={})=>{try{return JSON.stringify(e)}catch{return JSON.stringify(JSON.parse(JSON.stringify(e)))}},Z=(e="",t="")=>e?e.toLowerCase().includes(t.toLowerCase()):null,L=(e,t)=>e&&"object"==typeof e?Array.isArray(e)?e.map((e=>L(e,t))):Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e))).map((([e,a])=>[e,"object"==typeof a?L(a,t):a]))):e,j=e=>{const t={...e.fingerprint,deviceIndexes:Array.isArray(e.fingerprint.deviceIndexes)?e.fingerprint.deviceIndexes:[]},a={keyData:Array.isArray(e.keyData)?e.keyData:new Uint8Array,fingerprint:{rawId:t.rawId||0,currentIndex:t.rawId||0,deviceIndexes:t.deviceIndexes},timestamp:(s=e.timestamp,"string"==typeof s?parseInt(s,10):s)};var s;return"string"==typeof e.keyData&&(a.keyData=(e=>{let t=e.length;if(!t)return new Uint8Array(1);let a=0;for(;--t%4>1&&"="===e.charAt(t);)++a;return new Uint8Array(Math.ceil(3*e.length)/4-a).fill(0)})(e.keyData)),a},P={};((e,t)=>{for(var a in t)A(e,a,{get:t[a],enumerable:!0})})(P,{BRAND:()=>mt,DIRTY:()=>X,EMPTY_PATH:()=>B,INVALID:()=>Q,NEVER:()=>da,OK:()=>ee,ParseStatus:()=>H,Schema:()=>ce,ZodAny:()=>qe,ZodArray:()=>Ue,ZodBigInt:()=>Ze,ZodBoolean:()=>Le,ZodBranded:()=>ft,ZodCatch:()=>pt,ZodDate:()=>je,ZodDefault:()=>ut,ZodDiscriminatedUnion:()=>Ge,ZodEffects:()=>dt,ZodEnum:()=>it,ZodError:()=>z,ZodFirstPartyTypeKind:()=>wt,ZodFunction:()=>tt,ZodIntersection:()=>Ye,ZodIssueCode:()=>q,ZodLazy:()=>at,ZodLiteral:()=>st,ZodMap:()=>Xe,ZodNaN:()=>ht,ZodNativeEnum:()=>rt,ZodNever:()=>ze,ZodNull:()=>Fe,ZodNullable:()=>lt,ZodNumber:()=>Ee,ZodObject:()=>Ke,ZodOptional:()=>ct,ZodParsedType:()=>R,ZodPipeline:()=>gt,ZodPromise:()=>ot,ZodReadonly:()=>yt,ZodRecord:()=>Qe,ZodSchema:()=>ce,ZodSet:()=>et,ZodString:()=>Ae,ZodSymbol:()=>Pe,ZodTransformer:()=>dt,ZodTuple:()=>He,ZodType:()=>ce,ZodUndefined:()=>Re,ZodUnion:()=>Je,ZodUnknown:()=>$e,ZodVoid:()=>De,addIssueToContext:()=>G,any:()=>Zt,array:()=>Rt,bigint:()=>St,boolean:()=>Nt,coerce:()=>oa,custom:()=>_t,date:()=>Tt,datetimeRegex:()=>Se,defaultErrorMap:()=>D,discriminatedUnion:()=>zt,effect:()=>Xt,enum:()=>Yt,function:()=>Bt,getErrorMap:()=>K,getParsedType:()=>F,instanceof:()=>kt,intersection:()=>Dt,isAborted:()=>te,isAsync:()=>ne,isDirty:()=>ae,isValid:()=>se,late:()=>xt,lazy:()=>Gt,literal:()=>Wt,makeIssue:()=>J,map:()=>Kt,nan:()=>It,nativeEnum:()=>Ht,never:()=>jt,null:()=>Et,nullable:()=>ta,number:()=>Mt,object:()=>Ft,objectUtil:()=>w,oboolean:()=>ra,onumber:()=>ia,optional:()=>ea,ostring:()=>na,pipeline:()=>sa,preprocess:()=>aa,promise:()=>Qt,quotelessJson:()=>$,record:()=>Vt,set:()=>Jt,setErrorMap:()=>V,strictObject:()=>qt,string:()=>Ct,symbol:()=>At,transformer:()=>Xt,tuple:()=>Ut,undefined:()=>Ot,union:()=>$t,unknown:()=>Lt,util:()=>v,void:()=>Pt}),(_=v||(v={})).assertEqual=e=>{},_.assertIs=function(e){},_.assertNever=function(e){throw new Error},_.arrayToEnum=e=>{const t={};for(const a of e)t[a]=a;return t},_.getValidEnumValues=e=>{const t=_.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),a={};for(const s of t)a[s]=e[s];return _.objectValues(a)},_.objectValues=e=>_.objectKeys(e).map((function(t){return e[t]})),_.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.push(a);return t},_.find=(e,t)=>{for(const a of e)if(t(a))return a},_.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,_.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},_.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(w||(w={})).mergeShapes=(e,t)=>({...e,...t});var R=v.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),F=e=>{switch(typeof e){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(e)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(e)?R.array:null===e?R.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?R.promise:"undefined"!=typeof Map&&e instanceof Map?R.map:"undefined"!=typeof Set&&e instanceof Set?R.set:"undefined"!=typeof Date&&e instanceof Date?R.date:R.object;default:return R.unknown}},q=v.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),z=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};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},a={_errors:[]},s=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(s);else if("invalid_return_type"===n.code)s(n.returnTypeError);else if("invalid_arguments"===n.code)s(n.argumentsError);else if(0===n.path.length)a._errors.push(t(n));else{let e=a,s=0;for(;s<n.path.length;){const a=n.path[s];s===n.path.length-1?(e[a]=e[a]||{_errors:[]},e[a]._errors.push(t(n))):e[a]=e[a]||{_errors:[]},e=e[a],s++}}};return s(this),a}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,v.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},a=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):a.push(e(s));return{formErrors:a,fieldErrors:t}}get formErrors(){return this.flatten()}};z.create=e=>new z(e);var D=(e,t)=>{let a;switch(e.code){case q.invalid_type:a=e.received===R.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case q.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(e.expected,v.jsonStringifyReplacer)}`;break;case q.unrecognized_keys:a=`Unrecognized key(s) in object: ${v.joinValues(e.keys,", ")}`;break;case q.invalid_union:a="Invalid input";break;case q.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${v.joinValues(e.options)}`;break;case q.invalid_enum_value:a=`Invalid enum value. Expected ${v.joinValues(e.options)}, received '${e.received}'`;break;case q.invalid_arguments:a="Invalid function arguments";break;case q.invalid_return_type:a="Invalid function return type";break;case q.invalid_date:a="Invalid date";break;case q.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(a=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(a=`${a} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?a=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?a=`Invalid input: must end with "${e.validation.endsWith}"`:v.assertNever(e.validation):a="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case q.too_small:a="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?`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 q.too_big:a="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 q.custom:a="Invalid input";break;case q.invalid_intersection_types:a="Intersection results could not be merged";break;case q.not_multiple_of:a=`Number must be a multiple of ${e.multipleOf}`;break;case q.not_finite:a="Number must be finite";break;default:a=t.defaultError,v.assertNever(e)}return{message:a}},U=D;function V(e){U=e}function K(){return U}var J=e=>{const{data:t,path:a,errorMaps:s,issueData:n}=e,i=[...a,...n.path||[]],r={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const d=s.filter((e=>!!e)).slice().reverse();for(const e of d)o=e(r,{data:t,defaultError:o}).message;return{...n,path:i,message:o}},B=[];function G(e,t){const a=K(),s=J({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,a,a===D?void 0:D].filter((e=>!!e))});e.common.issues.push(s)}var W,Y,H=class e{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const a=[];for(const s of t){if("aborted"===s.status)return Q;"dirty"===s.status&&e.dirty(),a.push(s.value)}return{status:e.value,value:a}}static async mergeObjectAsync(t,a){const s=[];for(const e of a){const t=await e.key,a=await e.value;s.push({key:t,value:a})}return e.mergeObjectSync(t,s)}static mergeObjectSync(e,t){const a={};for(const s of t){const{key:t,value:n}=s;if("aborted"===t.status)return Q;if("aborted"===n.status)return Q;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!s.alwaysSet||(a[t.value]=n.value)}return{status:e.value,value:a}}},Q=Object.freeze({status:"aborted"}),X=e=>({status:"dirty",value:e}),ee=e=>({status:"valid",value:e}),te=e=>"aborted"===e.status,ae=e=>"dirty"===e.status,se=e=>"valid"===e.status,ne=e=>"undefined"!=typeof Promise&&e instanceof Promise;(Y=W||(W={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},Y.toString=e=>"string"==typeof e?e:e?.message;var ie=class{constructor(e,t,a,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=a,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},re=(e,t)=>{if(se(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._error)return this._error;const t=new z(e.common.issues);return this._error=t,this._error}}};function oe(e){if(!e)return{};const{errorMap:t,invalid_type_error:a,required_error:s,description:n}=e;if(t&&(a||s))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??s??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??a??n.defaultError}},description:n}}var de,ce=class{get description(){return this._def.description}_getType(e){return F(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:F(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new H,ctx:{common:e.parent.common,data:e.data,parsedType:F(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ne(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const a=this.safeParse(e,t);if(a.success)return a.data;throw a.error}safeParse(e,t){const a={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:F(e)},s=this._parseSync({data:e,path:a.path,parent:a});return re(a,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:F(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:t});return se(a)?{value:a.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((e=>se(e)?{value:e.value}:{issues:t.common.issues}))}async parseAsync(e,t){const a=await this.safeParseAsync(e,t);if(a.success)return a.data;throw a.error}async safeParseAsync(e,t){const a={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:F(e)},s=this._parse({data:e,path:a.path,parent:a}),n=await(ne(s)?s:Promise.resolve(s));return re(a,n)}refine(e,t){const a=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,s)=>{const n=e(t),i=()=>s.addIssue({code:q.custom,...a(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then((e=>!!e||(i(),!1))):!!n||(i(),!1)}))}refinement(e,t){return this._refinement(((a,s)=>!!e(a)||(s.addIssue("function"==typeof t?t(a,s):t),!1)))}_refinement(e){return new dt({schema:this,typeName:wt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return ct.create(this,this._def)}nullable(){return lt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ue.create(this)}promise(){return ot.create(this,this._def)}or(e){return Je.create([this,e],this._def)}and(e){return Ye.create(this,e,this._def)}transform(e){return new dt({...oe(this._def),schema:this,typeName:wt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ut({...oe(this._def),innerType:this,defaultValue:t,typeName:wt.ZodDefault})}brand(){return new ft({typeName:wt.ZodBranded,type:this,...oe(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new pt({...oe(this._def),innerType:this,catchValue:t,typeName:wt.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return gt.create(this,e)}readonly(){return yt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},le=/^c[^\s-]{8,}$/i,ue=/^[0-9a-z]+$/,pe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,he=/^[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,me=/^[a-z0-9_-]{21}$/i,fe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ge=/^[-+]?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)?)??$/,ye=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ve=/^(?:(?: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])$/,_e=/^(?:(?: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])$/,we=/^(([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]))$/,be=/^(([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])$/,xe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ke=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ce="((\\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])))",Me=new RegExp(`^${Ce}$`);function Ie(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 Se(e){let t=`${Ce}T${Ie(e)}`;const a=[];return a.push(e.local?"Z?":"Z"),e.offset&&a.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${a.join("|")})`,new RegExp(`^${t}$`)}function Ne(e,t){if(!fe.test(e))return!1;try{const[a]=e.split("."),s=a.replace(/-/g,"+").replace(/_/g,"/").padEnd(a.length+(4-a.length%4)%4,"="),n=JSON.parse(atob(s));return"object"==typeof n&&null!==n&&((!("typ"in n)||"JWT"===n?.typ)&&(!!n.alg&&(!t||n.alg===t)))}catch{return!1}}function Te(e,t){return!("v4"!==t&&t||!_e.test(e))||!("v6"!==t&&t||!be.test(e))}var Ae=class e extends ce{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==R.string){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.string,received:t.parsedType}),Q}const t=new H;let a;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(a=this._getOrReturnCtx(e,a),G(a,{code:q.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("max"===i.kind)e.data.length>i.value&&(a=this._getOrReturnCtx(e,a),G(a,{code:q.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("length"===i.kind){const s=e.data.length>i.value,n=e.data.length<i.value;(s||n)&&(a=this._getOrReturnCtx(e,a),s?G(a,{code:q.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&G(a,{code:q.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)ye.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"email",code:q.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)de||(de=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),de.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"emoji",code:q.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)he.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"uuid",code:q.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)me.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"nanoid",code:q.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)le.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"cuid",code:q.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)ue.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"cuid2",code:q.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)pe.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"ulid",code:q.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a),G(a,{validation:"url",code:q.invalid_string,message:i.message}),t.dirty()}else if("regex"===i.kind){i.regex.lastIndex=0;i.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"regex",code:q.invalid_string,message:i.message}),t.dirty())}else if("trim"===i.kind)e.data=e.data.trim();else if("includes"===i.kind)e.data.includes(i.value,i.position)||(a=this._getOrReturnCtx(e,a),G(a,{code:q.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),t.dirty());else if("toLowerCase"===i.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===i.kind)e.data=e.data.toUpperCase();else if("startsWith"===i.kind)e.data.startsWith(i.value)||(a=this._getOrReturnCtx(e,a),G(a,{code:q.invalid_string,validation:{startsWith:i.value},message:i.message}),t.dirty());else if("endsWith"===i.kind)e.data.endsWith(i.value)||(a=this._getOrReturnCtx(e,a),G(a,{code:q.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){Se(i).test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{code:q.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){Me.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{code:q.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${Ie(i)}$`).test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{code:q.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?ge.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"duration",code:q.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(s=e.data,("v4"!==(n=i.version)&&n||!ve.test(s))&&("v6"!==n&&n||!we.test(s))&&(a=this._getOrReturnCtx(e,a),G(a,{validation:"ip",code:q.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?Ne(e.data,i.alg)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"jwt",code:q.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?Te(e.data,i.version)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"cidr",code:q.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?xe.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"base64",code:q.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?ke.test(e.data)||(a=this._getOrReturnCtx(e,a),G(a,{validation:"base64url",code:q.invalid_string,message:i.message}),t.dirty()):v.assertNever(i);var s,n;return{status:t.value,value:e.data}}_regex(e,t,a){return this.refinement((t=>e.test(t)),{validation:t,code:q.invalid_string,...W.errToObj(a)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...W.errToObj(e)})}url(e){return this._addCheck({kind:"url",...W.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...W.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...W.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...W.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...W.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...W.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...W.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...W.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...W.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...W.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...W.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...W.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...W.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...W.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...W.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...W.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...W.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...W.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...W.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...W.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...W.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...W.errToObj(t)})}nonempty(e){return this.min(1,W.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};function Oe(e,t){const a=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,n=a>s?a:s;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}Ae.create=e=>new Ae({checks:[],typeName:wt.ZodString,coerce:e?.coerce??!1,...oe(e)});var Ee=class e extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==R.number){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.number,received:t.parsedType}),Q}let t;const a=new H;for(const s of this._def.checks)if("int"===s.kind)v.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),G(t,{code:q.invalid_type,expected:"integer",received:"float",message:s.message}),a.dirty());else if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:q.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:q.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty())}else"multipleOf"===s.kind?0!==Oe(e.data,s.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:q.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),G(t,{code:q.not_finite,message:s.message}),a.dirty()):v.assertNever(s);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,W.toString(t))}gt(e,t){return this.setLimit("min",e,!1,W.toString(t))}lte(e,t){return this.setLimit("max",e,!0,W.toString(t))}lt(e,t){return this.setLimit("max",e,!1,W.toString(t))}setLimit(t,a,s,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:a,inclusive:s,message:W.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:W.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:W.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&v.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const a of this._def.checks){if("finite"===a.kind||"int"===a.kind||"multipleOf"===a.kind)return!0;"min"===a.kind?(null===t||a.value>t)&&(t=a.value):"max"===a.kind&&(null===e||a.value<e)&&(e=a.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Ee.create=e=>new Ee({checks:[],typeName:wt.ZodNumber,coerce:e?.coerce||!1,...oe(e)});var Ze=class e extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==R.bigint)return this._getInvalidInput(e);let t;const a=new H;for(const s of this._def.checks)if("min"===s.kind){(s.inclusive?e.data<s.value:e.data<=s.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:q.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty())}else if("max"===s.kind){(s.inclusive?e.data>s.value:e.data>=s.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:q.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty())}else"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),G(t,{code:q.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):v.assertNever(s);return{status:a.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.bigint,received:t.parsedType}),Q}gte(e,t){return this.setLimit("min",e,!0,W.toString(t))}gt(e,t){return this.setLimit("min",e,!1,W.toString(t))}lte(e,t){return this.setLimit("max",e,!0,W.toString(t))}lt(e,t){return this.setLimit("max",e,!1,W.toString(t))}setLimit(t,a,s,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:a,inclusive:s,message:W.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};Ze.create=e=>new Ze({checks:[],typeName:wt.ZodBigInt,coerce:e?.coerce??!1,...oe(e)});var Le=class extends ce{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==R.boolean){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.boolean,received:t.parsedType}),Q}return ee(e.data)}};Le.create=e=>new Le({typeName:wt.ZodBoolean,coerce:e?.coerce||!1,...oe(e)});var je=class e extends ce{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==R.date){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.date,received:t.parsedType}),Q}if(Number.isNaN(e.data.getTime())){return G(this._getOrReturnCtx(e),{code:q.invalid_date}),Q}const t=new H;let a;for(const s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(a=this._getOrReturnCtx(e,a),G(a,{code:q.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),t.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(a=this._getOrReturnCtx(e,a),G(a,{code:q.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),t.dirty()):v.assertNever(s);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:W.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:W.toString(t)})}get minDate(){let e=null;for(const t of this._def.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._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}};je.create=e=>new je({checks:[],coerce:e?.coerce||!1,typeName:wt.ZodDate,...oe(e)});var Pe=class extends ce{_parse(e){if(this._getType(e)!==R.symbol){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.symbol,received:t.parsedType}),Q}return ee(e.data)}};Pe.create=e=>new Pe({typeName:wt.ZodSymbol,...oe(e)});var Re=class extends ce{_parse(e){if(this._getType(e)!==R.undefined){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.undefined,received:t.parsedType}),Q}return ee(e.data)}};Re.create=e=>new Re({typeName:wt.ZodUndefined,...oe(e)});var Fe=class extends ce{_parse(e){if(this._getType(e)!==R.null){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.null,received:t.parsedType}),Q}return ee(e.data)}};Fe.create=e=>new Fe({typeName:wt.ZodNull,...oe(e)});var qe=class extends ce{constructor(){super(...arguments),this._any=!0}_parse(e){return ee(e.data)}};qe.create=e=>new qe({typeName:wt.ZodAny,...oe(e)});var $e=class extends ce{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ee(e.data)}};$e.create=e=>new $e({typeName:wt.ZodUnknown,...oe(e)});var ze=class extends ce{_parse(e){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.never,received:t.parsedType}),Q}};ze.create=e=>new ze({typeName:wt.ZodNever,...oe(e)});var De=class extends ce{_parse(e){if(this._getType(e)!==R.undefined){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.void,received:t.parsedType}),Q}return ee(e.data)}};De.create=e=>new De({typeName:wt.ZodVoid,...oe(e)});var Ue=class e extends ce{_parse(e){const{ctx:t,status:a}=this._processInputParams(e),s=this._def;if(t.parsedType!==R.array)return G(t,{code:q.invalid_type,expected:R.array,received:t.parsedType}),Q;if(null!==s.exactLength){const e=t.data.length>s.exactLength.value,n=t.data.length<s.exactLength.value;(e||n)&&(G(t,{code:e?q.too_big:q.too_small,minimum:n?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),a.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(G(t,{code:q.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),a.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(G(t,{code:q.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),a.dirty()),t.common.async)return Promise.all([...t.data].map(((e,a)=>s.type._parseAsync(new ie(t,e,t.path,a))))).then((e=>H.mergeArray(a,e)));const n=[...t.data].map(((e,a)=>s.type._parseSync(new ie(t,e,t.path,a))));return H.mergeArray(a,n)}get element(){return this._def.type}min(t,a){return new e({...this._def,minLength:{value:t,message:W.toString(a)}})}max(t,a){return new e({...this._def,maxLength:{value:t,message:W.toString(a)}})}length(t,a){return new e({...this._def,exactLength:{value:t,message:W.toString(a)}})}nonempty(e){return this.min(1,e)}};function Ve(e){if(e instanceof Ke){const t={};for(const a in e.shape){const s=e.shape[a];t[a]=ct.create(Ve(s))}return new Ke({...e._def,shape:()=>t})}return e instanceof Ue?new Ue({...e._def,type:Ve(e.element)}):e instanceof ct?ct.create(Ve(e.unwrap())):e instanceof lt?lt.create(Ve(e.unwrap())):e instanceof He?He.create(e.items.map((e=>Ve(e)))):e}Ue.create=(e,t)=>new Ue({type:e,minLength:null,maxLength:null,exactLength:null,typeName:wt.ZodArray,...oe(t)});var Ke=class e extends ce{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=v.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==R.object){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.object,received:t.parsedType}),Q}const{status:t,ctx:a}=this._processInputParams(e),{shape:s,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof ze&&"strip"===this._def.unknownKeys))for(const e in a.data)n.includes(e)||i.push(e);const r=[];for(const e of n){const t=s[e],n=a.data[e];r.push({key:{status:"valid",value:e},value:t._parse(new ie(a,n,a.path,e)),alwaysSet:e in a.data})}if(this._def.catchall instanceof ze){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)r.push({key:{status:"valid",value:e},value:{status:"valid",value:a.data[e]}});else if("strict"===e)i.length>0&&(G(a,{code:q.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const s=a.data[t];r.push({key:{status:"valid",value:t},value:e._parse(new ie(a,s,a.path,t)),alwaysSet:t in a.data})}}return a.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of r){const a=await t.key,s=await t.value;e.push({key:a,value:s,alwaysSet:t.alwaysSet})}return e})).then((e=>H.mergeObjectSync(t,e))):H.mergeObjectSync(t,r)}get shape(){return this._def.shape()}strict(t){return W.errToObj,new e({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(e,a)=>{const s=this._def.errorMap?.(e,a).message??a.defaultError;return"unrecognized_keys"===e.code?{message:W.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:wt.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){const a={};for(const e of v.objectKeys(t))t[e]&&this.shape[e]&&(a[e]=this.shape[e]);return new e({...this._def,shape:()=>a})}omit(t){const a={};for(const e of v.objectKeys(this.shape))t[e]||(a[e]=this.shape[e]);return new e({...this._def,shape:()=>a})}deepPartial(){return Ve(this)}partial(t){const a={};for(const e of v.objectKeys(this.shape)){const s=this.shape[e];t&&!t[e]?a[e]=s:a[e]=s.optional()}return new e({...this._def,shape:()=>a})}required(t){const a={};for(const e of v.objectKeys(this.shape))if(t&&!t[e])a[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof ct;)t=t._def.innerType;a[e]=t}return new e({...this._def,shape:()=>a})}keyof(){return nt(v.objectKeys(this.shape))}};Ke.create=(e,t)=>new Ke({shape:()=>e,unknownKeys:"strip",catchall:ze.create(),typeName:wt.ZodObject,...oe(t)}),Ke.strictCreate=(e,t)=>new Ke({shape:()=>e,unknownKeys:"strict",catchall:ze.create(),typeName:wt.ZodObject,...oe(t)}),Ke.lazycreate=(e,t)=>new Ke({shape:e,unknownKeys:"strip",catchall:ze.create(),typeName:wt.ZodObject,...oe(t)});var Je=class extends ce{_parse(e){const{ctx:t}=this._processInputParams(e),a=this._def.options;if(t.common.async)return Promise.all(a.map((async e=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const a of e)if("dirty"===a.result.status)return t.common.issues.push(...a.ctx.common.issues),a.result;const a=e.map((e=>new z(e.ctx.common.issues)));return G(t,{code:q.invalid_union,unionErrors:a}),Q}));{let e;const s=[];for(const n of a){const a={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:a});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:a}),a.common.issues.length&&s.push(a.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=s.map((e=>new z(e)));return G(t,{code:q.invalid_union,unionErrors:n}),Q}}get options(){return this._def.options}};Je.create=(e,t)=>new Je({options:e,typeName:wt.ZodUnion,...oe(t)});var Be=e=>e instanceof at?Be(e.schema):e instanceof dt?Be(e.innerType()):e instanceof st?[e.value]:e instanceof it?e.options:e instanceof rt?v.objectValues(e.enum):e instanceof ut?Be(e._def.innerType):e instanceof Re?[void 0]:e instanceof Fe?[null]:e instanceof ct?[void 0,...Be(e.unwrap())]:e instanceof lt?[null,...Be(e.unwrap())]:e instanceof ft||e instanceof yt?Be(e.unwrap()):e instanceof pt?Be(e._def.innerType):[],Ge=class e extends ce{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.object)return G(t,{code:q.invalid_type,expected:R.object,received:t.parsedType}),Q;const a=this.discriminator,s=t.data[a],n=this.optionsMap.get(s);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(G(t,{code:q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),Q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,a,s){const n=new Map;for(const e of a){const a=Be(e.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const s of a){if(n.has(s))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(s)}`);n.set(s,e)}}return new e({typeName:wt.ZodDiscriminatedUnion,discriminator:t,options:a,optionsMap:n,...oe(s)})}};function We(e,t){const a=F(e),s=F(t);if(e===t)return{valid:!0,data:e};if(a===R.object&&s===R.object){const a=v.objectKeys(t),s=v.objectKeys(e).filter((e=>-1!==a.indexOf(e))),n={...e,...t};for(const a of s){const s=We(e[a],t[a]);if(!s.valid)return{valid:!1};n[a]=s.data}return{valid:!0,data:n}}if(a===R.array&&s===R.array){if(e.length!==t.length)return{valid:!1};const a=[];for(let s=0;s<e.length;s++){const n=We(e[s],t[s]);if(!n.valid)return{valid:!1};a.push(n.data)}return{valid:!0,data:a}}return a===R.date&&s===R.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}var Ye=class extends ce{_parse(e){const{status:t,ctx:a}=this._processInputParams(e),s=(e,s)=>{if(te(e)||te(s))return Q;const n=We(e.value,s.value);return n.valid?((ae(e)||ae(s))&&t.dirty(),{status:t.value,value:n.data}):(G(a,{code:q.invalid_intersection_types}),Q)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then((([e,t])=>s(e,t))):s(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};Ye.create=(e,t,a)=>new Ye({left:e,right:t,typeName:wt.ZodIntersection,...oe(a)});var He=class e extends ce{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==R.array)return G(a,{code:q.invalid_type,expected:R.array,received:a.parsedType}),Q;if(a.data.length<this._def.items.length)return G(a,{code:q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q;!this._def.rest&&a.data.length>this._def.items.length&&(G(a,{code:q.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...a.data].map(((e,t)=>{const s=this._def.items[t]||this._def.rest;return s?s._parse(new ie(a,e,a.path,t)):null})).filter((e=>!!e));return a.common.async?Promise.all(s).then((e=>H.mergeArray(t,e))):H.mergeArray(t,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};He.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new He({items:e,typeName:wt.ZodTuple,rest:null,...oe(t)})};var Qe=class e extends ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==R.object)return G(a,{code:q.invalid_type,expected:R.object,received:a.parsedType}),Q;const s=[],n=this._def.keyType,i=this._def.valueType;for(const e in a.data)s.push({key:n._parse(new ie(a,e,a.path,e)),value:i._parse(new ie(a,a.data[e],a.path,e)),alwaysSet:e in a.data});return a.common.async?H.mergeObjectAsync(t,s):H.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(t,a,s){return new e(a instanceof ce?{keyType:t,valueType:a,typeName:wt.ZodRecord,...oe(s)}:{keyType:Ae.create(),valueType:t,typeName:wt.ZodRecord,...oe(a)})}},Xe=class extends ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==R.map)return G(a,{code:q.invalid_type,expected:R.map,received:a.parsedType}),Q;const s=this._def.keyType,n=this._def.valueType,i=[...a.data.entries()].map((([e,t],i)=>({key:s._parse(new ie(a,e,a.path,[i,"key"])),value:n._parse(new ie(a,t,a.path,[i,"value"]))})));if(a.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const a of i){const s=await a.key,n=await a.value;if("aborted"===s.status||"aborted"===n.status)return Q;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const a of i){const s=a.key,n=a.value;if("aborted"===s.status||"aborted"===n.status)return Q;"dirty"!==s.status&&"dirty"!==n.status||t.dirty(),e.set(s.value,n.value)}return{status:t.value,value:e}}}};Xe.create=(e,t,a)=>new Xe({valueType:t,keyType:e,typeName:wt.ZodMap,...oe(a)});var et=class e extends ce{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==R.set)return G(a,{code:q.invalid_type,expected:R.set,received:a.parsedType}),Q;const s=this._def;null!==s.minSize&&a.data.size<s.minSize.value&&(G(a,{code:q.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&a.data.size>s.maxSize.value&&(G(a,{code:q.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const a=new Set;for(const s of e){if("aborted"===s.status)return Q;"dirty"===s.status&&t.dirty(),a.add(s.value)}return{status:t.value,value:a}}const r=[...a.data.values()].map(((e,t)=>n._parse(new ie(a,e,a.path,t))));return a.common.async?Promise.all(r).then((e=>i(e))):i(r)}min(t,a){return new e({...this._def,minSize:{value:t,message:W.toString(a)}})}max(t,a){return new e({...this._def,maxSize:{value:t,message:W.toString(a)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};et.create=(e,t)=>new et({valueType:e,minSize:null,maxSize:null,typeName:wt.ZodSet,...oe(t)});var tt=class e extends ce{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.function)return G(t,{code:q.invalid_type,expected:R.function,received:t.parsedType}),Q;function a(e,a){return J({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,K(),D].filter((e=>!!e)),issueData:{code:q.invalid_arguments,argumentsError:a}})}function s(e,a){return J({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,K(),D].filter((e=>!!e)),issueData:{code:q.invalid_return_type,returnTypeError:a}})}const n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof ot){const e=this;return ee((async function(...t){const r=new z([]),o=await e._def.args.parseAsync(t,n).catch((e=>{throw r.addIssue(a(t,e)),r})),d=await Reflect.apply(i,this,o);return await e._def.returns._def.type.parseAsync(d,n).catch((e=>{throw r.addIssue(s(d,e)),r}))}))}{const e=this;return ee((function(...t){const r=e._def.args.safeParse(t,n);if(!r.success)throw new z([a(t,r.error)]);const o=Reflect.apply(i,this,r.data),d=e._def.returns.safeParse(o,n);if(!d.success)throw new z([s(o,d.error)]);return d.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:He.create(t).rest($e.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,a,s){return new e({args:t||He.create([]).rest($e.create()),returns:a||$e.create(),typeName:wt.ZodFunction,...oe(s)})}},at=class extends ce{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};at.create=(e,t)=>new at({getter:e,typeName:wt.ZodLazy,...oe(t)});var st=class extends ce{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return G(t,{received:t.data,code:q.invalid_literal,expected:this._def.value}),Q}return{status:"valid",value:e.data}}get value(){return this._def.value}};function nt(e,t){return new it({values:e,typeName:wt.ZodEnum,...oe(t)})}st.create=(e,t)=>new st({value:e,typeName:wt.ZodLiteral,...oe(t)});var it=class e extends ce{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),a=this._def.values;return G(t,{expected:v.joinValues(a),received:t.parsedType,code:q.invalid_type}),Q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),a=this._def.values;return G(t,{received:t.data,code:q.invalid_enum_value,options:a}),Q}return ee(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(t,a=this._def){return e.create(t,{...this._def,...a})}exclude(t,a=this._def){return e.create(this.options.filter((e=>!t.includes(e))),{...this._def,...a})}};it.create=nt;var rt=class extends ce{_parse(e){const t=v.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==R.string&&a.parsedType!==R.number){const e=v.objectValues(t);return G(a,{expected:v.joinValues(e),received:a.parsedType,code:q.invalid_type}),Q}if(this._cache||(this._cache=new Set(v.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=v.objectValues(t);return G(a,{received:a.data,code:q.invalid_enum_value,options:e}),Q}return ee(e.data)}get enum(){return this._def.values}};rt.create=(e,t)=>new rt({values:e,typeName:wt.ZodNativeEnum,...oe(t)});var ot=class extends ce{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==R.promise&&!1===t.common.async)return G(t,{code:q.invalid_type,expected:R.promise,received:t.parsedType}),Q;const a=t.parsedType===R.promise?t.data:Promise.resolve(t.data);return ee(a.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}};ot.create=(e,t)=>new ot({type:e,typeName:wt.ZodPromise,...oe(t)});var dt=class extends ce{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===wt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:a}=this._processInputParams(e),s=this._def.effect||null,n={addIssue:e=>{G(a,e),e.fatal?t.abort():t.dirty()},get path(){return a.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===s.type){const e=s.transform(a.data,n);if(a.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return Q;const s=await this._def.schema._parseAsync({data:e,path:a.path,parent:a});return"aborted"===s.status?Q:"dirty"===s.status||"dirty"===t.value?X(s.value):s}));{if("aborted"===t.value)return Q;const s=this._def.schema._parseSync({data:e,path:a.path,parent:a});return"aborted"===s.status?Q:"dirty"===s.status||"dirty"===t.value?X(s.value):s}}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,n);if(a.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===a.common.async){const s=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===s.status?Q:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then((a=>"aborted"===a.status?Q:("dirty"===a.status&&t.dirty(),e(a.value).then((()=>({status:t.value,value:a.value}))))))}if("transform"===s.type){if(!1===a.common.async){const e=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!se(e))return Q;const i=s.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then((e=>se(e)?Promise.resolve(s.transform(e.value,n)).then((e=>({status:t.value,value:e}))):Q))}v.assertNever(s)}};dt.create=(e,t,a)=>new dt({schema:e,typeName:wt.ZodEffects,effect:t,...oe(a)}),dt.createWithPreprocess=(e,t,a)=>new dt({schema:t,effect:{type:"preprocess",transform:e},typeName:wt.ZodEffects,...oe(a)});var ct=class extends ce{_parse(e){return this._getType(e)===R.undefined?ee(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ct.create=(e,t)=>new ct({innerType:e,typeName:wt.ZodOptional,...oe(t)});var lt=class extends ce{_parse(e){return this._getType(e)===R.null?ee(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};lt.create=(e,t)=>new lt({innerType:e,typeName:wt.ZodNullable,...oe(t)});var ut=class extends ce{_parse(e){const{ctx:t}=this._processInputParams(e);let a=t.data;return t.parsedType===R.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ut.create=(e,t)=>new ut({innerType:e,typeName:wt.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...oe(t)});var pt=class extends ce{_parse(e){const{ctx:t}=this._processInputParams(e),a={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return ne(s)?s.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new z(a.common.issues)},input:a.data})}))):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new z(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};pt.create=(e,t)=>new pt({innerType:e,typeName:wt.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...oe(t)});var ht=class extends ce{_parse(e){if(this._getType(e)!==R.nan){const t=this._getOrReturnCtx(e);return G(t,{code:q.invalid_type,expected:R.nan,received:t.parsedType}),Q}return{status:"valid",value:e.data}}};ht.create=e=>new ht({typeName:wt.ZodNaN,...oe(e)});var mt=Symbol("zod_brand"),ft=class extends ce{_parse(e){const{ctx:t}=this._processInputParams(e),a=t.data;return this._def.type._parse({data:a,path:t.path,parent:t})}unwrap(){return this._def.type}},gt=class e extends ce{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?Q:"dirty"===e.status?(t.dirty(),X(e.value)):this._def.out._parseAsync({data:e.value,path:a.path,parent:a})})()}{const e=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?Q:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:a.path,parent:a})}}static create(t,a){return new e({in:t,out:a,typeName:wt.ZodPipeline})}},yt=class extends ce{_parse(e){const t=this._def.innerType._parse(e),a=e=>(se(e)&&(e.value=Object.freeze(e.value)),e);return ne(t)?t.then((e=>a(e))):a(t)}unwrap(){return this._def.innerType}};function vt(e,t){const a="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof a?{message:a}:a}function _t(e,t={},a){return e?qe.create().superRefine(((s,n)=>{const i=e(s);if(i instanceof Promise)return i.then((e=>{if(!e){const e=vt(t,s),i=e.fatal??a??!0;n.addIssue({code:"custom",...e,fatal:i})}}));if(!i){const e=vt(t,s),i=e.fatal??a??!0;n.addIssue({code:"custom",...e,fatal:i})}})):qe.create()}yt.create=(e,t)=>new yt({innerType:e,typeName:wt.ZodReadonly,...oe(t)});var wt,bt,xt={object:Ke.lazycreate};(bt=wt||(wt={})).ZodString="ZodString",bt.ZodNumber="ZodNumber",bt.ZodNaN="ZodNaN",bt.ZodBigInt="ZodBigInt",bt.ZodBoolean="ZodBoolean",bt.ZodDate="ZodDate",bt.ZodSymbol="ZodSymbol",bt.ZodUndefined="ZodUndefined",bt.ZodNull="ZodNull",bt.ZodAny="ZodAny",bt.ZodUnknown="ZodUnknown",bt.ZodNever="ZodNever",bt.ZodVoid="ZodVoid",bt.ZodArray="ZodArray",bt.ZodObject="ZodObject",bt.ZodUnion="ZodUnion",bt.ZodDiscriminatedUnion="ZodDiscriminatedUnion",bt.ZodIntersection="ZodIntersection",bt.ZodTuple="ZodTuple",bt.ZodRecord="ZodRecord",bt.ZodMap="ZodMap",bt.ZodSet="ZodSet",bt.ZodFunction="ZodFunction",bt.ZodLazy="ZodLazy",bt.ZodLiteral="ZodLiteral",bt.ZodEnum="ZodEnum",bt.ZodEffects="ZodEffects",bt.ZodNativeEnum="ZodNativeEnum",bt.ZodOptional="ZodOptional",bt.ZodNullable="ZodNullable",bt.ZodDefault="ZodDefault",bt.ZodCatch="ZodCatch",bt.ZodPromise="ZodPromise",bt.ZodBranded="ZodBranded",bt.ZodPipeline="ZodPipeline",bt.ZodReadonly="ZodReadonly";var kt=(e,t={message:`Input not instance of ${e.name}`})=>_t((t=>t instanceof e),t),Ct=Ae.create,Mt=Ee.create,It=ht.create,St=Ze.create,Nt=Le.create,Tt=je.create,At=Pe.create,Ot=Re.create,Et=Fe.create,Zt=qe.create,Lt=$e.create,jt=ze.create,Pt=De.create,Rt=Ue.create,Ft=Ke.create,qt=Ke.strictCreate,$t=Je.create,zt=Ge.create,Dt=Ye.create,Ut=He.create,Vt=Qe.create,Kt=Xe.create,Jt=et.create,Bt=tt.create,Gt=at.create,Wt=st.create,Yt=it.create,Ht=rt.create,Qt=ot.create,Xt=dt.create,ea=ct.create,ta=lt.create,aa=dt.createWithPreprocess,sa=gt.create,na=()=>Ct().optional(),ia=()=>Mt().optional(),ra=()=>Nt().optional(),oa={string:e=>Ae.create({...e,coerce:!0}),number:e=>Ee.create({...e,coerce:!0}),boolean:e=>Le.create({...e,coerce:!0}),bigint:e=>Ze.create({...e,coerce:!0}),date:e=>je.create({...e,coerce:!0})},da=Q,ca={text:"text",conversation:"text",imageMessage:"image",contactMessage:"contact",locationMessage:"location",documentMessage:"document",audioMessage:"audio",videoMessage:"video",protocolMessage:"protocol",contactsArrayMessage:"contactsArray",highlyStructuredMessage:"highlyStructured",sendPaymentMessage:"sendPayment",liveLocationMessage:"liveLocation",requestPaymentMessage:"requestPayment",declinePaymentRequestMessage:"declinePaymentRequest",cancelPaymentRequestMessage:"cancelPaymentRequest",templateMessage:"template",stickerMessage:"sticker",groupInviteMessage:"groupInvite",templateButtonReplyMessage:"templateButtonReply",productMessage:"product",deviceSentMessage:"deviceSent",listMessage:"list",viewOnceMessage:"viewOnce",orderMessage:"order",listResponseMessage:"listResponse",ephemeralMessage:"ephemeral",invoiceMessage:"invoice",buttonsMessage:"buttons",buttonsResponseMessage:"buttonsResponse",paymentInviteMessage:"paymentInvite",interactiveMessage:"interactive",reactionMessage:"reaction",stickerSyncRmrMessage:"sticker",interactiveResponseMessage:"interactiveResponse",pollCreationMessage:"pollCreation",pollUpdateMessage:"pollUpdate",keepInChatMessage:"keepInChat",documentWithCaptionMessage:"document",requestPhoneNumberMessage:"requestPhoneNumber",viewOnceMessageV2:"viewOnce",encReactionMessage:"reaction",editedMessage:"text",viewOnceMessageV2Extension:"viewOnce",pollCreationMessageV2:"pollCreation",scheduledCallCreationMessage:"scheduledCallCreation",groupMentionedMessage:"groupMentioned",pinInChatMessage:"pinInChat",pollCreationMessageV3:"pollCreation",scheduledCallEditMessage:"scheduledCallEdit",ptvMessage:"ptv",botInvokeMessage:"botInvoke",callLogMesssage:"callLog",encCommentMessage:"encComment",bcallMessage:"bcall",lottieStickerMessage:"lottieSticker",eventMessage:"event",commentMessage:"comment",newsletterAdminInviteMessage:"text",extendedTextMessageWithParentKey:"text",extendedTextMessage:"text",placeholderMessage:"placeholder",encEventUpdateMessage:"encEventUpdate"},la={whatsapp:"0@s.whatsapp.net",meta:"13135550002@s.whatsapp.net",chatgpt:"18002428478@s.whatsapp.net",copilot:"18772241042@s.whatsapp.net",instagram:"447723442971@s.whatsapp.net",tiktok:"6285574670498@s.whatsapp.net"},ua=P.enum(["text","text","image","contact","location","document","audio","video","protocol","contactsArray","highlyStructured","sendPayment","liveLocation","requestPayment","declinePaymentRequest","cancelPaymentRequest","template","sticker","groupInvite","templateButtonReply","product","deviceSent","list","viewOnce","order","listResponse","ephemeral","invoice","buttons","buttonsResponse","paymentInvite","interactive","reaction","sticker","interactiveResponse","pollCreation","pollUpdate","keepInChat","document","requestPhoneNumber","viewOnce","reaction","text","viewOnce","pollCreation","scheduledCallCreation","groupMentioned","pinInChat","pollCreation","scheduledCallEdit","ptv","botInvoke","callLog","encComment","bcall","lottieSticker","event","comment","text","text","placeholder","encEventUpdate"]),pa=P.enum(["unknown","android","ios","desktop","web"]),ha=P.object({chatId:P.string(),channelId:P.string(),uniqueId:P.string(),receiverId:P.string(),receiverName:P.string(),roomId:P.string(),roomName:P.string(),senderId:P.string(),senderName:P.string(),senderDevice:pa,chatType:ua,timestamp:P.number(),mentions:P.string().array(),text:P.string().nullable(),links:P.string().array(),isPrefix:P.boolean(),isFromMe:P.boolean(),isTagMe:P.boolean(),isGroup:P.boolean(),isStory:P.boolean(),isViewOnce:P.boolean(),isEdited:P.boolean(),isDeleted:P.boolean(),isPinned:P.boolean(),isUnPinned:P.boolean(),isChannel:P.boolean(),isBroadcast:P.boolean(),isEphemeral:P.boolean(),isForwarded:P.boolean(),citation:P.record(P.string(),P.boolean()).nullable(),media:P.object({buffer:P.function().returns(P.instanceof(Buffer)),stream:P.function().returns(P.instanceof(m.Readable))}).passthrough().nullable(),message:P.function().returns(P.record(P.string(),P.any()))});ha.extend({replied:ha.nullable()});var ma=class{constructor(e,t,a){this.socket=e,this.client=t,this.db=a}maxReplies=0;async connection(t){this.client.stopSpinner("connection",!1),this.client.startSpinner("connection","Connecting to WhatsApp...");const{connection:a,lastDisconnect:s,qr:n}=t;if(this.client.emit("connection",{status:"connecting"}),"qr"===this.client.options?.authType&&n)return console.log(),console.log(await N.default.toString(n,{type:"terminal",small:!0})),this.client.startSpinner("qr","Waiting for QR code scan..."),void this.socket?.ev.on("connection.update",(()=>this.client.stopSpinner("qr",!1)));if("close"===a){const t=s?.error?.output?.statusCode,n=t===e.DisconnectReason.restartRequired||t===e.DisconnectReason.connectionLost;if(this.client.failSpinner("connection",`[Connection Closed] [${t}]\n${s?.error?.message}\n`),401===t||405===t||500===t)return void console.error("Invalid session, please delete manually");n&&"close"==a&&await this.client.initialize()}else"open"===a&&(this.client.stopSpinner("connection",!0,"Connected to WhatsApp\n"),this.client.emit("connection",{status:"open"}))}async messages(t,a){if(t?.messageStubType||t?.messageStubParameters?.length||t?.message?.protocolMessage?.peerDataOperationRequestResponseMessage||t?.message?.botInvokeMessage||!t?.key?.id||!t?.message)return null;if(this.client.options?.ignoreMe&&t?.key?.fromMe&&"status@broadcast"!=t?.key?.remoteJid&&!t?.participant)return null;this.client.options?.autoRead&&await this.socket.readMessages([t?.key]);const s=t,n=t?.message?.pinInChatMessage?.key?.id,i=1==t?.message?.pinInChatMessage?.type,r=2==t?.message?.pinInChatMessage?.type;if(n){const e=await this.db.selectFrom("messages").select("value").where("id","=",n).executeTakeFirst(),a=O(e?.value);t=a}const o=!t?.message?.protocolMessage?.editedMessage&&t?.message?.protocolMessage?.key?.id,d=!!o;if(o){const e=await this.db.selectFrom("messages").select("value").where("id","=",o).executeTakeFirst(),a=O(e?.value);t=a}const c={},l=e.getContentType(t?.message?.protocolMessage?.editedMessage||t?.message);c.chatId=t?.message?.protocolMessage?.key?.id||t?.key?.id,c.channelId="",c.uniqueId="",c.receiverId=e.jidNormalizedUser(this.socket.user?.id),c.receiverName=this.socket.user?.name||this.socket.user?.verifiedName,c.roomId=e.jidNormalizedUser(t?.key?.remoteJid);const u=await this.db.selectFrom("chats").select("value").where("id","=",c.roomId).executeTakeFirst();c.roomName=O(u?.value)?.name,c.senderId=e.jidNormalizedUser(t?.participant||t?.key?.participant||t?.key?.remoteJid);const p=await this.db.selectFrom("chats").select("value").where("id","=",c.senderId).executeTakeFirst();c.senderName=t?.pushName||t?.verifiedBizName||O(p?.value)?.name||c.receiverName,c.roomName=c.roomName||c.senderName,c.senderDevice=e.getDevice(c.chatId),c.chatType=ca[l],c.timestamp=t?.messageTimestamp?.low||t?.messageTimestamp||0,c.mentions=[],c.text=null,c.links=[],c.isPrefix=!1,c.isFromMe=t?.key?.fromMe,c.isTagMe=!1,c.isGroup=c.roomId.includes("@g.us"),c.isStory=c.roomId.includes("@broadcast"),c.isViewOnce=!1,c.isEdited=!1,c.isDeleted=d,c.isPinned=i,c.isUnPinned=r,c.isChannel=c.roomId.includes("@newsletter"),c.isBroadcast=!!t?.broadcast,c.isEphemeral=!1,c.isForwarded=!1,c.citation=null,c.media=null,c.replied=null,c.channelId=c.roomId.split("@")[0]+"-"+c.senderId.split("@")[0],c.uniqueId=c.channelId+"-"+c.chatId;const h=this.client.options?.citation;if(Object.keys(h).length){c.citation={};for(const e of Object.keys(h))c.citation[e]=h[e].includes(Number(c.senderId.split("@")[0]))||h[e].includes(Number(c.roomId.split("@")[0]))}const m=(t?.message?.protocolMessage?.editedMessage?.[l]||t?.message?.[l])?.message?.documentMessage||t?.message?.[l];"text"!=c.chatType&&(c.media={...L(m,["url","contextInfo","fileSha256","fileEncSha256","mediaKey","directPath","waveform","thumbnail","jpegThumbnail","thumbnailEncSha256","thumbnailSha256","thumbnailDirectPath","firstFrameSidecar","streamingSidecar","scansSidecar","callKey","midQualityFileSha256"]),buffer:async()=>await e.downloadMediaMessage(t,"buffer",{}),stream:async()=>await e.downloadMediaMessage(t,"stream",{})});const f=t?.message?.[l]?.contextInfo?.stanzaId;if(f&&this.maxReplies<1){this.maxReplies++;const a=await this.db.selectFrom("messages").select("value").where("id","=",f).executeTakeFirst(),s=O(a?.value);if(s)c.replied=await this.messages(s,!0);else{const a=t,s=e.getContentType(a.message?.extendedTextMessage?.contextInfo.quotedMessage);a.key.id=a.message?.extendedTextMessage?.contextInfo.stanzaId,a.message[s]=a.message?.extendedTextMessage?.contextInfo.quotedMessage[s],delete a.message?.extendedTextMessage,c.replied=await this.messages(a,!0)}}const g="string"==typeof m?m:m?.text||m?.caption||m?.name||m?.displayName||"";c.text=((e="")=>e?e.replace(/\u202E([\s\S]*?)\u202C/g,((e,t)=>Array.from(t).reverse().join(""))).replace(/[\u202A-\u202E\u202C]/g,""):null)(g)||null,c.mentions=((e="")=>{if(!e)return[];const t=new Set;for(const a of e.matchAll(/@(\d+)/g))t.add(a[1]);return[...t]})(c.text),c.links=((e="")=>e&&e.match(/(?:https?:\/\/)?[^\s<>"']+\.[^\s<>"']+/g)||[])(c.text);const y=t?.message?.[l];return c.isPrefix=!!this.client.options?.prefix&&!!c.text?.startsWith(this.client.options?.prefix),c.isTagMe=c.mentions.includes(c.receiverId.split("@")[0]),c.isEdited=Z(E(t),"editedMessage"),c.isEphemeral=Z(E(y?.contextInfo),"ephemeralSettingTimestamp"),c.isForwarded=Z(E(y?.contextInfo),"forwardingScore"),c.isViewOnce=!!y?.viewOnce,c.isPrefix&&(c.text=c.text.replace(new RegExp(`^${this.client.options?.prefix}`),"")),c.message=()=>s,a||this.client.emit("messages",c),c}async calls(e){this.client.options?.autoRejectCall&&await this.socket.rejectCall(e.id,e.from);const t={};t.callId=e.id,t.roomId=e.chatId,t.callerId=e.from,t.date=e.date,t.offline=e.offline,t.status=e.status,t.isVideo=!!e.isVideo,t.isGroup=!!e.isGroup,this.client.emit("calls",t)}},fa=async(t,a,s)=>{const n="auth";await(async(e,t)=>{await e.transaction().execute((async e=>{await e.schema.createTable("auth").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("auth_session_id_unique",["session","id"]).execute(),await e.schema.createTable("chats").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("chats_session_id_unique",["session","id"]).execute(),await e.schema.createTable("contacts").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("contacts_session_id_unique",["session","id"]).execute(),await e.schema.createTable("messages").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("messages_session_id_unique",["session","id"]).execute(),t.loadLLMSchemas&&(await e.schema.createTable("llm_messages").ifNotExists().addColumn("uniqueId","char(36)",(e=>e.notNull().primaryKey())).addColumn("channelId","char(36)").addColumn("model","char(36)").addColumn("role","varchar(20)",(e=>e.notNull())).addColumn("content","text",(e=>e.notNull())).addColumn("additional","text").addUniqueConstraint("llm_messages_id_unique",["uniqueId"]).execute(),await e.schema.createTable("llm_personalization").ifNotExists().addColumn("uniqueId","char(36)",(e=>e.notNull().primaryKey())).addColumn("senderId","char(36)").addColumn("content","text",(e=>e.notNull())).addUniqueConstraint("llm_personalization_id_unique",["uniqueId"]).execute(),await e.schema.createTable("llm_rag").ifNotExists().addColumn("metadata.id","char(36)",(e=>e.notNull().primaryKey())).addColumn("pageContent","text",(e=>e.notNull())).addUniqueConstraint("llm_rag_id_unique",["metadata.id"]).execute()),await Promise.all([e.schema.createIndex("auth_session_id_idx").ifNotExists().on("auth").columns(["session","id"]).execute(),e.schema.createIndex("chats_session_id_idx").ifNotExists().on("chats").columns(["session","id"]).execute(),e.schema.createIndex("contacts_session_id_idx").ifNotExists().on("contacts").columns(["session","id"]).execute(),e.schema.createIndex("messages_session_id_idx").ifNotExists().on("messages").columns(["session","id"]).execute(),e.schema.createIndex("llm_messages_uniqueId_idx").ifNotExists().on("llm_messages").column("uniqueId").execute(),e.schema.createIndex("llm_messages_channelId_idx").ifNotExists().on("llm_messages").column("channelId").execute(),e.schema.createIndex("llm_messages_model_idx").ifNotExists().on("llm_messages").column("model").execute(),e.schema.createIndex("llm_messages_role_idx").ifNotExists().on("llm_messages").column("role").execute(),e.schema.createIndex("llm_personalization_uniqueId_idx").ifNotExists().on("llm_personalization").column("uniqueId").execute(),e.schema.createIndex("llm_personalization_senderId_idx").ifNotExists().on("llm_personalization").column("senderId").execute(),e.schema.createIndex("llm_rag_id_idx").ifNotExists().on("llm_rag").column("metadata.id").execute(),e.schema.createIndex("llm_rag_pageContent_idx").ifNotExists().on("llm_rag").column("pageContent").execute()])}))})(t,s);const i=async e=>{for(let t=0;t<10;t++)try{return await e()}catch(e){await new Promise((e=>setTimeout(e,200)))}throw new Error("Max retries reached")},r=async s=>{const r=await i((()=>t.selectFrom(n).select(["value"]).where("id","=",s).where("session","=",a).executeTakeFirst()));if(!r?.value)return null;const o="object"==typeof r.value?JSON.stringify(r.value):r.value;return JSON.parse(o,e.BufferJSON.reviver)},o=async(s,r)=>{const o=JSON.stringify(r,e.BufferJSON.replacer);await i((()=>t.insertInto(n).values({session:a,id:s,value:o}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:o}))).execute()))},d=async e=>{await i((()=>t.deleteFrom(n).where("id","=",e).where("session","=",a).execute()))},c=await r("creds")||e.initAuthCreds();return{state:{creds:c,keys:{get:async(e,t)=>{const a={};for(const s of t){let t=await r(`${e}-${s}`);"app-state-sync-key"===e&&t&&(t=j(t)),a[s]=t}return a},set:async e=>{for(const t in e)for(const a in e[t]){const s=e[t][a],n=`${t}-${a}`;s?await o(n,s):await d(n)}}}},saveCreds:async()=>{await o("creds",c)},clear:async()=>{await(async()=>{await i((()=>t.deleteFrom(n).where("session","=",a).where("id","!=","creds").execute()))})()},removeCreds:async()=>{await(async()=>{await i((()=>t.deleteFrom(n).where("session","=",a).execute()))})()}}},ga=P.object({type:P.enum(["sqlite","postgresql","mysql"]).default("sqlite"),connection:P.object({url:P.string().default("./session/zaileys.db")}).optional().default({})}).optional().default({}),ya=P.record(P.function().returns(P.union([P.number().array(),P.promise(P.number().array())]))).optional().transform((async e=>{if(!e)return{};const t={};for(const[a,s]of Object.entries(e)){t[`is${a.charAt(0).toUpperCase()}${a.slice(1)}`]=await s()}return t})),va=P.object({prefix:P.string().optional(),ignoreMe:P.boolean().optional().default(!0),showLogs:P.boolean().optional().default(!0),autoMentions:P.boolean().optional().default(!0),autoOnline:P.boolean().optional().default(!0),autoRead:P.boolean().optional().default(!0),autoPresence:P.boolean().optional().default(!0),autoRejectCall:P.boolean().optional().default(!0),loadLLMSchemas:P.boolean().optional().default(!1),database:ga,citation:ya}),_a=P.object({authType:P.literal("pairing"),phoneNumber:P.number()}).extend(va.shape),wa=P.object({authType:P.literal("qr"),phoneNumber:P.undefined().optional()}).extend(va.shape),ba=P.discriminatedUnion("authType",[_a,wa]),xa=P.object({channelId:P.string(),uniqueId:P.string(),model:P.string().min(2).max(100).optional().nullable(),role:P.string().min(2).max(100),content:P.string().min(1).max(65e3),additional:P.string().max(2e4).optional().nullable()}),ka=P.object({uniqueId:P.string(),senderId:P.string(),content:P.string().min(1).max(5e3)}),Ca=P.object({metadata:P.object({id:P.string().default((()=>(e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";return Array.from({length:e},(()=>t[Math.floor(62*Math.random())])).join("")})(5)))}).default({}),pageContent:P.string().min(1).max(128e3)});Ca.pick({pageContent:!0});var Ma=P.union([P.string().url(),P.instanceof(Buffer).or(P.instanceof(m.Readable))]),Ia=P.union([P.string(),P.object({image:Ma,text:P.string().optional()}),P.object({video:Ma,text:P.string().optional()}),P.object({videoNote:Ma}),P.object({gif:Ma,text:P.string().optional()}),P.object({audio:Ma}),P.object({audioNote:Ma}),P.object({sticker:Ma})]),Sa=P.object({roomId:P.string(),asForwarded:P.boolean().optional(),asViewOnce:P.boolean().optional(),verifiedReply:P.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).optional(),quoted:P.function().returns(P.record(P.string(),P.any())).optional()}),Na=Sa,Ta=P.object({latitude:P.number(),longitude:P.number(),title:P.string().optional(),footer:P.string().optional()}),Aa=Sa,Oa=P.object({fullname:P.string(),nickname:P.string().optional(),organization:P.string().optional(),role:P.string().optional(),email:P.string().email().optional(),whatsAppNumber:P.number(),callNumber:P.number().optional(),voiceNumber:P.number().optional(),website:P.string().url().optional(),homeAddress:P.string().optional(),workAddress:P.string().optional(),avatar:P.string().url().optional()}),Ea=P.object({message:P.function().returns(P.record(P.string(),P.any()))}),Za=P.string(),La=P.object({message:P.function().returns(P.record(P.string(),P.any()))}),ja=P.object({action:P.enum(["pin","unpin"]),expired:P.enum(["24h","7d","30d"])}),Pa=Sa.pick({roomId:!0}),Ra=P.object({name:P.string(),answers:P.string().array(),multipleAnswers:P.boolean().optional()}),Fa=P.object({message:P.function().returns(P.record(P.string(),P.any()))}),qa=P.string(),$a=P.object({message:P.function().returns(P.record(P.string(),P.any()))}),za=P.object({callId:P.string(),callerId:P.string()}),Da=Sa.pick({roomId:!0}),Ua=P.object({expired:P.enum(["remove","8h","7d"])}),Va=P.string();P.object({type:P.enum(["group","user"]),id:P.string(),name:P.string(),bio:P.string(),avatar:P.string().url(),ephemeralDuration:P.number().optional(),isRestrict:P.boolean().optional(),isAnnounce:P.boolean().optional(),isCommunity:P.boolean().optional(),isCommunityAnnounce:P.boolean().optional(),isJoinApprovalMode:P.boolean().optional(),isMemberAddMode:P.boolean().optional(),owner:P.object({type:P.literal("user"),id:P.string()}).nullable(),roomCreatedAt:P.number().optional(),nameUpdatedAt:P.number().optional(),bioUpdatedAt:P.number().optional(),membersLength:P.number().optional(),members:P.object({type:P.enum(["user","admin","superadmin"]),id:P.string()}).array().optional()});var Ka=Sa.pick({roomId:!0}),Ja=P.enum(["typing","recording","online","offline","paused"]),Ba=class{constructor(e){this.wa=e,this.parser=new ma(e.socket,e.client,e.db)}parser;caching=new x.default({stdTTL:600,checkperiod:120,maxKeys:1e3});async sendMessage(e,t,a){let s=[];this.wa.client.options?.autoMentions&&(s=((e="")=>{if(!e)return[];const t=new Set;for(const a of e.matchAll(/@(\d+)/g))t.add(a[1]);return[...t].flatMap((e=>[`${e}@s.whatsapp.net`,`${e}@g.us`]))})(t?.text||t?.caption)),this.wa.client.options?.autoPresence&&this.wa.socket?.sendPresenceUpdate("composing",e),this.wa.client.options?.autoPresence&&(t?.audio||t?.audioNote)&&this.wa.socket?.sendPresenceUpdate("recording",e);const n=t,i={contextInfo:{isForwarded:!!n?.asForwarded}};if("function"==typeof n?.quoted){let t=n?.quoted();t.key.remoteJid=la[n?.verifiedReply]||t.key.remoteJid;const r=await(this.wa.socket?.sendMessage(e,{...n,mentions:s,...i},{quoted:t,...a}));return await this.parser.messages(r)}{const t=await(this.wa.socket?.sendMessage(e,{...n,mentions:s,...i},a));return await this.parser.messages(t)}}async text(e,t){if(e=Ia.parse(e),t=Sa.parse(t),"string"==typeof e)return await this.sendMessage(t.roomId,{text:e,...t});if("object"==typeof e){const a=Object.keys(e),s=e;if(a.includes("image")){const e="string"==typeof s.image?{url:s.image}:s.image;return await this.sendMessage(t.roomId,{caption:s?.text,image:e,viewOnce:!!t.asViewOnce,...t})}if(a.includes("video")){const e="string"==typeof s.video?{url:s.video}:s.video;return await this.sendMessage(t.roomId,{caption:s?.text,video:e,ptv:!1,viewOnce:!!t.asViewOnce,...t})}if(a.includes("videoNote")){const e="string"==typeof s.videoNote?{url:s.videoNote}:s.videoNote;return await this.sendMessage(t.roomId,{caption:s?.text,video:e,ptv:!0,...t})}if(a.includes("gif")){const e="string"==typeof s.gif?{url:s.gif}:s.gif;return await this.sendMessage(t.roomId,{caption:s?.text,video:e,gifPlayback:!0,viewOnce:!!t.asViewOnce,...t})}if(a.includes("audio")){const e="string"==typeof s.audio?{url:s.audio}:s.audio;return await this.sendMessage(t.roomId,{caption:s?.text,audio:e,viewOnce:!!t.asViewOnce,...t})}if(a.includes("audioNote")){const e="string"==typeof s.audioNote?{url:s.audioNote}:s.audioNote;return await this.sendMessage(t.roomId,{caption:s?.text,audio:e,ptt:!0,viewOnce:!!t.asViewOnce,...t})}if(a.includes("sticker")){const e="string"==typeof s.sticker?{url:s.sticker}:s.sticker;return await this.sendMessage(t.roomId,{caption:s?.text,sticker:e,...t})}}}async location(e,t){return e=Ta.parse(e),t=Na.parse(t),await this.sendMessage(t.roomId,{location:{degreesLatitude:e.latitude,degreesLongitude:e.longitude,url:e.title,address:e.footer,name:e.title},...t})}async contact(e,t){e=Oa.parse(e),t=Aa.parse(t);const a=["BEGIN:VCARD","VERSION:3.0",`N:;${e.fullname};;;`,`FN:${e.fullname}`,e.nickname?`NICKNAME:${e.nickname}`:"",e.organization||e.role?`ORG:${e.organization??""};`:"",e.role?`TITLE:${e.role}`:"",`TEL;TYPE=CELL,VOICE;waid=${e.whatsAppNumber}:+${e.whatsAppNumber}`,e.callNumber?`TEL;TYPE=WORK,VOICE:+${e.callNumber}`:"",e.voiceNumber?`TEL;TYPE=VOICE:+${e.voiceNumber}`:"",e.email?`EMAIL;TYPE=INTERNET:${e.email}`:"",e.website?`URL;TYPE=WORK:${e.website}`:"",e.homeAddress?`ADR;TYPE=HOME:;;${e.homeAddress};;;;`:"",e.workAddress?`ADR;TYPE=WORK:;;${e.workAddress};;;;`:"",e.avatar?`PHOTO;VALUE=URI;TYPE=JPEG:${e.avatar}`:"","END:VCARD"].join("\n");return await this.sendMessage(t.roomId,{contacts:{displayName:e.fullname,contacts:[{vcard:a}]},...t})}async reaction(e,t){return e=Za.parse(e),t=Ea.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{react:{text:e,key:t.message()?.key},...t})}async pin(e,t){e=ja.parse(e),t=La.parse(t);return await this.sendMessage(t.message()?.key?.remoteJid,{pin:{type:"pin"==e.action?1:0,time:{"24h":86400,"7d":604800,"30d":2592e3}[e.expired],key:t.message()?.key},...t})}async poll(e,t){return e=Ra.parse(e),t=Pa.parse(t),await this.sendMessage(t.roomId,{poll:{name:e.name,values:e.answers,selectableCount:e.multipleAnswers?1:0,toAnnouncementGroup:!0},...t})}async edit(e,t){return e=qa.parse(e),t=Fa.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{text:e,edit:t.message()?.key,...t})}async delete(e){return e=$a.parse(e),await this.sendMessage(e.message()?.key?.remoteJid,{delete:e.message()?.key})}async rejectCall(e){return e=za.parse(e),await(this.wa.socket?.rejectCall(e.callId,e.callerId))}async mute(e,t){e=Ua.parse(e),t=Da.parse(t);return await(this.wa.socket?.chatModify({mute:{remove:null,"8h":864e5,"7d":6048e5}[e.expired]},t.roomId))}async profile(t){const a=(t=Va.parse(t)).includes("@g.us"),s={};s.id=t;if(e.jidNormalizedUser(this.wa.socket?.user?.id)==t)s.name=this.wa.socket?.user?.name||this.wa.socket?.user?.verifiedName;else if(a){const e=await(this.wa.socket?.groupMetadata(t));s.type="group",s.name=e?.subject,s.bio=e?.desc,s.avatar=await(this.wa.socket?.profilePictureUrl(t)),s.ephemeralDuration=e?.ephemeralDuration,s.isRestrict=e?.restrict,s.isAnnounce=e?.announce,s.isCommunity=e?.isCommunity,s.isCommunityAnnounce=e?.isCommunityAnnounce,s.isJoinApprovalMode=e?.joinApprovalMode,s.isMemberAddMode=e?.memberAddMode,s.owner={type:"user",id:e?.owner},s.roomCreatedAt=e?.creation,s.nameUpdatedAt=e?.subjectTime,s.membersLength=e?.size,s.members=e?.participants.map((e=>({id:e.id,type:"admin"==e.admin||"superadmin"==e.admin?e.admin:"user"})))}else{const e=await(this.wa.db?.selectFrom("chats").select("value").where("id","=",t).executeTakeFirst()),a=O(e?.value),n=(await(this.wa?.socket?.fetchStatus(t)))[0]?.status;s.type="user",s.name=a?.name,s.bio=n?.status,s.avatar=await(this.wa?.socket?.profilePictureUrl(t)),s.bioUpdatedAt=new Date(n?.setAt).getTime()}return s}async presence(e,t){e=Ja.parse(e),t=Ka.parse(t);return await(this.wa.socket?.sendPresenceUpdate({typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"}[e],t.roomId))}async addCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=xa.parse(e);if(!await(this.wa.db?.insertInto("llm_messages").values(e).executeTakeFirst()))throw new Error("Failed to add completion");return e}async deleteCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_messages").where("uniqueId","=",e).executeTakeFirst()))throw new Error("Failed to delete completion");return!0}async updateCompletion(e,t){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const a=xa.partial().parse(t),s=await(this.wa.db?.updateTable("llm_messages").set(a).where("uniqueId","=",e).returningAll().executeTakeFirst());if(!s)throw new Error("Failed to update completion");return xa.parse(s)}async clearCompletions(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_messages").where("channelId","=",e).executeTakeFirst()))throw new Error("Failed to clear completions");return!0}async getCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_messages").selectAll().where("uniqueId","=",e).executeTakeFirst());return t?xa.parse(t):null}async getCompletions(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_messages").selectAll().where("channelId","=",e).execute());return t?.map((e=>xa.parse(e)))||[]}async addPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=ka.parse(e);if(!await(this.wa.db?.insertInto("llm_personalization").values(e).executeTakeFirst()))throw new Error("Failed to add completion");return e}async deletePersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_personalization").where("uniqueId","=",e).executeTakeFirst()))throw new Error("Failed to delete completion");return!0}async clearPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_personalization").where("senderId","=",e).executeTakeFirst()))throw new Error("Failed to clear completions");return!0}async getPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_personalization").selectAll().where("senderId","=",e).execute());return t?.map((e=>ka.parse(e)))||[]}async addRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=Ca.parse(e);if(!await(this.wa.db?.insertInto("llm_rag").values({pageContent:e.pageContent.toLowerCase(),"metadata.id":e.metadata?.id}).executeTakeFirst()))throw new Error("Failed to add RAG");return e}async deleteRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_rag").where(d.sql`"metadata.id"`,"=",e).executeTakeFirst()))throw new Error("Failed to delete RAG");return!0}async updateRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.updateTable("llm_rag").set({metadata:{id:e}}).where(d.sql`"metadata.id"`,"=",e).returningAll().executeTakeFirst());if(!t)throw new Error("Failed to update RAG");return Ca.parse(t)}async clearRAGs(){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_rag").executeTakeFirst()))throw new Error("Failed to clear RAGs");return!0}async getRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_rag").selectAll().where(d.sql`"metadata.id"`,"=",e).executeTakeFirst());return t?Ca.parse(t):null}async getRAGs(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=e.toLowerCase().trim(),a=this.caching.get(t);if(a)return a;const s=t.split(/\s+/).filter((e=>e.length>0));if(!s.length)return[];const n=await(this.wa.db?.selectFrom("llm_rag").select([d.sql`"metadata.id"`.as("metadata.id"),"pageContent"]).where("pageContent","!=","").limit(1e4).execute().then((e=>e.map((e=>Ca.parse({...e,metadata:{id:e["metadata.id"]}}))))).then((e=>e.filter((e=>{const t=e.pageContent.toLowerCase().split(/\s+/);return s.some((e=>t.some((t=>T.get(e,t)<=Math.max(1,Math.floor(e.length/4))))))})))));return this.caching.set(t,n),n||[]}llms={addCompletion:this.addCompletion.bind(this),deleteCompletion:this.deleteCompletion.bind(this),updateCompletion:this.updateCompletion.bind(this),clearCompletions:this.clearCompletions.bind(this),getCompletion:this.getCompletion.bind(this),getCompletions:this.getCompletions.bind(this),addPersonalization:this.addPersonalization.bind(this),deletePersonalization:this.deletePersonalization.bind(this),clearPersonalization:this.clearPersonalization.bind(this),getPersonalization:this.getPersonalization.bind(this),addRAG:this.addRAG.bind(this),deleteRAG:this.deleteRAG.bind(this),updateRAG:this.updateRAG.bind(this),clearRAGs:this.clearRAGs.bind(this),getRAG:this.getRAG.bind(this),getRAGs:this.getRAGs.bind(this)}};exports.Client=class{constructor(e){return this.props=e,this.initialize(),this.worker,new Proxy(this,{get:(e,t)=>t in e?e[t]:e.worker[t]})}options={};cache=new x.default({stdTTL:300,useClones:!1});chatId="zaileys-chats";logger=C.default({level:"silent",enabled:!1});db;socket;events=new t.EventEmitter;spinners=new Map;worker;async initialize(){console.clear(),await((e="ZAILEYS")=>new Promise((t=>{b.default(e,((e,a)=>{if(e)return t("");console.log(a),t(a||"")}))})))(),this.options=await ba.parseAsync(this.props),this.startSpinner("db","Initializing database..."),this.db=await(e=>{const{type:t,connection:a}=e.database;if("sqlite"===t){const e=a.url||"./db/zaileys.db",t=S.default.resolve(e);return o.mkdirSync(S.default.dirname(t),{recursive:!0}),o.writeFileSync(t,"",{flag:"a"}),new d.Kysely({dialect:new d.SqliteDialect({database:new M.default(t)})})}const s=new p.URL(a.url),n=s.protocol.replace(":","");if("mysql"===t)return new d.Kysely({dialect:new d.MysqlDialect({pool:I.default.createPool({host:s.hostname,user:s.username,password:s.password,database:s.pathname.replace("/",""),port:parseInt(s.port||"3306",10)})})});if("postgresql"===t)return new d.Kysely({dialect:new d.PostgresDialect({pool:new u.Pool({host:s.hostname,user:s.username,password:s.password,database:s.pathname.replace("/",""),port:parseInt(s.port||"5432",10)})})});throw new Error(`Unsupported database protocol: ${n}`)})(this.options),this.stopSpinner("db",!0,"Database initialized"),this.startSpinner("auth","Setting up auth adapter...");const{state:t,saveCreds:a}=await fa(this.db,this.chatId,this.options);this.stopSpinner("auth",!0,"Auth adapter ready"),this.startSpinner("store","Setting up store adapter...");const s=await(async(e,t,a)=>({bind:s=>{const n=new ma(s,e,t);s?.ev.on("connection.update",(async e=>{await n.connection(e)})),s?.ev.on("call",(async e=>{for(const t of e)await n.calls(t)})),s?.ev.on("messaging-history.set",(async e=>{const{chats:s,contacts:n,messages:i}=e;for(const e of s)await t.insertInto("chats").values({session:a,id:e.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute();for(const e of n)await t.insertInto("contacts").values({session:a,id:e.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute();for(const e of i){if(!e.message)return;if(e.message?.protocolMessage)return;await t.insertInto("messages").values({session:a,id:e.key.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute()}})),s?.ev.on("messages.upsert",(async({messages:e})=>{for(const s of e){if(!s.message)return;if(s.message?.protocolMessage)return;await n.messages(s),await t.insertInto("messages").values({session:a,id:s.key.id,value:JSON.stringify(s)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(s)}))).execute()}})),s?.ev.on("chats.upsert",(async e=>{for(const s of e)await t.insertInto("chats").values({session:a,id:s.id,value:JSON.stringify(s)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(s)}))).execute()})),s?.ev.on("contacts.upsert",(async e=>{for(const s of e)await t.insertInto("contacts").values({session:a,id:s.id,value:JSON.stringify(s)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(s)}))).execute()})),s?.ev.on("groups.update",(async([t])=>{const a=await(s?.groupMetadata(t.id));e.cache.set(t.id,a)})),s?.ev.on("group-participants.update",(async t=>{const a=await(s?.groupMetadata(t.id));e.cache.set(t.id,a)}))}}))(this,this.db,this.chatId);this.stopSpinner("store",!0,"Store adapter ready");const{version:n}=await e.fetchLatestBaileysVersion();if(this.socket=e.makeWASocket({version:n,logger:this.logger,markOnlineOnConnect:this.options.autoOnline,syncFullHistory:!1,defaultQueryTimeoutMs:void 0,msgRetryCounterCache:new x.default,mediaCache:new x.default({stdTTL:60}),userDevicesCache:new x.default,cachedGroupMetadata:async e=>this.cache.get(e),printQRInTerminal:!1,browser:e.Browsers.ubuntu("qr"===this.options.authType?"Zaileys Library":"Chrome"),auth:{creds:t.creds,keys:e.makeCacheableSignalKeyStore(t.keys,this.logger)},getMessage:async e=>{const t=await(this.db?.selectFrom("messages").select("value").where("id","=",e.id).executeTakeFirst());return O(t?.value)}}),"pairing"===this.options.authType&&this.options.phoneNumber&&!this.socket?.authState.creds.registered){this.startSpinner("pairing","Generating pairing code...");(await this.socket.onWhatsApp(this.options.phoneNumber.toString()+"@s.whatsapp.net"))[0].exists||(this.failSpinner("pairing","Phone is not registered on WhatsApp"),process.exit(1)),setTimeout((async()=>{try{if("pairing"===this.options?.authType){const e=await(this.socket?.requestPairingCode(this.options.phoneNumber.toString()));this.stopSpinner("pairing",!0,`Pairing code: ${e}`)}}catch{this.failSpinner("pairing","Connection failed"),process.exit(1)}}),5e3)}this.worker=new Ba({client:this,db:this.db,socket:this.socket}),this.socket?.ev.on("creds.update",a),s.bind(this.socket)}startSpinner(e,t){let a=this.spinners.get(e);return a||(a=k.default(t).start(),this.spinners.set(e,a)),a}stopSpinner(e,t,a){const s=this.spinners.get(e);s&&(t?s.succeed(a):s.stop(),this.spinners.delete(e))}failSpinner(e,t){const a=this.spinners.get(e);a&&(a.fail(t),this.spinners.delete(e))}on(e,t){this.events.on(e,t)}emit(e,...t){this.events.emit(e,...t)}};
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fetchLatestBaileysVersion as e,makeWASocket as t,makeCacheableSignalKeyStore as s,Browsers as a,initAuthCreds as n,jidNormalizedUser as i,BufferJSON as r,DisconnectReason as o,getContentType as d,getDevice as c,downloadMediaMessage as l}from"baileys";import{EventEmitter as u}from"events";import p from"figlet";import h from"node-cache";import m from"ora";import f from"pino";import g from"better-sqlite3";import{mkdirSync as y,writeFileSync as v}from"fs";import{Kysely as _,SqliteDialect as w,MysqlDialect as b,PostgresDialect as x,sql as k}from"kysely";import C from"mysql2";import I from"path";import{Pool as M}from"pg";import{URL as T}from"url";import S from"qrcode";import{Readable as N}from"stream";import*as A from"fast-levenshtein";var O,E,Z,L=Object.defineProperty,j=(e="")=>{try{return JSON.parse(e)}catch{return JSON.parse(JSON.stringify(e))}},P=(e={})=>{try{return JSON.stringify(e)}catch{return JSON.stringify(JSON.parse(JSON.stringify(e)))}},R=(e="",t="")=>e?e.toLowerCase().includes(t.toLowerCase()):null,F=(e,t)=>e&&"object"==typeof e?Array.isArray(e)?e.map((e=>F(e,t))):Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e))).map((([e,s])=>[e,"object"==typeof s?F(s,t):s]))):e,$=e=>{const t={...e.fingerprint,deviceIndexes:Array.isArray(e.fingerprint.deviceIndexes)?e.fingerprint.deviceIndexes:[]},s={keyData:Array.isArray(e.keyData)?e.keyData:new Uint8Array,fingerprint:{rawId:t.rawId||0,currentIndex:t.rawId||0,deviceIndexes:t.deviceIndexes},timestamp:(a=e.timestamp,"string"==typeof a?parseInt(a,10):a)};var a;return"string"==typeof e.keyData&&(s.keyData=(e=>{let t=e.length;if(!t)return new Uint8Array(1);let s=0;for(;--t%4>1&&"="===e.charAt(t);)++s;return new Uint8Array(Math.ceil(3*e.length)/4-s).fill(0)})(e.keyData)),s},q={};((e,t)=>{for(var s in t)L(e,s,{get:t[s],enumerable:!0})})(q,{BRAND:()=>vt,DIRTY:()=>ae,EMPTY_PATH:()=>H,INVALID:()=>se,NEVER:()=>ps,OK:()=>ne,ParseStatus:()=>te,Schema:()=>he,ZodAny:()=>De,ZodArray:()=>Ge,ZodBigInt:()=>Re,ZodBoolean:()=>Fe,ZodBranded:()=>_t,ZodCatch:()=>gt,ZodDate:()=>$e,ZodDefault:()=>ft,ZodDiscriminatedUnion:()=>Qe,ZodEffects:()=>pt,ZodEnum:()=>ct,ZodError:()=>J,ZodFirstPartyTypeKind:()=>Ct,ZodFunction:()=>it,ZodIntersection:()=>et,ZodIssueCode:()=>D,ZodLazy:()=>rt,ZodLiteral:()=>ot,ZodMap:()=>at,ZodNaN:()=>yt,ZodNativeEnum:()=>lt,ZodNever:()=>Je,ZodNull:()=>Ue,ZodNullable:()=>mt,ZodNumber:()=>Pe,ZodObject:()=>We,ZodOptional:()=>ht,ZodParsedType:()=>z,ZodPipeline:()=>wt,ZodPromise:()=>ut,ZodReadonly:()=>bt,ZodRecord:()=>st,ZodSchema:()=>he,ZodSet:()=>nt,ZodString:()=>Le,ZodSymbol:()=>qe,ZodTransformer:()=>pt,ZodTuple:()=>tt,ZodType:()=>he,ZodUndefined:()=>ze,ZodUnion:()=>Ye,ZodUnknown:()=>Ve,ZodVoid:()=>Ke,addIssueToContext:()=>Q,any:()=>Rt,array:()=>zt,bigint:()=>Ot,boolean:()=>Et,coerce:()=>us,custom:()=>kt,date:()=>Zt,datetimeRegex:()=>Oe,defaultErrorMap:()=>K,discriminatedUnion:()=>Jt,effect:()=>as,enum:()=>es,function:()=>Ht,getErrorMap:()=>W,getParsedType:()=>U,instanceof:()=>Tt,intersection:()=>Kt,isAborted:()=>ie,isAsync:()=>de,isDirty:()=>re,isValid:()=>oe,late:()=>Mt,lazy:()=>Qt,literal:()=>Xt,makeIssue:()=>Y,map:()=>Wt,nan:()=>At,nativeEnum:()=>ts,never:()=>$t,null:()=>Pt,nullable:()=>is,number:()=>Nt,object:()=>Ut,objectUtil:()=>Z,oboolean:()=>ls,onumber:()=>cs,optional:()=>ns,ostring:()=>ds,pipeline:()=>os,preprocess:()=>rs,promise:()=>ss,quotelessJson:()=>V,record:()=>Bt,set:()=>Yt,setErrorMap:()=>B,strictObject:()=>Dt,string:()=>St,symbol:()=>Lt,transformer:()=>as,tuple:()=>Gt,undefined:()=>jt,union:()=>Vt,unknown:()=>Ft,util:()=>O,void:()=>qt}),(E=O||(O={})).assertEqual=e=>{},E.assertIs=function(e){},E.assertNever=function(e){throw new Error},E.arrayToEnum=e=>{const t={};for(const s of e)t[s]=s;return t},E.getValidEnumValues=e=>{const t=E.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),s={};for(const a of t)s[a]=e[a];return E.objectValues(s)},E.objectValues=e=>E.objectKeys(e).map((function(t){return e[t]})),E.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.push(s);return t},E.find=(e,t)=>{for(const s of e)if(t(s))return s},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,(Z||(Z={})).mergeShapes=(e,t)=>({...e,...t});var z=O.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),U=e=>{switch(typeof e){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(e)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(e)?z.array:null===e?z.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?z.promise:"undefined"!=typeof Map&&e instanceof Map?z.map:"undefined"!=typeof Set&&e instanceof Set?z.set:"undefined"!=typeof Date&&e instanceof Date?z.date:z.object;default:return z.unknown}},D=O.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"]),V=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),J=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};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},s={_errors:[]},a=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(a);else if("invalid_return_type"===n.code)a(n.returnTypeError);else if("invalid_arguments"===n.code)a(n.argumentsError);else if(0===n.path.length)s._errors.push(t(n));else{let e=s,a=0;for(;a<n.path.length;){const s=n.path[a];a===n.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(n))):e[s]=e[s]||{_errors:[]},e=e[s],a++}}};return a(this),s}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,O.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},s=[];for(const a of this.issues)a.path.length>0?(t[a.path[0]]=t[a.path[0]]||[],t[a.path[0]].push(e(a))):s.push(e(a));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};J.create=e=>new J(e);var K=(e,t)=>{let s;switch(e.code){case D.invalid_type:s=e.received===z.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case D.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,O.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:s=`Unrecognized key(s) in object: ${O.joinValues(e.keys,", ")}`;break;case D.invalid_union:s="Invalid input";break;case D.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${O.joinValues(e.options)}`;break;case D.invalid_enum_value:s=`Invalid enum value. Expected ${O.joinValues(e.options)}, received '${e.received}'`;break;case D.invalid_arguments:s="Invalid function arguments";break;case D.invalid_return_type:s="Invalid function return type";break;case D.invalid_date:s="Invalid date";break;case D.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:O.assertNever(e.validation):s="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case D.too_small:s="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?`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 D.too_big:s="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 D.custom:s="Invalid input";break;case D.invalid_intersection_types:s="Intersection results could not be merged";break;case D.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case D.not_finite:s="Number must be finite";break;default:s=t.defaultError,O.assertNever(e)}return{message:s}},G=K;function B(e){G=e}function W(){return G}var Y=e=>{const{data:t,path:s,errorMaps:a,issueData:n}=e,i=[...s,...n.path||[]],r={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const d=a.filter((e=>!!e)).slice().reverse();for(const e of d)o=e(r,{data:t,defaultError:o}).message;return{...n,path:i,message:o}},H=[];function Q(e,t){const s=W(),a=Y({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===K?void 0:K].filter((e=>!!e))});e.common.issues.push(a)}var X,ee,te=class e{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const a of t){if("aborted"===a.status)return se;"dirty"===a.status&&e.dirty(),s.push(a.value)}return{status:e.value,value:s}}static async mergeObjectAsync(t,s){const a=[];for(const e of s){const t=await e.key,s=await e.value;a.push({key:t,value:s})}return e.mergeObjectSync(t,a)}static mergeObjectSync(e,t){const s={};for(const a of t){const{key:t,value:n}=a;if("aborted"===t.status)return se;if("aborted"===n.status)return se;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!a.alwaysSet||(s[t.value]=n.value)}return{status:e.value,value:s}}},se=Object.freeze({status:"aborted"}),ae=e=>({status:"dirty",value:e}),ne=e=>({status:"valid",value:e}),ie=e=>"aborted"===e.status,re=e=>"dirty"===e.status,oe=e=>"valid"===e.status,de=e=>"undefined"!=typeof Promise&&e instanceof Promise;(ee=X||(X={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},ee.toString=e=>"string"==typeof e?e:e?.message;var ce=class{constructor(e,t,s,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},le=(e,t)=>{if(oe(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._error)return this._error;const t=new J(e.common.issues);return this._error=t,this._error}}};function ue(e){if(!e)return{};const{errorMap:t,invalid_type_error:s,required_error:a,description:n}=e;if(t&&(s||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??a??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??s??n.defaultError}},description:n}}var pe,he=class{get description(){return this._def.description}_getType(e){return U(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:U(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new te,ctx:{common:e.parent.common,data:e.data,parsedType:U(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(de(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:U(e)},a=this._parseSync({data:e,path:s.path,parent:s});return le(s,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:U(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return oe(s)?{value:s.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((e=>oe(e)?{value:e.value}:{issues:t.common.issues}))}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:U(e)},a=this._parse({data:e,path:s.path,parent:s}),n=await(de(a)?a:Promise.resolve(a));return le(s,n)}refine(e,t){const s=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,a)=>{const n=e(t),i=()=>a.addIssue({code:D.custom,...s(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then((e=>!!e||(i(),!1))):!!n||(i(),!1)}))}refinement(e,t){return this._refinement(((s,a)=>!!e(s)||(a.addIssue("function"==typeof t?t(s,a):t),!1)))}_refinement(e){return new pt({schema:this,typeName:Ct.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return ht.create(this,this._def)}nullable(){return mt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ge.create(this)}promise(){return ut.create(this,this._def)}or(e){return Ye.create([this,e],this._def)}and(e){return et.create(this,e,this._def)}transform(e){return new pt({...ue(this._def),schema:this,typeName:Ct.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ft({...ue(this._def),innerType:this,defaultValue:t,typeName:Ct.ZodDefault})}brand(){return new _t({typeName:Ct.ZodBranded,type:this,...ue(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new gt({...ue(this._def),innerType:this,catchValue:t,typeName:Ct.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return wt.create(this,e)}readonly(){return bt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},me=/^c[^\s-]{8,}$/i,fe=/^[0-9a-z]+$/,ge=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ye=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ve=/^[a-z0-9_-]{21}$/i,_e=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,we=/^[-+]?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)?)??$/,be=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xe=/^(?:(?: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])$/,ke=/^(?:(?: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])$/,Ce=/^(([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]))$/,Ie=/^(([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])$/,Me=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Te=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Se="((\\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])))",Ne=new RegExp(`^${Se}$`);function Ae(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 Oe(e){let t=`${Se}T${Ae(e)}`;const s=[];return s.push(e.local?"Z?":"Z"),e.offset&&s.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${s.join("|")})`,new RegExp(`^${t}$`)}function Ee(e,t){if(!_e.test(e))return!1;try{const[s]=e.split("."),a=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),n=JSON.parse(atob(a));return"object"==typeof n&&null!==n&&((!("typ"in n)||"JWT"===n?.typ)&&(!!n.alg&&(!t||n.alg===t)))}catch{return!1}}function Ze(e,t){return!("v4"!==t&&t||!ke.test(e))||!("v6"!==t&&t||!Ie.test(e))}var Le=class e extends he{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==z.string){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.string,received:t.parsedType}),se}const t=new te;let s;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),Q(s,{code:D.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("max"===i.kind)e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),Q(s,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("length"===i.kind){const a=e.data.length>i.value,n=e.data.length<i.value;(a||n)&&(s=this._getOrReturnCtx(e,s),a?Q(s,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&Q(s,{code:D.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)be.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"email",code:D.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)pe||(pe=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),pe.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"emoji",code:D.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)ye.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"uuid",code:D.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)ve.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"nanoid",code:D.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)me.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"cuid",code:D.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)fe.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"cuid2",code:D.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)ge.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"ulid",code:D.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),Q(s,{validation:"url",code:D.invalid_string,message:i.message}),t.dirty()}else if("regex"===i.kind){i.regex.lastIndex=0;i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"regex",code:D.invalid_string,message:i.message}),t.dirty())}else if("trim"===i.kind)e.data=e.data.trim();else if("includes"===i.kind)e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),Q(s,{code:D.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),t.dirty());else if("toLowerCase"===i.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===i.kind)e.data=e.data.toUpperCase();else if("startsWith"===i.kind)e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),Q(s,{code:D.invalid_string,validation:{startsWith:i.value},message:i.message}),t.dirty());else if("endsWith"===i.kind)e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),Q(s,{code:D.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){Oe(i).test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{code:D.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){Ne.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{code:D.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${Ae(i)}$`).test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{code:D.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?we.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"duration",code:D.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(a=e.data,("v4"!==(n=i.version)&&n||!xe.test(a))&&("v6"!==n&&n||!Ce.test(a))&&(s=this._getOrReturnCtx(e,s),Q(s,{validation:"ip",code:D.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?Ee(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"jwt",code:D.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?Ze(e.data,i.version)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"cidr",code:D.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?Me.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"base64",code:D.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?Te.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"base64url",code:D.invalid_string,message:i.message}),t.dirty()):O.assertNever(i);var a,n;return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement((t=>e.test(t)),{validation:t,code:D.invalid_string,...X.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...X.errToObj(e)})}url(e){return this._addCheck({kind:"url",...X.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...X.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...X.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...X.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...X.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...X.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...X.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...X.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...X.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...X.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...X.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...X.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...X.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...X.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...X.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...X.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...X.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...X.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...X.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...X.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...X.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...X.errToObj(t)})}nonempty(e){return this.min(1,X.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};function je(e,t){const s=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,n=s>a?s:a;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}Le.create=e=>new Le({checks:[],typeName:Ct.ZodString,coerce:e?.coerce??!1,...ue(e)});var Pe=class e extends he{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==z.number){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.number,received:t.parsedType}),se}let t;const s=new te;for(const a of this._def.checks)if("int"===a.kind)O.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Q(t,{code:D.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty());else if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),Q(t,{code:D.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),Q(t,{code:D.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty())}else"multipleOf"===a.kind?0!==je(e.data,a.value)&&(t=this._getOrReturnCtx(e,t),Q(t,{code:D.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Q(t,{code:D.not_finite,message:a.message}),s.dirty()):O.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,X.toString(t))}gt(e,t){return this.setLimit("min",e,!1,X.toString(t))}lte(e,t){return this.setLimit("max",e,!0,X.toString(t))}lt(e,t){return this.setLimit("max",e,!1,X.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:X.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:X.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:X.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:X.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&O.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if("finite"===s.kind||"int"===s.kind||"multipleOf"===s.kind)return!0;"min"===s.kind?(null===t||s.value>t)&&(t=s.value):"max"===s.kind&&(null===e||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Pe.create=e=>new Pe({checks:[],typeName:Ct.ZodNumber,coerce:e?.coerce||!1,...ue(e)});var Re=class e extends he{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let t;const s=new te;for(const a of this._def.checks)if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),Q(t,{code:D.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),Q(t,{code:D.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty())}else"multipleOf"===a.kind?e.data%a.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),Q(t,{code:D.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):O.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.bigint,received:t.parsedType}),se}gte(e,t){return this.setLimit("min",e,!0,X.toString(t))}gt(e,t){return this.setLimit("min",e,!1,X.toString(t))}lte(e,t){return this.setLimit("max",e,!0,X.toString(t))}lt(e,t){return this.setLimit("max",e,!1,X.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:X.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:X.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:X.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};Re.create=e=>new Re({checks:[],typeName:Ct.ZodBigInt,coerce:e?.coerce??!1,...ue(e)});var Fe=class extends he{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==z.boolean){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.boolean,received:t.parsedType}),se}return ne(e.data)}};Fe.create=e=>new Fe({typeName:Ct.ZodBoolean,coerce:e?.coerce||!1,...ue(e)});var $e=class e extends he{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==z.date){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.date,received:t.parsedType}),se}if(Number.isNaN(e.data.getTime())){return Q(this._getOrReturnCtx(e),{code:D.invalid_date}),se}const t=new te;let s;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),Q(s,{code:D.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),t.dirty()):"max"===a.kind?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),Q(s,{code:D.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):O.assertNever(a);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:X.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:X.toString(t)})}get minDate(){let e=null;for(const t of this._def.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._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}};$e.create=e=>new $e({checks:[],coerce:e?.coerce||!1,typeName:Ct.ZodDate,...ue(e)});var qe=class extends he{_parse(e){if(this._getType(e)!==z.symbol){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.symbol,received:t.parsedType}),se}return ne(e.data)}};qe.create=e=>new qe({typeName:Ct.ZodSymbol,...ue(e)});var ze=class extends he{_parse(e){if(this._getType(e)!==z.undefined){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.undefined,received:t.parsedType}),se}return ne(e.data)}};ze.create=e=>new ze({typeName:Ct.ZodUndefined,...ue(e)});var Ue=class extends he{_parse(e){if(this._getType(e)!==z.null){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.null,received:t.parsedType}),se}return ne(e.data)}};Ue.create=e=>new Ue({typeName:Ct.ZodNull,...ue(e)});var De=class extends he{constructor(){super(...arguments),this._any=!0}_parse(e){return ne(e.data)}};De.create=e=>new De({typeName:Ct.ZodAny,...ue(e)});var Ve=class extends he{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ne(e.data)}};Ve.create=e=>new Ve({typeName:Ct.ZodUnknown,...ue(e)});var Je=class extends he{_parse(e){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.never,received:t.parsedType}),se}};Je.create=e=>new Je({typeName:Ct.ZodNever,...ue(e)});var Ke=class extends he{_parse(e){if(this._getType(e)!==z.undefined){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.void,received:t.parsedType}),se}return ne(e.data)}};Ke.create=e=>new Ke({typeName:Ct.ZodVoid,...ue(e)});var Ge=class e extends he{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==z.array)return Q(t,{code:D.invalid_type,expected:z.array,received:t.parsedType}),se;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,n=t.data.length<a.exactLength.value;(e||n)&&(Q(t,{code:e?D.too_big:D.too_small,minimum:n?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),s.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(Q(t,{code:D.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),s.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(Q(t,{code:D.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map(((e,s)=>a.type._parseAsync(new ce(t,e,t.path,s))))).then((e=>te.mergeArray(s,e)));const n=[...t.data].map(((e,s)=>a.type._parseSync(new ce(t,e,t.path,s))));return te.mergeArray(s,n)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:X.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:X.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:X.toString(s)}})}nonempty(e){return this.min(1,e)}};function Be(e){if(e instanceof We){const t={};for(const s in e.shape){const a=e.shape[s];t[s]=ht.create(Be(a))}return new We({...e._def,shape:()=>t})}return e instanceof Ge?new Ge({...e._def,type:Be(e.element)}):e instanceof ht?ht.create(Be(e.unwrap())):e instanceof mt?mt.create(Be(e.unwrap())):e instanceof tt?tt.create(e.items.map((e=>Be(e)))):e}Ge.create=(e,t)=>new Ge({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ct.ZodArray,...ue(t)});var We=class e extends he{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=O.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==z.object){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.object,received:t.parsedType}),se}const{status:t,ctx:s}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof Je&&"strip"===this._def.unknownKeys))for(const e in s.data)n.includes(e)||i.push(e);const r=[];for(const e of n){const t=a[e],n=s.data[e];r.push({key:{status:"valid",value:e},value:t._parse(new ce(s,n,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof Je){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)r.push({key:{status:"valid",value:e},value:{status:"valid",value:s.data[e]}});else if("strict"===e)i.length>0&&(Q(s,{code:D.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const a=s.data[t];r.push({key:{status:"valid",value:t},value:e._parse(new ce(s,a,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of r){const s=await t.key,a=await t.value;e.push({key:s,value:a,alwaysSet:t.alwaysSet})}return e})).then((e=>te.mergeObjectSync(t,e))):te.mergeObjectSync(t,r)}get shape(){return this._def.shape()}strict(t){return X.errToObj,new e({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(e,s)=>{const a=this._def.errorMap?.(e,s).message??s.defaultError;return"unrecognized_keys"===e.code?{message:X.errToObj(t).message??a}:{message:a}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Ct.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){const s={};for(const e of O.objectKeys(t))t[e]&&this.shape[e]&&(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}omit(t){const s={};for(const e of O.objectKeys(this.shape))t[e]||(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}deepPartial(){return Be(this)}partial(t){const s={};for(const e of O.objectKeys(this.shape)){const a=this.shape[e];t&&!t[e]?s[e]=a:s[e]=a.optional()}return new e({...this._def,shape:()=>s})}required(t){const s={};for(const e of O.objectKeys(this.shape))if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof ht;)t=t._def.innerType;s[e]=t}return new e({...this._def,shape:()=>s})}keyof(){return dt(O.objectKeys(this.shape))}};We.create=(e,t)=>new We({shape:()=>e,unknownKeys:"strip",catchall:Je.create(),typeName:Ct.ZodObject,...ue(t)}),We.strictCreate=(e,t)=>new We({shape:()=>e,unknownKeys:"strict",catchall:Je.create(),typeName:Ct.ZodObject,...ue(t)}),We.lazycreate=(e,t)=>new We({shape:e,unknownKeys:"strip",catchall:Je.create(),typeName:Ct.ZodObject,...ue(t)});var Ye=class extends he{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;if(t.common.async)return Promise.all(s.map((async e=>{const s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const s of e)if("dirty"===s.result.status)return t.common.issues.push(...s.ctx.common.issues),s.result;const s=e.map((e=>new J(e.ctx.common.issues)));return Q(t,{code:D.invalid_union,unionErrors:s}),se}));{let e;const a=[];for(const n of s){const s={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:s});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:s}),s.common.issues.length&&a.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=a.map((e=>new J(e)));return Q(t,{code:D.invalid_union,unionErrors:n}),se}}get options(){return this._def.options}};Ye.create=(e,t)=>new Ye({options:e,typeName:Ct.ZodUnion,...ue(t)});var He=e=>e instanceof rt?He(e.schema):e instanceof pt?He(e.innerType()):e instanceof ot?[e.value]:e instanceof ct?e.options:e instanceof lt?O.objectValues(e.enum):e instanceof ft?He(e._def.innerType):e instanceof ze?[void 0]:e instanceof Ue?[null]:e instanceof ht?[void 0,...He(e.unwrap())]:e instanceof mt?[null,...He(e.unwrap())]:e instanceof _t||e instanceof bt?He(e.unwrap()):e instanceof gt?He(e._def.innerType):[],Qe=class e extends he{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.object)return Q(t,{code:D.invalid_type,expected:z.object,received:t.parsedType}),se;const s=this.discriminator,a=t.data[s],n=this.optionsMap.get(a);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(Q(t,{code:D.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),se)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,s,a){const n=new Map;for(const e of s){const s=He(e.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const a of s){if(n.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);n.set(a,e)}}return new e({typeName:Ct.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:n,...ue(a)})}};function Xe(e,t){const s=U(e),a=U(t);if(e===t)return{valid:!0,data:e};if(s===z.object&&a===z.object){const s=O.objectKeys(t),a=O.objectKeys(e).filter((e=>-1!==s.indexOf(e))),n={...e,...t};for(const s of a){const a=Xe(e[s],t[s]);if(!a.valid)return{valid:!1};n[s]=a.data}return{valid:!0,data:n}}if(s===z.array&&a===z.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let a=0;a<e.length;a++){const n=Xe(e[a],t[a]);if(!n.valid)return{valid:!1};s.push(n.data)}return{valid:!0,data:s}}return s===z.date&&a===z.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}var et=class extends he{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=(e,a)=>{if(ie(e)||ie(a))return se;const n=Xe(e.value,a.value);return n.valid?((re(e)||re(a))&&t.dirty(),{status:t.value,value:n.data}):(Q(s,{code:D.invalid_intersection_types}),se)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then((([e,t])=>a(e,t))):a(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};et.create=(e,t,s)=>new et({left:e,right:t,typeName:Ct.ZodIntersection,...ue(s)});var tt=class e extends he{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==z.array)return Q(s,{code:D.invalid_type,expected:z.array,received:s.parsedType}),se;if(s.data.length<this._def.items.length)return Q(s,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),se;!this._def.rest&&s.data.length>this._def.items.length&&(Q(s,{code:D.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...s.data].map(((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new ce(s,e,s.path,t)):null})).filter((e=>!!e));return s.common.async?Promise.all(a).then((e=>te.mergeArray(t,e))):te.mergeArray(t,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};tt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new tt({items:e,typeName:Ct.ZodTuple,rest:null,...ue(t)})};var st=class e extends he{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==z.object)return Q(s,{code:D.invalid_type,expected:z.object,received:s.parsedType}),se;const a=[],n=this._def.keyType,i=this._def.valueType;for(const e in s.data)a.push({key:n._parse(new ce(s,e,s.path,e)),value:i._parse(new ce(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?te.mergeObjectAsync(t,a):te.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(t,s,a){return new e(s instanceof he?{keyType:t,valueType:s,typeName:Ct.ZodRecord,...ue(a)}:{keyType:Le.create(),valueType:t,typeName:Ct.ZodRecord,...ue(s)})}},at=class extends he{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==z.map)return Q(s,{code:D.invalid_type,expected:z.map,received:s.parsedType}),se;const a=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map((([e,t],i)=>({key:a._parse(new ce(s,e,s.path,[i,"key"])),value:n._parse(new ce(s,t,s.path,[i,"value"]))})));if(s.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const s of i){const a=await s.key,n=await s.value;if("aborted"===a.status||"aborted"===n.status)return se;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const s of i){const a=s.key,n=s.value;if("aborted"===a.status||"aborted"===n.status)return se;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}};at.create=(e,t,s)=>new at({valueType:t,keyType:e,typeName:Ct.ZodMap,...ue(s)});var nt=class e extends he{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==z.set)return Q(s,{code:D.invalid_type,expected:z.set,received:s.parsedType}),se;const a=this._def;null!==a.minSize&&s.data.size<a.minSize.value&&(Q(s,{code:D.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&s.data.size>a.maxSize.value&&(Q(s,{code:D.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const s=new Set;for(const a of e){if("aborted"===a.status)return se;"dirty"===a.status&&t.dirty(),s.add(a.value)}return{status:t.value,value:s}}const r=[...s.data.values()].map(((e,t)=>n._parse(new ce(s,e,s.path,t))));return s.common.async?Promise.all(r).then((e=>i(e))):i(r)}min(t,s){return new e({...this._def,minSize:{value:t,message:X.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:X.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};nt.create=(e,t)=>new nt({valueType:e,minSize:null,maxSize:null,typeName:Ct.ZodSet,...ue(t)});var it=class e extends he{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.function)return Q(t,{code:D.invalid_type,expected:z.function,received:t.parsedType}),se;function s(e,s){return Y({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,W(),K].filter((e=>!!e)),issueData:{code:D.invalid_arguments,argumentsError:s}})}function a(e,s){return Y({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,W(),K].filter((e=>!!e)),issueData:{code:D.invalid_return_type,returnTypeError:s}})}const n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof ut){const e=this;return ne((async function(...t){const r=new J([]),o=await e._def.args.parseAsync(t,n).catch((e=>{throw r.addIssue(s(t,e)),r})),d=await Reflect.apply(i,this,o);return await e._def.returns._def.type.parseAsync(d,n).catch((e=>{throw r.addIssue(a(d,e)),r}))}))}{const e=this;return ne((function(...t){const r=e._def.args.safeParse(t,n);if(!r.success)throw new J([s(t,r.error)]);const o=Reflect.apply(i,this,r.data),d=e._def.returns.safeParse(o,n);if(!d.success)throw new J([a(o,d.error)]);return d.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:tt.create(t).rest(Ve.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,s,a){return new e({args:t||tt.create([]).rest(Ve.create()),returns:s||Ve.create(),typeName:Ct.ZodFunction,...ue(a)})}},rt=class extends he{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};rt.create=(e,t)=>new rt({getter:e,typeName:Ct.ZodLazy,...ue(t)});var ot=class extends he{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Q(t,{received:t.data,code:D.invalid_literal,expected:this._def.value}),se}return{status:"valid",value:e.data}}get value(){return this._def.value}};function dt(e,t){return new ct({values:e,typeName:Ct.ZodEnum,...ue(t)})}ot.create=(e,t)=>new ot({value:e,typeName:Ct.ZodLiteral,...ue(t)});var ct=class e extends he{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),s=this._def.values;return Q(t,{expected:O.joinValues(s),received:t.parsedType,code:D.invalid_type}),se}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return Q(t,{received:t.data,code:D.invalid_enum_value,options:s}),se}return ne(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(t,s=this._def){return e.create(t,{...this._def,...s})}exclude(t,s=this._def){return e.create(this.options.filter((e=>!t.includes(e))),{...this._def,...s})}};ct.create=dt;var lt=class extends he{_parse(e){const t=O.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==z.string&&s.parsedType!==z.number){const e=O.objectValues(t);return Q(s,{expected:O.joinValues(e),received:s.parsedType,code:D.invalid_type}),se}if(this._cache||(this._cache=new Set(O.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=O.objectValues(t);return Q(s,{received:s.data,code:D.invalid_enum_value,options:e}),se}return ne(e.data)}get enum(){return this._def.values}};lt.create=(e,t)=>new lt({values:e,typeName:Ct.ZodNativeEnum,...ue(t)});var ut=class extends he{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.promise&&!1===t.common.async)return Q(t,{code:D.invalid_type,expected:z.promise,received:t.parsedType}),se;const s=t.parsedType===z.promise?t.data:Promise.resolve(t.data);return ne(s.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}};ut.create=(e,t)=>new ut({type:e,typeName:Ct.ZodPromise,...ue(t)});var pt=class extends he{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ct.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=this._def.effect||null,n={addIssue:e=>{Q(s,e),e.fatal?t.abort():t.dirty()},get path(){return s.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===a.type){const e=a.transform(s.data,n);if(s.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return se;const a=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===a.status?se:"dirty"===a.status||"dirty"===t.value?ae(a.value):a}));{if("aborted"===t.value)return se;const a=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===a.status?se:"dirty"===a.status||"dirty"===t.value?ae(a.value):a}}if("refinement"===a.type){const e=e=>{const t=a.refinement(e,n);if(s.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===s.common.async){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===a.status?se:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((s=>"aborted"===s.status?se:("dirty"===s.status&&t.dirty(),e(s.value).then((()=>({status:t.value,value:s.value}))))))}if("transform"===a.type){if(!1===s.common.async){const e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!oe(e))return se;const i=a.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((e=>oe(e)?Promise.resolve(a.transform(e.value,n)).then((e=>({status:t.value,value:e}))):se))}O.assertNever(a)}};pt.create=(e,t,s)=>new pt({schema:e,typeName:Ct.ZodEffects,effect:t,...ue(s)}),pt.createWithPreprocess=(e,t,s)=>new pt({schema:t,effect:{type:"preprocess",transform:e},typeName:Ct.ZodEffects,...ue(s)});var ht=class extends he{_parse(e){return this._getType(e)===z.undefined?ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ht.create=(e,t)=>new ht({innerType:e,typeName:Ct.ZodOptional,...ue(t)});var mt=class extends he{_parse(e){return this._getType(e)===z.null?ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};mt.create=(e,t)=>new mt({innerType:e,typeName:Ct.ZodNullable,...ue(t)});var ft=class extends he{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===z.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ft.create=(e,t)=>new ft({innerType:e,typeName:Ct.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...ue(t)});var gt=class extends he{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return de(a)?a.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new J(s.common.issues)},input:s.data})}))):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new J(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};gt.create=(e,t)=>new gt({innerType:e,typeName:Ct.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...ue(t)});var yt=class extends he{_parse(e){if(this._getType(e)!==z.nan){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.nan,received:t.parsedType}),se}return{status:"valid",value:e.data}}};yt.create=e=>new yt({typeName:Ct.ZodNaN,...ue(e)});var vt=Symbol("zod_brand"),_t=class extends he{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},wt=class e extends he{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?se:"dirty"===e.status?(t.dirty(),ae(e.value)):this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})()}{const e=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?se:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:s.path,parent:s})}}static create(t,s){return new e({in:t,out:s,typeName:Ct.ZodPipeline})}},bt=class extends he{_parse(e){const t=this._def.innerType._parse(e),s=e=>(oe(e)&&(e.value=Object.freeze(e.value)),e);return de(t)?t.then((e=>s(e))):s(t)}unwrap(){return this._def.innerType}};function xt(e,t){const s="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof s?{message:s}:s}function kt(e,t={},s){return e?De.create().superRefine(((a,n)=>{const i=e(a);if(i instanceof Promise)return i.then((e=>{if(!e){const e=xt(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}}));if(!i){const e=xt(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}})):De.create()}bt.create=(e,t)=>new bt({innerType:e,typeName:Ct.ZodReadonly,...ue(t)});var Ct,It,Mt={object:We.lazycreate};(It=Ct||(Ct={})).ZodString="ZodString",It.ZodNumber="ZodNumber",It.ZodNaN="ZodNaN",It.ZodBigInt="ZodBigInt",It.ZodBoolean="ZodBoolean",It.ZodDate="ZodDate",It.ZodSymbol="ZodSymbol",It.ZodUndefined="ZodUndefined",It.ZodNull="ZodNull",It.ZodAny="ZodAny",It.ZodUnknown="ZodUnknown",It.ZodNever="ZodNever",It.ZodVoid="ZodVoid",It.ZodArray="ZodArray",It.ZodObject="ZodObject",It.ZodUnion="ZodUnion",It.ZodDiscriminatedUnion="ZodDiscriminatedUnion",It.ZodIntersection="ZodIntersection",It.ZodTuple="ZodTuple",It.ZodRecord="ZodRecord",It.ZodMap="ZodMap",It.ZodSet="ZodSet",It.ZodFunction="ZodFunction",It.ZodLazy="ZodLazy",It.ZodLiteral="ZodLiteral",It.ZodEnum="ZodEnum",It.ZodEffects="ZodEffects",It.ZodNativeEnum="ZodNativeEnum",It.ZodOptional="ZodOptional",It.ZodNullable="ZodNullable",It.ZodDefault="ZodDefault",It.ZodCatch="ZodCatch",It.ZodPromise="ZodPromise",It.ZodBranded="ZodBranded",It.ZodPipeline="ZodPipeline",It.ZodReadonly="ZodReadonly";var Tt=(e,t={message:`Input not instance of ${e.name}`})=>kt((t=>t instanceof e),t),St=Le.create,Nt=Pe.create,At=yt.create,Ot=Re.create,Et=Fe.create,Zt=$e.create,Lt=qe.create,jt=ze.create,Pt=Ue.create,Rt=De.create,Ft=Ve.create,$t=Je.create,qt=Ke.create,zt=Ge.create,Ut=We.create,Dt=We.strictCreate,Vt=Ye.create,Jt=Qe.create,Kt=et.create,Gt=tt.create,Bt=st.create,Wt=at.create,Yt=nt.create,Ht=it.create,Qt=rt.create,Xt=ot.create,es=ct.create,ts=lt.create,ss=ut.create,as=pt.create,ns=ht.create,is=mt.create,rs=pt.createWithPreprocess,os=wt.create,ds=()=>St().optional(),cs=()=>Nt().optional(),ls=()=>Et().optional(),us={string:e=>Le.create({...e,coerce:!0}),number:e=>Pe.create({...e,coerce:!0}),boolean:e=>Fe.create({...e,coerce:!0}),bigint:e=>Re.create({...e,coerce:!0}),date:e=>$e.create({...e,coerce:!0})},ps=se,hs={text:"text",conversation:"text",imageMessage:"image",contactMessage:"contact",locationMessage:"location",documentMessage:"document",audioMessage:"audio",videoMessage:"video",protocolMessage:"protocol",contactsArrayMessage:"contactsArray",highlyStructuredMessage:"highlyStructured",sendPaymentMessage:"sendPayment",liveLocationMessage:"liveLocation",requestPaymentMessage:"requestPayment",declinePaymentRequestMessage:"declinePaymentRequest",cancelPaymentRequestMessage:"cancelPaymentRequest",templateMessage:"template",stickerMessage:"sticker",groupInviteMessage:"groupInvite",templateButtonReplyMessage:"templateButtonReply",productMessage:"product",deviceSentMessage:"deviceSent",listMessage:"list",viewOnceMessage:"viewOnce",orderMessage:"order",listResponseMessage:"listResponse",ephemeralMessage:"ephemeral",invoiceMessage:"invoice",buttonsMessage:"buttons",buttonsResponseMessage:"buttonsResponse",paymentInviteMessage:"paymentInvite",interactiveMessage:"interactive",reactionMessage:"reaction",stickerSyncRmrMessage:"sticker",interactiveResponseMessage:"interactiveResponse",pollCreationMessage:"pollCreation",pollUpdateMessage:"pollUpdate",keepInChatMessage:"keepInChat",documentWithCaptionMessage:"document",requestPhoneNumberMessage:"requestPhoneNumber",viewOnceMessageV2:"viewOnce",encReactionMessage:"reaction",editedMessage:"text",viewOnceMessageV2Extension:"viewOnce",pollCreationMessageV2:"pollCreation",scheduledCallCreationMessage:"scheduledCallCreation",groupMentionedMessage:"groupMentioned",pinInChatMessage:"pinInChat",pollCreationMessageV3:"pollCreation",scheduledCallEditMessage:"scheduledCallEdit",ptvMessage:"ptv",botInvokeMessage:"botInvoke",callLogMesssage:"callLog",encCommentMessage:"encComment",bcallMessage:"bcall",lottieStickerMessage:"lottieSticker",eventMessage:"event",commentMessage:"comment",newsletterAdminInviteMessage:"text",extendedTextMessageWithParentKey:"text",extendedTextMessage:"text",placeholderMessage:"placeholder",encEventUpdateMessage:"encEventUpdate"},ms={whatsapp:"0@s.whatsapp.net",meta:"13135550002@s.whatsapp.net",chatgpt:"18002428478@s.whatsapp.net",copilot:"18772241042@s.whatsapp.net",instagram:"447723442971@s.whatsapp.net",tiktok:"6285574670498@s.whatsapp.net"},fs=q.enum(["text","text","image","contact","location","document","audio","video","protocol","contactsArray","highlyStructured","sendPayment","liveLocation","requestPayment","declinePaymentRequest","cancelPaymentRequest","template","sticker","groupInvite","templateButtonReply","product","deviceSent","list","viewOnce","order","listResponse","ephemeral","invoice","buttons","buttonsResponse","paymentInvite","interactive","reaction","sticker","interactiveResponse","pollCreation","pollUpdate","keepInChat","document","requestPhoneNumber","viewOnce","reaction","text","viewOnce","pollCreation","scheduledCallCreation","groupMentioned","pinInChat","pollCreation","scheduledCallEdit","ptv","botInvoke","callLog","encComment","bcall","lottieSticker","event","comment","text","text","placeholder","encEventUpdate"]),gs=q.enum(["unknown","android","ios","desktop","web"]),ys=q.object({chatId:q.string(),channelId:q.string(),uniqueId:q.string(),receiverId:q.string(),receiverName:q.string(),roomId:q.string(),roomName:q.string(),senderId:q.string(),senderName:q.string(),senderDevice:gs,chatType:fs,timestamp:q.number(),mentions:q.string().array(),text:q.string().nullable(),links:q.string().array(),isPrefix:q.boolean(),isFromMe:q.boolean(),isTagMe:q.boolean(),isGroup:q.boolean(),isStory:q.boolean(),isViewOnce:q.boolean(),isEdited:q.boolean(),isDeleted:q.boolean(),isPinned:q.boolean(),isUnPinned:q.boolean(),isChannel:q.boolean(),isBroadcast:q.boolean(),isEphemeral:q.boolean(),isForwarded:q.boolean(),citation:q.record(q.string(),q.boolean()).nullable(),media:q.object({buffer:q.function().returns(q.instanceof(Buffer)),stream:q.function().returns(q.instanceof(N))}).passthrough().nullable(),message:q.function().returns(q.record(q.string(),q.any()))});ys.extend({replied:ys.nullable()});var vs=class{constructor(e,t,s){this.socket=e,this.client=t,this.db=s}maxReplies=0;async connection(e){this.client.stopSpinner("connection",!1),this.client.startSpinner("connection","Connecting to WhatsApp...");const{connection:t,lastDisconnect:s,qr:a}=e;if(this.client.emit("connection",{status:"connecting"}),"qr"===this.client.options?.authType&&a)return this.client.stopSpinner("reconnect",!1),console.log(),console.log(await S.toString(a,{type:"terminal",small:!0})),this.client.startSpinner("qr","Waiting for QR code scan..."),void this.socket?.ev.on("connection.update",(()=>this.client.stopSpinner("qr",!1)));if("close"===t){const e=s?.error?.output?.statusCode,a=e===o.restartRequired||e===o.connectionLost;if(this.client.failSpinner("connection",`[Connection Closed] [${e}]\n${s?.error?.message}\n`),401===e||405===e||500===e)return void console.error("Invalid session, please delete manually");a&&"close"==t&&(await this.client.startSpinner("reconnect","Automatically restarting..."),await this.client.initialize())}else"open"===t&&(this.client.stopSpinner("connection",!0,"Connected to WhatsApp\n"),this.client.emit("connection",{status:"open"}))}async messages(e,t){if(e?.messageStubType||e?.messageStubParameters?.length||e?.message?.protocolMessage?.peerDataOperationRequestResponseMessage||e?.message?.botInvokeMessage||!e?.key?.id||!e?.message)return null;if(this.client.options?.ignoreMe&&e?.key?.fromMe&&"status@broadcast"!=e?.key?.remoteJid&&!e?.participant)return null;this.client.options?.autoRead&&await this.socket.readMessages([e?.key]);const s=e,a=e?.message?.pinInChatMessage?.key?.id,n=1==e?.message?.pinInChatMessage?.type,r=2==e?.message?.pinInChatMessage?.type;if(a){const t=await this.db.selectFrom("messages").select("value").where("id","=",a).executeTakeFirst(),s=j(t?.value);e=s}const o=!e?.message?.protocolMessage?.editedMessage&&e?.message?.protocolMessage?.key?.id,u=!!o;if(o){const t=await this.db.selectFrom("messages").select("value").where("id","=",o).executeTakeFirst(),s=j(t?.value);e=s}const p={},h=d(e?.message?.protocolMessage?.editedMessage||e?.message);p.chatId=e?.message?.protocolMessage?.key?.id||e?.key?.id,p.channelId="",p.uniqueId="",p.receiverId=i(this.socket.user?.id),p.receiverName=this.socket.user?.name||this.socket.user?.verifiedName,p.roomId=i(e?.key?.remoteJid);const m=await this.db.selectFrom("chats").select("value").where("id","=",p.roomId).executeTakeFirst();p.roomName=j(m?.value)?.name,p.senderId=i(e?.participant||e?.key?.participant||e?.key?.remoteJid);const f=await this.db.selectFrom("chats").select("value").where("id","=",p.senderId).executeTakeFirst();p.senderName=e?.pushName||e?.verifiedBizName||j(f?.value)?.name||p.receiverName,p.roomName=p.roomName||p.senderName,p.senderDevice=c(p.chatId),p.chatType=hs[h],p.timestamp=e?.messageTimestamp?.low||e?.messageTimestamp||0,p.mentions=[],p.text=null,p.links=[],p.isPrefix=!1,p.isFromMe=e?.key?.fromMe,p.isTagMe=!1,p.isGroup=p.roomId.includes("@g.us"),p.isStory=p.roomId.includes("@broadcast"),p.isViewOnce=!1,p.isEdited=!1,p.isDeleted=u,p.isPinned=n,p.isUnPinned=r,p.isChannel=p.roomId.includes("@newsletter"),p.isBroadcast=!!e?.broadcast,p.isEphemeral=!1,p.isForwarded=!1,p.citation=null,p.media=null,p.replied=null,p.channelId=p.roomId.split("@")[0]+"-"+p.senderId.split("@")[0],p.uniqueId=p.channelId+"-"+p.chatId;const g=this.client.options?.citation;if(Object.keys(g).length){p.citation={};for(const e of Object.keys(g))p.citation[e]=g[e].includes(Number(p.senderId.split("@")[0]))||g[e].includes(Number(p.roomId.split("@")[0]))}const y=(e?.message?.protocolMessage?.editedMessage?.[h]||e?.message?.[h])?.message?.documentMessage||e?.message?.[h];"text"!=p.chatType&&(p.media={...F(y,["url","contextInfo","fileSha256","fileEncSha256","mediaKey","directPath","waveform","thumbnail","jpegThumbnail","thumbnailEncSha256","thumbnailSha256","thumbnailDirectPath","firstFrameSidecar","streamingSidecar","scansSidecar","callKey","midQualityFileSha256"]),buffer:async()=>await l(e,"buffer",{}),stream:async()=>await l(e,"stream",{})});const v=e?.message?.[h]?.contextInfo?.stanzaId;if(v&&this.maxReplies<1){this.maxReplies++;const t=await this.db.selectFrom("messages").select("value").where("id","=",v).executeTakeFirst(),s=j(t?.value);if(s)p.replied=await this.messages(s,!0);else{const t=e,s=d(t.message?.extendedTextMessage?.contextInfo.quotedMessage);t.key.id=t.message?.extendedTextMessage?.contextInfo.stanzaId,t.message[s]=t.message?.extendedTextMessage?.contextInfo.quotedMessage[s],delete t.message?.extendedTextMessage,p.replied=await this.messages(t,!0)}}const _="string"==typeof y?y:y?.text||y?.caption||y?.name||y?.displayName||"";p.text=((e="")=>e?e.replace(/\u202E([\s\S]*?)\u202C/g,((e,t)=>Array.from(t).reverse().join(""))).replace(/[\u202A-\u202E\u202C]/g,""):null)(_)||null,p.mentions=((e="")=>{if(!e)return[];const t=new Set;for(const s of e.matchAll(/@(\d+)/g))t.add(s[1]);return[...t]})(p.text),p.links=((e="")=>e&&e.match(/(?:https?:\/\/)?[^\s<>"']+\.[^\s<>"']+/g)||[])(p.text);const w=e?.message?.[h];return p.isPrefix=!!this.client.options?.prefix&&!!p.text?.startsWith(this.client.options?.prefix),p.isTagMe=p.mentions.includes(p.receiverId.split("@")[0]),p.isEdited=R(P(e),"editedMessage"),p.isEphemeral=R(P(w?.contextInfo),"ephemeralSettingTimestamp"),p.isForwarded=R(P(w?.contextInfo),"forwardingScore"),p.isViewOnce=!!w?.viewOnce,p.isPrefix&&(p.text=p.text.replace(new RegExp(`^${this.client.options?.prefix}`),"")),p.message=()=>s,t||this.client.emit("messages",p),p}async calls(e){this.client.options?.autoRejectCall&&await this.socket.rejectCall(e.id,e.from);const t={};t.callId=e.id,t.roomId=e.chatId,t.callerId=e.from,t.date=e.date,t.offline=e.offline,t.status=e.status,t.isVideo=!!e.isVideo,t.isGroup=!!e.isGroup,this.client.emit("calls",t)}},_s=async(e,t,s)=>{const a="auth";await(async(e,t)=>{await e.transaction().execute((async e=>{await e.schema.createTable("auth").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("auth_session_id_unique",["session","id"]).execute(),await e.schema.createTable("chats").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("chats_session_id_unique",["session","id"]).execute(),await e.schema.createTable("contacts").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("contacts_session_id_unique",["session","id"]).execute(),await e.schema.createTable("messages").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("messages_session_id_unique",["session","id"]).execute(),t.loadLLMSchemas&&(await e.schema.createTable("llm_messages").ifNotExists().addColumn("uniqueId","char(36)",(e=>e.notNull().primaryKey())).addColumn("channelId","char(36)").addColumn("model","char(36)").addColumn("role","varchar(20)",(e=>e.notNull())).addColumn("content","text",(e=>e.notNull())).addColumn("additional","text").addUniqueConstraint("llm_messages_id_unique",["uniqueId"]).execute(),await e.schema.createTable("llm_personalization").ifNotExists().addColumn("uniqueId","char(36)",(e=>e.notNull().primaryKey())).addColumn("senderId","char(36)").addColumn("content","text",(e=>e.notNull())).addUniqueConstraint("llm_personalization_id_unique",["uniqueId"]).execute(),await e.schema.createTable("llm_rag").ifNotExists().addColumn("metadata.id","char(36)",(e=>e.notNull().primaryKey())).addColumn("pageContent","text",(e=>e.notNull())).addUniqueConstraint("llm_rag_id_unique",["metadata.id"]).execute()),await Promise.all([e.schema.createIndex("auth_session_id_idx").ifNotExists().on("auth").columns(["session","id"]).execute(),e.schema.createIndex("chats_session_id_idx").ifNotExists().on("chats").columns(["session","id"]).execute(),e.schema.createIndex("contacts_session_id_idx").ifNotExists().on("contacts").columns(["session","id"]).execute(),e.schema.createIndex("messages_session_id_idx").ifNotExists().on("messages").columns(["session","id"]).execute(),e.schema.createIndex("llm_messages_uniqueId_idx").ifNotExists().on("llm_messages").column("uniqueId").execute(),e.schema.createIndex("llm_messages_channelId_idx").ifNotExists().on("llm_messages").column("channelId").execute(),e.schema.createIndex("llm_messages_model_idx").ifNotExists().on("llm_messages").column("model").execute(),e.schema.createIndex("llm_messages_role_idx").ifNotExists().on("llm_messages").column("role").execute(),e.schema.createIndex("llm_personalization_uniqueId_idx").ifNotExists().on("llm_personalization").column("uniqueId").execute(),e.schema.createIndex("llm_personalization_senderId_idx").ifNotExists().on("llm_personalization").column("senderId").execute(),e.schema.createIndex("llm_rag_id_idx").ifNotExists().on("llm_rag").column("metadata.id").execute(),e.schema.createIndex("llm_rag_pageContent_idx").ifNotExists().on("llm_rag").column("pageContent").execute()])}))})(e,s);const i=async e=>{for(let t=0;t<10;t++)try{return await e()}catch(e){await new Promise((e=>setTimeout(e,200)))}throw new Error("Max retries reached")},o=async s=>{const n=await i((()=>e.selectFrom(a).select(["value"]).where("id","=",s).where("session","=",t).executeTakeFirst()));if(!n?.value)return null;const o="object"==typeof n.value?JSON.stringify(n.value):n.value;return JSON.parse(o,r.reviver)},d=async(s,n)=>{const o=JSON.stringify(n,r.replacer);await i((()=>e.insertInto(a).values({session:t,id:s,value:o}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:o}))).execute()))},c=async s=>{await i((()=>e.deleteFrom(a).where("id","=",s).where("session","=",t).execute()))},l=await o("creds")||n();return{state:{creds:l,keys:{get:async(e,t)=>{const s={};for(const a of t){let t=await o(`${e}-${a}`);"app-state-sync-key"===e&&t&&(t=$(t)),s[a]=t}return s},set:async e=>{for(const t in e)for(const s in e[t]){const a=e[t][s],n=`${t}-${s}`;a?await d(n,a):await c(n)}}}},saveCreds:async()=>{await d("creds",l)},clear:async()=>{await(async()=>{await i((()=>e.deleteFrom(a).where("session","=",t).where("id","!=","creds").execute()))})()},removeCreds:async()=>{await(async()=>{await i((()=>e.deleteFrom(a).where("session","=",t).execute()))})()}}},ws=q.object({type:q.enum(["sqlite","postgresql","mysql"]).default("sqlite"),connection:q.object({url:q.string().default("./session/zaileys.db")}).optional().default({})}).optional().default({}),bs=q.record(q.function().returns(q.union([q.number().array(),q.promise(q.number().array())]))).optional().transform((async e=>{if(!e)return{};const t={};for(const[s,a]of Object.entries(e)){t[`is${s.charAt(0).toUpperCase()}${s.slice(1)}`]=await a()}return t})),xs=q.object({prefix:q.string().optional(),ignoreMe:q.boolean().optional().default(!0),showLogs:q.boolean().optional().default(!0),autoMentions:q.boolean().optional().default(!0),autoOnline:q.boolean().optional().default(!0),autoRead:q.boolean().optional().default(!0),autoPresence:q.boolean().optional().default(!0),autoRejectCall:q.boolean().optional().default(!0),loadLLMSchemas:q.boolean().optional().default(!1),database:ws,citation:bs}),ks=q.object({authType:q.literal("pairing"),phoneNumber:q.number()}).extend(xs.shape),Cs=q.object({authType:q.literal("qr"),phoneNumber:q.undefined().optional()}).extend(xs.shape),Is=q.discriminatedUnion("authType",[ks,Cs]),Ms=q.object({channelId:q.string(),uniqueId:q.string(),model:q.string().min(2).max(100).optional().nullable(),role:q.string().min(2).max(100),content:q.string().min(1).max(65e3),additional:q.string().max(2e4).optional().nullable()}),Ts=q.object({uniqueId:q.string(),senderId:q.string(),content:q.string().min(1).max(5e3)}),Ss=q.object({metadata:q.object({id:q.string().default((()=>(e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";return Array.from({length:e},(()=>t[Math.floor(62*Math.random())])).join("")})(5)))}).default({}),pageContent:q.string().min(1).max(128e3)});Ss.pick({pageContent:!0});var Ns=q.union([q.string().url(),q.instanceof(Buffer).or(q.instanceof(N))]),As=q.union([q.string(),q.object({image:Ns,text:q.string().optional()}),q.object({video:Ns,text:q.string().optional()}),q.object({videoNote:Ns}),q.object({gif:Ns,text:q.string().optional()}),q.object({audio:Ns}),q.object({audioNote:Ns}),q.object({sticker:Ns})]),Os=q.object({roomId:q.string(),asForwarded:q.boolean().optional(),asViewOnce:q.boolean().optional(),verifiedReply:q.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).optional(),quoted:q.function().returns(q.record(q.string(),q.any())).optional()}),Es=Os,Zs=q.object({latitude:q.number(),longitude:q.number(),title:q.string().optional(),footer:q.string().optional()}),Ls=Os,js=q.object({fullname:q.string(),nickname:q.string().optional(),organization:q.string().optional(),role:q.string().optional(),email:q.string().email().optional(),whatsAppNumber:q.number(),callNumber:q.number().optional(),voiceNumber:q.number().optional(),website:q.string().url().optional(),homeAddress:q.string().optional(),workAddress:q.string().optional(),avatar:q.string().url().optional()}),Ps=q.object({message:q.function().returns(q.record(q.string(),q.any()))}),Rs=q.string(),Fs=q.object({message:q.function().returns(q.record(q.string(),q.any()))}),$s=q.object({action:q.enum(["pin","unpin"]),expired:q.enum(["24h","7d","30d"])}),qs=Os.pick({roomId:!0}),zs=q.object({name:q.string(),answers:q.string().array(),multipleAnswers:q.boolean().optional()}),Us=q.object({message:q.function().returns(q.record(q.string(),q.any()))}),Ds=q.string(),Vs=q.object({message:q.function().returns(q.record(q.string(),q.any()))}),Js=q.object({callId:q.string(),callerId:q.string()}),Ks=Os.pick({roomId:!0}),Gs=q.object({expired:q.enum(["remove","8h","7d"])}),Bs=q.string();q.object({type:q.enum(["group","user"]),id:q.string(),name:q.string(),bio:q.string(),avatar:q.string().url(),ephemeralDuration:q.number().optional(),isRestrict:q.boolean().optional(),isAnnounce:q.boolean().optional(),isCommunity:q.boolean().optional(),isCommunityAnnounce:q.boolean().optional(),isJoinApprovalMode:q.boolean().optional(),isMemberAddMode:q.boolean().optional(),owner:q.object({type:q.literal("user"),id:q.string()}).nullable(),roomCreatedAt:q.number().optional(),nameUpdatedAt:q.number().optional(),bioUpdatedAt:q.number().optional(),membersLength:q.number().optional(),members:q.object({type:q.enum(["user","admin","superadmin"]),id:q.string()}).array().optional()});var Ws=Os.pick({roomId:!0}),Ys=q.enum(["typing","recording","online","offline","paused"]),Hs=class{constructor(e){this.wa=e,this.parser=new vs(e.socket,e.client,e.db)}parser;caching=new h({stdTTL:600,checkperiod:120,maxKeys:1e3});async sendMessage(e,t,s){let a=[];this.wa.client.options?.autoMentions&&(a=((e="")=>{if(!e)return[];const t=new Set;for(const s of e.matchAll(/@(\d+)/g))t.add(s[1]);return[...t].flatMap((e=>[`${e}@s.whatsapp.net`,`${e}@g.us`]))})(t?.text||t?.caption)),this.wa.client.options?.autoPresence&&this.wa.socket?.sendPresenceUpdate("composing",e),this.wa.client.options?.autoPresence&&(t?.audio||t?.audioNote)&&this.wa.socket?.sendPresenceUpdate("recording",e);const n=t,i={contextInfo:{isForwarded:!!n?.asForwarded}};if("function"==typeof n?.quoted){let t=n?.quoted();t.key.remoteJid=ms[n?.verifiedReply]||t.key.remoteJid;const r=await(this.wa.socket?.sendMessage(e,{...n,mentions:a,...i},{quoted:t,...s}));return await this.parser.messages(r)}{const t=await(this.wa.socket?.sendMessage(e,{...n,mentions:a,...i},s));return await this.parser.messages(t)}}async text(e,t){if(e=As.parse(e),t=Os.parse(t),"string"==typeof e)return await this.sendMessage(t.roomId,{text:e,...t});if("object"==typeof e){const s=Object.keys(e),a=e;if(s.includes("image")){const e="string"==typeof a.image?{url:a.image}:a.image;return await this.sendMessage(t.roomId,{caption:a?.text,image:e,viewOnce:!!t.asViewOnce,...t})}if(s.includes("video")){const e="string"==typeof a.video?{url:a.video}:a.video;return await this.sendMessage(t.roomId,{caption:a?.text,video:e,ptv:!1,viewOnce:!!t.asViewOnce,...t})}if(s.includes("videoNote")){const e="string"==typeof a.videoNote?{url:a.videoNote}:a.videoNote;return await this.sendMessage(t.roomId,{caption:a?.text,video:e,ptv:!0,...t})}if(s.includes("gif")){const e="string"==typeof a.gif?{url:a.gif}:a.gif;return await this.sendMessage(t.roomId,{caption:a?.text,video:e,gifPlayback:!0,viewOnce:!!t.asViewOnce,...t})}if(s.includes("audio")){const e="string"==typeof a.audio?{url:a.audio}:a.audio;return await this.sendMessage(t.roomId,{caption:a?.text,audio:e,viewOnce:!!t.asViewOnce,...t})}if(s.includes("audioNote")){const e="string"==typeof a.audioNote?{url:a.audioNote}:a.audioNote;return await this.sendMessage(t.roomId,{caption:a?.text,audio:e,ptt:!0,viewOnce:!!t.asViewOnce,...t})}if(s.includes("sticker")){const e="string"==typeof a.sticker?{url:a.sticker}:a.sticker;return await this.sendMessage(t.roomId,{caption:a?.text,sticker:e,...t})}}}async location(e,t){return e=Zs.parse(e),t=Es.parse(t),await this.sendMessage(t.roomId,{location:{degreesLatitude:e.latitude,degreesLongitude:e.longitude,url:e.title,address:e.footer,name:e.title},...t})}async contact(e,t){e=js.parse(e),t=Ls.parse(t);const s=["BEGIN:VCARD","VERSION:3.0",`N:;${e.fullname};;;`,`FN:${e.fullname}`,e.nickname?`NICKNAME:${e.nickname}`:"",e.organization||e.role?`ORG:${e.organization??""};`:"",e.role?`TITLE:${e.role}`:"",`TEL;TYPE=CELL,VOICE;waid=${e.whatsAppNumber}:+${e.whatsAppNumber}`,e.callNumber?`TEL;TYPE=WORK,VOICE:+${e.callNumber}`:"",e.voiceNumber?`TEL;TYPE=VOICE:+${e.voiceNumber}`:"",e.email?`EMAIL;TYPE=INTERNET:${e.email}`:"",e.website?`URL;TYPE=WORK:${e.website}`:"",e.homeAddress?`ADR;TYPE=HOME:;;${e.homeAddress};;;;`:"",e.workAddress?`ADR;TYPE=WORK:;;${e.workAddress};;;;`:"",e.avatar?`PHOTO;VALUE=URI;TYPE=JPEG:${e.avatar}`:"","END:VCARD"].join("\n");return await this.sendMessage(t.roomId,{contacts:{displayName:e.fullname,contacts:[{vcard:s}]},...t})}async reaction(e,t){return e=Rs.parse(e),t=Ps.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{react:{text:e,key:t.message()?.key},...t})}async pin(e,t){e=$s.parse(e),t=Fs.parse(t);return await this.sendMessage(t.message()?.key?.remoteJid,{pin:{type:"pin"==e.action?1:0,time:{"24h":86400,"7d":604800,"30d":2592e3}[e.expired],key:t.message()?.key},...t})}async poll(e,t){return e=zs.parse(e),t=qs.parse(t),await this.sendMessage(t.roomId,{poll:{name:e.name,values:e.answers,selectableCount:e.multipleAnswers?1:0,toAnnouncementGroup:!0},...t})}async edit(e,t){return e=Ds.parse(e),t=Us.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{text:e,edit:t.message()?.key,...t})}async delete(e){return e=Vs.parse(e),await this.sendMessage(e.message()?.key?.remoteJid,{delete:e.message()?.key})}async rejectCall(e){return e=Js.parse(e),await(this.wa.socket?.rejectCall(e.callId,e.callerId))}async mute(e,t){e=Gs.parse(e),t=Ks.parse(t);return await(this.wa.socket?.chatModify({mute:{remove:null,"8h":864e5,"7d":6048e5}[e.expired]},t.roomId))}async profile(e){const t=(e=Bs.parse(e)).includes("@g.us"),s={};s.id=e;if(i(this.wa.socket?.user?.id)==e)s.name=this.wa.socket?.user?.name||this.wa.socket?.user?.verifiedName;else if(t){const t=await(this.wa.socket?.groupMetadata(e));s.type="group",s.name=t?.subject,s.bio=t?.desc,s.avatar=await(this.wa.socket?.profilePictureUrl(e)),s.ephemeralDuration=t?.ephemeralDuration,s.isRestrict=t?.restrict,s.isAnnounce=t?.announce,s.isCommunity=t?.isCommunity,s.isCommunityAnnounce=t?.isCommunityAnnounce,s.isJoinApprovalMode=t?.joinApprovalMode,s.isMemberAddMode=t?.memberAddMode,s.owner={type:"user",id:t?.owner},s.roomCreatedAt=t?.creation,s.nameUpdatedAt=t?.subjectTime,s.membersLength=t?.size,s.members=t?.participants.map((e=>({id:e.id,type:"admin"==e.admin||"superadmin"==e.admin?e.admin:"user"})))}else{const t=await(this.wa.db?.selectFrom("chats").select("value").where("id","=",e).executeTakeFirst()),a=j(t?.value),n=(await(this.wa?.socket?.fetchStatus(e)))[0]?.status;s.type="user",s.name=a?.name,s.bio=n?.status,s.avatar=await(this.wa?.socket?.profilePictureUrl(e)),s.bioUpdatedAt=new Date(n?.setAt).getTime()}return s}async presence(e,t){e=Ys.parse(e),t=Ws.parse(t);return await(this.wa.socket?.sendPresenceUpdate({typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"}[e],t.roomId))}async addCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=Ms.parse(e);if(!await(this.wa.db?.insertInto("llm_messages").values(e).executeTakeFirst()))throw new Error("Failed to add completion");return e}async deleteCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_messages").where("uniqueId","=",e).executeTakeFirst()))throw new Error("Failed to delete completion");return!0}async updateCompletion(e,t){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const s=Ms.partial().parse(t),a=await(this.wa.db?.updateTable("llm_messages").set(s).where("uniqueId","=",e).returningAll().executeTakeFirst());if(!a)throw new Error("Failed to update completion");return Ms.parse(a)}async clearCompletions(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_messages").where("channelId","=",e).executeTakeFirst()))throw new Error("Failed to clear completions");return!0}async getCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_messages").selectAll().where("uniqueId","=",e).executeTakeFirst());return t?Ms.parse(t):null}async getCompletions(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_messages").selectAll().where("channelId","=",e).execute());return t?.map((e=>Ms.parse(e)))||[]}async addPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=Ts.parse(e);if(!await(this.wa.db?.insertInto("llm_personalization").values(e).executeTakeFirst()))throw new Error("Failed to add completion");return e}async deletePersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_personalization").where("uniqueId","=",e).executeTakeFirst()))throw new Error("Failed to delete completion");return!0}async clearPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_personalization").where("senderId","=",e).executeTakeFirst()))throw new Error("Failed to clear completions");return!0}async getPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_personalization").selectAll().where("senderId","=",e).execute());return t?.map((e=>Ts.parse(e)))||[]}async addRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=Ss.parse(e);if(!await(this.wa.db?.insertInto("llm_rag").values({pageContent:e.pageContent.toLowerCase(),"metadata.id":e.metadata?.id}).executeTakeFirst()))throw new Error("Failed to add RAG");return e}async deleteRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_rag").where(k`"metadata.id"`,"=",e).executeTakeFirst()))throw new Error("Failed to delete RAG");return!0}async updateRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.updateTable("llm_rag").set({metadata:{id:e}}).where(k`"metadata.id"`,"=",e).returningAll().executeTakeFirst());if(!t)throw new Error("Failed to update RAG");return Ss.parse(t)}async clearRAGs(){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_rag").executeTakeFirst()))throw new Error("Failed to clear RAGs");return!0}async getRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_rag").selectAll().where(k`"metadata.id"`,"=",e).executeTakeFirst());return t?Ss.parse(t):null}async getRAGs(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas not loaded");const t=e.toLowerCase().trim(),s=this.caching.get(t);if(s)return s;const a=t.split(/\s+/).filter((e=>e.length>0));if(!a.length)return[];const n=await(this.wa.db?.selectFrom("llm_rag").select([k`"metadata.id"`.as("metadata.id"),"pageContent"]).where("pageContent","!=","").limit(1e4).execute().then((e=>e.map((e=>Ss.parse({...e,metadata:{id:e["metadata.id"]}}))))).then((e=>e.filter((e=>{const t=e.pageContent.toLowerCase().split(/\s+/);return a.some((e=>t.some((t=>A.get(e,t)<=Math.max(1,Math.floor(e.length/4))))))})))));return this.caching.set(t,n),n||[]}llms={addCompletion:this.addCompletion.bind(this),deleteCompletion:this.deleteCompletion.bind(this),updateCompletion:this.updateCompletion.bind(this),clearCompletions:this.clearCompletions.bind(this),getCompletion:this.getCompletion.bind(this),getCompletions:this.getCompletions.bind(this),addPersonalization:this.addPersonalization.bind(this),deletePersonalization:this.deletePersonalization.bind(this),clearPersonalization:this.clearPersonalization.bind(this),getPersonalization:this.getPersonalization.bind(this),addRAG:this.addRAG.bind(this),deleteRAG:this.deleteRAG.bind(this),updateRAG:this.updateRAG.bind(this),clearRAGs:this.clearRAGs.bind(this),getRAG:this.getRAG.bind(this),getRAGs:this.getRAGs.bind(this)}},Qs=class{constructor(e){return this.props=e,this.initialize(),this.worker,new Proxy(this,{get:(e,t)=>t in e?e[t]:e.worker[t]})}options={};cache=new h({stdTTL:300,useClones:!1});chatId="zaileys-chats";logger=f({level:"silent",enabled:!1});db;socket;events=new u;spinners=new Map;worker;async initialize(){console.clear(),await((e="ZAILEYS")=>new Promise((t=>{p(e,((e,s)=>{if(e)return t("");console.log(s),t(s||"")}))})))(),this.options=await Is.parseAsync(this.props),this.startSpinner("db","Initializing database..."),this.db=await(e=>{const{type:t,connection:s}=e.database;if("sqlite"===t){const e=s.url||"./db/zaileys.db",t=I.resolve(e);return y(I.dirname(t),{recursive:!0}),v(t,"",{flag:"a"}),new _({dialect:new w({database:new g(t)})})}const a=new T(s.url),n=a.protocol.replace(":","");if("mysql"===t)return new _({dialect:new b({pool:C.createPool({host:a.hostname,user:a.username,password:a.password,database:a.pathname.replace("/",""),port:parseInt(a.port||"3306",10)})})});if("postgresql"===t)return new _({dialect:new x({pool:new M({host:a.hostname,user:a.username,password:a.password,database:a.pathname.replace("/",""),port:parseInt(a.port||"5432",10)})})});throw new Error(`Unsupported database protocol: ${n}`)})(this.options),this.stopSpinner("db",!0,"Database initialized"),this.startSpinner("auth","Setting up auth adapter...");const{state:n,saveCreds:i}=await _s(this.db,this.chatId,this.options);this.stopSpinner("auth",!0,"Auth adapter ready"),this.startSpinner("store","Setting up store adapter...");const r=await(async(e,t,s)=>({bind:a=>{const n=new vs(a,e,t);a?.ev.on("connection.update",(async e=>{await n.connection(e)})),a?.ev.on("call",(async e=>{for(const t of e)await n.calls(t)})),a?.ev.on("messaging-history.set",(async e=>{const{chats:a,contacts:n,messages:i}=e;for(const e of a)await t.insertInto("chats").values({session:s,id:e.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute();for(const e of n)await t.insertInto("contacts").values({session:s,id:e.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute();for(const e of i){if(!e.message)return;if(e.message?.protocolMessage)return;await t.insertInto("messages").values({session:s,id:e.key.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute()}})),a?.ev.on("messages.upsert",(async({messages:e})=>{for(const a of e){if(!a.message)return;if(a.message?.protocolMessage)return;await n.messages(a),await t.insertInto("messages").values({session:s,id:a.key.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute()}})),a?.ev.on("chats.upsert",(async e=>{for(const a of e)await t.insertInto("chats").values({session:s,id:a.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute()})),a?.ev.on("contacts.upsert",(async e=>{for(const a of e)await t.insertInto("contacts").values({session:s,id:a.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute()})),a?.ev.on("groups.update",(async([t])=>{const s=await(a?.groupMetadata(t.id));e.cache.set(t.id,s)})),a?.ev.on("group-participants.update",(async t=>{const s=await(a?.groupMetadata(t.id));e.cache.set(t.id,s)}))}}))(this,this.db,this.chatId);this.stopSpinner("store",!0,"Store adapter ready");const{version:o}=await e();if(this.socket=t({version:o,logger:this.logger,markOnlineOnConnect:this.options.autoOnline,syncFullHistory:!1,defaultQueryTimeoutMs:void 0,msgRetryCounterCache:new h,mediaCache:new h({stdTTL:60}),userDevicesCache:new h,cachedGroupMetadata:async e=>this.cache.get(e),printQRInTerminal:!1,browser:a.ubuntu("qr"===this.options.authType?"Zaileys Library":"Chrome"),auth:{creds:n.creds,keys:s(n.keys,this.logger)},getMessage:async e=>{const t=await(this.db?.selectFrom("messages").select("value").where("id","=",e.id).executeTakeFirst());return j(t?.value)}}),"pairing"===this.options.authType&&this.options.phoneNumber&&!this.socket?.authState.creds.registered){this.startSpinner("pairing","Generating pairing code...");(await this.socket.onWhatsApp(this.options.phoneNumber.toString()+"@s.whatsapp.net"))[0].exists||(this.failSpinner("pairing","Phone is not registered on WhatsApp"),process.exit(1)),setTimeout((async()=>{try{if("pairing"===this.options?.authType){const e=await(this.socket?.requestPairingCode(this.options.phoneNumber.toString()));this.stopSpinner("pairing",!0,`Pairing code: ${e}`)}}catch{this.failSpinner("pairing","Connection failed"),process.exit(1)}}),5e3)}this.worker=new Hs({client:this,db:this.db,socket:this.socket}),this.socket?.ev.on("creds.update",i),r.bind(this.socket)}startSpinner(e,t){let s=this.spinners.get(e);return s||(s=m(t).start(),this.spinners.set(e,s)),s}stopSpinner(e,t,s){const a=this.spinners.get(e);a&&(t?a.succeed(s):a.stop(),this.spinners.delete(e))}failSpinner(e,t){const s=this.spinners.get(e);s&&(s.fail(t),this.spinners.delete(e))}on(e,t){this.events.on(e,t)}emit(e,...t){this.events.emit(e,...t)}};export{Qs as Client};
|
|
1
|
+
import{fetchLatestBaileysVersion as e,makeWASocket as t,makeCacheableSignalKeyStore as s,Browsers as a,initAuthCreds as n,jidNormalizedUser as i,BufferJSON as r,DisconnectReason as o,getContentType as d,getDevice as c,downloadMediaMessage as l}from"baileys";import{EventEmitter as u}from"events";import p from"figlet";import h from"node-cache";import m from"ora";import f from"pino";import g from"better-sqlite3";import{mkdirSync as y,writeFileSync as v}from"fs";import{Kysely as _,SqliteDialect as w,MysqlDialect as b,PostgresDialect as x,sql as k}from"kysely";import C from"mysql2";import I from"path";import{Pool as M}from"pg";import{URL as T}from"url";import N from"qrcode";import{Readable as S}from"stream";import*as A from"fast-levenshtein";var O,E,Z,L=Object.defineProperty,P=(e="")=>{try{return JSON.parse(e)}catch{return JSON.parse(JSON.stringify(e))}},j=(e={})=>{try{return JSON.stringify(e)}catch{return JSON.stringify(JSON.parse(JSON.stringify(e)))}},R=(e="",t="")=>e?e.toLowerCase().includes(t.toLowerCase()):null,F=(e,t)=>e&&"object"==typeof e?Array.isArray(e)?e.map((e=>F(e,t))):Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e))).map((([e,s])=>[e,"object"==typeof s?F(s,t):s]))):e,$=e=>{const t={...e.fingerprint,deviceIndexes:Array.isArray(e.fingerprint.deviceIndexes)?e.fingerprint.deviceIndexes:[]},s={keyData:Array.isArray(e.keyData)?e.keyData:new Uint8Array,fingerprint:{rawId:t.rawId||0,currentIndex:t.rawId||0,deviceIndexes:t.deviceIndexes},timestamp:(a=e.timestamp,"string"==typeof a?parseInt(a,10):a)};var a;return"string"==typeof e.keyData&&(s.keyData=(e=>{let t=e.length;if(!t)return new Uint8Array(1);let s=0;for(;--t%4>1&&"="===e.charAt(t);)++s;return new Uint8Array(Math.ceil(3*e.length)/4-s).fill(0)})(e.keyData)),s},q={};((e,t)=>{for(var s in t)L(e,s,{get:t[s],enumerable:!0})})(q,{BRAND:()=>vt,DIRTY:()=>ae,EMPTY_PATH:()=>H,INVALID:()=>se,NEVER:()=>ps,OK:()=>ne,ParseStatus:()=>te,Schema:()=>he,ZodAny:()=>De,ZodArray:()=>Ge,ZodBigInt:()=>Re,ZodBoolean:()=>Fe,ZodBranded:()=>_t,ZodCatch:()=>gt,ZodDate:()=>$e,ZodDefault:()=>ft,ZodDiscriminatedUnion:()=>Qe,ZodEffects:()=>pt,ZodEnum:()=>ct,ZodError:()=>J,ZodFirstPartyTypeKind:()=>Ct,ZodFunction:()=>it,ZodIntersection:()=>et,ZodIssueCode:()=>D,ZodLazy:()=>rt,ZodLiteral:()=>ot,ZodMap:()=>at,ZodNaN:()=>yt,ZodNativeEnum:()=>lt,ZodNever:()=>Je,ZodNull:()=>Ue,ZodNullable:()=>mt,ZodNumber:()=>je,ZodObject:()=>We,ZodOptional:()=>ht,ZodParsedType:()=>z,ZodPipeline:()=>wt,ZodPromise:()=>ut,ZodReadonly:()=>bt,ZodRecord:()=>st,ZodSchema:()=>he,ZodSet:()=>nt,ZodString:()=>Le,ZodSymbol:()=>qe,ZodTransformer:()=>pt,ZodTuple:()=>tt,ZodType:()=>he,ZodUndefined:()=>ze,ZodUnion:()=>Ye,ZodUnknown:()=>Ve,ZodVoid:()=>Ke,addIssueToContext:()=>Q,any:()=>Rt,array:()=>zt,bigint:()=>Ot,boolean:()=>Et,coerce:()=>us,custom:()=>kt,date:()=>Zt,datetimeRegex:()=>Oe,defaultErrorMap:()=>K,discriminatedUnion:()=>Jt,effect:()=>as,enum:()=>es,function:()=>Ht,getErrorMap:()=>W,getParsedType:()=>U,instanceof:()=>Tt,intersection:()=>Kt,isAborted:()=>ie,isAsync:()=>de,isDirty:()=>re,isValid:()=>oe,late:()=>Mt,lazy:()=>Qt,literal:()=>Xt,makeIssue:()=>Y,map:()=>Wt,nan:()=>At,nativeEnum:()=>ts,never:()=>$t,null:()=>jt,nullable:()=>is,number:()=>St,object:()=>Ut,objectUtil:()=>Z,oboolean:()=>ls,onumber:()=>cs,optional:()=>ns,ostring:()=>ds,pipeline:()=>os,preprocess:()=>rs,promise:()=>ss,quotelessJson:()=>V,record:()=>Bt,set:()=>Yt,setErrorMap:()=>B,strictObject:()=>Dt,string:()=>Nt,symbol:()=>Lt,transformer:()=>as,tuple:()=>Gt,undefined:()=>Pt,union:()=>Vt,unknown:()=>Ft,util:()=>O,void:()=>qt}),(E=O||(O={})).assertEqual=e=>{},E.assertIs=function(e){},E.assertNever=function(e){throw new Error},E.arrayToEnum=e=>{const t={};for(const s of e)t[s]=s;return t},E.getValidEnumValues=e=>{const t=E.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),s={};for(const a of t)s[a]=e[a];return E.objectValues(s)},E.objectValues=e=>E.objectKeys(e).map((function(t){return e[t]})),E.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.push(s);return t},E.find=(e,t)=>{for(const s of e)if(t(s))return s},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,(Z||(Z={})).mergeShapes=(e,t)=>({...e,...t});var z=O.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),U=e=>{switch(typeof e){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(e)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(e)?z.array:null===e?z.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?z.promise:"undefined"!=typeof Map&&e instanceof Map?z.map:"undefined"!=typeof Set&&e instanceof Set?z.set:"undefined"!=typeof Date&&e instanceof Date?z.date:z.object;default:return z.unknown}},D=O.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"]),V=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),J=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};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},s={_errors:[]},a=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(a);else if("invalid_return_type"===n.code)a(n.returnTypeError);else if("invalid_arguments"===n.code)a(n.argumentsError);else if(0===n.path.length)s._errors.push(t(n));else{let e=s,a=0;for(;a<n.path.length;){const s=n.path[a];a===n.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(n))):e[s]=e[s]||{_errors:[]},e=e[s],a++}}};return a(this),s}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,O.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},s=[];for(const a of this.issues)a.path.length>0?(t[a.path[0]]=t[a.path[0]]||[],t[a.path[0]].push(e(a))):s.push(e(a));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};J.create=e=>new J(e);var K=(e,t)=>{let s;switch(e.code){case D.invalid_type:s=e.received===z.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case D.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,O.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:s=`Unrecognized key(s) in object: ${O.joinValues(e.keys,", ")}`;break;case D.invalid_union:s="Invalid input";break;case D.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${O.joinValues(e.options)}`;break;case D.invalid_enum_value:s=`Invalid enum value. Expected ${O.joinValues(e.options)}, received '${e.received}'`;break;case D.invalid_arguments:s="Invalid function arguments";break;case D.invalid_return_type:s="Invalid function return type";break;case D.invalid_date:s="Invalid date";break;case D.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:O.assertNever(e.validation):s="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case D.too_small:s="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?`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 D.too_big:s="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 D.custom:s="Invalid input";break;case D.invalid_intersection_types:s="Intersection results could not be merged";break;case D.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case D.not_finite:s="Number must be finite";break;default:s=t.defaultError,O.assertNever(e)}return{message:s}},G=K;function B(e){G=e}function W(){return G}var Y=e=>{const{data:t,path:s,errorMaps:a,issueData:n}=e,i=[...s,...n.path||[]],r={...n,path:i};if(void 0!==n.message)return{...n,path:i,message:n.message};let o="";const d=a.filter((e=>!!e)).slice().reverse();for(const e of d)o=e(r,{data:t,defaultError:o}).message;return{...n,path:i,message:o}},H=[];function Q(e,t){const s=W(),a=Y({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===K?void 0:K].filter((e=>!!e))});e.common.issues.push(a)}var X,ee,te=class e{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const a of t){if("aborted"===a.status)return se;"dirty"===a.status&&e.dirty(),s.push(a.value)}return{status:e.value,value:s}}static async mergeObjectAsync(t,s){const a=[];for(const e of s){const t=await e.key,s=await e.value;a.push({key:t,value:s})}return e.mergeObjectSync(t,a)}static mergeObjectSync(e,t){const s={};for(const a of t){const{key:t,value:n}=a;if("aborted"===t.status)return se;if("aborted"===n.status)return se;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!a.alwaysSet||(s[t.value]=n.value)}return{status:e.value,value:s}}},se=Object.freeze({status:"aborted"}),ae=e=>({status:"dirty",value:e}),ne=e=>({status:"valid",value:e}),ie=e=>"aborted"===e.status,re=e=>"dirty"===e.status,oe=e=>"valid"===e.status,de=e=>"undefined"!=typeof Promise&&e instanceof Promise;(ee=X||(X={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},ee.toString=e=>"string"==typeof e?e:e?.message;var ce=class{constructor(e,t,s,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},le=(e,t)=>{if(oe(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._error)return this._error;const t=new J(e.common.issues);return this._error=t,this._error}}};function ue(e){if(!e)return{};const{errorMap:t,invalid_type_error:s,required_error:a,description:n}=e;if(t&&(s||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(t,n)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??n.defaultError}:void 0===n.data?{message:i??a??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:i??s??n.defaultError}},description:n}}var pe,he=class{get description(){return this._def.description}_getType(e){return U(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:U(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new te,ctx:{common:e.parent.common,data:e.data,parsedType:U(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(de(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:U(e)},a=this._parseSync({data:e,path:s.path,parent:s});return le(s,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:U(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return oe(s)?{value:s.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((e=>oe(e)?{value:e.value}:{issues:t.common.issues}))}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:U(e)},a=this._parse({data:e,path:s.path,parent:s}),n=await(de(a)?a:Promise.resolve(a));return le(s,n)}refine(e,t){const s=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,a)=>{const n=e(t),i=()=>a.addIssue({code:D.custom,...s(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then((e=>!!e||(i(),!1))):!!n||(i(),!1)}))}refinement(e,t){return this._refinement(((s,a)=>!!e(s)||(a.addIssue("function"==typeof t?t(s,a):t),!1)))}_refinement(e){return new pt({schema:this,typeName:Ct.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return ht.create(this,this._def)}nullable(){return mt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ge.create(this)}promise(){return ut.create(this,this._def)}or(e){return Ye.create([this,e],this._def)}and(e){return et.create(this,e,this._def)}transform(e){return new pt({...ue(this._def),schema:this,typeName:Ct.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ft({...ue(this._def),innerType:this,defaultValue:t,typeName:Ct.ZodDefault})}brand(){return new _t({typeName:Ct.ZodBranded,type:this,...ue(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new gt({...ue(this._def),innerType:this,catchValue:t,typeName:Ct.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return wt.create(this,e)}readonly(){return bt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},me=/^c[^\s-]{8,}$/i,fe=/^[0-9a-z]+$/,ge=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ye=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ve=/^[a-z0-9_-]{21}$/i,_e=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,we=/^[-+]?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)?)??$/,be=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xe=/^(?:(?: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])$/,ke=/^(?:(?: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])$/,Ce=/^(([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]))$/,Ie=/^(([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])$/,Me=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Te=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ne="((\\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])))",Se=new RegExp(`^${Ne}$`);function Ae(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 Oe(e){let t=`${Ne}T${Ae(e)}`;const s=[];return s.push(e.local?"Z?":"Z"),e.offset&&s.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${s.join("|")})`,new RegExp(`^${t}$`)}function Ee(e,t){if(!_e.test(e))return!1;try{const[s]=e.split("."),a=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),n=JSON.parse(atob(a));return"object"==typeof n&&null!==n&&((!("typ"in n)||"JWT"===n?.typ)&&(!!n.alg&&(!t||n.alg===t)))}catch{return!1}}function Ze(e,t){return!("v4"!==t&&t||!ke.test(e))||!("v6"!==t&&t||!Ie.test(e))}var Le=class e extends he{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==z.string){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.string,received:t.parsedType}),se}const t=new te;let s;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),Q(s,{code:D.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("max"===i.kind)e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),Q(s,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("length"===i.kind){const a=e.data.length>i.value,n=e.data.length<i.value;(a||n)&&(s=this._getOrReturnCtx(e,s),a?Q(s,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&Q(s,{code:D.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)be.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"email",code:D.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)pe||(pe=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),pe.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"emoji",code:D.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)ye.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"uuid",code:D.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)ve.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"nanoid",code:D.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)me.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"cuid",code:D.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)fe.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"cuid2",code:D.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)ge.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"ulid",code:D.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),Q(s,{validation:"url",code:D.invalid_string,message:i.message}),t.dirty()}else if("regex"===i.kind){i.regex.lastIndex=0;i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"regex",code:D.invalid_string,message:i.message}),t.dirty())}else if("trim"===i.kind)e.data=e.data.trim();else if("includes"===i.kind)e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),Q(s,{code:D.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),t.dirty());else if("toLowerCase"===i.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===i.kind)e.data=e.data.toUpperCase();else if("startsWith"===i.kind)e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),Q(s,{code:D.invalid_string,validation:{startsWith:i.value},message:i.message}),t.dirty());else if("endsWith"===i.kind)e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),Q(s,{code:D.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){Oe(i).test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{code:D.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){Se.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{code:D.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${Ae(i)}$`).test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{code:D.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?we.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"duration",code:D.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(a=e.data,("v4"!==(n=i.version)&&n||!xe.test(a))&&("v6"!==n&&n||!Ce.test(a))&&(s=this._getOrReturnCtx(e,s),Q(s,{validation:"ip",code:D.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?Ee(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"jwt",code:D.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?Ze(e.data,i.version)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"cidr",code:D.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?Me.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"base64",code:D.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?Te.test(e.data)||(s=this._getOrReturnCtx(e,s),Q(s,{validation:"base64url",code:D.invalid_string,message:i.message}),t.dirty()):O.assertNever(i);var a,n;return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement((t=>e.test(t)),{validation:t,code:D.invalid_string,...X.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...X.errToObj(e)})}url(e){return this._addCheck({kind:"url",...X.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...X.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...X.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...X.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...X.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...X.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...X.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...X.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...X.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...X.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...X.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...X.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...X.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...X.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...X.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...X.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...X.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...X.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...X.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...X.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...X.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...X.errToObj(t)})}nonempty(e){return this.min(1,X.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};function Pe(e,t){const s=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,n=s>a?s:a;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}Le.create=e=>new Le({checks:[],typeName:Ct.ZodString,coerce:e?.coerce??!1,...ue(e)});var je=class e extends he{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==z.number){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.number,received:t.parsedType}),se}let t;const s=new te;for(const a of this._def.checks)if("int"===a.kind)O.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),Q(t,{code:D.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty());else if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),Q(t,{code:D.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),Q(t,{code:D.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty())}else"multipleOf"===a.kind?0!==Pe(e.data,a.value)&&(t=this._getOrReturnCtx(e,t),Q(t,{code:D.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),Q(t,{code:D.not_finite,message:a.message}),s.dirty()):O.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,X.toString(t))}gt(e,t){return this.setLimit("min",e,!1,X.toString(t))}lte(e,t){return this.setLimit("max",e,!0,X.toString(t))}lt(e,t){return this.setLimit("max",e,!1,X.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:X.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:X.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:X.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:X.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&O.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if("finite"===s.kind||"int"===s.kind||"multipleOf"===s.kind)return!0;"min"===s.kind?(null===t||s.value>t)&&(t=s.value):"max"===s.kind&&(null===e||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}};je.create=e=>new je({checks:[],typeName:Ct.ZodNumber,coerce:e?.coerce||!1,...ue(e)});var Re=class e extends he{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let t;const s=new te;for(const a of this._def.checks)if("min"===a.kind){(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),Q(t,{code:D.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty())}else if("max"===a.kind){(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),Q(t,{code:D.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty())}else"multipleOf"===a.kind?e.data%a.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),Q(t,{code:D.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):O.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.bigint,received:t.parsedType}),se}gte(e,t){return this.setLimit("min",e,!0,X.toString(t))}gt(e,t){return this.setLimit("min",e,!1,X.toString(t))}lte(e,t){return this.setLimit("max",e,!0,X.toString(t))}lt(e,t){return this.setLimit("max",e,!1,X.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:X.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:X.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:X.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}};Re.create=e=>new Re({checks:[],typeName:Ct.ZodBigInt,coerce:e?.coerce??!1,...ue(e)});var Fe=class extends he{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==z.boolean){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.boolean,received:t.parsedType}),se}return ne(e.data)}};Fe.create=e=>new Fe({typeName:Ct.ZodBoolean,coerce:e?.coerce||!1,...ue(e)});var $e=class e extends he{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==z.date){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.date,received:t.parsedType}),se}if(Number.isNaN(e.data.getTime())){return Q(this._getOrReturnCtx(e),{code:D.invalid_date}),se}const t=new te;let s;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),Q(s,{code:D.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),t.dirty()):"max"===a.kind?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),Q(s,{code:D.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):O.assertNever(a);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:X.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:X.toString(t)})}get minDate(){let e=null;for(const t of this._def.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._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}};$e.create=e=>new $e({checks:[],coerce:e?.coerce||!1,typeName:Ct.ZodDate,...ue(e)});var qe=class extends he{_parse(e){if(this._getType(e)!==z.symbol){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.symbol,received:t.parsedType}),se}return ne(e.data)}};qe.create=e=>new qe({typeName:Ct.ZodSymbol,...ue(e)});var ze=class extends he{_parse(e){if(this._getType(e)!==z.undefined){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.undefined,received:t.parsedType}),se}return ne(e.data)}};ze.create=e=>new ze({typeName:Ct.ZodUndefined,...ue(e)});var Ue=class extends he{_parse(e){if(this._getType(e)!==z.null){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.null,received:t.parsedType}),se}return ne(e.data)}};Ue.create=e=>new Ue({typeName:Ct.ZodNull,...ue(e)});var De=class extends he{constructor(){super(...arguments),this._any=!0}_parse(e){return ne(e.data)}};De.create=e=>new De({typeName:Ct.ZodAny,...ue(e)});var Ve=class extends he{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ne(e.data)}};Ve.create=e=>new Ve({typeName:Ct.ZodUnknown,...ue(e)});var Je=class extends he{_parse(e){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.never,received:t.parsedType}),se}};Je.create=e=>new Je({typeName:Ct.ZodNever,...ue(e)});var Ke=class extends he{_parse(e){if(this._getType(e)!==z.undefined){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.void,received:t.parsedType}),se}return ne(e.data)}};Ke.create=e=>new Ke({typeName:Ct.ZodVoid,...ue(e)});var Ge=class e extends he{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==z.array)return Q(t,{code:D.invalid_type,expected:z.array,received:t.parsedType}),se;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,n=t.data.length<a.exactLength.value;(e||n)&&(Q(t,{code:e?D.too_big:D.too_small,minimum:n?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),s.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(Q(t,{code:D.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),s.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(Q(t,{code:D.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map(((e,s)=>a.type._parseAsync(new ce(t,e,t.path,s))))).then((e=>te.mergeArray(s,e)));const n=[...t.data].map(((e,s)=>a.type._parseSync(new ce(t,e,t.path,s))));return te.mergeArray(s,n)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:X.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:X.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:X.toString(s)}})}nonempty(e){return this.min(1,e)}};function Be(e){if(e instanceof We){const t={};for(const s in e.shape){const a=e.shape[s];t[s]=ht.create(Be(a))}return new We({...e._def,shape:()=>t})}return e instanceof Ge?new Ge({...e._def,type:Be(e.element)}):e instanceof ht?ht.create(Be(e.unwrap())):e instanceof mt?mt.create(Be(e.unwrap())):e instanceof tt?tt.create(e.items.map((e=>Be(e)))):e}Ge.create=(e,t)=>new Ge({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ct.ZodArray,...ue(t)});var We=class e extends he{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=O.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==z.object){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.object,received:t.parsedType}),se}const{status:t,ctx:s}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof Je&&"strip"===this._def.unknownKeys))for(const e in s.data)n.includes(e)||i.push(e);const r=[];for(const e of n){const t=a[e],n=s.data[e];r.push({key:{status:"valid",value:e},value:t._parse(new ce(s,n,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof Je){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)r.push({key:{status:"valid",value:e},value:{status:"valid",value:s.data[e]}});else if("strict"===e)i.length>0&&(Q(s,{code:D.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const a=s.data[t];r.push({key:{status:"valid",value:t},value:e._parse(new ce(s,a,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of r){const s=await t.key,a=await t.value;e.push({key:s,value:a,alwaysSet:t.alwaysSet})}return e})).then((e=>te.mergeObjectSync(t,e))):te.mergeObjectSync(t,r)}get shape(){return this._def.shape()}strict(t){return X.errToObj,new e({...this._def,unknownKeys:"strict",...void 0!==t?{errorMap:(e,s)=>{const a=this._def.errorMap?.(e,s).message??s.defaultError;return"unrecognized_keys"===e.code?{message:X.errToObj(t).message??a}:{message:a}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Ct.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){const s={};for(const e of O.objectKeys(t))t[e]&&this.shape[e]&&(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}omit(t){const s={};for(const e of O.objectKeys(this.shape))t[e]||(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}deepPartial(){return Be(this)}partial(t){const s={};for(const e of O.objectKeys(this.shape)){const a=this.shape[e];t&&!t[e]?s[e]=a:s[e]=a.optional()}return new e({...this._def,shape:()=>s})}required(t){const s={};for(const e of O.objectKeys(this.shape))if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof ht;)t=t._def.innerType;s[e]=t}return new e({...this._def,shape:()=>s})}keyof(){return dt(O.objectKeys(this.shape))}};We.create=(e,t)=>new We({shape:()=>e,unknownKeys:"strip",catchall:Je.create(),typeName:Ct.ZodObject,...ue(t)}),We.strictCreate=(e,t)=>new We({shape:()=>e,unknownKeys:"strict",catchall:Je.create(),typeName:Ct.ZodObject,...ue(t)}),We.lazycreate=(e,t)=>new We({shape:e,unknownKeys:"strip",catchall:Je.create(),typeName:Ct.ZodObject,...ue(t)});var Ye=class extends he{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;if(t.common.async)return Promise.all(s.map((async e=>{const s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const s of e)if("dirty"===s.result.status)return t.common.issues.push(...s.ctx.common.issues),s.result;const s=e.map((e=>new J(e.ctx.common.issues)));return Q(t,{code:D.invalid_union,unionErrors:s}),se}));{let e;const a=[];for(const n of s){const s={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:s});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:s}),s.common.issues.length&&a.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=a.map((e=>new J(e)));return Q(t,{code:D.invalid_union,unionErrors:n}),se}}get options(){return this._def.options}};Ye.create=(e,t)=>new Ye({options:e,typeName:Ct.ZodUnion,...ue(t)});var He=e=>e instanceof rt?He(e.schema):e instanceof pt?He(e.innerType()):e instanceof ot?[e.value]:e instanceof ct?e.options:e instanceof lt?O.objectValues(e.enum):e instanceof ft?He(e._def.innerType):e instanceof ze?[void 0]:e instanceof Ue?[null]:e instanceof ht?[void 0,...He(e.unwrap())]:e instanceof mt?[null,...He(e.unwrap())]:e instanceof _t||e instanceof bt?He(e.unwrap()):e instanceof gt?He(e._def.innerType):[],Qe=class e extends he{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.object)return Q(t,{code:D.invalid_type,expected:z.object,received:t.parsedType}),se;const s=this.discriminator,a=t.data[s],n=this.optionsMap.get(a);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(Q(t,{code:D.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),se)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,s,a){const n=new Map;for(const e of s){const s=He(e.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const a of s){if(n.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);n.set(a,e)}}return new e({typeName:Ct.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:n,...ue(a)})}};function Xe(e,t){const s=U(e),a=U(t);if(e===t)return{valid:!0,data:e};if(s===z.object&&a===z.object){const s=O.objectKeys(t),a=O.objectKeys(e).filter((e=>-1!==s.indexOf(e))),n={...e,...t};for(const s of a){const a=Xe(e[s],t[s]);if(!a.valid)return{valid:!1};n[s]=a.data}return{valid:!0,data:n}}if(s===z.array&&a===z.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let a=0;a<e.length;a++){const n=Xe(e[a],t[a]);if(!n.valid)return{valid:!1};s.push(n.data)}return{valid:!0,data:s}}return s===z.date&&a===z.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}var et=class extends he{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=(e,a)=>{if(ie(e)||ie(a))return se;const n=Xe(e.value,a.value);return n.valid?((re(e)||re(a))&&t.dirty(),{status:t.value,value:n.data}):(Q(s,{code:D.invalid_intersection_types}),se)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then((([e,t])=>a(e,t))):a(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}};et.create=(e,t,s)=>new et({left:e,right:t,typeName:Ct.ZodIntersection,...ue(s)});var tt=class e extends he{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==z.array)return Q(s,{code:D.invalid_type,expected:z.array,received:s.parsedType}),se;if(s.data.length<this._def.items.length)return Q(s,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),se;!this._def.rest&&s.data.length>this._def.items.length&&(Q(s,{code:D.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...s.data].map(((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new ce(s,e,s.path,t)):null})).filter((e=>!!e));return s.common.async?Promise.all(a).then((e=>te.mergeArray(t,e))):te.mergeArray(t,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};tt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new tt({items:e,typeName:Ct.ZodTuple,rest:null,...ue(t)})};var st=class e extends he{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==z.object)return Q(s,{code:D.invalid_type,expected:z.object,received:s.parsedType}),se;const a=[],n=this._def.keyType,i=this._def.valueType;for(const e in s.data)a.push({key:n._parse(new ce(s,e,s.path,e)),value:i._parse(new ce(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?te.mergeObjectAsync(t,a):te.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(t,s,a){return new e(s instanceof he?{keyType:t,valueType:s,typeName:Ct.ZodRecord,...ue(a)}:{keyType:Le.create(),valueType:t,typeName:Ct.ZodRecord,...ue(s)})}},at=class extends he{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==z.map)return Q(s,{code:D.invalid_type,expected:z.map,received:s.parsedType}),se;const a=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map((([e,t],i)=>({key:a._parse(new ce(s,e,s.path,[i,"key"])),value:n._parse(new ce(s,t,s.path,[i,"value"]))})));if(s.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const s of i){const a=await s.key,n=await s.value;if("aborted"===a.status||"aborted"===n.status)return se;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const s of i){const a=s.key,n=s.value;if("aborted"===a.status||"aborted"===n.status)return se;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}};at.create=(e,t,s)=>new at({valueType:t,keyType:e,typeName:Ct.ZodMap,...ue(s)});var nt=class e extends he{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==z.set)return Q(s,{code:D.invalid_type,expected:z.set,received:s.parsedType}),se;const a=this._def;null!==a.minSize&&s.data.size<a.minSize.value&&(Q(s,{code:D.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&s.data.size>a.maxSize.value&&(Q(s,{code:D.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const n=this._def.valueType;function i(e){const s=new Set;for(const a of e){if("aborted"===a.status)return se;"dirty"===a.status&&t.dirty(),s.add(a.value)}return{status:t.value,value:s}}const r=[...s.data.values()].map(((e,t)=>n._parse(new ce(s,e,s.path,t))));return s.common.async?Promise.all(r).then((e=>i(e))):i(r)}min(t,s){return new e({...this._def,minSize:{value:t,message:X.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:X.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};nt.create=(e,t)=>new nt({valueType:e,minSize:null,maxSize:null,typeName:Ct.ZodSet,...ue(t)});var it=class e extends he{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.function)return Q(t,{code:D.invalid_type,expected:z.function,received:t.parsedType}),se;function s(e,s){return Y({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,W(),K].filter((e=>!!e)),issueData:{code:D.invalid_arguments,argumentsError:s}})}function a(e,s){return Y({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,W(),K].filter((e=>!!e)),issueData:{code:D.invalid_return_type,returnTypeError:s}})}const n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof ut){const e=this;return ne((async function(...t){const r=new J([]),o=await e._def.args.parseAsync(t,n).catch((e=>{throw r.addIssue(s(t,e)),r})),d=await Reflect.apply(i,this,o);return await e._def.returns._def.type.parseAsync(d,n).catch((e=>{throw r.addIssue(a(d,e)),r}))}))}{const e=this;return ne((function(...t){const r=e._def.args.safeParse(t,n);if(!r.success)throw new J([s(t,r.error)]);const o=Reflect.apply(i,this,r.data),d=e._def.returns.safeParse(o,n);if(!d.success)throw new J([a(o,d.error)]);return d.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:tt.create(t).rest(Ve.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,s,a){return new e({args:t||tt.create([]).rest(Ve.create()),returns:s||Ve.create(),typeName:Ct.ZodFunction,...ue(a)})}},rt=class extends he{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};rt.create=(e,t)=>new rt({getter:e,typeName:Ct.ZodLazy,...ue(t)});var ot=class extends he{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return Q(t,{received:t.data,code:D.invalid_literal,expected:this._def.value}),se}return{status:"valid",value:e.data}}get value(){return this._def.value}};function dt(e,t){return new ct({values:e,typeName:Ct.ZodEnum,...ue(t)})}ot.create=(e,t)=>new ot({value:e,typeName:Ct.ZodLiteral,...ue(t)});var ct=class e extends he{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),s=this._def.values;return Q(t,{expected:O.joinValues(s),received:t.parsedType,code:D.invalid_type}),se}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return Q(t,{received:t.data,code:D.invalid_enum_value,options:s}),se}return ne(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(t,s=this._def){return e.create(t,{...this._def,...s})}exclude(t,s=this._def){return e.create(this.options.filter((e=>!t.includes(e))),{...this._def,...s})}};ct.create=dt;var lt=class extends he{_parse(e){const t=O.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==z.string&&s.parsedType!==z.number){const e=O.objectValues(t);return Q(s,{expected:O.joinValues(e),received:s.parsedType,code:D.invalid_type}),se}if(this._cache||(this._cache=new Set(O.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=O.objectValues(t);return Q(s,{received:s.data,code:D.invalid_enum_value,options:e}),se}return ne(e.data)}get enum(){return this._def.values}};lt.create=(e,t)=>new lt({values:e,typeName:Ct.ZodNativeEnum,...ue(t)});var ut=class extends he{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.promise&&!1===t.common.async)return Q(t,{code:D.invalid_type,expected:z.promise,received:t.parsedType}),se;const s=t.parsedType===z.promise?t.data:Promise.resolve(t.data);return ne(s.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}};ut.create=(e,t)=>new ut({type:e,typeName:Ct.ZodPromise,...ue(t)});var pt=class extends he{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ct.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=this._def.effect||null,n={addIssue:e=>{Q(s,e),e.fatal?t.abort():t.dirty()},get path(){return s.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===a.type){const e=a.transform(s.data,n);if(s.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return se;const a=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===a.status?se:"dirty"===a.status||"dirty"===t.value?ae(a.value):a}));{if("aborted"===t.value)return se;const a=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===a.status?se:"dirty"===a.status||"dirty"===t.value?ae(a.value):a}}if("refinement"===a.type){const e=e=>{const t=a.refinement(e,n);if(s.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===s.common.async){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===a.status?se:("dirty"===a.status&&t.dirty(),e(a.value),{status:t.value,value:a.value})}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((s=>"aborted"===s.status?se:("dirty"===s.status&&t.dirty(),e(s.value).then((()=>({status:t.value,value:s.value}))))))}if("transform"===a.type){if(!1===s.common.async){const e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!oe(e))return se;const i=a.transform(e.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((e=>oe(e)?Promise.resolve(a.transform(e.value,n)).then((e=>({status:t.value,value:e}))):se))}O.assertNever(a)}};pt.create=(e,t,s)=>new pt({schema:e,typeName:Ct.ZodEffects,effect:t,...ue(s)}),pt.createWithPreprocess=(e,t,s)=>new pt({schema:t,effect:{type:"preprocess",transform:e},typeName:Ct.ZodEffects,...ue(s)});var ht=class extends he{_parse(e){return this._getType(e)===z.undefined?ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ht.create=(e,t)=>new ht({innerType:e,typeName:Ct.ZodOptional,...ue(t)});var mt=class extends he{_parse(e){return this._getType(e)===z.null?ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};mt.create=(e,t)=>new mt({innerType:e,typeName:Ct.ZodNullable,...ue(t)});var ft=class extends he{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===z.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ft.create=(e,t)=>new ft({innerType:e,typeName:Ct.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...ue(t)});var gt=class extends he{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return de(a)?a.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new J(s.common.issues)},input:s.data})}))):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new J(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};gt.create=(e,t)=>new gt({innerType:e,typeName:Ct.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...ue(t)});var yt=class extends he{_parse(e){if(this._getType(e)!==z.nan){const t=this._getOrReturnCtx(e);return Q(t,{code:D.invalid_type,expected:z.nan,received:t.parsedType}),se}return{status:"valid",value:e.data}}};yt.create=e=>new yt({typeName:Ct.ZodNaN,...ue(e)});var vt=Symbol("zod_brand"),_t=class extends he{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}},wt=class e extends he{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?se:"dirty"===e.status?(t.dirty(),ae(e.value)):this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})()}{const e=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?se:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:s.path,parent:s})}}static create(t,s){return new e({in:t,out:s,typeName:Ct.ZodPipeline})}},bt=class extends he{_parse(e){const t=this._def.innerType._parse(e),s=e=>(oe(e)&&(e.value=Object.freeze(e.value)),e);return de(t)?t.then((e=>s(e))):s(t)}unwrap(){return this._def.innerType}};function xt(e,t){const s="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof s?{message:s}:s}function kt(e,t={},s){return e?De.create().superRefine(((a,n)=>{const i=e(a);if(i instanceof Promise)return i.then((e=>{if(!e){const e=xt(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}}));if(!i){const e=xt(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}})):De.create()}bt.create=(e,t)=>new bt({innerType:e,typeName:Ct.ZodReadonly,...ue(t)});var Ct,It,Mt={object:We.lazycreate};(It=Ct||(Ct={})).ZodString="ZodString",It.ZodNumber="ZodNumber",It.ZodNaN="ZodNaN",It.ZodBigInt="ZodBigInt",It.ZodBoolean="ZodBoolean",It.ZodDate="ZodDate",It.ZodSymbol="ZodSymbol",It.ZodUndefined="ZodUndefined",It.ZodNull="ZodNull",It.ZodAny="ZodAny",It.ZodUnknown="ZodUnknown",It.ZodNever="ZodNever",It.ZodVoid="ZodVoid",It.ZodArray="ZodArray",It.ZodObject="ZodObject",It.ZodUnion="ZodUnion",It.ZodDiscriminatedUnion="ZodDiscriminatedUnion",It.ZodIntersection="ZodIntersection",It.ZodTuple="ZodTuple",It.ZodRecord="ZodRecord",It.ZodMap="ZodMap",It.ZodSet="ZodSet",It.ZodFunction="ZodFunction",It.ZodLazy="ZodLazy",It.ZodLiteral="ZodLiteral",It.ZodEnum="ZodEnum",It.ZodEffects="ZodEffects",It.ZodNativeEnum="ZodNativeEnum",It.ZodOptional="ZodOptional",It.ZodNullable="ZodNullable",It.ZodDefault="ZodDefault",It.ZodCatch="ZodCatch",It.ZodPromise="ZodPromise",It.ZodBranded="ZodBranded",It.ZodPipeline="ZodPipeline",It.ZodReadonly="ZodReadonly";var Tt=(e,t={message:`Input not instance of ${e.name}`})=>kt((t=>t instanceof e),t),Nt=Le.create,St=je.create,At=yt.create,Ot=Re.create,Et=Fe.create,Zt=$e.create,Lt=qe.create,Pt=ze.create,jt=Ue.create,Rt=De.create,Ft=Ve.create,$t=Je.create,qt=Ke.create,zt=Ge.create,Ut=We.create,Dt=We.strictCreate,Vt=Ye.create,Jt=Qe.create,Kt=et.create,Gt=tt.create,Bt=st.create,Wt=at.create,Yt=nt.create,Ht=it.create,Qt=rt.create,Xt=ot.create,es=ct.create,ts=lt.create,ss=ut.create,as=pt.create,ns=ht.create,is=mt.create,rs=pt.createWithPreprocess,os=wt.create,ds=()=>Nt().optional(),cs=()=>St().optional(),ls=()=>Et().optional(),us={string:e=>Le.create({...e,coerce:!0}),number:e=>je.create({...e,coerce:!0}),boolean:e=>Fe.create({...e,coerce:!0}),bigint:e=>Re.create({...e,coerce:!0}),date:e=>$e.create({...e,coerce:!0})},ps=se,hs={text:"text",conversation:"text",imageMessage:"image",contactMessage:"contact",locationMessage:"location",documentMessage:"document",audioMessage:"audio",videoMessage:"video",protocolMessage:"protocol",contactsArrayMessage:"contactsArray",highlyStructuredMessage:"highlyStructured",sendPaymentMessage:"sendPayment",liveLocationMessage:"liveLocation",requestPaymentMessage:"requestPayment",declinePaymentRequestMessage:"declinePaymentRequest",cancelPaymentRequestMessage:"cancelPaymentRequest",templateMessage:"template",stickerMessage:"sticker",groupInviteMessage:"groupInvite",templateButtonReplyMessage:"templateButtonReply",productMessage:"product",deviceSentMessage:"deviceSent",listMessage:"list",viewOnceMessage:"viewOnce",orderMessage:"order",listResponseMessage:"listResponse",ephemeralMessage:"ephemeral",invoiceMessage:"invoice",buttonsMessage:"buttons",buttonsResponseMessage:"buttonsResponse",paymentInviteMessage:"paymentInvite",interactiveMessage:"interactive",reactionMessage:"reaction",stickerSyncRmrMessage:"sticker",interactiveResponseMessage:"interactiveResponse",pollCreationMessage:"pollCreation",pollUpdateMessage:"pollUpdate",keepInChatMessage:"keepInChat",documentWithCaptionMessage:"document",requestPhoneNumberMessage:"requestPhoneNumber",viewOnceMessageV2:"viewOnce",encReactionMessage:"reaction",editedMessage:"text",viewOnceMessageV2Extension:"viewOnce",pollCreationMessageV2:"pollCreation",scheduledCallCreationMessage:"scheduledCallCreation",groupMentionedMessage:"groupMentioned",pinInChatMessage:"pinInChat",pollCreationMessageV3:"pollCreation",scheduledCallEditMessage:"scheduledCallEdit",ptvMessage:"ptv",botInvokeMessage:"botInvoke",callLogMesssage:"callLog",encCommentMessage:"encComment",bcallMessage:"bcall",lottieStickerMessage:"lottieSticker",eventMessage:"event",commentMessage:"comment",newsletterAdminInviteMessage:"text",extendedTextMessageWithParentKey:"text",extendedTextMessage:"text",placeholderMessage:"placeholder",encEventUpdateMessage:"encEventUpdate"},ms={whatsapp:"0@s.whatsapp.net",meta:"13135550002@s.whatsapp.net",chatgpt:"18002428478@s.whatsapp.net",copilot:"18772241042@s.whatsapp.net",instagram:"447723442971@s.whatsapp.net",tiktok:"6285574670498@s.whatsapp.net"},fs=q.enum(["text","text","image","contact","location","document","audio","video","protocol","contactsArray","highlyStructured","sendPayment","liveLocation","requestPayment","declinePaymentRequest","cancelPaymentRequest","template","sticker","groupInvite","templateButtonReply","product","deviceSent","list","viewOnce","order","listResponse","ephemeral","invoice","buttons","buttonsResponse","paymentInvite","interactive","reaction","sticker","interactiveResponse","pollCreation","pollUpdate","keepInChat","document","requestPhoneNumber","viewOnce","reaction","text","viewOnce","pollCreation","scheduledCallCreation","groupMentioned","pinInChat","pollCreation","scheduledCallEdit","ptv","botInvoke","callLog","encComment","bcall","lottieSticker","event","comment","text","text","placeholder","encEventUpdate"]),gs=q.enum(["unknown","android","ios","desktop","web"]),ys=q.object({chatId:q.string(),channelId:q.string(),uniqueId:q.string(),receiverId:q.string(),receiverName:q.string(),roomId:q.string(),roomName:q.string(),senderId:q.string(),senderName:q.string(),senderDevice:gs,chatType:fs,timestamp:q.number(),mentions:q.string().array(),text:q.string().nullable(),links:q.string().array(),isPrefix:q.boolean(),isFromMe:q.boolean(),isTagMe:q.boolean(),isGroup:q.boolean(),isStory:q.boolean(),isViewOnce:q.boolean(),isEdited:q.boolean(),isDeleted:q.boolean(),isPinned:q.boolean(),isUnPinned:q.boolean(),isChannel:q.boolean(),isBroadcast:q.boolean(),isEphemeral:q.boolean(),isForwarded:q.boolean(),citation:q.record(q.string(),q.boolean()).nullable(),media:q.object({buffer:q.function().returns(q.instanceof(Buffer)),stream:q.function().returns(q.instanceof(S))}).passthrough().nullable(),message:q.function().returns(q.record(q.string(),q.any()))});ys.extend({replied:ys.nullable()});var vs=class{constructor(e,t,s){this.socket=e,this.client=t,this.db=s}maxReplies=0;async connection(e){this.client.stopSpinner("connection",!1),this.client.startSpinner("connection","Connecting to WhatsApp...");const{connection:t,lastDisconnect:s,qr:a}=e;if(this.client.emit("connection",{status:"connecting"}),"qr"===this.client.options?.authType&&a)return console.log(),console.log(await N.toString(a,{type:"terminal",small:!0})),this.client.startSpinner("qr","Waiting for QR code scan..."),void this.socket?.ev.on("connection.update",(()=>this.client.stopSpinner("qr",!1)));if("close"===t){const e=s?.error?.output?.statusCode,a=e===o.restartRequired||e===o.connectionLost;if(this.client.failSpinner("connection",`[Connection Closed] [${e}]\n${s?.error?.message}\n`),401===e||405===e||500===e)return void console.error("Invalid session, please delete manually");a&&"close"==t&&await this.client.initialize()}else"open"===t&&(this.client.stopSpinner("connection",!0,"Connected to WhatsApp\n"),this.client.emit("connection",{status:"open"}))}async messages(e,t){if(e?.messageStubType||e?.messageStubParameters?.length||e?.message?.protocolMessage?.peerDataOperationRequestResponseMessage||e?.message?.botInvokeMessage||!e?.key?.id||!e?.message)return null;if(this.client.options?.ignoreMe&&e?.key?.fromMe&&"status@broadcast"!=e?.key?.remoteJid&&!e?.participant)return null;this.client.options?.autoRead&&await this.socket.readMessages([e?.key]);const s=e,a=e?.message?.pinInChatMessage?.key?.id,n=1==e?.message?.pinInChatMessage?.type,r=2==e?.message?.pinInChatMessage?.type;if(a){const t=await this.db.selectFrom("messages").select("value").where("id","=",a).executeTakeFirst(),s=P(t?.value);e=s}const o=!e?.message?.protocolMessage?.editedMessage&&e?.message?.protocolMessage?.key?.id,u=!!o;if(o){const t=await this.db.selectFrom("messages").select("value").where("id","=",o).executeTakeFirst(),s=P(t?.value);e=s}const p={},h=d(e?.message?.protocolMessage?.editedMessage||e?.message);p.chatId=e?.message?.protocolMessage?.key?.id||e?.key?.id,p.channelId="",p.uniqueId="",p.receiverId=i(this.socket.user?.id),p.receiverName=this.socket.user?.name||this.socket.user?.verifiedName,p.roomId=i(e?.key?.remoteJid);const m=await this.db.selectFrom("chats").select("value").where("id","=",p.roomId).executeTakeFirst();p.roomName=P(m?.value)?.name,p.senderId=i(e?.participant||e?.key?.participant||e?.key?.remoteJid);const f=await this.db.selectFrom("chats").select("value").where("id","=",p.senderId).executeTakeFirst();p.senderName=e?.pushName||e?.verifiedBizName||P(f?.value)?.name||p.receiverName,p.roomName=p.roomName||p.senderName,p.senderDevice=c(p.chatId),p.chatType=hs[h],p.timestamp=e?.messageTimestamp?.low||e?.messageTimestamp||0,p.mentions=[],p.text=null,p.links=[],p.isPrefix=!1,p.isFromMe=e?.key?.fromMe,p.isTagMe=!1,p.isGroup=p.roomId.includes("@g.us"),p.isStory=p.roomId.includes("@broadcast"),p.isViewOnce=!1,p.isEdited=!1,p.isDeleted=u,p.isPinned=n,p.isUnPinned=r,p.isChannel=p.roomId.includes("@newsletter"),p.isBroadcast=!!e?.broadcast,p.isEphemeral=!1,p.isForwarded=!1,p.citation=null,p.media=null,p.replied=null,p.channelId=p.roomId.split("@")[0]+"-"+p.senderId.split("@")[0],p.uniqueId=p.channelId+"-"+p.chatId;const g=this.client.options?.citation;if(Object.keys(g).length){p.citation={};for(const e of Object.keys(g))p.citation[e]=g[e].includes(Number(p.senderId.split("@")[0]))||g[e].includes(Number(p.roomId.split("@")[0]))}const y=(e?.message?.protocolMessage?.editedMessage?.[h]||e?.message?.[h])?.message?.documentMessage||e?.message?.[h];"text"!=p.chatType&&(p.media={...F(y,["url","contextInfo","fileSha256","fileEncSha256","mediaKey","directPath","waveform","thumbnail","jpegThumbnail","thumbnailEncSha256","thumbnailSha256","thumbnailDirectPath","firstFrameSidecar","streamingSidecar","scansSidecar","callKey","midQualityFileSha256"]),buffer:async()=>await l(e,"buffer",{}),stream:async()=>await l(e,"stream",{})});const v=e?.message?.[h]?.contextInfo?.stanzaId;if(v&&this.maxReplies<1){this.maxReplies++;const t=await this.db.selectFrom("messages").select("value").where("id","=",v).executeTakeFirst(),s=P(t?.value);if(s)p.replied=await this.messages(s,!0);else{const t=e,s=d(t.message?.extendedTextMessage?.contextInfo.quotedMessage);t.key.id=t.message?.extendedTextMessage?.contextInfo.stanzaId,t.message[s]=t.message?.extendedTextMessage?.contextInfo.quotedMessage[s],delete t.message?.extendedTextMessage,p.replied=await this.messages(t,!0)}}const _="string"==typeof y?y:y?.text||y?.caption||y?.name||y?.displayName||"";p.text=((e="")=>e?e.replace(/\u202E([\s\S]*?)\u202C/g,((e,t)=>Array.from(t).reverse().join(""))).replace(/[\u202A-\u202E\u202C]/g,""):null)(_)||null,p.mentions=((e="")=>{if(!e)return[];const t=new Set;for(const s of e.matchAll(/@(\d+)/g))t.add(s[1]);return[...t]})(p.text),p.links=((e="")=>e&&e.match(/(?:https?:\/\/)?[^\s<>"']+\.[^\s<>"']+/g)||[])(p.text);const w=e?.message?.[h];return p.isPrefix=!!this.client.options?.prefix&&!!p.text?.startsWith(this.client.options?.prefix),p.isTagMe=p.mentions.includes(p.receiverId.split("@")[0]),p.isEdited=R(j(e),"editedMessage"),p.isEphemeral=R(j(w?.contextInfo),"ephemeralSettingTimestamp"),p.isForwarded=R(j(w?.contextInfo),"forwardingScore"),p.isViewOnce=!!w?.viewOnce,p.isPrefix&&(p.text=p.text.replace(new RegExp(`^${this.client.options?.prefix}`),"")),p.message=()=>s,t||this.client.emit("messages",p),p}async calls(e){this.client.options?.autoRejectCall&&await this.socket.rejectCall(e.id,e.from);const t={};t.callId=e.id,t.roomId=e.chatId,t.callerId=e.from,t.date=e.date,t.offline=e.offline,t.status=e.status,t.isVideo=!!e.isVideo,t.isGroup=!!e.isGroup,this.client.emit("calls",t)}},_s=async(e,t,s)=>{const a="auth";await(async(e,t)=>{await e.transaction().execute((async e=>{await e.schema.createTable("auth").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("auth_session_id_unique",["session","id"]).execute(),await e.schema.createTable("chats").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("chats_session_id_unique",["session","id"]).execute(),await e.schema.createTable("contacts").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("contacts_session_id_unique",["session","id"]).execute(),await e.schema.createTable("messages").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("messages_session_id_unique",["session","id"]).execute(),t.loadLLMSchemas&&(await e.schema.createTable("llm_messages").ifNotExists().addColumn("uniqueId","char(36)",(e=>e.notNull().primaryKey())).addColumn("channelId","char(36)").addColumn("model","char(36)").addColumn("role","varchar(20)",(e=>e.notNull())).addColumn("content","text",(e=>e.notNull())).addColumn("additional","text").addUniqueConstraint("llm_messages_id_unique",["uniqueId"]).execute(),await e.schema.createTable("llm_personalization").ifNotExists().addColumn("uniqueId","char(36)",(e=>e.notNull().primaryKey())).addColumn("senderId","char(36)").addColumn("content","text",(e=>e.notNull())).addUniqueConstraint("llm_personalization_id_unique",["uniqueId"]).execute(),await e.schema.createTable("llm_rag").ifNotExists().addColumn("metadata.id","char(36)",(e=>e.notNull().primaryKey())).addColumn("pageContent","text",(e=>e.notNull())).addUniqueConstraint("llm_rag_id_unique",["metadata.id"]).execute()),await Promise.all([e.schema.createIndex("auth_session_id_idx").ifNotExists().on("auth").columns(["session","id"]).execute(),e.schema.createIndex("chats_session_id_idx").ifNotExists().on("chats").columns(["session","id"]).execute(),e.schema.createIndex("contacts_session_id_idx").ifNotExists().on("contacts").columns(["session","id"]).execute(),e.schema.createIndex("messages_session_id_idx").ifNotExists().on("messages").columns(["session","id"]).execute(),e.schema.createIndex("llm_messages_uniqueId_idx").ifNotExists().on("llm_messages").column("uniqueId").execute(),e.schema.createIndex("llm_messages_channelId_idx").ifNotExists().on("llm_messages").column("channelId").execute(),e.schema.createIndex("llm_messages_model_idx").ifNotExists().on("llm_messages").column("model").execute(),e.schema.createIndex("llm_messages_role_idx").ifNotExists().on("llm_messages").column("role").execute(),e.schema.createIndex("llm_personalization_uniqueId_idx").ifNotExists().on("llm_personalization").column("uniqueId").execute(),e.schema.createIndex("llm_personalization_senderId_idx").ifNotExists().on("llm_personalization").column("senderId").execute(),e.schema.createIndex("llm_rag_id_idx").ifNotExists().on("llm_rag").column("metadata.id").execute(),e.schema.createIndex("llm_rag_pageContent_idx").ifNotExists().on("llm_rag").column("pageContent").execute()])}))})(e,s);const i=async e=>{for(let t=0;t<10;t++)try{return await e()}catch(e){await new Promise((e=>setTimeout(e,200)))}throw new Error("Max retries reached")},o=async s=>{const n=await i((()=>e.selectFrom(a).select(["value"]).where("id","=",s).where("session","=",t).executeTakeFirst()));if(!n?.value)return null;const o="object"==typeof n.value?JSON.stringify(n.value):n.value;return JSON.parse(o,r.reviver)},d=async(s,n)=>{const o=JSON.stringify(n,r.replacer);await i((()=>e.insertInto(a).values({session:t,id:s,value:o}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:o}))).execute()))},c=async s=>{await i((()=>e.deleteFrom(a).where("id","=",s).where("session","=",t).execute()))},l=await o("creds")||n();return{state:{creds:l,keys:{get:async(e,t)=>{const s={};for(const a of t){let t=await o(`${e}-${a}`);"app-state-sync-key"===e&&t&&(t=$(t)),s[a]=t}return s},set:async e=>{for(const t in e)for(const s in e[t]){const a=e[t][s],n=`${t}-${s}`;a?await d(n,a):await c(n)}}}},saveCreds:async()=>{await d("creds",l)},clear:async()=>{await(async()=>{await i((()=>e.deleteFrom(a).where("session","=",t).where("id","!=","creds").execute()))})()},removeCreds:async()=>{await(async()=>{await i((()=>e.deleteFrom(a).where("session","=",t).execute()))})()}}},ws=q.object({type:q.enum(["sqlite","postgresql","mysql"]).default("sqlite"),connection:q.object({url:q.string().default("./session/zaileys.db")}).optional().default({})}).optional().default({}),bs=q.record(q.function().returns(q.union([q.number().array(),q.promise(q.number().array())]))).optional().transform((async e=>{if(!e)return{};const t={};for(const[s,a]of Object.entries(e)){t[`is${s.charAt(0).toUpperCase()}${s.slice(1)}`]=await a()}return t})),xs=q.object({prefix:q.string().optional(),ignoreMe:q.boolean().optional().default(!0),showLogs:q.boolean().optional().default(!0),autoMentions:q.boolean().optional().default(!0),autoOnline:q.boolean().optional().default(!0),autoRead:q.boolean().optional().default(!0),autoPresence:q.boolean().optional().default(!0),autoRejectCall:q.boolean().optional().default(!0),loadLLMSchemas:q.boolean().optional().default(!1),database:ws,citation:bs}),ks=q.object({authType:q.literal("pairing"),phoneNumber:q.number()}).extend(xs.shape),Cs=q.object({authType:q.literal("qr"),phoneNumber:q.undefined().optional()}).extend(xs.shape),Is=q.discriminatedUnion("authType",[ks,Cs]),Ms=q.object({channelId:q.string(),uniqueId:q.string(),model:q.string().min(2).max(100).optional().nullable(),role:q.string().min(2).max(100),content:q.string().min(1).max(65e3),additional:q.string().max(2e4).optional().nullable()}),Ts=q.object({uniqueId:q.string(),senderId:q.string(),content:q.string().min(1).max(5e3)}),Ns=q.object({metadata:q.object({id:q.string().default((()=>(e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";return Array.from({length:e},(()=>t[Math.floor(62*Math.random())])).join("")})(5)))}).default({}),pageContent:q.string().min(1).max(128e3)});Ns.pick({pageContent:!0});var Ss=q.union([q.string().url(),q.instanceof(Buffer).or(q.instanceof(S))]),As=q.union([q.string(),q.object({image:Ss,text:q.string().optional()}),q.object({video:Ss,text:q.string().optional()}),q.object({videoNote:Ss}),q.object({gif:Ss,text:q.string().optional()}),q.object({audio:Ss}),q.object({audioNote:Ss}),q.object({sticker:Ss})]),Os=q.object({roomId:q.string(),asForwarded:q.boolean().optional(),asViewOnce:q.boolean().optional(),verifiedReply:q.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).optional(),quoted:q.function().returns(q.record(q.string(),q.any())).optional()}),Es=Os,Zs=q.object({latitude:q.number(),longitude:q.number(),title:q.string().optional(),footer:q.string().optional()}),Ls=Os,Ps=q.object({fullname:q.string(),nickname:q.string().optional(),organization:q.string().optional(),role:q.string().optional(),email:q.string().email().optional(),whatsAppNumber:q.number(),callNumber:q.number().optional(),voiceNumber:q.number().optional(),website:q.string().url().optional(),homeAddress:q.string().optional(),workAddress:q.string().optional(),avatar:q.string().url().optional()}),js=q.object({message:q.function().returns(q.record(q.string(),q.any()))}),Rs=q.string(),Fs=q.object({message:q.function().returns(q.record(q.string(),q.any()))}),$s=q.object({action:q.enum(["pin","unpin"]),expired:q.enum(["24h","7d","30d"])}),qs=Os.pick({roomId:!0}),zs=q.object({name:q.string(),answers:q.string().array(),multipleAnswers:q.boolean().optional()}),Us=q.object({message:q.function().returns(q.record(q.string(),q.any()))}),Ds=q.string(),Vs=q.object({message:q.function().returns(q.record(q.string(),q.any()))}),Js=q.object({callId:q.string(),callerId:q.string()}),Ks=Os.pick({roomId:!0}),Gs=q.object({expired:q.enum(["remove","8h","7d"])}),Bs=q.string();q.object({type:q.enum(["group","user"]),id:q.string(),name:q.string(),bio:q.string(),avatar:q.string().url(),ephemeralDuration:q.number().optional(),isRestrict:q.boolean().optional(),isAnnounce:q.boolean().optional(),isCommunity:q.boolean().optional(),isCommunityAnnounce:q.boolean().optional(),isJoinApprovalMode:q.boolean().optional(),isMemberAddMode:q.boolean().optional(),owner:q.object({type:q.literal("user"),id:q.string()}).nullable(),roomCreatedAt:q.number().optional(),nameUpdatedAt:q.number().optional(),bioUpdatedAt:q.number().optional(),membersLength:q.number().optional(),members:q.object({type:q.enum(["user","admin","superadmin"]),id:q.string()}).array().optional()});var Ws=Os.pick({roomId:!0}),Ys=q.enum(["typing","recording","online","offline","paused"]),Hs=class{constructor(e){this.wa=e,this.parser=new vs(e.socket,e.client,e.db)}parser;caching=new h({stdTTL:600,checkperiod:120,maxKeys:1e3});async sendMessage(e,t,s){let a=[];this.wa.client.options?.autoMentions&&(a=((e="")=>{if(!e)return[];const t=new Set;for(const s of e.matchAll(/@(\d+)/g))t.add(s[1]);return[...t].flatMap((e=>[`${e}@s.whatsapp.net`,`${e}@g.us`]))})(t?.text||t?.caption)),this.wa.client.options?.autoPresence&&this.wa.socket?.sendPresenceUpdate("composing",e),this.wa.client.options?.autoPresence&&(t?.audio||t?.audioNote)&&this.wa.socket?.sendPresenceUpdate("recording",e);const n=t,i={contextInfo:{isForwarded:!!n?.asForwarded}};if("function"==typeof n?.quoted){let t=n?.quoted();t.key.remoteJid=ms[n?.verifiedReply]||t.key.remoteJid;const r=await(this.wa.socket?.sendMessage(e,{...n,mentions:a,...i},{quoted:t,...s}));return await this.parser.messages(r)}{const t=await(this.wa.socket?.sendMessage(e,{...n,mentions:a,...i},s));return await this.parser.messages(t)}}async text(e,t){if(e=As.parse(e),t=Os.parse(t),"string"==typeof e)return await this.sendMessage(t.roomId,{text:e,...t});if("object"==typeof e){const s=Object.keys(e),a=e;if(s.includes("image")){const e="string"==typeof a.image?{url:a.image}:a.image;return await this.sendMessage(t.roomId,{caption:a?.text,image:e,viewOnce:!!t.asViewOnce,...t})}if(s.includes("video")){const e="string"==typeof a.video?{url:a.video}:a.video;return await this.sendMessage(t.roomId,{caption:a?.text,video:e,ptv:!1,viewOnce:!!t.asViewOnce,...t})}if(s.includes("videoNote")){const e="string"==typeof a.videoNote?{url:a.videoNote}:a.videoNote;return await this.sendMessage(t.roomId,{caption:a?.text,video:e,ptv:!0,...t})}if(s.includes("gif")){const e="string"==typeof a.gif?{url:a.gif}:a.gif;return await this.sendMessage(t.roomId,{caption:a?.text,video:e,gifPlayback:!0,viewOnce:!!t.asViewOnce,...t})}if(s.includes("audio")){const e="string"==typeof a.audio?{url:a.audio}:a.audio;return await this.sendMessage(t.roomId,{caption:a?.text,audio:e,viewOnce:!!t.asViewOnce,...t})}if(s.includes("audioNote")){const e="string"==typeof a.audioNote?{url:a.audioNote}:a.audioNote;return await this.sendMessage(t.roomId,{caption:a?.text,audio:e,ptt:!0,viewOnce:!!t.asViewOnce,...t})}if(s.includes("sticker")){const e="string"==typeof a.sticker?{url:a.sticker}:a.sticker;return await this.sendMessage(t.roomId,{caption:a?.text,sticker:e,...t})}}}async location(e,t){return e=Zs.parse(e),t=Es.parse(t),await this.sendMessage(t.roomId,{location:{degreesLatitude:e.latitude,degreesLongitude:e.longitude,url:e.title,address:e.footer,name:e.title},...t})}async contact(e,t){e=Ps.parse(e),t=Ls.parse(t);const s=["BEGIN:VCARD","VERSION:3.0",`N:;${e.fullname};;;`,`FN:${e.fullname}`,e.nickname?`NICKNAME:${e.nickname}`:"",e.organization||e.role?`ORG:${e.organization??""};`:"",e.role?`TITLE:${e.role}`:"",`TEL;TYPE=CELL,VOICE;waid=${e.whatsAppNumber}:+${e.whatsAppNumber}`,e.callNumber?`TEL;TYPE=WORK,VOICE:+${e.callNumber}`:"",e.voiceNumber?`TEL;TYPE=VOICE:+${e.voiceNumber}`:"",e.email?`EMAIL;TYPE=INTERNET:${e.email}`:"",e.website?`URL;TYPE=WORK:${e.website}`:"",e.homeAddress?`ADR;TYPE=HOME:;;${e.homeAddress};;;;`:"",e.workAddress?`ADR;TYPE=WORK:;;${e.workAddress};;;;`:"",e.avatar?`PHOTO;VALUE=URI;TYPE=JPEG:${e.avatar}`:"","END:VCARD"].join("\n");return await this.sendMessage(t.roomId,{contacts:{displayName:e.fullname,contacts:[{vcard:s}]},...t})}async reaction(e,t){return e=Rs.parse(e),t=js.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{react:{text:e,key:t.message()?.key},...t})}async pin(e,t){e=$s.parse(e),t=Fs.parse(t);return await this.sendMessage(t.message()?.key?.remoteJid,{pin:{type:"pin"==e.action?1:0,time:{"24h":86400,"7d":604800,"30d":2592e3}[e.expired],key:t.message()?.key},...t})}async poll(e,t){return e=zs.parse(e),t=qs.parse(t),await this.sendMessage(t.roomId,{poll:{name:e.name,values:e.answers,selectableCount:e.multipleAnswers?1:0,toAnnouncementGroup:!0},...t})}async edit(e,t){return e=Ds.parse(e),t=Us.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{text:e,edit:t.message()?.key,...t})}async delete(e){return e=Vs.parse(e),await this.sendMessage(e.message()?.key?.remoteJid,{delete:e.message()?.key})}async rejectCall(e){return e=Js.parse(e),await(this.wa.socket?.rejectCall(e.callId,e.callerId))}async mute(e,t){e=Gs.parse(e),t=Ks.parse(t);return await(this.wa.socket?.chatModify({mute:{remove:null,"8h":864e5,"7d":6048e5}[e.expired]},t.roomId))}async profile(e){const t=(e=Bs.parse(e)).includes("@g.us"),s={};s.id=e;if(i(this.wa.socket?.user?.id)==e)s.name=this.wa.socket?.user?.name||this.wa.socket?.user?.verifiedName;else if(t){const t=await(this.wa.socket?.groupMetadata(e));s.type="group",s.name=t?.subject,s.bio=t?.desc,s.avatar=await(this.wa.socket?.profilePictureUrl(e)),s.ephemeralDuration=t?.ephemeralDuration,s.isRestrict=t?.restrict,s.isAnnounce=t?.announce,s.isCommunity=t?.isCommunity,s.isCommunityAnnounce=t?.isCommunityAnnounce,s.isJoinApprovalMode=t?.joinApprovalMode,s.isMemberAddMode=t?.memberAddMode,s.owner={type:"user",id:t?.owner},s.roomCreatedAt=t?.creation,s.nameUpdatedAt=t?.subjectTime,s.membersLength=t?.size,s.members=t?.participants.map((e=>({id:e.id,type:"admin"==e.admin||"superadmin"==e.admin?e.admin:"user"})))}else{const t=await(this.wa.db?.selectFrom("chats").select("value").where("id","=",e).executeTakeFirst()),a=P(t?.value),n=(await(this.wa?.socket?.fetchStatus(e)))[0]?.status;s.type="user",s.name=a?.name,s.bio=n?.status,s.avatar=await(this.wa?.socket?.profilePictureUrl(e)),s.bioUpdatedAt=new Date(n?.setAt).getTime()}return s}async presence(e,t){e=Ys.parse(e),t=Ws.parse(t);return await(this.wa.socket?.sendPresenceUpdate({typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"}[e],t.roomId))}async addCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=Ms.parse(e);if(!await(this.wa.db?.insertInto("llm_messages").values(e).executeTakeFirst()))throw new Error("Failed to add completion");return e}async deleteCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_messages").where("uniqueId","=",e).executeTakeFirst()))throw new Error("Failed to delete completion");return!0}async updateCompletion(e,t){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const s=Ms.partial().parse(t),a=await(this.wa.db?.updateTable("llm_messages").set(s).where("uniqueId","=",e).returningAll().executeTakeFirst());if(!a)throw new Error("Failed to update completion");return Ms.parse(a)}async clearCompletions(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_messages").where("channelId","=",e).executeTakeFirst()))throw new Error("Failed to clear completions");return!0}async getCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_messages").selectAll().where("uniqueId","=",e).executeTakeFirst());return t?Ms.parse(t):null}async getCompletions(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_messages").selectAll().where("channelId","=",e).execute());return t?.map((e=>Ms.parse(e)))||[]}async addPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=Ts.parse(e);if(!await(this.wa.db?.insertInto("llm_personalization").values(e).executeTakeFirst()))throw new Error("Failed to add completion");return e}async deletePersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_personalization").where("uniqueId","=",e).executeTakeFirst()))throw new Error("Failed to delete completion");return!0}async clearPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_personalization").where("senderId","=",e).executeTakeFirst()))throw new Error("Failed to clear completions");return!0}async getPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_personalization").selectAll().where("senderId","=",e).execute());return t?.map((e=>Ts.parse(e)))||[]}async addRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=Ns.parse(e);if(!await(this.wa.db?.insertInto("llm_rag").values({pageContent:e.pageContent.toLowerCase(),"metadata.id":e.metadata?.id}).executeTakeFirst()))throw new Error("Failed to add RAG");return e}async deleteRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_rag").where(k`"metadata.id"`,"=",e).executeTakeFirst()))throw new Error("Failed to delete RAG");return!0}async updateRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.updateTable("llm_rag").set({metadata:{id:e}}).where(k`"metadata.id"`,"=",e).returningAll().executeTakeFirst());if(!t)throw new Error("Failed to update RAG");return Ns.parse(t)}async clearRAGs(){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_rag").executeTakeFirst()))throw new Error("Failed to clear RAGs");return!0}async getRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_rag").selectAll().where(k`"metadata.id"`,"=",e).executeTakeFirst());return t?Ns.parse(t):null}async getRAGs(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=e.toLowerCase().trim(),s=this.caching.get(t);if(s)return s;const a=t.split(/\s+/).filter((e=>e.length>0));if(!a.length)return[];const n=await(this.wa.db?.selectFrom("llm_rag").select([k`"metadata.id"`.as("metadata.id"),"pageContent"]).where("pageContent","!=","").limit(1e4).execute().then((e=>e.map((e=>Ns.parse({...e,metadata:{id:e["metadata.id"]}}))))).then((e=>e.filter((e=>{const t=e.pageContent.toLowerCase().split(/\s+/);return a.some((e=>t.some((t=>A.get(e,t)<=Math.max(1,Math.floor(e.length/4))))))})))));return this.caching.set(t,n),n||[]}llms={addCompletion:this.addCompletion.bind(this),deleteCompletion:this.deleteCompletion.bind(this),updateCompletion:this.updateCompletion.bind(this),clearCompletions:this.clearCompletions.bind(this),getCompletion:this.getCompletion.bind(this),getCompletions:this.getCompletions.bind(this),addPersonalization:this.addPersonalization.bind(this),deletePersonalization:this.deletePersonalization.bind(this),clearPersonalization:this.clearPersonalization.bind(this),getPersonalization:this.getPersonalization.bind(this),addRAG:this.addRAG.bind(this),deleteRAG:this.deleteRAG.bind(this),updateRAG:this.updateRAG.bind(this),clearRAGs:this.clearRAGs.bind(this),getRAG:this.getRAG.bind(this),getRAGs:this.getRAGs.bind(this)}},Qs=class{constructor(e){return this.props=e,this.initialize(),this.worker,new Proxy(this,{get:(e,t)=>t in e?e[t]:e.worker[t]})}options={};cache=new h({stdTTL:300,useClones:!1});chatId="zaileys-chats";logger=f({level:"silent",enabled:!1});db;socket;events=new u;spinners=new Map;worker;async initialize(){console.clear(),await((e="ZAILEYS")=>new Promise((t=>{p(e,((e,s)=>{if(e)return t("");console.log(s),t(s||"")}))})))(),this.options=await Is.parseAsync(this.props),this.startSpinner("db","Initializing database..."),this.db=await(e=>{const{type:t,connection:s}=e.database;if("sqlite"===t){const e=s.url||"./db/zaileys.db",t=I.resolve(e);return y(I.dirname(t),{recursive:!0}),v(t,"",{flag:"a"}),new _({dialect:new w({database:new g(t)})})}const a=new T(s.url),n=a.protocol.replace(":","");if("mysql"===t)return new _({dialect:new b({pool:C.createPool({host:a.hostname,user:a.username,password:a.password,database:a.pathname.replace("/",""),port:parseInt(a.port||"3306",10)})})});if("postgresql"===t)return new _({dialect:new x({pool:new M({host:a.hostname,user:a.username,password:a.password,database:a.pathname.replace("/",""),port:parseInt(a.port||"5432",10)})})});throw new Error(`Unsupported database protocol: ${n}`)})(this.options),this.stopSpinner("db",!0,"Database initialized"),this.startSpinner("auth","Setting up auth adapter...");const{state:n,saveCreds:i}=await _s(this.db,this.chatId,this.options);this.stopSpinner("auth",!0,"Auth adapter ready"),this.startSpinner("store","Setting up store adapter...");const r=await(async(e,t,s)=>({bind:a=>{const n=new vs(a,e,t);a?.ev.on("connection.update",(async e=>{await n.connection(e)})),a?.ev.on("call",(async e=>{for(const t of e)await n.calls(t)})),a?.ev.on("messaging-history.set",(async e=>{const{chats:a,contacts:n,messages:i}=e;for(const e of a)await t.insertInto("chats").values({session:s,id:e.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute();for(const e of n)await t.insertInto("contacts").values({session:s,id:e.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute();for(const e of i){if(!e.message)return;if(e.message?.protocolMessage)return;await t.insertInto("messages").values({session:s,id:e.key.id,value:JSON.stringify(e)}).onConflict((t=>t.columns(["session","id"]).doUpdateSet({value:JSON.stringify(e)}))).execute()}})),a?.ev.on("messages.upsert",(async({messages:e})=>{for(const a of e){if(!a.message)return;if(a.message?.protocolMessage)return;await n.messages(a),await t.insertInto("messages").values({session:s,id:a.key.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute()}})),a?.ev.on("chats.upsert",(async e=>{for(const a of e)await t.insertInto("chats").values({session:s,id:a.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute()})),a?.ev.on("contacts.upsert",(async e=>{for(const a of e)await t.insertInto("contacts").values({session:s,id:a.id,value:JSON.stringify(a)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(a)}))).execute()})),a?.ev.on("groups.update",(async([t])=>{const s=await(a?.groupMetadata(t.id));e.cache.set(t.id,s)})),a?.ev.on("group-participants.update",(async t=>{const s=await(a?.groupMetadata(t.id));e.cache.set(t.id,s)}))}}))(this,this.db,this.chatId);this.stopSpinner("store",!0,"Store adapter ready");const{version:o}=await e();if(this.socket=t({version:o,logger:this.logger,markOnlineOnConnect:this.options.autoOnline,syncFullHistory:!1,defaultQueryTimeoutMs:void 0,msgRetryCounterCache:new h,mediaCache:new h({stdTTL:60}),userDevicesCache:new h,cachedGroupMetadata:async e=>this.cache.get(e),printQRInTerminal:!1,browser:a.ubuntu("qr"===this.options.authType?"Zaileys Library":"Chrome"),auth:{creds:n.creds,keys:s(n.keys,this.logger)},getMessage:async e=>{const t=await(this.db?.selectFrom("messages").select("value").where("id","=",e.id).executeTakeFirst());return P(t?.value)}}),"pairing"===this.options.authType&&this.options.phoneNumber&&!this.socket?.authState.creds.registered){this.startSpinner("pairing","Generating pairing code...");(await this.socket.onWhatsApp(this.options.phoneNumber.toString()+"@s.whatsapp.net"))[0].exists||(this.failSpinner("pairing","Phone is not registered on WhatsApp"),process.exit(1)),setTimeout((async()=>{try{if("pairing"===this.options?.authType){const e=await(this.socket?.requestPairingCode(this.options.phoneNumber.toString()));this.stopSpinner("pairing",!0,`Pairing code: ${e}`)}}catch{this.failSpinner("pairing","Connection failed"),process.exit(1)}}),5e3)}this.worker=new Hs({client:this,db:this.db,socket:this.socket}),this.socket?.ev.on("creds.update",i),r.bind(this.socket)}startSpinner(e,t){let s=this.spinners.get(e);return s||(s=m(t).start(),this.spinners.set(e,s)),s}stopSpinner(e,t,s){const a=this.spinners.get(e);a&&(t?a.succeed(s):a.stop(),this.spinners.delete(e))}failSpinner(e,t){const s=this.spinners.get(e);s&&(s.fail(t),this.spinners.delete(e))}on(e,t){this.events.on(e,t)}emit(e,...t){this.events.emit(e,...t)}};export{Qs as Client};
|