zaileys 1.1.20 → 1.1.22
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.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +3 -7
package/dist/index.d.mts
CHANGED
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("baileys"),t=require("events"),s=require("figlet"),a=require("node-cache"),n=require("ora"),i=require("pino"),r=require("better-sqlite3"),o=require("fs"),d=require("kysely"),c=require("mysql2"),u=require("path"),l=require("pg"),p=require("url"),h=require("qrcode"),m=require("stream");function f(e){return e&&e.__esModule?e:{default:e}}var g,y,v,_=f(s),b=f(a),w=f(n),x=f(i),k=f(r),C=f(c),N=f(u),T=f(h),S=Object.defineProperty,I=(e="")=>{try{return JSON.parse(e)}catch{return JSON.parse(JSON.stringify(e))}},M=(e={})=>{try{return JSON.stringify(e)}catch{return JSON.stringify(JSON.parse(JSON.stringify(e)))}},O=(e="",t="")=>e?e.toLowerCase().includes(t.toLowerCase()):null,Z=(e,t)=>e&&"object"==typeof e?Array.isArray(e)?e.map((e=>Z(e,t))):Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e))).map((([e,s])=>[e,"object"==typeof s?Z(s,t):s]))):e,A={};((e,t)=>{for(var s in t)S(e,s,{get:t[s],enumerable:!0})})(A,{BRAND:()=>ut,DIRTY:()=>Y,EMPTY_PATH:()=>z,INVALID:()=>W,NEVER:()=>ns,OK:()=>G,ParseStatus:()=>B,Schema:()=>ie,ZodAny:()=>Re,ZodArray:()=>Le,ZodBigInt:()=>Me,ZodBoolean:()=>Oe,ZodBranded:()=>lt,ZodCatch:()=>dt,ZodDate:()=>Ze,ZodDefault:()=>ot,ZodDiscriminatedUnion:()=>Ve,ZodEffects:()=>nt,ZodEnum:()=>tt,ZodError:()=>$,ZodFirstPartyTypeKind:()=>gt,ZodFunction:()=>He,ZodIntersection:()=>Ke,ZodIssueCode:()=>R,ZodLazy:()=>Qe,ZodLiteral:()=>Xe,ZodMap:()=>Ye,ZodNaN:()=>ct,ZodNativeEnum:()=>st,ZodNever:()=>$e,ZodNull:()=>Ee,ZodNullable:()=>rt,ZodNumber:()=>Ie,ZodObject:()=>Ue,ZodOptional:()=>it,ZodParsedType:()=>j,ZodPipeline:()=>pt,ZodPromise:()=>at,ZodReadonly:()=>ht,ZodRecord:()=>We,ZodSchema:()=>ie,ZodSet:()=>Ge,ZodString:()=>Te,ZodSymbol:()=>Ae,ZodTransformer:()=>nt,ZodTuple:()=>Be,ZodType:()=>ie,ZodUndefined:()=>je,ZodUnion:()=>De,ZodUnknown:()=>Pe,ZodVoid:()=>Fe,addIssueToContext:()=>V,any:()=>Mt,array:()=>jt,bigint:()=>kt,boolean:()=>Ct,coerce:()=>as,custom:()=>ft,date:()=>Nt,datetimeRegex:()=>ke,defaultErrorMap:()=>F,discriminatedUnion:()=>$t,effect:()=>Yt,enum:()=>Kt,function:()=>zt,getErrorMap:()=>U,getParsedType:()=>E,instanceof:()=>_t,intersection:()=>Ft,isAborted:()=>H,isAsync:()=>ee,isDirty:()=>Q,isValid:()=>X,late:()=>vt,lazy:()=>Vt,literal:()=>Jt,makeIssue:()=>D,map:()=>Ut,nan:()=>xt,nativeEnum:()=>Bt,never:()=>Zt,null:()=>It,nullable:()=>Ht,number:()=>wt,object:()=>Et,objectUtil:()=>v,oboolean:()=>ss,onumber:()=>ts,optional:()=>Gt,ostring:()=>es,pipeline:()=>Xt,preprocess:()=>Qt,promise:()=>Wt,quotelessJson:()=>P,record:()=>qt,set:()=>Dt,setErrorMap:()=>q,strictObject:()=>Rt,string:()=>bt,symbol:()=>Tt,transformer:()=>Yt,tuple:()=>Lt,undefined:()=>St,union:()=>Pt,unknown:()=>Ot,util:()=>g,void:()=>At}),(y=g||(g={})).assertEqual=e=>{},y.assertIs=function(e){},y.assertNever=function(e){throw new Error},y.arrayToEnum=e=>{const t={};for(const s of e)t[s]=s;return t},y.getValidEnumValues=e=>{const t=y.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),s={};for(const a of t)s[a]=e[a];return y.objectValues(s)},y.objectValues=e=>y.objectKeys(e).map((function(t){return e[t]})),y.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},y.find=(e,t)=>{for(const s of e)if(t(s))return s},y.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,y.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},y.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(v||(v={})).mergeShapes=(e,t)=>({...e,...t});var j=g.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),E=e=>{switch(typeof e){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(e)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":return Array.isArray(e)?j.array:null===e?j.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?j.promise:"undefined"!=typeof Map&&e instanceof Map?j.map:"undefined"!=typeof Set&&e instanceof Set?j.set:"undefined"!=typeof Date&&e instanceof Date?j.date:j.object;default:return j.unknown}},R=g.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"]),P=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),$=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,g.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()}};$.create=e=>new $(e);var F=(e,t)=>{let s;switch(e.code){case R.invalid_type:s=e.received===j.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case R.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,g.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:s=`Unrecognized key(s) in object: ${g.joinValues(e.keys,", ")}`;break;case R.invalid_union:s="Invalid input";break;case R.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${g.joinValues(e.options)}`;break;case R.invalid_enum_value:s=`Invalid enum value. Expected ${g.joinValues(e.options)}, received '${e.received}'`;break;case R.invalid_arguments:s="Invalid function arguments";break;case R.invalid_return_type:s="Invalid function return type";break;case R.invalid_date:s="Invalid date";break;case R.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}"`:g.assertNever(e.validation):s="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case R.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 R.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 R.custom:s="Invalid input";break;case R.invalid_intersection_types:s="Intersection results could not be merged";break;case R.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case R.not_finite:s="Number must be finite";break;default:s=t.defaultError,g.assertNever(e)}return{message:s}},L=F;function q(e){L=e}function U(){return L}var D=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}},z=[];function V(e,t){const s=U(),a=D({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===F?void 0:F].filter((e=>!!e))});e.common.issues.push(a)}var J,K,B=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 W;"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 W;if("aborted"===n.status)return W;"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}}},W=Object.freeze({status:"aborted"}),Y=e=>({status:"dirty",value:e}),G=e=>({status:"valid",value:e}),H=e=>"aborted"===e.status,Q=e=>"dirty"===e.status,X=e=>"valid"===e.status,ee=e=>"undefined"!=typeof Promise&&e instanceof Promise;(K=J||(J={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},K.toString=e=>"string"==typeof e?e:e?.message;var te=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}},se=(e,t)=>{if(X(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 $(e.common.issues);return this._error=t,this._error}}};function ae(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 ne,ie=class{get description(){return this._def.description}_getType(e){return E(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:E(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new B,ctx:{common:e.parent.common,data:e.data,parsedType:E(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ee(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:E(e)},a=this._parseSync({data:e,path:s.path,parent:s});return se(s,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:E(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return X(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=>X(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:E(e)},a=this._parse({data:e,path:s.path,parent:s}),n=await(ee(a)?a:Promise.resolve(a));return se(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:R.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 nt({schema:this,typeName:gt.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 it.create(this,this._def)}nullable(){return rt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Le.create(this)}promise(){return at.create(this,this._def)}or(e){return De.create([this,e],this._def)}and(e){return Ke.create(this,e,this._def)}transform(e){return new nt({...ae(this._def),schema:this,typeName:gt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ot({...ae(this._def),innerType:this,defaultValue:t,typeName:gt.ZodDefault})}brand(){return new lt({typeName:gt.ZodBranded,type:this,...ae(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new dt({...ae(this._def),innerType:this,catchValue:t,typeName:gt.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return pt.create(this,e)}readonly(){return ht.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},re=/^c[^\s-]{8,}$/i,oe=/^[0-9a-z]+$/,de=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ce=/^[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,ue=/^[a-z0-9_-]{21}$/i,le=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pe=/^[-+]?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)?)??$/,he=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,me=/^(?:(?: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])$/,fe=/^(?:(?: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])$/,ge=/^(([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]))$/,ye=/^(([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])$/,ve=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_e=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,be="((\\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])))",we=new RegExp(`^${be}$`);function xe(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 ke(e){let t=`${be}T${xe(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 Ce(e,t){if(!le.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 Ne(e,t){return!("v4"!==t&&t||!fe.test(e))||!("v6"!==t&&t||!ye.test(e))}var Te=class e extends ie{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==j.string){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.string,received:t.parsedType}),W}const t=new B;let s;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),V(s,{code:R.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),V(s,{code:R.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?V(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&V(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)he.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"email",code:R.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)ne||(ne=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ne.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"emoji",code:R.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)ce.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"uuid",code:R.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)ue.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"nanoid",code:R.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)re.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"cuid",code:R.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)oe.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"cuid2",code:R.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)de.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"ulid",code:R.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),V(s,{validation:"url",code:R.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),V(s,{validation:"regex",code:R.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),V(s,{code:R.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),V(s,{code:R.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),V(s,{code:R.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){ke(i).test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{code:R.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){we.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{code:R.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${xe(i)}$`).test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{code:R.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?pe.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"duration",code:R.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(a=e.data,("v4"!==(n=i.version)&&n||!me.test(a))&&("v6"!==n&&n||!ge.test(a))&&(s=this._getOrReturnCtx(e,s),V(s,{validation:"ip",code:R.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?Ce(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"jwt",code:R.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?Ne(e.data,i.version)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"cidr",code:R.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?ve.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"base64",code:R.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?_e.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"base64url",code:R.invalid_string,message:i.message}),t.dirty()):g.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:R.invalid_string,...J.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...J.errToObj(e)})}url(e){return this._addCheck({kind:"url",...J.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...J.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...J.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...J.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...J.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...J.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...J.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...J.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...J.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...J.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...J.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...J.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,...J.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,...J.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...J.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...J.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...J.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...J.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...J.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...J.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...J.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...J.errToObj(t)})}nonempty(e){return this.min(1,J.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 Se(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}Te.create=e=>new Te({checks:[],typeName:gt.ZodString,coerce:e?.coerce??!1,...ae(e)});var Ie=class e extends ie{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)!==j.number){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.number,received:t.parsedType}),W}let t;const s=new B;for(const a of this._def.checks)if("int"===a.kind)g.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),V(t,{code:R.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),V(t,{code:R.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),V(t,{code:R.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty())}else"multipleOf"===a.kind?0!==Se(e.data,a.value)&&(t=this._getOrReturnCtx(e,t),V(t,{code:R.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),V(t,{code:R.not_finite,message:a.message}),s.dirty()):g.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,J.toString(t))}gt(e,t){return this.setLimit("min",e,!1,J.toString(t))}lte(e,t){return this.setLimit("max",e,!0,J.toString(t))}lt(e,t){return this.setLimit("max",e,!1,J.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:J.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:J.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:J.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:J.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:J.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:J.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&&g.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)}};Ie.create=e=>new Ie({checks:[],typeName:gt.ZodNumber,coerce:e?.coerce||!1,...ae(e)});var Me=class e extends ie{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)!==j.bigint)return this._getInvalidInput(e);let t;const s=new B;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),V(t,{code:R.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),V(t,{code:R.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),V(t,{code:R.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):g.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.bigint,received:t.parsedType}),W}gte(e,t){return this.setLimit("min",e,!0,J.toString(t))}gt(e,t){return this.setLimit("min",e,!1,J.toString(t))}lte(e,t){return this.setLimit("max",e,!0,J.toString(t))}lt(e,t){return this.setLimit("max",e,!1,J.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:J.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:J.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:J.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}};Me.create=e=>new Me({checks:[],typeName:gt.ZodBigInt,coerce:e?.coerce??!1,...ae(e)});var Oe=class extends ie{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==j.boolean){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.boolean,received:t.parsedType}),W}return G(e.data)}};Oe.create=e=>new Oe({typeName:gt.ZodBoolean,coerce:e?.coerce||!1,...ae(e)});var Ze=class e extends ie{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==j.date){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.date,received:t.parsedType}),W}if(Number.isNaN(e.data.getTime())){return V(this._getOrReturnCtx(e),{code:R.invalid_date}),W}const t=new B;let s;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),V(s,{code:R.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),V(s,{code:R.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):g.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:J.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:J.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}};Ze.create=e=>new Ze({checks:[],coerce:e?.coerce||!1,typeName:gt.ZodDate,...ae(e)});var Ae=class extends ie{_parse(e){if(this._getType(e)!==j.symbol){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.symbol,received:t.parsedType}),W}return G(e.data)}};Ae.create=e=>new Ae({typeName:gt.ZodSymbol,...ae(e)});var je=class extends ie{_parse(e){if(this._getType(e)!==j.undefined){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.undefined,received:t.parsedType}),W}return G(e.data)}};je.create=e=>new je({typeName:gt.ZodUndefined,...ae(e)});var Ee=class extends ie{_parse(e){if(this._getType(e)!==j.null){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.null,received:t.parsedType}),W}return G(e.data)}};Ee.create=e=>new Ee({typeName:gt.ZodNull,...ae(e)});var Re=class extends ie{constructor(){super(...arguments),this._any=!0}_parse(e){return G(e.data)}};Re.create=e=>new Re({typeName:gt.ZodAny,...ae(e)});var Pe=class extends ie{constructor(){super(...arguments),this._unknown=!0}_parse(e){return G(e.data)}};Pe.create=e=>new Pe({typeName:gt.ZodUnknown,...ae(e)});var $e=class extends ie{_parse(e){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.never,received:t.parsedType}),W}};$e.create=e=>new $e({typeName:gt.ZodNever,...ae(e)});var Fe=class extends ie{_parse(e){if(this._getType(e)!==j.undefined){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.void,received:t.parsedType}),W}return G(e.data)}};Fe.create=e=>new Fe({typeName:gt.ZodVoid,...ae(e)});var Le=class e extends ie{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==j.array)return V(t,{code:R.invalid_type,expected:j.array,received:t.parsedType}),W;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,n=t.data.length<a.exactLength.value;(e||n)&&(V(t,{code:e?R.too_big:R.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&&(V(t,{code:R.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&&(V(t,{code:R.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 te(t,e,t.path,s))))).then((e=>B.mergeArray(s,e)));const n=[...t.data].map(((e,s)=>a.type._parseSync(new te(t,e,t.path,s))));return B.mergeArray(s,n)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:J.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:J.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:J.toString(s)}})}nonempty(e){return this.min(1,e)}};function qe(e){if(e instanceof Ue){const t={};for(const s in e.shape){const a=e.shape[s];t[s]=it.create(qe(a))}return new Ue({...e._def,shape:()=>t})}return e instanceof Le?new Le({...e._def,type:qe(e.element)}):e instanceof it?it.create(qe(e.unwrap())):e instanceof rt?rt.create(qe(e.unwrap())):e instanceof Be?Be.create(e.items.map((e=>qe(e)))):e}Le.create=(e,t)=>new Le({type:e,minLength:null,maxLength:null,exactLength:null,typeName:gt.ZodArray,...ae(t)});var Ue=class e extends ie{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=g.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==j.object){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.object,received:t.parsedType}),W}const{status:t,ctx:s}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof $e&&"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 te(s,n,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof $e){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&&(V(s,{code:R.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 te(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=>B.mergeObjectSync(t,e))):B.mergeObjectSync(t,r)}get shape(){return this._def.shape()}strict(t){return J.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:J.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:gt.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 g.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 g.objectKeys(this.shape))t[e]||(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}deepPartial(){return qe(this)}partial(t){const s={};for(const e of g.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 g.objectKeys(this.shape))if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof it;)t=t._def.innerType;s[e]=t}return new e({...this._def,shape:()=>s})}keyof(){return et(g.objectKeys(this.shape))}};Ue.create=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strip",catchall:$e.create(),typeName:gt.ZodObject,...ae(t)}),Ue.strictCreate=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strict",catchall:$e.create(),typeName:gt.ZodObject,...ae(t)}),Ue.lazycreate=(e,t)=>new Ue({shape:e,unknownKeys:"strip",catchall:$e.create(),typeName:gt.ZodObject,...ae(t)});var De=class extends ie{_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 $(e.ctx.common.issues)));return V(t,{code:R.invalid_union,unionErrors:s}),W}));{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 $(e)));return V(t,{code:R.invalid_union,unionErrors:n}),W}}get options(){return this._def.options}};De.create=(e,t)=>new De({options:e,typeName:gt.ZodUnion,...ae(t)});var ze=e=>e instanceof Qe?ze(e.schema):e instanceof nt?ze(e.innerType()):e instanceof Xe?[e.value]:e instanceof tt?e.options:e instanceof st?g.objectValues(e.enum):e instanceof ot?ze(e._def.innerType):e instanceof je?[void 0]:e instanceof Ee?[null]:e instanceof it?[void 0,...ze(e.unwrap())]:e instanceof rt?[null,...ze(e.unwrap())]:e instanceof lt||e instanceof ht?ze(e.unwrap()):e instanceof dt?ze(e._def.innerType):[],Ve=class e extends ie{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.object)return V(t,{code:R.invalid_type,expected:j.object,received:t.parsedType}),W;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}):(V(t,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),W)}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=ze(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:gt.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:n,...ae(a)})}};function Je(e,t){const s=E(e),a=E(t);if(e===t)return{valid:!0,data:e};if(s===j.object&&a===j.object){const s=g.objectKeys(t),a=g.objectKeys(e).filter((e=>-1!==s.indexOf(e))),n={...e,...t};for(const s of a){const a=Je(e[s],t[s]);if(!a.valid)return{valid:!1};n[s]=a.data}return{valid:!0,data:n}}if(s===j.array&&a===j.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let a=0;a<e.length;a++){const n=Je(e[a],t[a]);if(!n.valid)return{valid:!1};s.push(n.data)}return{valid:!0,data:s}}return s===j.date&&a===j.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}var Ke=class extends ie{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=(e,a)=>{if(H(e)||H(a))return W;const n=Je(e.value,a.value);return n.valid?((Q(e)||Q(a))&&t.dirty(),{status:t.value,value:n.data}):(V(s,{code:R.invalid_intersection_types}),W)};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}))}};Ke.create=(e,t,s)=>new Ke({left:e,right:t,typeName:gt.ZodIntersection,...ae(s)});var Be=class e extends ie{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==j.array)return V(s,{code:R.invalid_type,expected:j.array,received:s.parsedType}),W;if(s.data.length<this._def.items.length)return V(s,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&s.data.length>this._def.items.length&&(V(s,{code:R.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 te(s,e,s.path,t)):null})).filter((e=>!!e));return s.common.async?Promise.all(a).then((e=>B.mergeArray(t,e))):B.mergeArray(t,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Be.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Be({items:e,typeName:gt.ZodTuple,rest:null,...ae(t)})};var We=class e extends ie{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!==j.object)return V(s,{code:R.invalid_type,expected:j.object,received:s.parsedType}),W;const a=[],n=this._def.keyType,i=this._def.valueType;for(const e in s.data)a.push({key:n._parse(new te(s,e,s.path,e)),value:i._parse(new te(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?B.mergeObjectAsync(t,a):B.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(t,s,a){return new e(s instanceof ie?{keyType:t,valueType:s,typeName:gt.ZodRecord,...ae(a)}:{keyType:Te.create(),valueType:t,typeName:gt.ZodRecord,...ae(s)})}},Ye=class extends ie{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!==j.map)return V(s,{code:R.invalid_type,expected:j.map,received:s.parsedType}),W;const a=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map((([e,t],i)=>({key:a._parse(new te(s,e,s.path,[i,"key"])),value:n._parse(new te(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 W;"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 W;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}};Ye.create=(e,t,s)=>new Ye({valueType:t,keyType:e,typeName:gt.ZodMap,...ae(s)});var Ge=class e extends ie{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==j.set)return V(s,{code:R.invalid_type,expected:j.set,received:s.parsedType}),W;const a=this._def;null!==a.minSize&&s.data.size<a.minSize.value&&(V(s,{code:R.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&&(V(s,{code:R.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 W;"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 te(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:J.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:J.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Ge.create=(e,t)=>new Ge({valueType:e,minSize:null,maxSize:null,typeName:gt.ZodSet,...ae(t)});var He=class e extends ie{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.function)return V(t,{code:R.invalid_type,expected:j.function,received:t.parsedType}),W;function s(e,s){return D({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,U(),F].filter((e=>!!e)),issueData:{code:R.invalid_arguments,argumentsError:s}})}function a(e,s){return D({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,U(),F].filter((e=>!!e)),issueData:{code:R.invalid_return_type,returnTypeError:s}})}const n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof at){const e=this;return G((async function(...t){const r=new $([]),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 G((function(...t){const r=e._def.args.safeParse(t,n);if(!r.success)throw new $([s(t,r.error)]);const o=Reflect.apply(i,this,r.data),d=e._def.returns.safeParse(o,n);if(!d.success)throw new $([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:Be.create(t).rest(Pe.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||Be.create([]).rest(Pe.create()),returns:s||Pe.create(),typeName:gt.ZodFunction,...ae(a)})}},Qe=class extends ie{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})}};Qe.create=(e,t)=>new Qe({getter:e,typeName:gt.ZodLazy,...ae(t)});var Xe=class extends ie{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return V(t,{received:t.data,code:R.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:e.data}}get value(){return this._def.value}};function et(e,t){return new tt({values:e,typeName:gt.ZodEnum,...ae(t)})}Xe.create=(e,t)=>new Xe({value:e,typeName:gt.ZodLiteral,...ae(t)});var tt=class e extends ie{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),s=this._def.values;return V(t,{expected:g.joinValues(s),received:t.parsedType,code:R.invalid_type}),W}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 V(t,{received:t.data,code:R.invalid_enum_value,options:s}),W}return G(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})}};tt.create=et;var st=class extends ie{_parse(e){const t=g.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==j.string&&s.parsedType!==j.number){const e=g.objectValues(t);return V(s,{expected:g.joinValues(e),received:s.parsedType,code:R.invalid_type}),W}if(this._cache||(this._cache=new Set(g.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=g.objectValues(t);return V(s,{received:s.data,code:R.invalid_enum_value,options:e}),W}return G(e.data)}get enum(){return this._def.values}};st.create=(e,t)=>new st({values:e,typeName:gt.ZodNativeEnum,...ae(t)});var at=class extends ie{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.promise&&!1===t.common.async)return V(t,{code:R.invalid_type,expected:j.promise,received:t.parsedType}),W;const s=t.parsedType===j.promise?t.data:Promise.resolve(t.data);return G(s.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}};at.create=(e,t)=>new at({type:e,typeName:gt.ZodPromise,...ae(t)});var nt=class extends ie{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===gt.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=>{V(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 W;const a=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===a.status?W:"dirty"===a.status||"dirty"===t.value?Y(a.value):a}));{if("aborted"===t.value)return W;const a=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===a.status?W:"dirty"===a.status||"dirty"===t.value?Y(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?W:("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?W:("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(!X(e))return W;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=>X(e)?Promise.resolve(a.transform(e.value,n)).then((e=>({status:t.value,value:e}))):W))}g.assertNever(a)}};nt.create=(e,t,s)=>new nt({schema:e,typeName:gt.ZodEffects,effect:t,...ae(s)}),nt.createWithPreprocess=(e,t,s)=>new nt({schema:t,effect:{type:"preprocess",transform:e},typeName:gt.ZodEffects,...ae(s)});var it=class extends ie{_parse(e){return this._getType(e)===j.undefined?G(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};it.create=(e,t)=>new it({innerType:e,typeName:gt.ZodOptional,...ae(t)});var rt=class extends ie{_parse(e){return this._getType(e)===j.null?G(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rt.create=(e,t)=>new rt({innerType:e,typeName:gt.ZodNullable,...ae(t)});var ot=class extends ie{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===j.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ot.create=(e,t)=>new ot({innerType:e,typeName:gt.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...ae(t)});var dt=class extends ie{_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 ee(a)?a.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new $(s.common.issues)},input:s.data})}))):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new $(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};dt.create=(e,t)=>new dt({innerType:e,typeName:gt.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...ae(t)});var ct=class extends ie{_parse(e){if(this._getType(e)!==j.nan){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.nan,received:t.parsedType}),W}return{status:"valid",value:e.data}}};ct.create=e=>new ct({typeName:gt.ZodNaN,...ae(e)});var ut=Symbol("zod_brand"),lt=class extends ie{_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}},pt=class e extends ie{_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?W:"dirty"===e.status?(t.dirty(),Y(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?W:"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:gt.ZodPipeline})}},ht=class extends ie{_parse(e){const t=this._def.innerType._parse(e),s=e=>(X(e)&&(e.value=Object.freeze(e.value)),e);return ee(t)?t.then((e=>s(e))):s(t)}unwrap(){return this._def.innerType}};function mt(e,t){const s="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof s?{message:s}:s}function ft(e,t={},s){return e?Re.create().superRefine(((a,n)=>{const i=e(a);if(i instanceof Promise)return i.then((e=>{if(!e){const e=mt(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}}));if(!i){const e=mt(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}})):Re.create()}ht.create=(e,t)=>new ht({innerType:e,typeName:gt.ZodReadonly,...ae(t)});var gt,yt,vt={object:Ue.lazycreate};(yt=gt||(gt={})).ZodString="ZodString",yt.ZodNumber="ZodNumber",yt.ZodNaN="ZodNaN",yt.ZodBigInt="ZodBigInt",yt.ZodBoolean="ZodBoolean",yt.ZodDate="ZodDate",yt.ZodSymbol="ZodSymbol",yt.ZodUndefined="ZodUndefined",yt.ZodNull="ZodNull",yt.ZodAny="ZodAny",yt.ZodUnknown="ZodUnknown",yt.ZodNever="ZodNever",yt.ZodVoid="ZodVoid",yt.ZodArray="ZodArray",yt.ZodObject="ZodObject",yt.ZodUnion="ZodUnion",yt.ZodDiscriminatedUnion="ZodDiscriminatedUnion",yt.ZodIntersection="ZodIntersection",yt.ZodTuple="ZodTuple",yt.ZodRecord="ZodRecord",yt.ZodMap="ZodMap",yt.ZodSet="ZodSet",yt.ZodFunction="ZodFunction",yt.ZodLazy="ZodLazy",yt.ZodLiteral="ZodLiteral",yt.ZodEnum="ZodEnum",yt.ZodEffects="ZodEffects",yt.ZodNativeEnum="ZodNativeEnum",yt.ZodOptional="ZodOptional",yt.ZodNullable="ZodNullable",yt.ZodDefault="ZodDefault",yt.ZodCatch="ZodCatch",yt.ZodPromise="ZodPromise",yt.ZodBranded="ZodBranded",yt.ZodPipeline="ZodPipeline",yt.ZodReadonly="ZodReadonly";var _t=(e,t={message:`Input not instance of ${e.name}`})=>ft((t=>t instanceof e),t),bt=Te.create,wt=Ie.create,xt=ct.create,kt=Me.create,Ct=Oe.create,Nt=Ze.create,Tt=Ae.create,St=je.create,It=Ee.create,Mt=Re.create,Ot=Pe.create,Zt=$e.create,At=Fe.create,jt=Le.create,Et=Ue.create,Rt=Ue.strictCreate,Pt=De.create,$t=Ve.create,Ft=Ke.create,Lt=Be.create,qt=We.create,Ut=Ye.create,Dt=Ge.create,zt=He.create,Vt=Qe.create,Jt=Xe.create,Kt=tt.create,Bt=st.create,Wt=at.create,Yt=nt.create,Gt=it.create,Ht=rt.create,Qt=nt.createWithPreprocess,Xt=pt.create,es=()=>bt().optional(),ts=()=>wt().optional(),ss=()=>Ct().optional(),as={string:e=>Te.create({...e,coerce:!0}),number:e=>Ie.create({...e,coerce:!0}),boolean:e=>Oe.create({...e,coerce:!0}),bigint:e=>Me.create({...e,coerce:!0}),date:e=>Ze.create({...e,coerce:!0})},ns=W,is={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"},rs={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"},os=A.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"]),ds=A.enum(["unknown","android","ios","desktop","web"]),cs=A.object({chatId:A.string(),channelId:A.string(),receiverId:A.string(),receiverName:A.string(),roomId:A.string(),roomName:A.string(),senderId:A.string(),senderName:A.string(),senderDevice:ds,chatType:os,timestamp:A.number(),mentions:A.string().array(),text:A.string().nullable(),links:A.string().array(),isPrefix:A.boolean(),isFromMe:A.boolean(),isTagMe:A.boolean(),isGroup:A.boolean(),isStory:A.boolean(),isViewOnce:A.boolean(),isEdited:A.boolean(),isDeleted:A.boolean(),isPinned:A.boolean(),isUnPinned:A.boolean(),isChannel:A.boolean(),isBroadcast:A.boolean(),isEphemeral:A.boolean(),isForwarded:A.boolean(),citation:A.record(A.string(),A.boolean()).nullable(),media:A.object({buffer:A.function().returns(A.instanceof(Buffer)),stream:A.function().returns(A.instanceof(m.Readable))}).passthrough().nullable(),message:A.function().returns(A.record(A.string(),A.any()))});cs.extend({replied:cs.nullable()});var us=class{constructor(e,t,s){this.socket=e,this.client=t,this.db=s}maxReplies=0;async connection(t){this.client.startSpinner("connection","Connecting to WhatsApp...");const{connection:s,lastDisconnect:a,qr:n}=t;if(this.client.emit("connection",{status:"connecting"}),"qr"===this.client.options?.authType&&n)return this.client.stopSpinner("connection",!1),console.log(),console.log(await T.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"===s){this.client.failSpinner("connection","Connection closed");const t=a?.error?.output?.statusCode,s=t===e.DisconnectReason.restartRequired;if(console.log(a?.error?.message),401===t||405===t||500===t)return void console.error("Invalid session, please delete manually");s&&await this.client.initialize()}else"open"===s&&(this.client.stopSpinner("connection",!0,"Connected to WhatsApp\n"),this.client.emit("connection",{status:"open"}))}async messages(t,s){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 a=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(),s=I(e?.value);t=s}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(),s=I(e?.value);t=s}const c={},u=e.getContentType(t?.message?.protocolMessage?.editedMessage||t?.message);c.chatId=t?.message?.protocolMessage?.key?.id||t?.key?.id,c.channelId="",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 l=await this.db.selectFrom("chats").select("value").where("id","=",c.roomId).executeTakeFirst();c.roomName=I(l?.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||I(p?.value)?.name||c.receiverName,c.roomName=c.roomName||c.senderName,c.senderDevice=e.getDevice(c.chatId),c.chatType=is[u],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];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?.[u]||t?.message?.[u])?.message?.documentMessage||t?.message?.[u];"text"!=c.chatType&&(c.media={...Z(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?.[u]?.contextInfo?.stanzaId;if(f&&this.maxReplies<1){this.maxReplies++;const s=await this.db.selectFrom("messages").select("value").where("id","=",f).executeTakeFirst(),a=I(s?.value);if(a)c.replied=await this.messages(a,!0);else{const s=t,a=e.getContentType(s.message?.extendedTextMessage?.contextInfo.quotedMessage);s.key.id=s.message?.extendedTextMessage?.contextInfo.stanzaId,s.message[a]=s.message?.extendedTextMessage?.contextInfo.quotedMessage[a],delete s.message?.extendedTextMessage,c.replied=await this.messages(s,!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 s of e.matchAll(/@(\d+)/g))t.add(s[1]);return[...t]})(c.text),c.links=((e="")=>e&&e.match(/(?:https?:\/\/)?[^\s<>"']+\.[^\s<>"']+/g)||[])(c.text);const y=t?.message?.[u];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=O(M(t),"editedMessage"),c.isEphemeral=O(M(y?.contextInfo),"ephemeralSettingTimestamp"),c.isForwarded=O(M(y?.contextInfo),"forwardingScore"),c.isViewOnce=!!y?.viewOnce,c.isPrefix&&(c.text=c.text.replace(new RegExp(`^${this.client.options?.prefix}`),"")),c.message=()=>a,s||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)}},ls=async(t,s)=>{const a="auth";await(async e=>{await e.schema.createTable("auth").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("auth_session_id_unique",["session","id"]).execute(),await e.schema.createTable("chats").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("chats_session_id_unique",["session","id"]).execute(),await e.schema.createTable("contacts").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("contacts_session_id_unique",["session","id"]).execute(),await e.schema.createTable("messages").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("messages_session_id_unique",["session","id"]).execute(),await e.schema.createIndex("auth_session_idx").ifNotExists().on("auth").column("session").execute(),await e.schema.createIndex("auth_id_idx").ifNotExists().on("auth").column("id").execute(),await e.schema.createIndex("chats_session_idx").ifNotExists().on("chats").column("session").execute(),await e.schema.createIndex("chats_id_idx").ifNotExists().on("chats").column("id").execute(),await e.schema.createIndex("contacts_session_idx").ifNotExists().on("contacts").column("session").execute(),await e.schema.createIndex("contacts_id_idx").ifNotExists().on("contacts").column("id").execute(),await e.schema.createIndex("messages_session_idx").ifNotExists().on("messages").column("session").execute(),await e.schema.createIndex("messages_id_idx").ifNotExists().on("messages").column("id").execute()})(t);const n=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")},i=async i=>{const r=await n((()=>t.selectFrom(a).select(["value"]).where("id","=",i).where("session","=",s).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)},r=async(i,r)=>{const o=JSON.stringify(r,e.BufferJSON.replacer);await n((()=>t.insertInto(a).values({session:s,id:i,value:o}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:o}))).execute()))},o=async e=>{await n((()=>t.deleteFrom(a).where("id","=",e).where("session","=",s).execute()))},d=await i("creds")||e.initAuthCreds();return{state:{creds:d,keys:{get:async(t,s)=>{const a={};for(const n of s){let s=await i(`${t}-${n}`);"app-state-sync-key"===t&&s&&(s=e.proto.SenderKeyMessage.fromObject(s)),a[n]=s}return a},set:async e=>{for(const t in e)for(const s in e[t]){const a=e[t][s],n=`${t}-${s}`;a?await r(n,a):await o(n)}}}},saveCreds:async()=>{await r("creds",d)},clear:async()=>{await(async()=>{await n((()=>t.deleteFrom(a).where("session","=",s).where("id","!=","creds").execute()))})()},removeCreds:async()=>{await(async()=>{await n((()=>t.deleteFrom(a).where("session","=",s).execute()))})()}}},ps=A.object({type:A.enum(["sqlite","postgresql","mysql"]).default("sqlite"),connection:A.object({url:A.string().default("./session/zaileys.db")}).optional().default({})}).optional().default({}),hs=A.record(A.function().returns(A.union([A.number().array(),A.promise(A.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})),ms=A.object({prefix:A.string().optional(),ignoreMe:A.boolean().optional().default(!0),showLogs:A.boolean().optional().default(!0),autoMentions:A.boolean().optional().default(!0),autoOnline:A.boolean().optional().default(!0),autoRead:A.boolean().optional().default(!0),autoPresence:A.boolean().optional().default(!0),autoRejectCall:A.boolean().optional().default(!0),database:ps,citation:hs}),fs=A.object({authType:A.literal("pairing"),phoneNumber:A.number()}).extend(ms.shape),gs=A.object({authType:A.literal("qr"),phoneNumber:A.undefined().optional()}).extend(ms.shape),ys=A.discriminatedUnion("authType",[fs,gs]),vs=A.union([A.string().url(),A.instanceof(Buffer).or(A.instanceof(m.Readable))]),_s=A.union([A.string(),A.object({image:vs,text:A.string().optional()}),A.object({video:vs,text:A.string().optional()}),A.object({videoNote:vs}),A.object({gif:vs,text:A.string().optional()}),A.object({audio:vs}),A.object({audioNote:vs}),A.object({sticker:vs})]),bs=A.object({roomId:A.string(),asForwarded:A.boolean().optional(),asViewOnce:A.boolean().optional(),verifiedReply:A.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).optional(),quoted:A.function().returns(A.record(A.string(),A.any())).optional()}),ws=bs,xs=A.object({latitude:A.number(),longitude:A.number(),title:A.string().optional(),footer:A.string().optional()}),ks=bs,Cs=A.object({fullname:A.string(),nickname:A.string().optional(),organization:A.string().optional(),role:A.string().optional(),email:A.string().email().optional(),whatsAppNumber:A.number(),callNumber:A.number().optional(),voiceNumber:A.number().optional(),website:A.string().url().optional(),homeAddress:A.string().optional(),workAddress:A.string().optional(),avatar:A.string().url().optional()}),Ns=A.object({message:A.function().returns(A.record(A.string(),A.any()))}),Ts=A.string(),Ss=A.object({message:A.function().returns(A.record(A.string(),A.any()))}),Is=A.object({action:A.enum(["pin","unpin"]),expired:A.enum(["24h","7d","30d"])}),Ms=bs.pick({roomId:!0}),Os=A.object({name:A.string(),answers:A.string().array(),multipleAnswers:A.boolean().optional()}),Zs=A.object({message:A.function().returns(A.record(A.string(),A.any()))}),As=A.string(),js=A.object({message:A.function().returns(A.record(A.string(),A.any()))}),Es=A.object({callId:A.string(),callerId:A.string()}),Rs=bs.pick({roomId:!0}),Ps=A.object({expired:A.enum(["remove","8h","7d"])}),$s=A.string();A.object({type:A.enum(["group","user"]),id:A.string(),name:A.string(),bio:A.string(),avatar:A.string().url(),ephemeralDuration:A.number().optional(),isRestrict:A.boolean().optional(),isAnnounce:A.boolean().optional(),isCommunity:A.boolean().optional(),isCommunityAnnounce:A.boolean().optional(),isJoinApprovalMode:A.boolean().optional(),isMemberAddMode:A.boolean().optional(),owner:A.object({type:A.literal("user"),id:A.string()}).nullable(),roomCreatedAt:A.number().optional(),nameUpdatedAt:A.number().optional(),bioUpdatedAt:A.number().optional(),membersLength:A.number().optional(),members:A.object({type:A.enum(["user","admin","superadmin"]),id:A.string()}).array().optional()});var Fs=bs.pick({roomId:!0}),Ls=A.enum(["typing","recording","online","offline","paused"]),qs=class{constructor(e){this.wa=e,this.parser=new us(this.wa.socket,this.wa.client,this.wa.db)}parser;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=rs[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=_s.parse(e),t=bs.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=xs.parse(e),t=ws.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=Cs.parse(e),t=ks.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=Ts.parse(e),t=Ns.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{react:{text:e,key:t.message()?.key},...t})}async pin(e,t){e=Is.parse(e),t=Ss.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=Os.parse(e),t=Ms.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=As.parse(e),t=Zs.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{text:e,edit:t.message()?.key,...t})}async delete(e){return e=js.parse(e),await this.sendMessage(e.message()?.key?.remoteJid,{delete:e.message()?.key})}async rejectCall(e){return e=Es.parse(e),await(this.wa.socket?.rejectCall(e.callId,e.callerId))}async mute(e,t){e=Ps.parse(e),t=Rs.parse(t);return await(this.wa.socket?.chatModify({mute:{remove:null,"8h":864e5,"7d":6048e5}[e.expired]},t.roomId))}async profile(t){const s=(t=$s.parse(t)).includes("@g.us"),a={};a.id=t;if(e.jidNormalizedUser(this.wa.socket?.user?.id)==t)a.name=this.wa.socket?.user?.name||this.wa.socket?.user?.verifiedName;else if(s){const e=await(this.wa.socket?.groupMetadata(t));a.type="group",a.name=e?.subject,a.bio=e?.desc,a.avatar=await(this.wa.socket?.profilePictureUrl(t)),a.ephemeralDuration=e?.ephemeralDuration,a.isRestrict=e?.restrict,a.isAnnounce=e?.announce,a.isCommunity=e?.isCommunity,a.isCommunityAnnounce=e?.isCommunityAnnounce,a.isJoinApprovalMode=e?.joinApprovalMode,a.isMemberAddMode=e?.memberAddMode,a.owner={type:"user",id:e?.owner},a.roomCreatedAt=e?.creation,a.nameUpdatedAt=e?.subjectTime,a.membersLength=e?.size,a.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()),s=I(e?.value),n=(await(this.wa?.socket?.fetchStatus(t)))[0]?.status;a.type="user",a.name=s?.name,a.bio=n?.status,a.avatar=await(this.wa?.socket?.profilePictureUrl(t)),a.bioUpdatedAt=new Date(n?.setAt).getTime()}return a}async presence(e,t){e=Ls.parse(e),t=Fs.parse(t);return await(this.wa.socket?.sendPresenceUpdate({typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"}[e],t.roomId))}},Us=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 b.default({stdTTL:300,useClones:!1});chatId="zaileys-chats";logger=x.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=>{_.default(e,((e,s)=>{if(e)return t("");console.log(s),t(s||"")}))})))(),this.options=await ys.parseAsync(this.props),this.startSpinner("db","Initializing database..."),this.db=await((e,t)=>{if("sqlite"===e){const e=t||"./db/zaileys.db",s=N.default.resolve(e);return o.mkdirSync(N.default.dirname(s),{recursive:!0}),o.writeFileSync(s,"",{flag:"a"}),new d.Kysely({dialect:new d.SqliteDialect({database:new k.default(s)})})}const s=new p.URL(t),a=s.protocol.replace(":","");if("mysql"===e)return new d.Kysely({dialect:new d.MysqlDialect({pool:C.default.createPool({host:s.hostname,user:s.username,password:s.password,database:s.pathname.replace("/",""),port:parseInt(s.port||"3306",10)})})});if("postgresql"===e)return new d.Kysely({dialect:new d.PostgresDialect({pool:new l.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: ${a}`)})(this.options.database.type,this.options.database.connection.url),this.stopSpinner("db",!0,"Database initialized"),this.startSpinner("auth","Setting up auth adapter...");const{state:t,saveCreds:s}=await ls(this.db,this.chatId);this.stopSpinner("auth",!0,"Auth adapter ready"),this.startSpinner("store","Setting up store adapter...");const a=await(async(e,t,s)=>({bind:a=>{const n=new us(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: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 b.default,mediaCache:new b.default({stdTTL:60}),userDevicesCache:new b.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 I(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 qs({client:this,db:this.db,socket:this.socket}),this.socket?.ev.on("creds.update",s),a.bind(this.socket)}startSpinner(e,t){let s=this.spinners.get(e);return s||(s=w.default(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)}},Ds=Us;exports.Client=Us,exports.default=Ds;
|
|
1
|
+
"use strict";var e=require("baileys"),t=require("events"),s=require("figlet"),a=require("node-cache"),n=require("ora"),i=require("pino"),r=require("better-sqlite3"),o=require("fs"),d=require("kysely"),c=require("mysql2"),u=require("path"),l=require("pg"),p=require("url"),h=require("qrcode"),m=require("stream");function f(e){return e&&e.__esModule?e:{default:e}}var g,y,v,_=f(s),b=f(a),w=f(n),x=f(i),k=f(r),C=f(c),N=f(u),T=f(h),S=Object.defineProperty,I=(e="")=>{try{return JSON.parse(e)}catch{return JSON.parse(JSON.stringify(e))}},M=(e={})=>{try{return JSON.stringify(e)}catch{return JSON.stringify(JSON.parse(JSON.stringify(e)))}},O=(e="",t="")=>e?e.toLowerCase().includes(t.toLowerCase()):null,Z=(e,t)=>e&&"object"==typeof e?Array.isArray(e)?e.map((e=>Z(e,t))):Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e))).map((([e,s])=>[e,"object"==typeof s?Z(s,t):s]))):e,A={};((e,t)=>{for(var s in t)S(e,s,{get:t[s],enumerable:!0})})(A,{BRAND:()=>ut,DIRTY:()=>Y,EMPTY_PATH:()=>z,INVALID:()=>W,NEVER:()=>ns,OK:()=>G,ParseStatus:()=>B,Schema:()=>ie,ZodAny:()=>Re,ZodArray:()=>Le,ZodBigInt:()=>Me,ZodBoolean:()=>Oe,ZodBranded:()=>lt,ZodCatch:()=>dt,ZodDate:()=>Ze,ZodDefault:()=>ot,ZodDiscriminatedUnion:()=>Ve,ZodEffects:()=>nt,ZodEnum:()=>tt,ZodError:()=>$,ZodFirstPartyTypeKind:()=>gt,ZodFunction:()=>He,ZodIntersection:()=>Ke,ZodIssueCode:()=>R,ZodLazy:()=>Qe,ZodLiteral:()=>Xe,ZodMap:()=>Ye,ZodNaN:()=>ct,ZodNativeEnum:()=>st,ZodNever:()=>$e,ZodNull:()=>Ee,ZodNullable:()=>rt,ZodNumber:()=>Ie,ZodObject:()=>Ue,ZodOptional:()=>it,ZodParsedType:()=>j,ZodPipeline:()=>pt,ZodPromise:()=>at,ZodReadonly:()=>ht,ZodRecord:()=>We,ZodSchema:()=>ie,ZodSet:()=>Ge,ZodString:()=>Te,ZodSymbol:()=>Ae,ZodTransformer:()=>nt,ZodTuple:()=>Be,ZodType:()=>ie,ZodUndefined:()=>je,ZodUnion:()=>De,ZodUnknown:()=>Pe,ZodVoid:()=>Fe,addIssueToContext:()=>V,any:()=>Mt,array:()=>jt,bigint:()=>kt,boolean:()=>Ct,coerce:()=>as,custom:()=>ft,date:()=>Nt,datetimeRegex:()=>ke,defaultErrorMap:()=>F,discriminatedUnion:()=>$t,effect:()=>Yt,enum:()=>Kt,function:()=>zt,getErrorMap:()=>U,getParsedType:()=>E,instanceof:()=>_t,intersection:()=>Ft,isAborted:()=>H,isAsync:()=>ee,isDirty:()=>Q,isValid:()=>X,late:()=>vt,lazy:()=>Vt,literal:()=>Jt,makeIssue:()=>D,map:()=>Ut,nan:()=>xt,nativeEnum:()=>Bt,never:()=>Zt,null:()=>It,nullable:()=>Ht,number:()=>wt,object:()=>Et,objectUtil:()=>v,oboolean:()=>ss,onumber:()=>ts,optional:()=>Gt,ostring:()=>es,pipeline:()=>Xt,preprocess:()=>Qt,promise:()=>Wt,quotelessJson:()=>P,record:()=>qt,set:()=>Dt,setErrorMap:()=>q,strictObject:()=>Rt,string:()=>bt,symbol:()=>Tt,transformer:()=>Yt,tuple:()=>Lt,undefined:()=>St,union:()=>Pt,unknown:()=>Ot,util:()=>g,void:()=>At}),(y=g||(g={})).assertEqual=e=>{},y.assertIs=function(e){},y.assertNever=function(e){throw new Error},y.arrayToEnum=e=>{const t={};for(const s of e)t[s]=s;return t},y.getValidEnumValues=e=>{const t=y.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),s={};for(const a of t)s[a]=e[a];return y.objectValues(s)},y.objectValues=e=>y.objectKeys(e).map((function(t){return e[t]})),y.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},y.find=(e,t)=>{for(const s of e)if(t(s))return s},y.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,y.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},y.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(v||(v={})).mergeShapes=(e,t)=>({...e,...t});var j=g.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),E=e=>{switch(typeof e){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(e)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":return Array.isArray(e)?j.array:null===e?j.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?j.promise:"undefined"!=typeof Map&&e instanceof Map?j.map:"undefined"!=typeof Set&&e instanceof Set?j.set:"undefined"!=typeof Date&&e instanceof Date?j.date:j.object;default:return j.unknown}},R=g.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"]),P=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),$=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,g.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()}};$.create=e=>new $(e);var F=(e,t)=>{let s;switch(e.code){case R.invalid_type:s=e.received===j.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case R.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,g.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:s=`Unrecognized key(s) in object: ${g.joinValues(e.keys,", ")}`;break;case R.invalid_union:s="Invalid input";break;case R.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${g.joinValues(e.options)}`;break;case R.invalid_enum_value:s=`Invalid enum value. Expected ${g.joinValues(e.options)}, received '${e.received}'`;break;case R.invalid_arguments:s="Invalid function arguments";break;case R.invalid_return_type:s="Invalid function return type";break;case R.invalid_date:s="Invalid date";break;case R.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}"`:g.assertNever(e.validation):s="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case R.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 R.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 R.custom:s="Invalid input";break;case R.invalid_intersection_types:s="Intersection results could not be merged";break;case R.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case R.not_finite:s="Number must be finite";break;default:s=t.defaultError,g.assertNever(e)}return{message:s}},L=F;function q(e){L=e}function U(){return L}var D=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}},z=[];function V(e,t){const s=U(),a=D({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===F?void 0:F].filter((e=>!!e))});e.common.issues.push(a)}var J,K,B=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 W;"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 W;if("aborted"===n.status)return W;"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}}},W=Object.freeze({status:"aborted"}),Y=e=>({status:"dirty",value:e}),G=e=>({status:"valid",value:e}),H=e=>"aborted"===e.status,Q=e=>"dirty"===e.status,X=e=>"valid"===e.status,ee=e=>"undefined"!=typeof Promise&&e instanceof Promise;(K=J||(J={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},K.toString=e=>"string"==typeof e?e:e?.message;var te=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}},se=(e,t)=>{if(X(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 $(e.common.issues);return this._error=t,this._error}}};function ae(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 ne,ie=class{get description(){return this._def.description}_getType(e){return E(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:E(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new B,ctx:{common:e.parent.common,data:e.data,parsedType:E(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ee(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:E(e)},a=this._parseSync({data:e,path:s.path,parent:s});return se(s,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:E(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return X(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=>X(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:E(e)},a=this._parse({data:e,path:s.path,parent:s}),n=await(ee(a)?a:Promise.resolve(a));return se(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:R.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 nt({schema:this,typeName:gt.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 it.create(this,this._def)}nullable(){return rt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Le.create(this)}promise(){return at.create(this,this._def)}or(e){return De.create([this,e],this._def)}and(e){return Ke.create(this,e,this._def)}transform(e){return new nt({...ae(this._def),schema:this,typeName:gt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ot({...ae(this._def),innerType:this,defaultValue:t,typeName:gt.ZodDefault})}brand(){return new lt({typeName:gt.ZodBranded,type:this,...ae(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new dt({...ae(this._def),innerType:this,catchValue:t,typeName:gt.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return pt.create(this,e)}readonly(){return ht.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},re=/^c[^\s-]{8,}$/i,oe=/^[0-9a-z]+$/,de=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ce=/^[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,ue=/^[a-z0-9_-]{21}$/i,le=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pe=/^[-+]?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)?)??$/,he=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,me=/^(?:(?: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])$/,fe=/^(?:(?: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])$/,ge=/^(([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]))$/,ye=/^(([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])$/,ve=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_e=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,be="((\\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])))",we=new RegExp(`^${be}$`);function xe(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 ke(e){let t=`${be}T${xe(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 Ce(e,t){if(!le.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 Ne(e,t){return!("v4"!==t&&t||!fe.test(e))||!("v6"!==t&&t||!ye.test(e))}var Te=class e extends ie{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==j.string){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.string,received:t.parsedType}),W}const t=new B;let s;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),V(s,{code:R.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),V(s,{code:R.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?V(s,{code:R.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&V(s,{code:R.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)he.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"email",code:R.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)ne||(ne=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ne.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"emoji",code:R.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)ce.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"uuid",code:R.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)ue.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"nanoid",code:R.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)re.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"cuid",code:R.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)oe.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"cuid2",code:R.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)de.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"ulid",code:R.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),V(s,{validation:"url",code:R.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),V(s,{validation:"regex",code:R.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),V(s,{code:R.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),V(s,{code:R.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),V(s,{code:R.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){ke(i).test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{code:R.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){we.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{code:R.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${xe(i)}$`).test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{code:R.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?pe.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"duration",code:R.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(a=e.data,("v4"!==(n=i.version)&&n||!me.test(a))&&("v6"!==n&&n||!ge.test(a))&&(s=this._getOrReturnCtx(e,s),V(s,{validation:"ip",code:R.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?Ce(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"jwt",code:R.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?Ne(e.data,i.version)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"cidr",code:R.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?ve.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"base64",code:R.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?_e.test(e.data)||(s=this._getOrReturnCtx(e,s),V(s,{validation:"base64url",code:R.invalid_string,message:i.message}),t.dirty()):g.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:R.invalid_string,...J.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...J.errToObj(e)})}url(e){return this._addCheck({kind:"url",...J.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...J.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...J.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...J.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...J.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...J.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...J.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...J.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...J.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...J.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...J.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...J.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,...J.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,...J.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...J.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...J.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...J.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...J.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...J.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...J.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...J.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...J.errToObj(t)})}nonempty(e){return this.min(1,J.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 Se(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}Te.create=e=>new Te({checks:[],typeName:gt.ZodString,coerce:e?.coerce??!1,...ae(e)});var Ie=class e extends ie{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)!==j.number){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.number,received:t.parsedType}),W}let t;const s=new B;for(const a of this._def.checks)if("int"===a.kind)g.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),V(t,{code:R.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),V(t,{code:R.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),V(t,{code:R.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty())}else"multipleOf"===a.kind?0!==Se(e.data,a.value)&&(t=this._getOrReturnCtx(e,t),V(t,{code:R.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),V(t,{code:R.not_finite,message:a.message}),s.dirty()):g.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,J.toString(t))}gt(e,t){return this.setLimit("min",e,!1,J.toString(t))}lte(e,t){return this.setLimit("max",e,!0,J.toString(t))}lt(e,t){return this.setLimit("max",e,!1,J.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:J.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:J.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:J.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:J.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:J.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:J.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&&g.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)}};Ie.create=e=>new Ie({checks:[],typeName:gt.ZodNumber,coerce:e?.coerce||!1,...ae(e)});var Me=class e extends ie{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)!==j.bigint)return this._getInvalidInput(e);let t;const s=new B;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),V(t,{code:R.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),V(t,{code:R.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),V(t,{code:R.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):g.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.bigint,received:t.parsedType}),W}gte(e,t){return this.setLimit("min",e,!0,J.toString(t))}gt(e,t){return this.setLimit("min",e,!1,J.toString(t))}lte(e,t){return this.setLimit("max",e,!0,J.toString(t))}lt(e,t){return this.setLimit("max",e,!1,J.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:J.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:J.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:J.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}};Me.create=e=>new Me({checks:[],typeName:gt.ZodBigInt,coerce:e?.coerce??!1,...ae(e)});var Oe=class extends ie{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==j.boolean){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.boolean,received:t.parsedType}),W}return G(e.data)}};Oe.create=e=>new Oe({typeName:gt.ZodBoolean,coerce:e?.coerce||!1,...ae(e)});var Ze=class e extends ie{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==j.date){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.date,received:t.parsedType}),W}if(Number.isNaN(e.data.getTime())){return V(this._getOrReturnCtx(e),{code:R.invalid_date}),W}const t=new B;let s;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),V(s,{code:R.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),V(s,{code:R.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):g.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:J.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:J.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}};Ze.create=e=>new Ze({checks:[],coerce:e?.coerce||!1,typeName:gt.ZodDate,...ae(e)});var Ae=class extends ie{_parse(e){if(this._getType(e)!==j.symbol){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.symbol,received:t.parsedType}),W}return G(e.data)}};Ae.create=e=>new Ae({typeName:gt.ZodSymbol,...ae(e)});var je=class extends ie{_parse(e){if(this._getType(e)!==j.undefined){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.undefined,received:t.parsedType}),W}return G(e.data)}};je.create=e=>new je({typeName:gt.ZodUndefined,...ae(e)});var Ee=class extends ie{_parse(e){if(this._getType(e)!==j.null){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.null,received:t.parsedType}),W}return G(e.data)}};Ee.create=e=>new Ee({typeName:gt.ZodNull,...ae(e)});var Re=class extends ie{constructor(){super(...arguments),this._any=!0}_parse(e){return G(e.data)}};Re.create=e=>new Re({typeName:gt.ZodAny,...ae(e)});var Pe=class extends ie{constructor(){super(...arguments),this._unknown=!0}_parse(e){return G(e.data)}};Pe.create=e=>new Pe({typeName:gt.ZodUnknown,...ae(e)});var $e=class extends ie{_parse(e){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.never,received:t.parsedType}),W}};$e.create=e=>new $e({typeName:gt.ZodNever,...ae(e)});var Fe=class extends ie{_parse(e){if(this._getType(e)!==j.undefined){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.void,received:t.parsedType}),W}return G(e.data)}};Fe.create=e=>new Fe({typeName:gt.ZodVoid,...ae(e)});var Le=class e extends ie{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==j.array)return V(t,{code:R.invalid_type,expected:j.array,received:t.parsedType}),W;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,n=t.data.length<a.exactLength.value;(e||n)&&(V(t,{code:e?R.too_big:R.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&&(V(t,{code:R.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&&(V(t,{code:R.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 te(t,e,t.path,s))))).then((e=>B.mergeArray(s,e)));const n=[...t.data].map(((e,s)=>a.type._parseSync(new te(t,e,t.path,s))));return B.mergeArray(s,n)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:J.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:J.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:J.toString(s)}})}nonempty(e){return this.min(1,e)}};function qe(e){if(e instanceof Ue){const t={};for(const s in e.shape){const a=e.shape[s];t[s]=it.create(qe(a))}return new Ue({...e._def,shape:()=>t})}return e instanceof Le?new Le({...e._def,type:qe(e.element)}):e instanceof it?it.create(qe(e.unwrap())):e instanceof rt?rt.create(qe(e.unwrap())):e instanceof Be?Be.create(e.items.map((e=>qe(e)))):e}Le.create=(e,t)=>new Le({type:e,minLength:null,maxLength:null,exactLength:null,typeName:gt.ZodArray,...ae(t)});var Ue=class e extends ie{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=g.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==j.object){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.object,received:t.parsedType}),W}const{status:t,ctx:s}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof $e&&"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 te(s,n,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof $e){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&&(V(s,{code:R.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 te(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=>B.mergeObjectSync(t,e))):B.mergeObjectSync(t,r)}get shape(){return this._def.shape()}strict(t){return J.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:J.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:gt.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 g.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 g.objectKeys(this.shape))t[e]||(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}deepPartial(){return qe(this)}partial(t){const s={};for(const e of g.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 g.objectKeys(this.shape))if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof it;)t=t._def.innerType;s[e]=t}return new e({...this._def,shape:()=>s})}keyof(){return et(g.objectKeys(this.shape))}};Ue.create=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strip",catchall:$e.create(),typeName:gt.ZodObject,...ae(t)}),Ue.strictCreate=(e,t)=>new Ue({shape:()=>e,unknownKeys:"strict",catchall:$e.create(),typeName:gt.ZodObject,...ae(t)}),Ue.lazycreate=(e,t)=>new Ue({shape:e,unknownKeys:"strip",catchall:$e.create(),typeName:gt.ZodObject,...ae(t)});var De=class extends ie{_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 $(e.ctx.common.issues)));return V(t,{code:R.invalid_union,unionErrors:s}),W}));{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 $(e)));return V(t,{code:R.invalid_union,unionErrors:n}),W}}get options(){return this._def.options}};De.create=(e,t)=>new De({options:e,typeName:gt.ZodUnion,...ae(t)});var ze=e=>e instanceof Qe?ze(e.schema):e instanceof nt?ze(e.innerType()):e instanceof Xe?[e.value]:e instanceof tt?e.options:e instanceof st?g.objectValues(e.enum):e instanceof ot?ze(e._def.innerType):e instanceof je?[void 0]:e instanceof Ee?[null]:e instanceof it?[void 0,...ze(e.unwrap())]:e instanceof rt?[null,...ze(e.unwrap())]:e instanceof lt||e instanceof ht?ze(e.unwrap()):e instanceof dt?ze(e._def.innerType):[],Ve=class e extends ie{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.object)return V(t,{code:R.invalid_type,expected:j.object,received:t.parsedType}),W;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}):(V(t,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),W)}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=ze(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:gt.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:n,...ae(a)})}};function Je(e,t){const s=E(e),a=E(t);if(e===t)return{valid:!0,data:e};if(s===j.object&&a===j.object){const s=g.objectKeys(t),a=g.objectKeys(e).filter((e=>-1!==s.indexOf(e))),n={...e,...t};for(const s of a){const a=Je(e[s],t[s]);if(!a.valid)return{valid:!1};n[s]=a.data}return{valid:!0,data:n}}if(s===j.array&&a===j.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let a=0;a<e.length;a++){const n=Je(e[a],t[a]);if(!n.valid)return{valid:!1};s.push(n.data)}return{valid:!0,data:s}}return s===j.date&&a===j.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}var Ke=class extends ie{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=(e,a)=>{if(H(e)||H(a))return W;const n=Je(e.value,a.value);return n.valid?((Q(e)||Q(a))&&t.dirty(),{status:t.value,value:n.data}):(V(s,{code:R.invalid_intersection_types}),W)};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}))}};Ke.create=(e,t,s)=>new Ke({left:e,right:t,typeName:gt.ZodIntersection,...ae(s)});var Be=class e extends ie{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==j.array)return V(s,{code:R.invalid_type,expected:j.array,received:s.parsedType}),W;if(s.data.length<this._def.items.length)return V(s,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&s.data.length>this._def.items.length&&(V(s,{code:R.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 te(s,e,s.path,t)):null})).filter((e=>!!e));return s.common.async?Promise.all(a).then((e=>B.mergeArray(t,e))):B.mergeArray(t,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Be.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Be({items:e,typeName:gt.ZodTuple,rest:null,...ae(t)})};var We=class e extends ie{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!==j.object)return V(s,{code:R.invalid_type,expected:j.object,received:s.parsedType}),W;const a=[],n=this._def.keyType,i=this._def.valueType;for(const e in s.data)a.push({key:n._parse(new te(s,e,s.path,e)),value:i._parse(new te(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?B.mergeObjectAsync(t,a):B.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(t,s,a){return new e(s instanceof ie?{keyType:t,valueType:s,typeName:gt.ZodRecord,...ae(a)}:{keyType:Te.create(),valueType:t,typeName:gt.ZodRecord,...ae(s)})}},Ye=class extends ie{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!==j.map)return V(s,{code:R.invalid_type,expected:j.map,received:s.parsedType}),W;const a=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map((([e,t],i)=>({key:a._parse(new te(s,e,s.path,[i,"key"])),value:n._parse(new te(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 W;"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 W;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}};Ye.create=(e,t,s)=>new Ye({valueType:t,keyType:e,typeName:gt.ZodMap,...ae(s)});var Ge=class e extends ie{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==j.set)return V(s,{code:R.invalid_type,expected:j.set,received:s.parsedType}),W;const a=this._def;null!==a.minSize&&s.data.size<a.minSize.value&&(V(s,{code:R.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&&(V(s,{code:R.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 W;"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 te(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:J.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:J.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Ge.create=(e,t)=>new Ge({valueType:e,minSize:null,maxSize:null,typeName:gt.ZodSet,...ae(t)});var He=class e extends ie{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.function)return V(t,{code:R.invalid_type,expected:j.function,received:t.parsedType}),W;function s(e,s){return D({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,U(),F].filter((e=>!!e)),issueData:{code:R.invalid_arguments,argumentsError:s}})}function a(e,s){return D({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,U(),F].filter((e=>!!e)),issueData:{code:R.invalid_return_type,returnTypeError:s}})}const n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof at){const e=this;return G((async function(...t){const r=new $([]),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 G((function(...t){const r=e._def.args.safeParse(t,n);if(!r.success)throw new $([s(t,r.error)]);const o=Reflect.apply(i,this,r.data),d=e._def.returns.safeParse(o,n);if(!d.success)throw new $([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:Be.create(t).rest(Pe.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||Be.create([]).rest(Pe.create()),returns:s||Pe.create(),typeName:gt.ZodFunction,...ae(a)})}},Qe=class extends ie{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})}};Qe.create=(e,t)=>new Qe({getter:e,typeName:gt.ZodLazy,...ae(t)});var Xe=class extends ie{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return V(t,{received:t.data,code:R.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:e.data}}get value(){return this._def.value}};function et(e,t){return new tt({values:e,typeName:gt.ZodEnum,...ae(t)})}Xe.create=(e,t)=>new Xe({value:e,typeName:gt.ZodLiteral,...ae(t)});var tt=class e extends ie{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),s=this._def.values;return V(t,{expected:g.joinValues(s),received:t.parsedType,code:R.invalid_type}),W}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 V(t,{received:t.data,code:R.invalid_enum_value,options:s}),W}return G(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})}};tt.create=et;var st=class extends ie{_parse(e){const t=g.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==j.string&&s.parsedType!==j.number){const e=g.objectValues(t);return V(s,{expected:g.joinValues(e),received:s.parsedType,code:R.invalid_type}),W}if(this._cache||(this._cache=new Set(g.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=g.objectValues(t);return V(s,{received:s.data,code:R.invalid_enum_value,options:e}),W}return G(e.data)}get enum(){return this._def.values}};st.create=(e,t)=>new st({values:e,typeName:gt.ZodNativeEnum,...ae(t)});var at=class extends ie{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.promise&&!1===t.common.async)return V(t,{code:R.invalid_type,expected:j.promise,received:t.parsedType}),W;const s=t.parsedType===j.promise?t.data:Promise.resolve(t.data);return G(s.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}};at.create=(e,t)=>new at({type:e,typeName:gt.ZodPromise,...ae(t)});var nt=class extends ie{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===gt.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=>{V(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 W;const a=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===a.status?W:"dirty"===a.status||"dirty"===t.value?Y(a.value):a}));{if("aborted"===t.value)return W;const a=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===a.status?W:"dirty"===a.status||"dirty"===t.value?Y(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?W:("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?W:("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(!X(e))return W;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=>X(e)?Promise.resolve(a.transform(e.value,n)).then((e=>({status:t.value,value:e}))):W))}g.assertNever(a)}};nt.create=(e,t,s)=>new nt({schema:e,typeName:gt.ZodEffects,effect:t,...ae(s)}),nt.createWithPreprocess=(e,t,s)=>new nt({schema:t,effect:{type:"preprocess",transform:e},typeName:gt.ZodEffects,...ae(s)});var it=class extends ie{_parse(e){return this._getType(e)===j.undefined?G(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};it.create=(e,t)=>new it({innerType:e,typeName:gt.ZodOptional,...ae(t)});var rt=class extends ie{_parse(e){return this._getType(e)===j.null?G(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rt.create=(e,t)=>new rt({innerType:e,typeName:gt.ZodNullable,...ae(t)});var ot=class extends ie{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===j.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ot.create=(e,t)=>new ot({innerType:e,typeName:gt.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...ae(t)});var dt=class extends ie{_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 ee(a)?a.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new $(s.common.issues)},input:s.data})}))):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new $(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};dt.create=(e,t)=>new dt({innerType:e,typeName:gt.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...ae(t)});var ct=class extends ie{_parse(e){if(this._getType(e)!==j.nan){const t=this._getOrReturnCtx(e);return V(t,{code:R.invalid_type,expected:j.nan,received:t.parsedType}),W}return{status:"valid",value:e.data}}};ct.create=e=>new ct({typeName:gt.ZodNaN,...ae(e)});var ut=Symbol("zod_brand"),lt=class extends ie{_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}},pt=class e extends ie{_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?W:"dirty"===e.status?(t.dirty(),Y(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?W:"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:gt.ZodPipeline})}},ht=class extends ie{_parse(e){const t=this._def.innerType._parse(e),s=e=>(X(e)&&(e.value=Object.freeze(e.value)),e);return ee(t)?t.then((e=>s(e))):s(t)}unwrap(){return this._def.innerType}};function mt(e,t){const s="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof s?{message:s}:s}function ft(e,t={},s){return e?Re.create().superRefine(((a,n)=>{const i=e(a);if(i instanceof Promise)return i.then((e=>{if(!e){const e=mt(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}}));if(!i){const e=mt(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}})):Re.create()}ht.create=(e,t)=>new ht({innerType:e,typeName:gt.ZodReadonly,...ae(t)});var gt,yt,vt={object:Ue.lazycreate};(yt=gt||(gt={})).ZodString="ZodString",yt.ZodNumber="ZodNumber",yt.ZodNaN="ZodNaN",yt.ZodBigInt="ZodBigInt",yt.ZodBoolean="ZodBoolean",yt.ZodDate="ZodDate",yt.ZodSymbol="ZodSymbol",yt.ZodUndefined="ZodUndefined",yt.ZodNull="ZodNull",yt.ZodAny="ZodAny",yt.ZodUnknown="ZodUnknown",yt.ZodNever="ZodNever",yt.ZodVoid="ZodVoid",yt.ZodArray="ZodArray",yt.ZodObject="ZodObject",yt.ZodUnion="ZodUnion",yt.ZodDiscriminatedUnion="ZodDiscriminatedUnion",yt.ZodIntersection="ZodIntersection",yt.ZodTuple="ZodTuple",yt.ZodRecord="ZodRecord",yt.ZodMap="ZodMap",yt.ZodSet="ZodSet",yt.ZodFunction="ZodFunction",yt.ZodLazy="ZodLazy",yt.ZodLiteral="ZodLiteral",yt.ZodEnum="ZodEnum",yt.ZodEffects="ZodEffects",yt.ZodNativeEnum="ZodNativeEnum",yt.ZodOptional="ZodOptional",yt.ZodNullable="ZodNullable",yt.ZodDefault="ZodDefault",yt.ZodCatch="ZodCatch",yt.ZodPromise="ZodPromise",yt.ZodBranded="ZodBranded",yt.ZodPipeline="ZodPipeline",yt.ZodReadonly="ZodReadonly";var _t=(e,t={message:`Input not instance of ${e.name}`})=>ft((t=>t instanceof e),t),bt=Te.create,wt=Ie.create,xt=ct.create,kt=Me.create,Ct=Oe.create,Nt=Ze.create,Tt=Ae.create,St=je.create,It=Ee.create,Mt=Re.create,Ot=Pe.create,Zt=$e.create,At=Fe.create,jt=Le.create,Et=Ue.create,Rt=Ue.strictCreate,Pt=De.create,$t=Ve.create,Ft=Ke.create,Lt=Be.create,qt=We.create,Ut=Ye.create,Dt=Ge.create,zt=He.create,Vt=Qe.create,Jt=Xe.create,Kt=tt.create,Bt=st.create,Wt=at.create,Yt=nt.create,Gt=it.create,Ht=rt.create,Qt=nt.createWithPreprocess,Xt=pt.create,es=()=>bt().optional(),ts=()=>wt().optional(),ss=()=>Ct().optional(),as={string:e=>Te.create({...e,coerce:!0}),number:e=>Ie.create({...e,coerce:!0}),boolean:e=>Oe.create({...e,coerce:!0}),bigint:e=>Me.create({...e,coerce:!0}),date:e=>Ze.create({...e,coerce:!0})},ns=W,is={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"},rs={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"},os=A.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"]),ds=A.enum(["unknown","android","ios","desktop","web"]),cs=A.object({chatId:A.string(),channelId:A.string(),receiverId:A.string(),receiverName:A.string(),roomId:A.string(),roomName:A.string(),senderId:A.string(),senderName:A.string(),senderDevice:ds,chatType:os,timestamp:A.number(),mentions:A.string().array(),text:A.string().nullable(),links:A.string().array(),isPrefix:A.boolean(),isFromMe:A.boolean(),isTagMe:A.boolean(),isGroup:A.boolean(),isStory:A.boolean(),isViewOnce:A.boolean(),isEdited:A.boolean(),isDeleted:A.boolean(),isPinned:A.boolean(),isUnPinned:A.boolean(),isChannel:A.boolean(),isBroadcast:A.boolean(),isEphemeral:A.boolean(),isForwarded:A.boolean(),citation:A.record(A.string(),A.boolean()).nullable(),media:A.object({buffer:A.function().returns(A.instanceof(Buffer)),stream:A.function().returns(A.instanceof(m.Readable))}).passthrough().nullable(),message:A.function().returns(A.record(A.string(),A.any()))});cs.extend({replied:cs.nullable()});var us=class{constructor(e,t,s){this.socket=e,this.client=t,this.db=s}maxReplies=0;async connection(t){this.client.startSpinner("connection","Connecting to WhatsApp...");const{connection:s,lastDisconnect:a,qr:n}=t;if(this.client.emit("connection",{status:"connecting"}),"qr"===this.client.options?.authType&&n)return this.client.stopSpinner("connection",!1),console.log(),console.log(await T.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"===s){this.client.failSpinner("connection","Connection closed");const t=a?.error?.output?.statusCode,s=t===e.DisconnectReason.restartRequired;if(console.log(a?.error?.message),401===t||405===t||500===t)return void console.error("Invalid session, please delete manually");s&&await this.client.initialize()}else"open"===s&&(this.client.stopSpinner("connection",!0,"Connected to WhatsApp\n"),this.client.emit("connection",{status:"open"}))}async messages(t,s){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 a=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(),s=I(e?.value);t=s}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(),s=I(e?.value);t=s}const c={},u=e.getContentType(t?.message?.protocolMessage?.editedMessage||t?.message);c.chatId=t?.message?.protocolMessage?.key?.id||t?.key?.id,c.channelId="",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 l=await this.db.selectFrom("chats").select("value").where("id","=",c.roomId).executeTakeFirst();c.roomName=I(l?.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||I(p?.value)?.name||c.receiverName,c.roomName=c.roomName||c.senderName,c.senderDevice=e.getDevice(c.chatId),c.chatType=is[u],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];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?.[u]||t?.message?.[u])?.message?.documentMessage||t?.message?.[u];"text"!=c.chatType&&(c.media={...Z(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?.[u]?.contextInfo?.stanzaId;if(f&&this.maxReplies<1){this.maxReplies++;const s=await this.db.selectFrom("messages").select("value").where("id","=",f).executeTakeFirst(),a=I(s?.value);if(a)c.replied=await this.messages(a,!0);else{const s=t,a=e.getContentType(s.message?.extendedTextMessage?.contextInfo.quotedMessage);s.key.id=s.message?.extendedTextMessage?.contextInfo.stanzaId,s.message[a]=s.message?.extendedTextMessage?.contextInfo.quotedMessage[a],delete s.message?.extendedTextMessage,c.replied=await this.messages(s,!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 s of e.matchAll(/@(\d+)/g))t.add(s[1]);return[...t]})(c.text),c.links=((e="")=>e&&e.match(/(?:https?:\/\/)?[^\s<>"']+\.[^\s<>"']+/g)||[])(c.text);const y=t?.message?.[u];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=O(M(t),"editedMessage"),c.isEphemeral=O(M(y?.contextInfo),"ephemeralSettingTimestamp"),c.isForwarded=O(M(y?.contextInfo),"forwardingScore"),c.isViewOnce=!!y?.viewOnce,c.isPrefix&&(c.text=c.text.replace(new RegExp(`^${this.client.options?.prefix}`),"")),c.message=()=>a,s||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)}},ls=async(t,s)=>{const a="auth";await(async e=>{await e.schema.createTable("auth").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("auth_session_id_unique",["session","id"]).execute(),await e.schema.createTable("chats").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("chats_session_id_unique",["session","id"]).execute(),await e.schema.createTable("contacts").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("contacts_session_id_unique",["session","id"]).execute(),await e.schema.createTable("messages").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("messages_session_id_unique",["session","id"]).execute(),await e.schema.createIndex("auth_session_idx").ifNotExists().on("auth").column("session").execute(),await e.schema.createIndex("auth_id_idx").ifNotExists().on("auth").column("id").execute(),await e.schema.createIndex("chats_session_idx").ifNotExists().on("chats").column("session").execute(),await e.schema.createIndex("chats_id_idx").ifNotExists().on("chats").column("id").execute(),await e.schema.createIndex("contacts_session_idx").ifNotExists().on("contacts").column("session").execute(),await e.schema.createIndex("contacts_id_idx").ifNotExists().on("contacts").column("id").execute(),await e.schema.createIndex("messages_session_idx").ifNotExists().on("messages").column("session").execute(),await e.schema.createIndex("messages_id_idx").ifNotExists().on("messages").column("id").execute()})(t);const n=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")},i=async i=>{const r=await n((()=>t.selectFrom(a).select(["value"]).where("id","=",i).where("session","=",s).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)},r=async(i,r)=>{const o=JSON.stringify(r,e.BufferJSON.replacer);await n((()=>t.insertInto(a).values({session:s,id:i,value:o}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:o}))).execute()))},o=async e=>{await n((()=>t.deleteFrom(a).where("id","=",e).where("session","=",s).execute()))},d=await i("creds")||e.initAuthCreds();return{state:{creds:d,keys:{get:async(t,s)=>{const a={};for(const n of s){let s=await i(`${t}-${n}`);"app-state-sync-key"===t&&s&&(s=e.proto.SenderKeyMessage.fromObject(s)),a[n]=s}return a},set:async e=>{for(const t in e)for(const s in e[t]){const a=e[t][s],n=`${t}-${s}`;a?await r(n,a):await o(n)}}}},saveCreds:async()=>{await r("creds",d)},clear:async()=>{await(async()=>{await n((()=>t.deleteFrom(a).where("session","=",s).where("id","!=","creds").execute()))})()},removeCreds:async()=>{await(async()=>{await n((()=>t.deleteFrom(a).where("session","=",s).execute()))})()}}},ps=A.object({type:A.enum(["sqlite","postgresql","mysql"]).default("sqlite"),connection:A.object({url:A.string().default("./session/zaileys.db")}).optional().default({})}).optional().default({}),hs=A.record(A.function().returns(A.union([A.number().array(),A.promise(A.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})),ms=A.object({prefix:A.string().optional(),ignoreMe:A.boolean().optional().default(!0),showLogs:A.boolean().optional().default(!0),autoMentions:A.boolean().optional().default(!0),autoOnline:A.boolean().optional().default(!0),autoRead:A.boolean().optional().default(!0),autoPresence:A.boolean().optional().default(!0),autoRejectCall:A.boolean().optional().default(!0),database:ps,citation:hs}),fs=A.object({authType:A.literal("pairing"),phoneNumber:A.number()}).extend(ms.shape),gs=A.object({authType:A.literal("qr"),phoneNumber:A.undefined().optional()}).extend(ms.shape),ys=A.discriminatedUnion("authType",[fs,gs]),vs=A.union([A.string().url(),A.instanceof(Buffer).or(A.instanceof(m.Readable))]),_s=A.union([A.string(),A.object({image:vs,text:A.string().optional()}),A.object({video:vs,text:A.string().optional()}),A.object({videoNote:vs}),A.object({gif:vs,text:A.string().optional()}),A.object({audio:vs}),A.object({audioNote:vs}),A.object({sticker:vs})]),bs=A.object({roomId:A.string(),asForwarded:A.boolean().optional(),asViewOnce:A.boolean().optional(),verifiedReply:A.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).optional(),quoted:A.function().returns(A.record(A.string(),A.any())).optional()}),ws=bs,xs=A.object({latitude:A.number(),longitude:A.number(),title:A.string().optional(),footer:A.string().optional()}),ks=bs,Cs=A.object({fullname:A.string(),nickname:A.string().optional(),organization:A.string().optional(),role:A.string().optional(),email:A.string().email().optional(),whatsAppNumber:A.number(),callNumber:A.number().optional(),voiceNumber:A.number().optional(),website:A.string().url().optional(),homeAddress:A.string().optional(),workAddress:A.string().optional(),avatar:A.string().url().optional()}),Ns=A.object({message:A.function().returns(A.record(A.string(),A.any()))}),Ts=A.string(),Ss=A.object({message:A.function().returns(A.record(A.string(),A.any()))}),Is=A.object({action:A.enum(["pin","unpin"]),expired:A.enum(["24h","7d","30d"])}),Ms=bs.pick({roomId:!0}),Os=A.object({name:A.string(),answers:A.string().array(),multipleAnswers:A.boolean().optional()}),Zs=A.object({message:A.function().returns(A.record(A.string(),A.any()))}),As=A.string(),js=A.object({message:A.function().returns(A.record(A.string(),A.any()))}),Es=A.object({callId:A.string(),callerId:A.string()}),Rs=bs.pick({roomId:!0}),Ps=A.object({expired:A.enum(["remove","8h","7d"])}),$s=A.string();A.object({type:A.enum(["group","user"]),id:A.string(),name:A.string(),bio:A.string(),avatar:A.string().url(),ephemeralDuration:A.number().optional(),isRestrict:A.boolean().optional(),isAnnounce:A.boolean().optional(),isCommunity:A.boolean().optional(),isCommunityAnnounce:A.boolean().optional(),isJoinApprovalMode:A.boolean().optional(),isMemberAddMode:A.boolean().optional(),owner:A.object({type:A.literal("user"),id:A.string()}).nullable(),roomCreatedAt:A.number().optional(),nameUpdatedAt:A.number().optional(),bioUpdatedAt:A.number().optional(),membersLength:A.number().optional(),members:A.object({type:A.enum(["user","admin","superadmin"]),id:A.string()}).array().optional()});var Fs=bs.pick({roomId:!0}),Ls=A.enum(["typing","recording","online","offline","paused"]),qs=class{constructor(e){this.wa=e,this.parser=new us(this.wa.socket,this.wa.client,this.wa.db)}parser;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=rs[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=_s.parse(e),t=bs.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=xs.parse(e),t=ws.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=Cs.parse(e),t=ks.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=Ts.parse(e),t=Ns.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{react:{text:e,key:t.message()?.key},...t})}async pin(e,t){e=Is.parse(e),t=Ss.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=Os.parse(e),t=Ms.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=As.parse(e),t=Zs.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{text:e,edit:t.message()?.key,...t})}async delete(e){return e=js.parse(e),await this.sendMessage(e.message()?.key?.remoteJid,{delete:e.message()?.key})}async rejectCall(e){return e=Es.parse(e),await(this.wa.socket?.rejectCall(e.callId,e.callerId))}async mute(e,t){e=Ps.parse(e),t=Rs.parse(t);return await(this.wa.socket?.chatModify({mute:{remove:null,"8h":864e5,"7d":6048e5}[e.expired]},t.roomId))}async profile(t){const s=(t=$s.parse(t)).includes("@g.us"),a={};a.id=t;if(e.jidNormalizedUser(this.wa.socket?.user?.id)==t)a.name=this.wa.socket?.user?.name||this.wa.socket?.user?.verifiedName;else if(s){const e=await(this.wa.socket?.groupMetadata(t));a.type="group",a.name=e?.subject,a.bio=e?.desc,a.avatar=await(this.wa.socket?.profilePictureUrl(t)),a.ephemeralDuration=e?.ephemeralDuration,a.isRestrict=e?.restrict,a.isAnnounce=e?.announce,a.isCommunity=e?.isCommunity,a.isCommunityAnnounce=e?.isCommunityAnnounce,a.isJoinApprovalMode=e?.joinApprovalMode,a.isMemberAddMode=e?.memberAddMode,a.owner={type:"user",id:e?.owner},a.roomCreatedAt=e?.creation,a.nameUpdatedAt=e?.subjectTime,a.membersLength=e?.size,a.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()),s=I(e?.value),n=(await(this.wa?.socket?.fetchStatus(t)))[0]?.status;a.type="user",a.name=s?.name,a.bio=n?.status,a.avatar=await(this.wa?.socket?.profilePictureUrl(t)),a.bioUpdatedAt=new Date(n?.setAt).getTime()}return a}async presence(e,t){e=Ls.parse(e),t=Fs.parse(t);return await(this.wa.socket?.sendPresenceUpdate({typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"}[e],t.roomId))}},Us=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 b.default({stdTTL:300,useClones:!1});chatId="zaileys-chats";logger=x.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=>{_.default(e,((e,s)=>{if(e)return t("");console.log(s),t(s||"")}))})))(),this.options=await ys.parseAsync(this.props),this.startSpinner("db","Initializing database..."),this.db=await((e,t)=>{if("sqlite"===e){const e=t||"./db/zaileys.db",s=N.default.resolve(e);return o.mkdirSync(N.default.dirname(s),{recursive:!0}),o.writeFileSync(s,"",{flag:"a"}),new d.Kysely({dialect:new d.SqliteDialect({database:new k.default(s)})})}const s=new p.URL(t),a=s.protocol.replace(":","");if("mysql"===e)return new d.Kysely({dialect:new d.MysqlDialect({pool:C.default.createPool({host:s.hostname,user:s.username,password:s.password,database:s.pathname.replace("/",""),port:parseInt(s.port||"3306",10)})})});if("postgresql"===e)return new d.Kysely({dialect:new d.PostgresDialect({pool:new l.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: ${a}`)})(this.options.database.type,this.options.database.connection.url),this.stopSpinner("db",!0,"Database initialized"),this.startSpinner("auth","Setting up auth adapter...");const{state:t,saveCreds:s}=await ls(this.db,this.chatId);this.stopSpinner("auth",!0,"Auth adapter ready"),this.startSpinner("store","Setting up store adapter...");const a=await(async(e,t,s)=>({bind:a=>{const n=new us(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: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 b.default,mediaCache:new b.default({stdTTL:60}),userDevicesCache:new b.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 I(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 qs({client:this,db:this.db,socket:this.socket}),this.socket?.ev.on("creds.update",s),a.bind(this.socket)}startSpinner(e,t){let s=this.spinners.get(e);return s||(s=w.default(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)}};exports.Client=Us;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fetchLatestBaileysVersion as e,makeWASocket as t,makeCacheableSignalKeyStore as s,Browsers as a,initAuthCreds as n,proto as i,jidNormalizedUser as r,BufferJSON as o,DisconnectReason as d,getContentType as c,getDevice as u,downloadMediaMessage as l}from"baileys";import{EventEmitter as p}from"events";import h from"figlet";import m from"node-cache";import f from"ora";import g from"pino";import y from"better-sqlite3";import{mkdirSync as v,writeFileSync as _}from"fs";import{Kysely as b,SqliteDialect as w,MysqlDialect as x,PostgresDialect as k}from"kysely";import C from"mysql2";import T from"path";import{Pool as N}from"pg";import{URL as I}from"url";import O from"qrcode";import{Readable as S}from"stream";var M,Z,A,j=Object.defineProperty,E=(e="")=>{try{return JSON.parse(e)}catch{return JSON.parse(JSON.stringify(e))}},R=(e={})=>{try{return JSON.stringify(e)}catch{return JSON.stringify(JSON.parse(JSON.stringify(e)))}},P=(e="",t="")=>e?e.toLowerCase().includes(t.toLowerCase()):null,$=(e,t)=>e&&"object"==typeof e?Array.isArray(e)?e.map((e=>$(e,t))):Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e))).map((([e,s])=>[e,"object"==typeof s?$(s,t):s]))):e,F={};((e,t)=>{for(var s in t)j(e,s,{get:t[s],enumerable:!0})})(F,{BRAND:()=>gt,DIRTY:()=>te,EMPTY_PATH:()=>Y,INVALID:()=>ee,NEVER:()=>us,OK:()=>se,ParseStatus:()=>X,Schema:()=>le,ZodAny:()=>De,ZodArray:()=>Je,ZodBigInt:()=>Re,ZodBoolean:()=>Pe,ZodBranded:()=>yt,ZodCatch:()=>mt,ZodDate:()=>$e,ZodDefault:()=>ht,ZodDiscriminatedUnion:()=>Ge,ZodEffects:()=>ut,ZodEnum:()=>ot,ZodError:()=>V,ZodFirstPartyTypeKind:()=>xt,ZodFunction:()=>at,ZodIntersection:()=>Qe,ZodIssueCode:()=>D,ZodLazy:()=>nt,ZodLiteral:()=>it,ZodMap:()=>tt,ZodNaN:()=>ft,ZodNativeEnum:()=>dt,ZodNever:()=>Ve,ZodNull:()=>Ue,ZodNullable:()=>pt,ZodNumber:()=>Ee,ZodObject:()=>Be,ZodOptional:()=>lt,ZodParsedType:()=>L,ZodPipeline:()=>vt,ZodPromise:()=>ct,ZodReadonly:()=>_t,ZodRecord:()=>et,ZodSchema:()=>le,ZodSet:()=>st,ZodString:()=>Ae,ZodSymbol:()=>Fe,ZodTransformer:()=>ut,ZodTuple:()=>Xe,ZodType:()=>le,ZodUndefined:()=>Le,ZodUnion:()=>We,ZodUnknown:()=>ze,ZodVoid:()=>qe,addIssueToContext:()=>G,any:()=>Rt,array:()=>Lt,bigint:()=>St,boolean:()=>Mt,coerce:()=>cs,custom:()=>wt,date:()=>Zt,datetimeRegex:()=>Se,defaultErrorMap:()=>q,discriminatedUnion:()=>Vt,effect:()=>ts,enum:()=>Qt,function:()=>Yt,getErrorMap:()=>B,getParsedType:()=>U,instanceof:()=>Tt,intersection:()=>qt,isAborted:()=>ae,isAsync:()=>re,isDirty:()=>ne,isValid:()=>ie,late:()=>Ct,lazy:()=>Gt,literal:()=>Ht,makeIssue:()=>W,map:()=>Bt,nan:()=>Ot,nativeEnum:()=>Xt,never:()=>$t,null:()=>Et,nullable:()=>as,number:()=>It,object:()=>Ut,objectUtil:()=>A,oboolean:()=>ds,onumber:()=>os,optional:()=>ss,ostring:()=>rs,pipeline:()=>is,preprocess:()=>ns,promise:()=>es,quotelessJson:()=>z,record:()=>Kt,set:()=>Wt,setErrorMap:()=>K,strictObject:()=>Dt,string:()=>Nt,symbol:()=>At,transformer:()=>ts,tuple:()=>Jt,undefined:()=>jt,union:()=>zt,unknown:()=>Pt,util:()=>M,void:()=>Ft}),(Z=M||(M={})).assertEqual=e=>{},Z.assertIs=function(e){},Z.assertNever=function(e){throw new Error},Z.arrayToEnum=e=>{const t={};for(const s of e)t[s]=s;return t},Z.getValidEnumValues=e=>{const t=Z.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),s={};for(const a of t)s[a]=e[a];return Z.objectValues(s)},Z.objectValues=e=>Z.objectKeys(e).map((function(t){return e[t]})),Z.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},Z.find=(e,t)=>{for(const s of e)if(t(s))return s},Z.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,Z.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},Z.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(A||(A={})).mergeShapes=(e,t)=>({...e,...t});var L=M.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 L.undefined;case"string":return L.string;case"number":return Number.isNaN(e)?L.nan:L.number;case"boolean":return L.boolean;case"function":return L.function;case"bigint":return L.bigint;case"symbol":return L.symbol;case"object":return Array.isArray(e)?L.array:null===e?L.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?L.promise:"undefined"!=typeof Map&&e instanceof Map?L.map:"undefined"!=typeof Set&&e instanceof Set?L.set:"undefined"!=typeof Date&&e instanceof Date?L.date:L.object;default:return L.unknown}},D=M.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),z=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),V=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,M.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()}};V.create=e=>new V(e);var q=(e,t)=>{let s;switch(e.code){case D.invalid_type:s=e.received===L.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case D.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,M.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:s=`Unrecognized key(s) in object: ${M.joinValues(e.keys,", ")}`;break;case D.invalid_union:s="Invalid input";break;case D.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${M.joinValues(e.options)}`;break;case D.invalid_enum_value:s=`Invalid enum value. Expected ${M.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}"`:M.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,M.assertNever(e)}return{message:s}},J=q;function K(e){J=e}function B(){return J}var W=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}},Y=[];function G(e,t){const s=B(),a=W({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===q?void 0:q].filter((e=>!!e))});e.common.issues.push(a)}var H,Q,X=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 ee;"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 ee;if("aborted"===n.status)return ee;"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}}},ee=Object.freeze({status:"aborted"}),te=e=>({status:"dirty",value:e}),se=e=>({status:"valid",value:e}),ae=e=>"aborted"===e.status,ne=e=>"dirty"===e.status,ie=e=>"valid"===e.status,re=e=>"undefined"!=typeof Promise&&e instanceof Promise;(Q=H||(H={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},Q.toString=e=>"string"==typeof e?e:e?.message;var oe=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}},de=(e,t)=>{if(ie(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 V(e.common.issues);return this._error=t,this._error}}};function ce(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 ue,le=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 X,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(re(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 de(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 ie(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=>ie(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(re(a)?a:Promise.resolve(a));return de(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 ut({schema:this,typeName:xt.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 lt.create(this,this._def)}nullable(){return pt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Je.create(this)}promise(){return ct.create(this,this._def)}or(e){return We.create([this,e],this._def)}and(e){return Qe.create(this,e,this._def)}transform(e){return new ut({...ce(this._def),schema:this,typeName:xt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ht({...ce(this._def),innerType:this,defaultValue:t,typeName:xt.ZodDefault})}brand(){return new yt({typeName:xt.ZodBranded,type:this,...ce(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new mt({...ce(this._def),innerType:this,catchValue:t,typeName:xt.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return vt.create(this,e)}readonly(){return _t.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},pe=/^c[^\s-]{8,}$/i,he=/^[0-9a-z]+$/,me=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fe=/^[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,ge=/^[a-z0-9_-]{21}$/i,ye=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ve=/^[-+]?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)?)??$/,_e=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,be=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,we=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,xe=/^(([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]))$/,ke=/^(([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])$/,Ce=/^([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])))",Ie=new RegExp(`^${Ne}$`);function Oe(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=`${Ne}T${Oe(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 Me(e,t){if(!ye.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||!we.test(e))||!("v6"!==t&&t||!ke.test(e))}var Ae=class e extends le{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==L.string){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.string,received:t.parsedType}),ee}const t=new X;let s;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),G(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),G(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?G(s,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&G(s,{code:D.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)_e.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"email",code:D.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)ue||(ue=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ue.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"emoji",code:D.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)fe.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"uuid",code:D.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)ge.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"nanoid",code:D.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)pe.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"cuid",code:D.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)he.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"cuid2",code:D.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)me.test(e.data)||(s=this._getOrReturnCtx(e,s),G(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),G(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),G(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),G(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),G(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),G(s,{code:D.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){Se(i).test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{code:D.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){Ie.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{code:D.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${Oe(i)}$`).test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{code:D.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?ve.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"duration",code:D.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(a=e.data,("v4"!==(n=i.version)&&n||!be.test(a))&&("v6"!==n&&n||!xe.test(a))&&(s=this._getOrReturnCtx(e,s),G(s,{validation:"ip",code:D.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?Me(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),G(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),G(s,{validation:"cidr",code:D.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?Ce.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"base64",code:D.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?Te.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"base64url",code:D.invalid_string,message:i.message}),t.dirty()):M.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,...H.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...H.errToObj(e)})}url(e){return this._addCheck({kind:"url",...H.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...H.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...H.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...H.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...H.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...H.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...H.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...H.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...H.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...H.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...H.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...H.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,...H.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,...H.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...H.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...H.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...H.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...H.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...H.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...H.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...H.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...H.errToObj(t)})}nonempty(e){return this.min(1,H.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}Ae.create=e=>new Ae({checks:[],typeName:xt.ZodString,coerce:e?.coerce??!1,...ce(e)});var Ee=class e extends le{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)!==L.number){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.number,received:t.parsedType}),ee}let t;const s=new X;for(const a of this._def.checks)if("int"===a.kind)M.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),G(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),G(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),G(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),G(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),G(t,{code:D.not_finite,message:a.message}),s.dirty()):M.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,H.toString(t))}gt(e,t){return this.setLimit("min",e,!1,H.toString(t))}lte(e,t){return this.setLimit("max",e,!0,H.toString(t))}lt(e,t){return this.setLimit("max",e,!1,H.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:H.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:H.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:H.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:H.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:H.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:H.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:H.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&&M.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)}};Ee.create=e=>new Ee({checks:[],typeName:xt.ZodNumber,coerce:e?.coerce||!1,...ce(e)});var Re=class e extends le{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)!==L.bigint)return this._getInvalidInput(e);let t;const s=new X;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),G(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),G(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),G(t,{code:D.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):M.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.bigint,received:t.parsedType}),ee}gte(e,t){return this.setLimit("min",e,!0,H.toString(t))}gt(e,t){return this.setLimit("min",e,!1,H.toString(t))}lte(e,t){return this.setLimit("max",e,!0,H.toString(t))}lt(e,t){return this.setLimit("max",e,!1,H.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:H.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:H.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:H.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:H.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:xt.ZodBigInt,coerce:e?.coerce??!1,...ce(e)});var Pe=class extends le{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==L.boolean){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.boolean,received:t.parsedType}),ee}return se(e.data)}};Pe.create=e=>new Pe({typeName:xt.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});var $e=class e extends le{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==L.date){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.date,received:t.parsedType}),ee}if(Number.isNaN(e.data.getTime())){return G(this._getOrReturnCtx(e),{code:D.invalid_date}),ee}const t=new X;let s;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),G(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),G(s,{code:D.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):M.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:H.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:H.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:xt.ZodDate,...ce(e)});var Fe=class extends le{_parse(e){if(this._getType(e)!==L.symbol){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.symbol,received:t.parsedType}),ee}return se(e.data)}};Fe.create=e=>new Fe({typeName:xt.ZodSymbol,...ce(e)});var Le=class extends le{_parse(e){if(this._getType(e)!==L.undefined){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.undefined,received:t.parsedType}),ee}return se(e.data)}};Le.create=e=>new Le({typeName:xt.ZodUndefined,...ce(e)});var Ue=class extends le{_parse(e){if(this._getType(e)!==L.null){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.null,received:t.parsedType}),ee}return se(e.data)}};Ue.create=e=>new Ue({typeName:xt.ZodNull,...ce(e)});var De=class extends le{constructor(){super(...arguments),this._any=!0}_parse(e){return se(e.data)}};De.create=e=>new De({typeName:xt.ZodAny,...ce(e)});var ze=class extends le{constructor(){super(...arguments),this._unknown=!0}_parse(e){return se(e.data)}};ze.create=e=>new ze({typeName:xt.ZodUnknown,...ce(e)});var Ve=class extends le{_parse(e){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.never,received:t.parsedType}),ee}};Ve.create=e=>new Ve({typeName:xt.ZodNever,...ce(e)});var qe=class extends le{_parse(e){if(this._getType(e)!==L.undefined){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.void,received:t.parsedType}),ee}return se(e.data)}};qe.create=e=>new qe({typeName:xt.ZodVoid,...ce(e)});var Je=class e extends le{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==L.array)return G(t,{code:D.invalid_type,expected:L.array,received:t.parsedType}),ee;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,n=t.data.length<a.exactLength.value;(e||n)&&(G(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&&(G(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&&(G(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 oe(t,e,t.path,s))))).then((e=>X.mergeArray(s,e)));const n=[...t.data].map(((e,s)=>a.type._parseSync(new oe(t,e,t.path,s))));return X.mergeArray(s,n)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:H.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:H.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:H.toString(s)}})}nonempty(e){return this.min(1,e)}};function Ke(e){if(e instanceof Be){const t={};for(const s in e.shape){const a=e.shape[s];t[s]=lt.create(Ke(a))}return new Be({...e._def,shape:()=>t})}return e instanceof Je?new Je({...e._def,type:Ke(e.element)}):e instanceof lt?lt.create(Ke(e.unwrap())):e instanceof pt?pt.create(Ke(e.unwrap())):e instanceof Xe?Xe.create(e.items.map((e=>Ke(e)))):e}Je.create=(e,t)=>new Je({type:e,minLength:null,maxLength:null,exactLength:null,typeName:xt.ZodArray,...ce(t)});var Be=class e extends le{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=M.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==L.object){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.object,received:t.parsedType}),ee}const{status:t,ctx:s}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof Ve&&"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 oe(s,n,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof Ve){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&&(G(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 oe(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=>X.mergeObjectSync(t,e))):X.mergeObjectSync(t,r)}get shape(){return this._def.shape()}strict(t){return H.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:H.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:xt.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 M.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 M.objectKeys(this.shape))t[e]||(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}deepPartial(){return Ke(this)}partial(t){const s={};for(const e of M.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 M.objectKeys(this.shape))if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof lt;)t=t._def.innerType;s[e]=t}return new e({...this._def,shape:()=>s})}keyof(){return rt(M.objectKeys(this.shape))}};Be.create=(e,t)=>new Be({shape:()=>e,unknownKeys:"strip",catchall:Ve.create(),typeName:xt.ZodObject,...ce(t)}),Be.strictCreate=(e,t)=>new Be({shape:()=>e,unknownKeys:"strict",catchall:Ve.create(),typeName:xt.ZodObject,...ce(t)}),Be.lazycreate=(e,t)=>new Be({shape:e,unknownKeys:"strip",catchall:Ve.create(),typeName:xt.ZodObject,...ce(t)});var We=class extends le{_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 V(e.ctx.common.issues)));return G(t,{code:D.invalid_union,unionErrors:s}),ee}));{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 V(e)));return G(t,{code:D.invalid_union,unionErrors:n}),ee}}get options(){return this._def.options}};We.create=(e,t)=>new We({options:e,typeName:xt.ZodUnion,...ce(t)});var Ye=e=>e instanceof nt?Ye(e.schema):e instanceof ut?Ye(e.innerType()):e instanceof it?[e.value]:e instanceof ot?e.options:e instanceof dt?M.objectValues(e.enum):e instanceof ht?Ye(e._def.innerType):e instanceof Le?[void 0]:e instanceof Ue?[null]:e instanceof lt?[void 0,...Ye(e.unwrap())]:e instanceof pt?[null,...Ye(e.unwrap())]:e instanceof yt||e instanceof _t?Ye(e.unwrap()):e instanceof mt?Ye(e._def.innerType):[],Ge=class e extends le{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==L.object)return G(t,{code:D.invalid_type,expected:L.object,received:t.parsedType}),ee;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}):(G(t,{code:D.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),ee)}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=Ye(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:xt.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:n,...ce(a)})}};function He(e,t){const s=U(e),a=U(t);if(e===t)return{valid:!0,data:e};if(s===L.object&&a===L.object){const s=M.objectKeys(t),a=M.objectKeys(e).filter((e=>-1!==s.indexOf(e))),n={...e,...t};for(const s of a){const a=He(e[s],t[s]);if(!a.valid)return{valid:!1};n[s]=a.data}return{valid:!0,data:n}}if(s===L.array&&a===L.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let a=0;a<e.length;a++){const n=He(e[a],t[a]);if(!n.valid)return{valid:!1};s.push(n.data)}return{valid:!0,data:s}}return s===L.date&&a===L.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}var Qe=class extends le{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=(e,a)=>{if(ae(e)||ae(a))return ee;const n=He(e.value,a.value);return n.valid?((ne(e)||ne(a))&&t.dirty(),{status:t.value,value:n.data}):(G(s,{code:D.invalid_intersection_types}),ee)};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}))}};Qe.create=(e,t,s)=>new Qe({left:e,right:t,typeName:xt.ZodIntersection,...ce(s)});var Xe=class e extends le{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==L.array)return G(s,{code:D.invalid_type,expected:L.array,received:s.parsedType}),ee;if(s.data.length<this._def.items.length)return G(s,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ee;!this._def.rest&&s.data.length>this._def.items.length&&(G(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 oe(s,e,s.path,t)):null})).filter((e=>!!e));return s.common.async?Promise.all(a).then((e=>X.mergeArray(t,e))):X.mergeArray(t,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Xe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Xe({items:e,typeName:xt.ZodTuple,rest:null,...ce(t)})};var et=class e extends le{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!==L.object)return G(s,{code:D.invalid_type,expected:L.object,received:s.parsedType}),ee;const a=[],n=this._def.keyType,i=this._def.valueType;for(const e in s.data)a.push({key:n._parse(new oe(s,e,s.path,e)),value:i._parse(new oe(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?X.mergeObjectAsync(t,a):X.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(t,s,a){return new e(s instanceof le?{keyType:t,valueType:s,typeName:xt.ZodRecord,...ce(a)}:{keyType:Ae.create(),valueType:t,typeName:xt.ZodRecord,...ce(s)})}},tt=class extends le{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!==L.map)return G(s,{code:D.invalid_type,expected:L.map,received:s.parsedType}),ee;const a=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map((([e,t],i)=>({key:a._parse(new oe(s,e,s.path,[i,"key"])),value:n._parse(new oe(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 ee;"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 ee;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}};tt.create=(e,t,s)=>new tt({valueType:t,keyType:e,typeName:xt.ZodMap,...ce(s)});var st=class e extends le{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==L.set)return G(s,{code:D.invalid_type,expected:L.set,received:s.parsedType}),ee;const a=this._def;null!==a.minSize&&s.data.size<a.minSize.value&&(G(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&&(G(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 ee;"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 oe(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:H.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:H.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};st.create=(e,t)=>new st({valueType:e,minSize:null,maxSize:null,typeName:xt.ZodSet,...ce(t)});var at=class e extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==L.function)return G(t,{code:D.invalid_type,expected:L.function,received:t.parsedType}),ee;function s(e,s){return W({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,B(),q].filter((e=>!!e)),issueData:{code:D.invalid_arguments,argumentsError:s}})}function a(e,s){return W({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,B(),q].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 ct){const e=this;return se((async function(...t){const r=new V([]),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 se((function(...t){const r=e._def.args.safeParse(t,n);if(!r.success)throw new V([s(t,r.error)]);const o=Reflect.apply(i,this,r.data),d=e._def.returns.safeParse(o,n);if(!d.success)throw new V([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:Xe.create(t).rest(ze.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||Xe.create([]).rest(ze.create()),returns:s||ze.create(),typeName:xt.ZodFunction,...ce(a)})}},nt=class extends le{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})}};nt.create=(e,t)=>new nt({getter:e,typeName:xt.ZodLazy,...ce(t)});var it=class extends le{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return G(t,{received:t.data,code:D.invalid_literal,expected:this._def.value}),ee}return{status:"valid",value:e.data}}get value(){return this._def.value}};function rt(e,t){return new ot({values:e,typeName:xt.ZodEnum,...ce(t)})}it.create=(e,t)=>new it({value:e,typeName:xt.ZodLiteral,...ce(t)});var ot=class e extends le{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),s=this._def.values;return G(t,{expected:M.joinValues(s),received:t.parsedType,code:D.invalid_type}),ee}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 G(t,{received:t.data,code:D.invalid_enum_value,options:s}),ee}return se(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})}};ot.create=rt;var dt=class extends le{_parse(e){const t=M.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==L.string&&s.parsedType!==L.number){const e=M.objectValues(t);return G(s,{expected:M.joinValues(e),received:s.parsedType,code:D.invalid_type}),ee}if(this._cache||(this._cache=new Set(M.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=M.objectValues(t);return G(s,{received:s.data,code:D.invalid_enum_value,options:e}),ee}return se(e.data)}get enum(){return this._def.values}};dt.create=(e,t)=>new dt({values:e,typeName:xt.ZodNativeEnum,...ce(t)});var ct=class extends le{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==L.promise&&!1===t.common.async)return G(t,{code:D.invalid_type,expected:L.promise,received:t.parsedType}),ee;const s=t.parsedType===L.promise?t.data:Promise.resolve(t.data);return se(s.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}};ct.create=(e,t)=>new ct({type:e,typeName:xt.ZodPromise,...ce(t)});var ut=class extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===xt.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=>{G(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 ee;const a=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===a.status?ee:"dirty"===a.status||"dirty"===t.value?te(a.value):a}));{if("aborted"===t.value)return ee;const a=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===a.status?ee:"dirty"===a.status||"dirty"===t.value?te(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?ee:("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?ee:("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(!ie(e))return ee;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=>ie(e)?Promise.resolve(a.transform(e.value,n)).then((e=>({status:t.value,value:e}))):ee))}M.assertNever(a)}};ut.create=(e,t,s)=>new ut({schema:e,typeName:xt.ZodEffects,effect:t,...ce(s)}),ut.createWithPreprocess=(e,t,s)=>new ut({schema:t,effect:{type:"preprocess",transform:e},typeName:xt.ZodEffects,...ce(s)});var lt=class extends le{_parse(e){return this._getType(e)===L.undefined?se(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};lt.create=(e,t)=>new lt({innerType:e,typeName:xt.ZodOptional,...ce(t)});var pt=class extends le{_parse(e){return this._getType(e)===L.null?se(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};pt.create=(e,t)=>new pt({innerType:e,typeName:xt.ZodNullable,...ce(t)});var ht=class extends le{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===L.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ht.create=(e,t)=>new ht({innerType:e,typeName:xt.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...ce(t)});var mt=class extends le{_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 re(a)?a.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new V(s.common.issues)},input:s.data})}))):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new V(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};mt.create=(e,t)=>new mt({innerType:e,typeName:xt.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...ce(t)});var ft=class extends le{_parse(e){if(this._getType(e)!==L.nan){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.nan,received:t.parsedType}),ee}return{status:"valid",value:e.data}}};ft.create=e=>new ft({typeName:xt.ZodNaN,...ce(e)});var gt=Symbol("zod_brand"),yt=class extends le{_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}},vt=class e extends le{_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?ee:"dirty"===e.status?(t.dirty(),te(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?ee:"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:xt.ZodPipeline})}},_t=class extends le{_parse(e){const t=this._def.innerType._parse(e),s=e=>(ie(e)&&(e.value=Object.freeze(e.value)),e);return re(t)?t.then((e=>s(e))):s(t)}unwrap(){return this._def.innerType}};function bt(e,t){const s="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof s?{message:s}:s}function wt(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=bt(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}}));if(!i){const e=bt(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}})):De.create()}_t.create=(e,t)=>new _t({innerType:e,typeName:xt.ZodReadonly,...ce(t)});var xt,kt,Ct={object:Be.lazycreate};(kt=xt||(xt={})).ZodString="ZodString",kt.ZodNumber="ZodNumber",kt.ZodNaN="ZodNaN",kt.ZodBigInt="ZodBigInt",kt.ZodBoolean="ZodBoolean",kt.ZodDate="ZodDate",kt.ZodSymbol="ZodSymbol",kt.ZodUndefined="ZodUndefined",kt.ZodNull="ZodNull",kt.ZodAny="ZodAny",kt.ZodUnknown="ZodUnknown",kt.ZodNever="ZodNever",kt.ZodVoid="ZodVoid",kt.ZodArray="ZodArray",kt.ZodObject="ZodObject",kt.ZodUnion="ZodUnion",kt.ZodDiscriminatedUnion="ZodDiscriminatedUnion",kt.ZodIntersection="ZodIntersection",kt.ZodTuple="ZodTuple",kt.ZodRecord="ZodRecord",kt.ZodMap="ZodMap",kt.ZodSet="ZodSet",kt.ZodFunction="ZodFunction",kt.ZodLazy="ZodLazy",kt.ZodLiteral="ZodLiteral",kt.ZodEnum="ZodEnum",kt.ZodEffects="ZodEffects",kt.ZodNativeEnum="ZodNativeEnum",kt.ZodOptional="ZodOptional",kt.ZodNullable="ZodNullable",kt.ZodDefault="ZodDefault",kt.ZodCatch="ZodCatch",kt.ZodPromise="ZodPromise",kt.ZodBranded="ZodBranded",kt.ZodPipeline="ZodPipeline",kt.ZodReadonly="ZodReadonly";var Tt=(e,t={message:`Input not instance of ${e.name}`})=>wt((t=>t instanceof e),t),Nt=Ae.create,It=Ee.create,Ot=ft.create,St=Re.create,Mt=Pe.create,Zt=$e.create,At=Fe.create,jt=Le.create,Et=Ue.create,Rt=De.create,Pt=ze.create,$t=Ve.create,Ft=qe.create,Lt=Je.create,Ut=Be.create,Dt=Be.strictCreate,zt=We.create,Vt=Ge.create,qt=Qe.create,Jt=Xe.create,Kt=et.create,Bt=tt.create,Wt=st.create,Yt=at.create,Gt=nt.create,Ht=it.create,Qt=ot.create,Xt=dt.create,es=ct.create,ts=ut.create,ss=lt.create,as=pt.create,ns=ut.createWithPreprocess,is=vt.create,rs=()=>Nt().optional(),os=()=>It().optional(),ds=()=>Mt().optional(),cs={string:e=>Ae.create({...e,coerce:!0}),number:e=>Ee.create({...e,coerce:!0}),boolean:e=>Pe.create({...e,coerce:!0}),bigint:e=>Re.create({...e,coerce:!0}),date:e=>$e.create({...e,coerce:!0})},us=ee,ls={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"},ps={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"},hs=F.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"]),ms=F.enum(["unknown","android","ios","desktop","web"]),fs=F.object({chatId:F.string(),channelId:F.string(),receiverId:F.string(),receiverName:F.string(),roomId:F.string(),roomName:F.string(),senderId:F.string(),senderName:F.string(),senderDevice:ms,chatType:hs,timestamp:F.number(),mentions:F.string().array(),text:F.string().nullable(),links:F.string().array(),isPrefix:F.boolean(),isFromMe:F.boolean(),isTagMe:F.boolean(),isGroup:F.boolean(),isStory:F.boolean(),isViewOnce:F.boolean(),isEdited:F.boolean(),isDeleted:F.boolean(),isPinned:F.boolean(),isUnPinned:F.boolean(),isChannel:F.boolean(),isBroadcast:F.boolean(),isEphemeral:F.boolean(),isForwarded:F.boolean(),citation:F.record(F.string(),F.boolean()).nullable(),media:F.object({buffer:F.function().returns(F.instanceof(Buffer)),stream:F.function().returns(F.instanceof(S))}).passthrough().nullable(),message:F.function().returns(F.record(F.string(),F.any()))});fs.extend({replied:fs.nullable()});var gs=class{constructor(e,t,s){this.socket=e,this.client=t,this.db=s}maxReplies=0;async connection(e){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("connection",!1),console.log(),console.log(await O.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){this.client.failSpinner("connection","Connection closed");const e=s?.error?.output?.statusCode,t=e===d.restartRequired;if(console.log(s?.error?.message),401===e||405===e||500===e)return void console.error("Invalid session, please delete manually");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,i=2==e?.message?.pinInChatMessage?.type;if(a){const t=await this.db.selectFrom("messages").select("value").where("id","=",a).executeTakeFirst(),s=E(t?.value);e=s}const o=!e?.message?.protocolMessage?.editedMessage&&e?.message?.protocolMessage?.key?.id,d=!!o;if(o){const t=await this.db.selectFrom("messages").select("value").where("id","=",o).executeTakeFirst(),s=E(t?.value);e=s}const p={},h=c(e?.message?.protocolMessage?.editedMessage||e?.message);p.chatId=e?.message?.protocolMessage?.key?.id||e?.key?.id,p.channelId="",p.receiverId=r(this.socket.user?.id),p.receiverName=this.socket.user?.name||this.socket.user?.verifiedName,p.roomId=r(e?.key?.remoteJid);const m=await this.db.selectFrom("chats").select("value").where("id","=",p.roomId).executeTakeFirst();p.roomName=E(m?.value)?.name,p.senderId=r(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||E(f?.value)?.name||p.receiverName,p.roomName=p.roomName||p.senderName,p.senderDevice=u(p.chatId),p.chatType=ls[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=d,p.isPinned=n,p.isUnPinned=i,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];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={...$(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=E(t?.value);if(s)p.replied=await this.messages(s,!0);else{const t=e,s=c(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 b=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=P(R(e),"editedMessage"),p.isEphemeral=P(R(b?.contextInfo),"ephemeralSettingTimestamp"),p.isForwarded=P(R(b?.contextInfo),"forwardingScore"),p.isViewOnce=!!b?.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)}},ys=async(e,t)=>{const s="auth";await(async e=>{await e.schema.createTable("auth").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("auth_session_id_unique",["session","id"]).execute(),await e.schema.createTable("chats").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("chats_session_id_unique",["session","id"]).execute(),await e.schema.createTable("contacts").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("contacts_session_id_unique",["session","id"]).execute(),await e.schema.createTable("messages").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("messages_session_id_unique",["session","id"]).execute(),await e.schema.createIndex("auth_session_idx").ifNotExists().on("auth").column("session").execute(),await e.schema.createIndex("auth_id_idx").ifNotExists().on("auth").column("id").execute(),await e.schema.createIndex("chats_session_idx").ifNotExists().on("chats").column("session").execute(),await e.schema.createIndex("chats_id_idx").ifNotExists().on("chats").column("id").execute(),await e.schema.createIndex("contacts_session_idx").ifNotExists().on("contacts").column("session").execute(),await e.schema.createIndex("contacts_id_idx").ifNotExists().on("contacts").column("id").execute(),await e.schema.createIndex("messages_session_idx").ifNotExists().on("messages").column("session").execute(),await e.schema.createIndex("messages_id_idx").ifNotExists().on("messages").column("id").execute()})(e);const a=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 n=>{const i=await a((()=>e.selectFrom(s).select(["value"]).where("id","=",n).where("session","=",t).executeTakeFirst()));if(!i?.value)return null;const r="object"==typeof i.value?JSON.stringify(i.value):i.value;return JSON.parse(r,o.reviver)},d=async(n,i)=>{const r=JSON.stringify(i,o.replacer);await a((()=>e.insertInto(s).values({session:t,id:n,value:r}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:r}))).execute()))},c=async n=>{await a((()=>e.deleteFrom(s).where("id","=",n).where("session","=",t).execute()))},u=await r("creds")||n();return{state:{creds:u,keys:{get:async(e,t)=>{const s={};for(const a of t){let t=await r(`${e}-${a}`);"app-state-sync-key"===e&&t&&(t=i.SenderKeyMessage.fromObject(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",u)},clear:async()=>{await(async()=>{await a((()=>e.deleteFrom(s).where("session","=",t).where("id","!=","creds").execute()))})()},removeCreds:async()=>{await(async()=>{await a((()=>e.deleteFrom(s).where("session","=",t).execute()))})()}}},vs=F.object({type:F.enum(["sqlite","postgresql","mysql"]).default("sqlite"),connection:F.object({url:F.string().default("./session/zaileys.db")}).optional().default({})}).optional().default({}),_s=F.record(F.function().returns(F.union([F.number().array(),F.promise(F.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})),bs=F.object({prefix:F.string().optional(),ignoreMe:F.boolean().optional().default(!0),showLogs:F.boolean().optional().default(!0),autoMentions:F.boolean().optional().default(!0),autoOnline:F.boolean().optional().default(!0),autoRead:F.boolean().optional().default(!0),autoPresence:F.boolean().optional().default(!0),autoRejectCall:F.boolean().optional().default(!0),database:vs,citation:_s}),ws=F.object({authType:F.literal("pairing"),phoneNumber:F.number()}).extend(bs.shape),xs=F.object({authType:F.literal("qr"),phoneNumber:F.undefined().optional()}).extend(bs.shape),ks=F.discriminatedUnion("authType",[ws,xs]),Cs=F.union([F.string().url(),F.instanceof(Buffer).or(F.instanceof(S))]),Ts=F.union([F.string(),F.object({image:Cs,text:F.string().optional()}),F.object({video:Cs,text:F.string().optional()}),F.object({videoNote:Cs}),F.object({gif:Cs,text:F.string().optional()}),F.object({audio:Cs}),F.object({audioNote:Cs}),F.object({sticker:Cs})]),Ns=F.object({roomId:F.string(),asForwarded:F.boolean().optional(),asViewOnce:F.boolean().optional(),verifiedReply:F.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).optional(),quoted:F.function().returns(F.record(F.string(),F.any())).optional()}),Is=Ns,Os=F.object({latitude:F.number(),longitude:F.number(),title:F.string().optional(),footer:F.string().optional()}),Ss=Ns,Ms=F.object({fullname:F.string(),nickname:F.string().optional(),organization:F.string().optional(),role:F.string().optional(),email:F.string().email().optional(),whatsAppNumber:F.number(),callNumber:F.number().optional(),voiceNumber:F.number().optional(),website:F.string().url().optional(),homeAddress:F.string().optional(),workAddress:F.string().optional(),avatar:F.string().url().optional()}),Zs=F.object({message:F.function().returns(F.record(F.string(),F.any()))}),As=F.string(),js=F.object({message:F.function().returns(F.record(F.string(),F.any()))}),Es=F.object({action:F.enum(["pin","unpin"]),expired:F.enum(["24h","7d","30d"])}),Rs=Ns.pick({roomId:!0}),Ps=F.object({name:F.string(),answers:F.string().array(),multipleAnswers:F.boolean().optional()}),$s=F.object({message:F.function().returns(F.record(F.string(),F.any()))}),Fs=F.string(),Ls=F.object({message:F.function().returns(F.record(F.string(),F.any()))}),Us=F.object({callId:F.string(),callerId:F.string()}),Ds=Ns.pick({roomId:!0}),zs=F.object({expired:F.enum(["remove","8h","7d"])}),Vs=F.string();F.object({type:F.enum(["group","user"]),id:F.string(),name:F.string(),bio:F.string(),avatar:F.string().url(),ephemeralDuration:F.number().optional(),isRestrict:F.boolean().optional(),isAnnounce:F.boolean().optional(),isCommunity:F.boolean().optional(),isCommunityAnnounce:F.boolean().optional(),isJoinApprovalMode:F.boolean().optional(),isMemberAddMode:F.boolean().optional(),owner:F.object({type:F.literal("user"),id:F.string()}).nullable(),roomCreatedAt:F.number().optional(),nameUpdatedAt:F.number().optional(),bioUpdatedAt:F.number().optional(),membersLength:F.number().optional(),members:F.object({type:F.enum(["user","admin","superadmin"]),id:F.string()}).array().optional()});var qs=Ns.pick({roomId:!0}),Js=F.enum(["typing","recording","online","offline","paused"]),Ks=class{constructor(e){this.wa=e,this.parser=new gs(this.wa.socket,this.wa.client,this.wa.db)}parser;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=ps[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=Ts.parse(e),t=Ns.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=Os.parse(e),t=Is.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=Ms.parse(e),t=Ss.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=As.parse(e),t=Zs.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{react:{text:e,key:t.message()?.key},...t})}async pin(e,t){e=Es.parse(e),t=js.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=Ps.parse(e),t=Rs.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=Fs.parse(e),t=$s.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{text:e,edit:t.message()?.key,...t})}async delete(e){return e=Ls.parse(e),await this.sendMessage(e.message()?.key?.remoteJid,{delete:e.message()?.key})}async rejectCall(e){return e=Us.parse(e),await(this.wa.socket?.rejectCall(e.callId,e.callerId))}async mute(e,t){e=zs.parse(e),t=Ds.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=Vs.parse(e)).includes("@g.us"),s={};s.id=e;if(r(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=E(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=Js.parse(e),t=qs.parse(t);return await(this.wa.socket?.sendPresenceUpdate({typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"}[e],t.roomId))}},Bs=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 m({stdTTL:300,useClones:!1});chatId="zaileys-chats";logger=g({level:"silent",enabled:!1});db;socket;events=new p;spinners=new Map;worker;async initialize(){console.clear(),await((e="ZAILEYS")=>new Promise((t=>{h(e,((e,s)=>{if(e)return t("");console.log(s),t(s||"")}))})))(),this.options=await ks.parseAsync(this.props),this.startSpinner("db","Initializing database..."),this.db=await((e,t)=>{if("sqlite"===e){const e=t||"./db/zaileys.db",s=T.resolve(e);return v(T.dirname(s),{recursive:!0}),_(s,"",{flag:"a"}),new b({dialect:new w({database:new y(s)})})}const s=new I(t),a=s.protocol.replace(":","");if("mysql"===e)return new b({dialect:new x({pool:C.createPool({host:s.hostname,user:s.username,password:s.password,database:s.pathname.replace("/",""),port:parseInt(s.port||"3306",10)})})});if("postgresql"===e)return new b({dialect:new k({pool:new N({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: ${a}`)})(this.options.database.type,this.options.database.connection.url),this.stopSpinner("db",!0,"Database initialized"),this.startSpinner("auth","Setting up auth adapter...");const{state:n,saveCreds:i}=await ys(this.db,this.chatId);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 gs(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 m,mediaCache:new m({stdTTL:60}),userDevicesCache:new m,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 E(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 Ks({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=f(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)}},Ws=Bs;export{Bs as Client,Ws as default};
|
|
1
|
+
import{fetchLatestBaileysVersion as e,makeWASocket as t,makeCacheableSignalKeyStore as s,Browsers as a,initAuthCreds as n,proto as i,jidNormalizedUser as r,BufferJSON as o,DisconnectReason as d,getContentType as c,getDevice as u,downloadMediaMessage as l}from"baileys";import{EventEmitter as p}from"events";import h from"figlet";import m from"node-cache";import f from"ora";import g from"pino";import y from"better-sqlite3";import{mkdirSync as v,writeFileSync as _}from"fs";import{Kysely as b,SqliteDialect as w,MysqlDialect as x,PostgresDialect as k}from"kysely";import C from"mysql2";import T from"path";import{Pool as N}from"pg";import{URL as I}from"url";import O from"qrcode";import{Readable as S}from"stream";var M,Z,A,j=Object.defineProperty,E=(e="")=>{try{return JSON.parse(e)}catch{return JSON.parse(JSON.stringify(e))}},R=(e={})=>{try{return JSON.stringify(e)}catch{return JSON.stringify(JSON.parse(JSON.stringify(e)))}},P=(e="",t="")=>e?e.toLowerCase().includes(t.toLowerCase()):null,$=(e,t)=>e&&"object"==typeof e?Array.isArray(e)?e.map((e=>$(e,t))):Object.fromEntries(Object.entries(e).filter((([e])=>!t.includes(e))).map((([e,s])=>[e,"object"==typeof s?$(s,t):s]))):e,F={};((e,t)=>{for(var s in t)j(e,s,{get:t[s],enumerable:!0})})(F,{BRAND:()=>gt,DIRTY:()=>te,EMPTY_PATH:()=>Y,INVALID:()=>ee,NEVER:()=>us,OK:()=>se,ParseStatus:()=>X,Schema:()=>le,ZodAny:()=>De,ZodArray:()=>Je,ZodBigInt:()=>Re,ZodBoolean:()=>Pe,ZodBranded:()=>yt,ZodCatch:()=>mt,ZodDate:()=>$e,ZodDefault:()=>ht,ZodDiscriminatedUnion:()=>Ge,ZodEffects:()=>ut,ZodEnum:()=>ot,ZodError:()=>V,ZodFirstPartyTypeKind:()=>xt,ZodFunction:()=>at,ZodIntersection:()=>Qe,ZodIssueCode:()=>D,ZodLazy:()=>nt,ZodLiteral:()=>it,ZodMap:()=>tt,ZodNaN:()=>ft,ZodNativeEnum:()=>dt,ZodNever:()=>Ve,ZodNull:()=>Ue,ZodNullable:()=>pt,ZodNumber:()=>Ee,ZodObject:()=>Be,ZodOptional:()=>lt,ZodParsedType:()=>L,ZodPipeline:()=>vt,ZodPromise:()=>ct,ZodReadonly:()=>_t,ZodRecord:()=>et,ZodSchema:()=>le,ZodSet:()=>st,ZodString:()=>Ae,ZodSymbol:()=>Fe,ZodTransformer:()=>ut,ZodTuple:()=>Xe,ZodType:()=>le,ZodUndefined:()=>Le,ZodUnion:()=>We,ZodUnknown:()=>ze,ZodVoid:()=>qe,addIssueToContext:()=>G,any:()=>Rt,array:()=>Lt,bigint:()=>St,boolean:()=>Mt,coerce:()=>cs,custom:()=>wt,date:()=>Zt,datetimeRegex:()=>Se,defaultErrorMap:()=>q,discriminatedUnion:()=>Vt,effect:()=>ts,enum:()=>Qt,function:()=>Yt,getErrorMap:()=>B,getParsedType:()=>U,instanceof:()=>Tt,intersection:()=>qt,isAborted:()=>ae,isAsync:()=>re,isDirty:()=>ne,isValid:()=>ie,late:()=>Ct,lazy:()=>Gt,literal:()=>Ht,makeIssue:()=>W,map:()=>Bt,nan:()=>Ot,nativeEnum:()=>Xt,never:()=>$t,null:()=>Et,nullable:()=>as,number:()=>It,object:()=>Ut,objectUtil:()=>A,oboolean:()=>ds,onumber:()=>os,optional:()=>ss,ostring:()=>rs,pipeline:()=>is,preprocess:()=>ns,promise:()=>es,quotelessJson:()=>z,record:()=>Kt,set:()=>Wt,setErrorMap:()=>K,strictObject:()=>Dt,string:()=>Nt,symbol:()=>At,transformer:()=>ts,tuple:()=>Jt,undefined:()=>jt,union:()=>zt,unknown:()=>Pt,util:()=>M,void:()=>Ft}),(Z=M||(M={})).assertEqual=e=>{},Z.assertIs=function(e){},Z.assertNever=function(e){throw new Error},Z.arrayToEnum=e=>{const t={};for(const s of e)t[s]=s;return t},Z.getValidEnumValues=e=>{const t=Z.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),s={};for(const a of t)s[a]=e[a];return Z.objectValues(s)},Z.objectValues=e=>Z.objectKeys(e).map((function(t){return e[t]})),Z.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},Z.find=(e,t)=>{for(const s of e)if(t(s))return s},Z.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,Z.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},Z.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(A||(A={})).mergeShapes=(e,t)=>({...e,...t});var L=M.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 L.undefined;case"string":return L.string;case"number":return Number.isNaN(e)?L.nan:L.number;case"boolean":return L.boolean;case"function":return L.function;case"bigint":return L.bigint;case"symbol":return L.symbol;case"object":return Array.isArray(e)?L.array:null===e?L.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?L.promise:"undefined"!=typeof Map&&e instanceof Map?L.map:"undefined"!=typeof Set&&e instanceof Set?L.set:"undefined"!=typeof Date&&e instanceof Date?L.date:L.object;default:return L.unknown}},D=M.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),z=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),V=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,M.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()}};V.create=e=>new V(e);var q=(e,t)=>{let s;switch(e.code){case D.invalid_type:s=e.received===L.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case D.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,M.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:s=`Unrecognized key(s) in object: ${M.joinValues(e.keys,", ")}`;break;case D.invalid_union:s="Invalid input";break;case D.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${M.joinValues(e.options)}`;break;case D.invalid_enum_value:s=`Invalid enum value. Expected ${M.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}"`:M.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,M.assertNever(e)}return{message:s}},J=q;function K(e){J=e}function B(){return J}var W=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}},Y=[];function G(e,t){const s=B(),a=W({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===q?void 0:q].filter((e=>!!e))});e.common.issues.push(a)}var H,Q,X=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 ee;"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 ee;if("aborted"===n.status)return ee;"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}}},ee=Object.freeze({status:"aborted"}),te=e=>({status:"dirty",value:e}),se=e=>({status:"valid",value:e}),ae=e=>"aborted"===e.status,ne=e=>"dirty"===e.status,ie=e=>"valid"===e.status,re=e=>"undefined"!=typeof Promise&&e instanceof Promise;(Q=H||(H={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},Q.toString=e=>"string"==typeof e?e:e?.message;var oe=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}},de=(e,t)=>{if(ie(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 V(e.common.issues);return this._error=t,this._error}}};function ce(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 ue,le=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 X,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(re(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 de(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 ie(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=>ie(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(re(a)?a:Promise.resolve(a));return de(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 ut({schema:this,typeName:xt.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 lt.create(this,this._def)}nullable(){return pt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Je.create(this)}promise(){return ct.create(this,this._def)}or(e){return We.create([this,e],this._def)}and(e){return Qe.create(this,e,this._def)}transform(e){return new ut({...ce(this._def),schema:this,typeName:xt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ht({...ce(this._def),innerType:this,defaultValue:t,typeName:xt.ZodDefault})}brand(){return new yt({typeName:xt.ZodBranded,type:this,...ce(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new mt({...ce(this._def),innerType:this,catchValue:t,typeName:xt.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return vt.create(this,e)}readonly(){return _t.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},pe=/^c[^\s-]{8,}$/i,he=/^[0-9a-z]+$/,me=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fe=/^[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,ge=/^[a-z0-9_-]{21}$/i,ye=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ve=/^[-+]?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)?)??$/,_e=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,be=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,we=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,xe=/^(([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]))$/,ke=/^(([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])$/,Ce=/^([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])))",Ie=new RegExp(`^${Ne}$`);function Oe(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=`${Ne}T${Oe(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 Me(e,t){if(!ye.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||!we.test(e))||!("v6"!==t&&t||!ke.test(e))}var Ae=class e extends le{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==L.string){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.string,received:t.parsedType}),ee}const t=new X;let s;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),G(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),G(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?G(s,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&G(s,{code:D.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)_e.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"email",code:D.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)ue||(ue=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ue.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"emoji",code:D.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)fe.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"uuid",code:D.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)ge.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"nanoid",code:D.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)pe.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"cuid",code:D.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)he.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"cuid2",code:D.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)me.test(e.data)||(s=this._getOrReturnCtx(e,s),G(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),G(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),G(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),G(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),G(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),G(s,{code:D.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){Se(i).test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{code:D.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){Ie.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{code:D.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${Oe(i)}$`).test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{code:D.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?ve.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"duration",code:D.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(a=e.data,("v4"!==(n=i.version)&&n||!be.test(a))&&("v6"!==n&&n||!xe.test(a))&&(s=this._getOrReturnCtx(e,s),G(s,{validation:"ip",code:D.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?Me(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),G(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),G(s,{validation:"cidr",code:D.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?Ce.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"base64",code:D.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?Te.test(e.data)||(s=this._getOrReturnCtx(e,s),G(s,{validation:"base64url",code:D.invalid_string,message:i.message}),t.dirty()):M.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,...H.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...H.errToObj(e)})}url(e){return this._addCheck({kind:"url",...H.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...H.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...H.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...H.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...H.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...H.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...H.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...H.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...H.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...H.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...H.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...H.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,...H.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,...H.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...H.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...H.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...H.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...H.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...H.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...H.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...H.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...H.errToObj(t)})}nonempty(e){return this.min(1,H.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}Ae.create=e=>new Ae({checks:[],typeName:xt.ZodString,coerce:e?.coerce??!1,...ce(e)});var Ee=class e extends le{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)!==L.number){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.number,received:t.parsedType}),ee}let t;const s=new X;for(const a of this._def.checks)if("int"===a.kind)M.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),G(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),G(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),G(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),G(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),G(t,{code:D.not_finite,message:a.message}),s.dirty()):M.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,H.toString(t))}gt(e,t){return this.setLimit("min",e,!1,H.toString(t))}lte(e,t){return this.setLimit("max",e,!0,H.toString(t))}lt(e,t){return this.setLimit("max",e,!1,H.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:H.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:H.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:H.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:H.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:H.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:H.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:H.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:H.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&&M.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)}};Ee.create=e=>new Ee({checks:[],typeName:xt.ZodNumber,coerce:e?.coerce||!1,...ce(e)});var Re=class e extends le{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)!==L.bigint)return this._getInvalidInput(e);let t;const s=new X;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),G(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),G(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),G(t,{code:D.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):M.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.bigint,received:t.parsedType}),ee}gte(e,t){return this.setLimit("min",e,!0,H.toString(t))}gt(e,t){return this.setLimit("min",e,!1,H.toString(t))}lte(e,t){return this.setLimit("max",e,!0,H.toString(t))}lt(e,t){return this.setLimit("max",e,!1,H.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:H.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:H.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:H.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:H.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:H.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:H.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:xt.ZodBigInt,coerce:e?.coerce??!1,...ce(e)});var Pe=class extends le{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==L.boolean){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.boolean,received:t.parsedType}),ee}return se(e.data)}};Pe.create=e=>new Pe({typeName:xt.ZodBoolean,coerce:e?.coerce||!1,...ce(e)});var $e=class e extends le{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==L.date){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.date,received:t.parsedType}),ee}if(Number.isNaN(e.data.getTime())){return G(this._getOrReturnCtx(e),{code:D.invalid_date}),ee}const t=new X;let s;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),G(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),G(s,{code:D.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):M.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:H.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:H.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:xt.ZodDate,...ce(e)});var Fe=class extends le{_parse(e){if(this._getType(e)!==L.symbol){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.symbol,received:t.parsedType}),ee}return se(e.data)}};Fe.create=e=>new Fe({typeName:xt.ZodSymbol,...ce(e)});var Le=class extends le{_parse(e){if(this._getType(e)!==L.undefined){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.undefined,received:t.parsedType}),ee}return se(e.data)}};Le.create=e=>new Le({typeName:xt.ZodUndefined,...ce(e)});var Ue=class extends le{_parse(e){if(this._getType(e)!==L.null){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.null,received:t.parsedType}),ee}return se(e.data)}};Ue.create=e=>new Ue({typeName:xt.ZodNull,...ce(e)});var De=class extends le{constructor(){super(...arguments),this._any=!0}_parse(e){return se(e.data)}};De.create=e=>new De({typeName:xt.ZodAny,...ce(e)});var ze=class extends le{constructor(){super(...arguments),this._unknown=!0}_parse(e){return se(e.data)}};ze.create=e=>new ze({typeName:xt.ZodUnknown,...ce(e)});var Ve=class extends le{_parse(e){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.never,received:t.parsedType}),ee}};Ve.create=e=>new Ve({typeName:xt.ZodNever,...ce(e)});var qe=class extends le{_parse(e){if(this._getType(e)!==L.undefined){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.void,received:t.parsedType}),ee}return se(e.data)}};qe.create=e=>new qe({typeName:xt.ZodVoid,...ce(e)});var Je=class e extends le{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==L.array)return G(t,{code:D.invalid_type,expected:L.array,received:t.parsedType}),ee;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,n=t.data.length<a.exactLength.value;(e||n)&&(G(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&&(G(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&&(G(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 oe(t,e,t.path,s))))).then((e=>X.mergeArray(s,e)));const n=[...t.data].map(((e,s)=>a.type._parseSync(new oe(t,e,t.path,s))));return X.mergeArray(s,n)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:H.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:H.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:H.toString(s)}})}nonempty(e){return this.min(1,e)}};function Ke(e){if(e instanceof Be){const t={};for(const s in e.shape){const a=e.shape[s];t[s]=lt.create(Ke(a))}return new Be({...e._def,shape:()=>t})}return e instanceof Je?new Je({...e._def,type:Ke(e.element)}):e instanceof lt?lt.create(Ke(e.unwrap())):e instanceof pt?pt.create(Ke(e.unwrap())):e instanceof Xe?Xe.create(e.items.map((e=>Ke(e)))):e}Je.create=(e,t)=>new Je({type:e,minLength:null,maxLength:null,exactLength:null,typeName:xt.ZodArray,...ce(t)});var Be=class e extends le{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=M.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==L.object){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.object,received:t.parsedType}),ee}const{status:t,ctx:s}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof Ve&&"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 oe(s,n,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof Ve){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&&(G(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 oe(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=>X.mergeObjectSync(t,e))):X.mergeObjectSync(t,r)}get shape(){return this._def.shape()}strict(t){return H.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:H.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:xt.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 M.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 M.objectKeys(this.shape))t[e]||(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}deepPartial(){return Ke(this)}partial(t){const s={};for(const e of M.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 M.objectKeys(this.shape))if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof lt;)t=t._def.innerType;s[e]=t}return new e({...this._def,shape:()=>s})}keyof(){return rt(M.objectKeys(this.shape))}};Be.create=(e,t)=>new Be({shape:()=>e,unknownKeys:"strip",catchall:Ve.create(),typeName:xt.ZodObject,...ce(t)}),Be.strictCreate=(e,t)=>new Be({shape:()=>e,unknownKeys:"strict",catchall:Ve.create(),typeName:xt.ZodObject,...ce(t)}),Be.lazycreate=(e,t)=>new Be({shape:e,unknownKeys:"strip",catchall:Ve.create(),typeName:xt.ZodObject,...ce(t)});var We=class extends le{_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 V(e.ctx.common.issues)));return G(t,{code:D.invalid_union,unionErrors:s}),ee}));{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 V(e)));return G(t,{code:D.invalid_union,unionErrors:n}),ee}}get options(){return this._def.options}};We.create=(e,t)=>new We({options:e,typeName:xt.ZodUnion,...ce(t)});var Ye=e=>e instanceof nt?Ye(e.schema):e instanceof ut?Ye(e.innerType()):e instanceof it?[e.value]:e instanceof ot?e.options:e instanceof dt?M.objectValues(e.enum):e instanceof ht?Ye(e._def.innerType):e instanceof Le?[void 0]:e instanceof Ue?[null]:e instanceof lt?[void 0,...Ye(e.unwrap())]:e instanceof pt?[null,...Ye(e.unwrap())]:e instanceof yt||e instanceof _t?Ye(e.unwrap()):e instanceof mt?Ye(e._def.innerType):[],Ge=class e extends le{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==L.object)return G(t,{code:D.invalid_type,expected:L.object,received:t.parsedType}),ee;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}):(G(t,{code:D.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),ee)}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=Ye(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:xt.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:n,...ce(a)})}};function He(e,t){const s=U(e),a=U(t);if(e===t)return{valid:!0,data:e};if(s===L.object&&a===L.object){const s=M.objectKeys(t),a=M.objectKeys(e).filter((e=>-1!==s.indexOf(e))),n={...e,...t};for(const s of a){const a=He(e[s],t[s]);if(!a.valid)return{valid:!1};n[s]=a.data}return{valid:!0,data:n}}if(s===L.array&&a===L.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let a=0;a<e.length;a++){const n=He(e[a],t[a]);if(!n.valid)return{valid:!1};s.push(n.data)}return{valid:!0,data:s}}return s===L.date&&a===L.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}var Qe=class extends le{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=(e,a)=>{if(ae(e)||ae(a))return ee;const n=He(e.value,a.value);return n.valid?((ne(e)||ne(a))&&t.dirty(),{status:t.value,value:n.data}):(G(s,{code:D.invalid_intersection_types}),ee)};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}))}};Qe.create=(e,t,s)=>new Qe({left:e,right:t,typeName:xt.ZodIntersection,...ce(s)});var Xe=class e extends le{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==L.array)return G(s,{code:D.invalid_type,expected:L.array,received:s.parsedType}),ee;if(s.data.length<this._def.items.length)return G(s,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ee;!this._def.rest&&s.data.length>this._def.items.length&&(G(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 oe(s,e,s.path,t)):null})).filter((e=>!!e));return s.common.async?Promise.all(a).then((e=>X.mergeArray(t,e))):X.mergeArray(t,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Xe.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Xe({items:e,typeName:xt.ZodTuple,rest:null,...ce(t)})};var et=class e extends le{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!==L.object)return G(s,{code:D.invalid_type,expected:L.object,received:s.parsedType}),ee;const a=[],n=this._def.keyType,i=this._def.valueType;for(const e in s.data)a.push({key:n._parse(new oe(s,e,s.path,e)),value:i._parse(new oe(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?X.mergeObjectAsync(t,a):X.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(t,s,a){return new e(s instanceof le?{keyType:t,valueType:s,typeName:xt.ZodRecord,...ce(a)}:{keyType:Ae.create(),valueType:t,typeName:xt.ZodRecord,...ce(s)})}},tt=class extends le{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!==L.map)return G(s,{code:D.invalid_type,expected:L.map,received:s.parsedType}),ee;const a=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map((([e,t],i)=>({key:a._parse(new oe(s,e,s.path,[i,"key"])),value:n._parse(new oe(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 ee;"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 ee;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}};tt.create=(e,t,s)=>new tt({valueType:t,keyType:e,typeName:xt.ZodMap,...ce(s)});var st=class e extends le{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==L.set)return G(s,{code:D.invalid_type,expected:L.set,received:s.parsedType}),ee;const a=this._def;null!==a.minSize&&s.data.size<a.minSize.value&&(G(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&&(G(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 ee;"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 oe(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:H.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:H.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};st.create=(e,t)=>new st({valueType:e,minSize:null,maxSize:null,typeName:xt.ZodSet,...ce(t)});var at=class e extends le{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==L.function)return G(t,{code:D.invalid_type,expected:L.function,received:t.parsedType}),ee;function s(e,s){return W({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,B(),q].filter((e=>!!e)),issueData:{code:D.invalid_arguments,argumentsError:s}})}function a(e,s){return W({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,B(),q].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 ct){const e=this;return se((async function(...t){const r=new V([]),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 se((function(...t){const r=e._def.args.safeParse(t,n);if(!r.success)throw new V([s(t,r.error)]);const o=Reflect.apply(i,this,r.data),d=e._def.returns.safeParse(o,n);if(!d.success)throw new V([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:Xe.create(t).rest(ze.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||Xe.create([]).rest(ze.create()),returns:s||ze.create(),typeName:xt.ZodFunction,...ce(a)})}},nt=class extends le{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})}};nt.create=(e,t)=>new nt({getter:e,typeName:xt.ZodLazy,...ce(t)});var it=class extends le{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return G(t,{received:t.data,code:D.invalid_literal,expected:this._def.value}),ee}return{status:"valid",value:e.data}}get value(){return this._def.value}};function rt(e,t){return new ot({values:e,typeName:xt.ZodEnum,...ce(t)})}it.create=(e,t)=>new it({value:e,typeName:xt.ZodLiteral,...ce(t)});var ot=class e extends le{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),s=this._def.values;return G(t,{expected:M.joinValues(s),received:t.parsedType,code:D.invalid_type}),ee}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 G(t,{received:t.data,code:D.invalid_enum_value,options:s}),ee}return se(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})}};ot.create=rt;var dt=class extends le{_parse(e){const t=M.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==L.string&&s.parsedType!==L.number){const e=M.objectValues(t);return G(s,{expected:M.joinValues(e),received:s.parsedType,code:D.invalid_type}),ee}if(this._cache||(this._cache=new Set(M.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=M.objectValues(t);return G(s,{received:s.data,code:D.invalid_enum_value,options:e}),ee}return se(e.data)}get enum(){return this._def.values}};dt.create=(e,t)=>new dt({values:e,typeName:xt.ZodNativeEnum,...ce(t)});var ct=class extends le{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==L.promise&&!1===t.common.async)return G(t,{code:D.invalid_type,expected:L.promise,received:t.parsedType}),ee;const s=t.parsedType===L.promise?t.data:Promise.resolve(t.data);return se(s.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}};ct.create=(e,t)=>new ct({type:e,typeName:xt.ZodPromise,...ce(t)});var ut=class extends le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===xt.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=>{G(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 ee;const a=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===a.status?ee:"dirty"===a.status||"dirty"===t.value?te(a.value):a}));{if("aborted"===t.value)return ee;const a=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===a.status?ee:"dirty"===a.status||"dirty"===t.value?te(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?ee:("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?ee:("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(!ie(e))return ee;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=>ie(e)?Promise.resolve(a.transform(e.value,n)).then((e=>({status:t.value,value:e}))):ee))}M.assertNever(a)}};ut.create=(e,t,s)=>new ut({schema:e,typeName:xt.ZodEffects,effect:t,...ce(s)}),ut.createWithPreprocess=(e,t,s)=>new ut({schema:t,effect:{type:"preprocess",transform:e},typeName:xt.ZodEffects,...ce(s)});var lt=class extends le{_parse(e){return this._getType(e)===L.undefined?se(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};lt.create=(e,t)=>new lt({innerType:e,typeName:xt.ZodOptional,...ce(t)});var pt=class extends le{_parse(e){return this._getType(e)===L.null?se(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};pt.create=(e,t)=>new pt({innerType:e,typeName:xt.ZodNullable,...ce(t)});var ht=class extends le{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===L.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ht.create=(e,t)=>new ht({innerType:e,typeName:xt.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...ce(t)});var mt=class extends le{_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 re(a)?a.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new V(s.common.issues)},input:s.data})}))):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new V(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};mt.create=(e,t)=>new mt({innerType:e,typeName:xt.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...ce(t)});var ft=class extends le{_parse(e){if(this._getType(e)!==L.nan){const t=this._getOrReturnCtx(e);return G(t,{code:D.invalid_type,expected:L.nan,received:t.parsedType}),ee}return{status:"valid",value:e.data}}};ft.create=e=>new ft({typeName:xt.ZodNaN,...ce(e)});var gt=Symbol("zod_brand"),yt=class extends le{_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}},vt=class e extends le{_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?ee:"dirty"===e.status?(t.dirty(),te(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?ee:"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:xt.ZodPipeline})}},_t=class extends le{_parse(e){const t=this._def.innerType._parse(e),s=e=>(ie(e)&&(e.value=Object.freeze(e.value)),e);return re(t)?t.then((e=>s(e))):s(t)}unwrap(){return this._def.innerType}};function bt(e,t){const s="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof s?{message:s}:s}function wt(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=bt(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}}));if(!i){const e=bt(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}})):De.create()}_t.create=(e,t)=>new _t({innerType:e,typeName:xt.ZodReadonly,...ce(t)});var xt,kt,Ct={object:Be.lazycreate};(kt=xt||(xt={})).ZodString="ZodString",kt.ZodNumber="ZodNumber",kt.ZodNaN="ZodNaN",kt.ZodBigInt="ZodBigInt",kt.ZodBoolean="ZodBoolean",kt.ZodDate="ZodDate",kt.ZodSymbol="ZodSymbol",kt.ZodUndefined="ZodUndefined",kt.ZodNull="ZodNull",kt.ZodAny="ZodAny",kt.ZodUnknown="ZodUnknown",kt.ZodNever="ZodNever",kt.ZodVoid="ZodVoid",kt.ZodArray="ZodArray",kt.ZodObject="ZodObject",kt.ZodUnion="ZodUnion",kt.ZodDiscriminatedUnion="ZodDiscriminatedUnion",kt.ZodIntersection="ZodIntersection",kt.ZodTuple="ZodTuple",kt.ZodRecord="ZodRecord",kt.ZodMap="ZodMap",kt.ZodSet="ZodSet",kt.ZodFunction="ZodFunction",kt.ZodLazy="ZodLazy",kt.ZodLiteral="ZodLiteral",kt.ZodEnum="ZodEnum",kt.ZodEffects="ZodEffects",kt.ZodNativeEnum="ZodNativeEnum",kt.ZodOptional="ZodOptional",kt.ZodNullable="ZodNullable",kt.ZodDefault="ZodDefault",kt.ZodCatch="ZodCatch",kt.ZodPromise="ZodPromise",kt.ZodBranded="ZodBranded",kt.ZodPipeline="ZodPipeline",kt.ZodReadonly="ZodReadonly";var Tt=(e,t={message:`Input not instance of ${e.name}`})=>wt((t=>t instanceof e),t),Nt=Ae.create,It=Ee.create,Ot=ft.create,St=Re.create,Mt=Pe.create,Zt=$e.create,At=Fe.create,jt=Le.create,Et=Ue.create,Rt=De.create,Pt=ze.create,$t=Ve.create,Ft=qe.create,Lt=Je.create,Ut=Be.create,Dt=Be.strictCreate,zt=We.create,Vt=Ge.create,qt=Qe.create,Jt=Xe.create,Kt=et.create,Bt=tt.create,Wt=st.create,Yt=at.create,Gt=nt.create,Ht=it.create,Qt=ot.create,Xt=dt.create,es=ct.create,ts=ut.create,ss=lt.create,as=pt.create,ns=ut.createWithPreprocess,is=vt.create,rs=()=>Nt().optional(),os=()=>It().optional(),ds=()=>Mt().optional(),cs={string:e=>Ae.create({...e,coerce:!0}),number:e=>Ee.create({...e,coerce:!0}),boolean:e=>Pe.create({...e,coerce:!0}),bigint:e=>Re.create({...e,coerce:!0}),date:e=>$e.create({...e,coerce:!0})},us=ee,ls={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"},ps={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"},hs=F.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"]),ms=F.enum(["unknown","android","ios","desktop","web"]),fs=F.object({chatId:F.string(),channelId:F.string(),receiverId:F.string(),receiverName:F.string(),roomId:F.string(),roomName:F.string(),senderId:F.string(),senderName:F.string(),senderDevice:ms,chatType:hs,timestamp:F.number(),mentions:F.string().array(),text:F.string().nullable(),links:F.string().array(),isPrefix:F.boolean(),isFromMe:F.boolean(),isTagMe:F.boolean(),isGroup:F.boolean(),isStory:F.boolean(),isViewOnce:F.boolean(),isEdited:F.boolean(),isDeleted:F.boolean(),isPinned:F.boolean(),isUnPinned:F.boolean(),isChannel:F.boolean(),isBroadcast:F.boolean(),isEphemeral:F.boolean(),isForwarded:F.boolean(),citation:F.record(F.string(),F.boolean()).nullable(),media:F.object({buffer:F.function().returns(F.instanceof(Buffer)),stream:F.function().returns(F.instanceof(S))}).passthrough().nullable(),message:F.function().returns(F.record(F.string(),F.any()))});fs.extend({replied:fs.nullable()});var gs=class{constructor(e,t,s){this.socket=e,this.client=t,this.db=s}maxReplies=0;async connection(e){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("connection",!1),console.log(),console.log(await O.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){this.client.failSpinner("connection","Connection closed");const e=s?.error?.output?.statusCode,t=e===d.restartRequired;if(console.log(s?.error?.message),401===e||405===e||500===e)return void console.error("Invalid session, please delete manually");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,i=2==e?.message?.pinInChatMessage?.type;if(a){const t=await this.db.selectFrom("messages").select("value").where("id","=",a).executeTakeFirst(),s=E(t?.value);e=s}const o=!e?.message?.protocolMessage?.editedMessage&&e?.message?.protocolMessage?.key?.id,d=!!o;if(o){const t=await this.db.selectFrom("messages").select("value").where("id","=",o).executeTakeFirst(),s=E(t?.value);e=s}const p={},h=c(e?.message?.protocolMessage?.editedMessage||e?.message);p.chatId=e?.message?.protocolMessage?.key?.id||e?.key?.id,p.channelId="",p.receiverId=r(this.socket.user?.id),p.receiverName=this.socket.user?.name||this.socket.user?.verifiedName,p.roomId=r(e?.key?.remoteJid);const m=await this.db.selectFrom("chats").select("value").where("id","=",p.roomId).executeTakeFirst();p.roomName=E(m?.value)?.name,p.senderId=r(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||E(f?.value)?.name||p.receiverName,p.roomName=p.roomName||p.senderName,p.senderDevice=u(p.chatId),p.chatType=ls[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=d,p.isPinned=n,p.isUnPinned=i,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];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={...$(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=E(t?.value);if(s)p.replied=await this.messages(s,!0);else{const t=e,s=c(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 b=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=P(R(e),"editedMessage"),p.isEphemeral=P(R(b?.contextInfo),"ephemeralSettingTimestamp"),p.isForwarded=P(R(b?.contextInfo),"forwardingScore"),p.isViewOnce=!!b?.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)}},ys=async(e,t)=>{const s="auth";await(async e=>{await e.schema.createTable("auth").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("auth_session_id_unique",["session","id"]).execute(),await e.schema.createTable("chats").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("chats_session_id_unique",["session","id"]).execute(),await e.schema.createTable("contacts").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("contacts_session_id_unique",["session","id"]).execute(),await e.schema.createTable("messages").ifNotExists().addColumn("session","varchar(50)",(e=>e.notNull())).addColumn("id","varchar(80)",(e=>e.notNull())).addColumn("value","text",(e=>e.defaultTo(null))).addUniqueConstraint("messages_session_id_unique",["session","id"]).execute(),await e.schema.createIndex("auth_session_idx").ifNotExists().on("auth").column("session").execute(),await e.schema.createIndex("auth_id_idx").ifNotExists().on("auth").column("id").execute(),await e.schema.createIndex("chats_session_idx").ifNotExists().on("chats").column("session").execute(),await e.schema.createIndex("chats_id_idx").ifNotExists().on("chats").column("id").execute(),await e.schema.createIndex("contacts_session_idx").ifNotExists().on("contacts").column("session").execute(),await e.schema.createIndex("contacts_id_idx").ifNotExists().on("contacts").column("id").execute(),await e.schema.createIndex("messages_session_idx").ifNotExists().on("messages").column("session").execute(),await e.schema.createIndex("messages_id_idx").ifNotExists().on("messages").column("id").execute()})(e);const a=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 n=>{const i=await a((()=>e.selectFrom(s).select(["value"]).where("id","=",n).where("session","=",t).executeTakeFirst()));if(!i?.value)return null;const r="object"==typeof i.value?JSON.stringify(i.value):i.value;return JSON.parse(r,o.reviver)},d=async(n,i)=>{const r=JSON.stringify(i,o.replacer);await a((()=>e.insertInto(s).values({session:t,id:n,value:r}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:r}))).execute()))},c=async n=>{await a((()=>e.deleteFrom(s).where("id","=",n).where("session","=",t).execute()))},u=await r("creds")||n();return{state:{creds:u,keys:{get:async(e,t)=>{const s={};for(const a of t){let t=await r(`${e}-${a}`);"app-state-sync-key"===e&&t&&(t=i.SenderKeyMessage.fromObject(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",u)},clear:async()=>{await(async()=>{await a((()=>e.deleteFrom(s).where("session","=",t).where("id","!=","creds").execute()))})()},removeCreds:async()=>{await(async()=>{await a((()=>e.deleteFrom(s).where("session","=",t).execute()))})()}}},vs=F.object({type:F.enum(["sqlite","postgresql","mysql"]).default("sqlite"),connection:F.object({url:F.string().default("./session/zaileys.db")}).optional().default({})}).optional().default({}),_s=F.record(F.function().returns(F.union([F.number().array(),F.promise(F.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})),bs=F.object({prefix:F.string().optional(),ignoreMe:F.boolean().optional().default(!0),showLogs:F.boolean().optional().default(!0),autoMentions:F.boolean().optional().default(!0),autoOnline:F.boolean().optional().default(!0),autoRead:F.boolean().optional().default(!0),autoPresence:F.boolean().optional().default(!0),autoRejectCall:F.boolean().optional().default(!0),database:vs,citation:_s}),ws=F.object({authType:F.literal("pairing"),phoneNumber:F.number()}).extend(bs.shape),xs=F.object({authType:F.literal("qr"),phoneNumber:F.undefined().optional()}).extend(bs.shape),ks=F.discriminatedUnion("authType",[ws,xs]),Cs=F.union([F.string().url(),F.instanceof(Buffer).or(F.instanceof(S))]),Ts=F.union([F.string(),F.object({image:Cs,text:F.string().optional()}),F.object({video:Cs,text:F.string().optional()}),F.object({videoNote:Cs}),F.object({gif:Cs,text:F.string().optional()}),F.object({audio:Cs}),F.object({audioNote:Cs}),F.object({sticker:Cs})]),Ns=F.object({roomId:F.string(),asForwarded:F.boolean().optional(),asViewOnce:F.boolean().optional(),verifiedReply:F.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).optional(),quoted:F.function().returns(F.record(F.string(),F.any())).optional()}),Is=Ns,Os=F.object({latitude:F.number(),longitude:F.number(),title:F.string().optional(),footer:F.string().optional()}),Ss=Ns,Ms=F.object({fullname:F.string(),nickname:F.string().optional(),organization:F.string().optional(),role:F.string().optional(),email:F.string().email().optional(),whatsAppNumber:F.number(),callNumber:F.number().optional(),voiceNumber:F.number().optional(),website:F.string().url().optional(),homeAddress:F.string().optional(),workAddress:F.string().optional(),avatar:F.string().url().optional()}),Zs=F.object({message:F.function().returns(F.record(F.string(),F.any()))}),As=F.string(),js=F.object({message:F.function().returns(F.record(F.string(),F.any()))}),Es=F.object({action:F.enum(["pin","unpin"]),expired:F.enum(["24h","7d","30d"])}),Rs=Ns.pick({roomId:!0}),Ps=F.object({name:F.string(),answers:F.string().array(),multipleAnswers:F.boolean().optional()}),$s=F.object({message:F.function().returns(F.record(F.string(),F.any()))}),Fs=F.string(),Ls=F.object({message:F.function().returns(F.record(F.string(),F.any()))}),Us=F.object({callId:F.string(),callerId:F.string()}),Ds=Ns.pick({roomId:!0}),zs=F.object({expired:F.enum(["remove","8h","7d"])}),Vs=F.string();F.object({type:F.enum(["group","user"]),id:F.string(),name:F.string(),bio:F.string(),avatar:F.string().url(),ephemeralDuration:F.number().optional(),isRestrict:F.boolean().optional(),isAnnounce:F.boolean().optional(),isCommunity:F.boolean().optional(),isCommunityAnnounce:F.boolean().optional(),isJoinApprovalMode:F.boolean().optional(),isMemberAddMode:F.boolean().optional(),owner:F.object({type:F.literal("user"),id:F.string()}).nullable(),roomCreatedAt:F.number().optional(),nameUpdatedAt:F.number().optional(),bioUpdatedAt:F.number().optional(),membersLength:F.number().optional(),members:F.object({type:F.enum(["user","admin","superadmin"]),id:F.string()}).array().optional()});var qs=Ns.pick({roomId:!0}),Js=F.enum(["typing","recording","online","offline","paused"]),Ks=class{constructor(e){this.wa=e,this.parser=new gs(this.wa.socket,this.wa.client,this.wa.db)}parser;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=ps[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=Ts.parse(e),t=Ns.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=Os.parse(e),t=Is.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=Ms.parse(e),t=Ss.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=As.parse(e),t=Zs.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{react:{text:e,key:t.message()?.key},...t})}async pin(e,t){e=Es.parse(e),t=js.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=Ps.parse(e),t=Rs.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=Fs.parse(e),t=$s.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{text:e,edit:t.message()?.key,...t})}async delete(e){return e=Ls.parse(e),await this.sendMessage(e.message()?.key?.remoteJid,{delete:e.message()?.key})}async rejectCall(e){return e=Us.parse(e),await(this.wa.socket?.rejectCall(e.callId,e.callerId))}async mute(e,t){e=zs.parse(e),t=Ds.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=Vs.parse(e)).includes("@g.us"),s={};s.id=e;if(r(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=E(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=Js.parse(e),t=qs.parse(t);return await(this.wa.socket?.sendPresenceUpdate({typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"}[e],t.roomId))}},Bs=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 m({stdTTL:300,useClones:!1});chatId="zaileys-chats";logger=g({level:"silent",enabled:!1});db;socket;events=new p;spinners=new Map;worker;async initialize(){console.clear(),await((e="ZAILEYS")=>new Promise((t=>{h(e,((e,s)=>{if(e)return t("");console.log(s),t(s||"")}))})))(),this.options=await ks.parseAsync(this.props),this.startSpinner("db","Initializing database..."),this.db=await((e,t)=>{if("sqlite"===e){const e=t||"./db/zaileys.db",s=T.resolve(e);return v(T.dirname(s),{recursive:!0}),_(s,"",{flag:"a"}),new b({dialect:new w({database:new y(s)})})}const s=new I(t),a=s.protocol.replace(":","");if("mysql"===e)return new b({dialect:new x({pool:C.createPool({host:s.hostname,user:s.username,password:s.password,database:s.pathname.replace("/",""),port:parseInt(s.port||"3306",10)})})});if("postgresql"===e)return new b({dialect:new k({pool:new N({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: ${a}`)})(this.options.database.type,this.options.database.connection.url),this.stopSpinner("db",!0,"Database initialized"),this.startSpinner("auth","Setting up auth adapter...");const{state:n,saveCreds:i}=await ys(this.db,this.chatId);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 gs(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 m,mediaCache:new m({stdTTL:60}),userDevicesCache:new m,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 E(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 Ks({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=f(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{Bs as Client};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "zaileys",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.22",
|
|
4
4
|
"description": "Zaileys - Simplify Typescript/Javascript WhatsApp NodeJS API",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
"better-sqlite3": "^11.10.0",
|
|
65
65
|
"events": "^3.3.0",
|
|
66
66
|
"figlet": "^1.8.1",
|
|
67
|
-
"jimp": "^
|
|
67
|
+
"jimp": "^0.16.1",
|
|
68
68
|
"kysely": "^0.28.2",
|
|
69
69
|
"mysql2": "^3.14.1",
|
|
70
70
|
"node-cache": "^5.1.2",
|
|
@@ -72,9 +72,5 @@
|
|
|
72
72
|
"pg": "^8.16.0",
|
|
73
73
|
"pino": "^9.6.0",
|
|
74
74
|
"qrcode": "^1.5.4"
|
|
75
|
-
}
|
|
76
|
-
"trustedDependencies": [
|
|
77
|
-
"baileys",
|
|
78
|
-
"protobufjs"
|
|
79
|
-
]
|
|
75
|
+
}
|
|
80
76
|
}
|