zaileys 1.1.33 → 1.1.35
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/CHANGELOG.md +92 -0
- package/README.md +565 -294
- package/dist/index.d.mts +898 -2387
- package/dist/index.d.ts +898 -2387
- package/dist/index.js +1986 -1
- package/dist/index.mjs +1960 -1
- package/package.json +42 -35
package/dist/index.js
CHANGED
|
@@ -1 +1,1986 @@
|
|
|
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"),l=require("path"),u=require("pg"),p=require("url"),h=require("qrcode"),m=require("os"),f=require("stream"),g=require("bottleneck"),y=require("hono"),v=require("@hono/node-server"),_=require("fast-levenshtein");function w(e){return e&&e.__esModule?e:{default:e}}function b(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if("default"!==s){var a=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,a.get?a:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var x,k,C,T=w(s),M=w(a),I=w(n),S=w(i),N=w(r),A=w(c),O=w(l),E=w(h),L=w(m),P=w(g),Z=b(_),j=Object.defineProperty,R=e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";return Array.from({length:e},(()=>t[Math.floor(62*Math.random())])).join("")},F=(e="")=>{try{return JSON.parse(e)}catch{return JSON.parse(JSON.stringify(e))}},q=(e={})=>{try{return JSON.stringify(e)}catch{return JSON.stringify(JSON.parse(JSON.stringify(e)))}},$=(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,D=e=>{const t={...e.fingerprint,deviceIndexes:Array.isArray(e.fingerprint.deviceIndexes)?e.fingerprint.deviceIndexes:[]},s={keyData:Array.isArray(e.keyData)?e.keyData:new Uint8Array,fingerprint:{rawId:t.rawId||0,currentIndex:t.rawId||0,deviceIndexes:t.deviceIndexes},timestamp:(a=e.timestamp,"string"==typeof a?parseInt(a,10):a)};var a;return"string"==typeof e.keyData&&(s.keyData=(e=>{let t=e.length;if(!t)return new Uint8Array(1);let s=0;for(;--t%4>1&&"="===e.charAt(t);)++s;return new Uint8Array(Math.ceil(3*e.length)/4-s).fill(0)})(e.keyData)),s},U={};((e,t)=>{for(var s in t)j(e,s,{get:t[s],enumerable:!0})})(U,{BRAND:()=>bt,DIRTY:()=>re,EMPTY_PATH:()=>ee,INVALID:()=>ie,NEVER:()=>fs,OK:()=>oe,ParseStatus:()=>ne,Schema:()=>ge,ZodAny:()=>Be,ZodArray:()=>Ye,ZodBigInt:()=>$e,ZodBoolean:()=>ze,ZodBranded:()=>xt,ZodCatch:()=>_t,ZodDate:()=>De,ZodDefault:()=>vt,ZodDiscriminatedUnion:()=>tt,ZodEffects:()=>ft,ZodEnum:()=>pt,ZodError:()=>J,ZodFirstPartyTypeKind:()=>It,ZodFunction:()=>dt,ZodIntersection:()=>at,ZodIssueCode:()=>B,ZodLazy:()=>ct,ZodLiteral:()=>lt,ZodMap:()=>rt,ZodNaN:()=>wt,ZodNativeEnum:()=>ht,ZodNever:()=>Je,ZodNull:()=>We,ZodNullable:()=>yt,ZodNumber:()=>qe,ZodObject:()=>Qe,ZodOptional:()=>gt,ZodParsedType:()=>V,ZodPipeline:()=>kt,ZodPromise:()=>mt,ZodReadonly:()=>Ct,ZodRecord:()=>it,ZodSchema:()=>ge,ZodSet:()=>ot,ZodString:()=>Re,ZodSymbol:()=>Ue,ZodTransformer:()=>ft,ZodTuple:()=>nt,ZodType:()=>ge,ZodUndefined:()=>Ve,ZodUnion:()=>Xe,ZodUnknown:()=>Ke,ZodVoid:()=>Ge,addIssueToContext:()=>te,any:()=>$t,array:()=>Vt,bigint:()=>Pt,boolean:()=>Zt,coerce:()=>ms,custom:()=>Mt,date:()=>jt,datetimeRegex:()=>Pe,defaultErrorMap:()=>G,discriminatedUnion:()=>Jt,effect:()=>rs,enum:()=>as,function:()=>es,getErrorMap:()=>Q,getParsedType:()=>W,instanceof:()=>At,intersection:()=>Gt,isAborted:()=>de,isAsync:()=>ue,isDirty:()=>ce,isValid:()=>le,late:()=>Nt,lazy:()=>ts,literal:()=>ss,makeIssue:()=>X,map:()=>Qt,nan:()=>Lt,nativeEnum:()=>ns,never:()=>Dt,null:()=>qt,nullable:()=>ds,number:()=>Et,object:()=>Wt,objectUtil:()=>C,oboolean:()=>hs,onumber:()=>ps,optional:()=>os,ostring:()=>us,pipeline:()=>ls,preprocess:()=>cs,promise:()=>is,quotelessJson:()=>K,record:()=>Ht,set:()=>Xt,setErrorMap:()=>H,strictObject:()=>Bt,string:()=>Ot,symbol:()=>Rt,transformer:()=>rs,tuple:()=>Yt,undefined:()=>Ft,union:()=>Kt,unknown:()=>zt,util:()=>x,void:()=>Ut}),(k=x||(x={})).assertEqual=e=>{},k.assertIs=function(e){},k.assertNever=function(e){throw new Error},k.arrayToEnum=e=>{const t={};for(const s of e)t[s]=s;return t},k.getValidEnumValues=e=>{const t=k.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),s={};for(const a of t)s[a]=e[a];return k.objectValues(s)},k.objectValues=e=>k.objectKeys(e).map((function(t){return e[t]})),k.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},k.find=(e,t)=>{for(const s of e)if(t(s))return s},k.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,k.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},k.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(C||(C={})).mergeShapes=(e,t)=>({...e,...t});var V=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),W=e=>{switch(typeof e){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(e)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(e)?V.array:null===e?V.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?V.promise:"undefined"!=typeof Map&&e instanceof Map?V.map:"undefined"!=typeof Set&&e instanceof Set?V.set:"undefined"!=typeof Date&&e instanceof Date?V.date:V.object;default:return V.unknown}},B=x.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"]),K=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),J=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},s={_errors:[]},a=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(a);else if("invalid_return_type"===n.code)a(n.returnTypeError);else if("invalid_arguments"===n.code)a(n.argumentsError);else if(0===n.path.length)s._errors.push(t(n));else{let e=s,a=0;for(;a<n.path.length;){const s=n.path[a];a===n.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(n))):e[s]=e[s]||{_errors:[]},e=e[s],a++}}};return a(this),s}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},s=[];for(const a of this.issues)a.path.length>0?(t[a.path[0]]=t[a.path[0]]||[],t[a.path[0]].push(e(a))):s.push(e(a));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}};J.create=e=>new J(e);var G=(e,t)=>{let s;switch(e.code){case B.invalid_type:s=e.received===V.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case B.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(e.expected,x.jsonStringifyReplacer)}`;break;case B.unrecognized_keys:s=`Unrecognized key(s) in object: ${x.joinValues(e.keys,", ")}`;break;case B.invalid_union:s="Invalid input";break;case B.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${x.joinValues(e.options)}`;break;case B.invalid_enum_value:s=`Invalid enum value. Expected ${x.joinValues(e.options)}, received '${e.received}'`;break;case B.invalid_arguments:s="Invalid function arguments";break;case B.invalid_return_type:s="Invalid function return type";break;case B.invalid_date:s="Invalid date";break;case B.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}"`:x.assertNever(e.validation):s="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case B.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 B.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 B.custom:s="Invalid input";break;case B.invalid_intersection_types:s="Intersection results could not be merged";break;case B.not_multiple_of:s=`Number must be a multiple of ${e.multipleOf}`;break;case B.not_finite:s="Number must be finite";break;default:s=t.defaultError,x.assertNever(e)}return{message:s}},Y=G;function H(e){Y=e}function Q(){return Y}var X=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}},ee=[];function te(e,t){const s=Q(),a=X({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===G?void 0:G].filter((e=>!!e))});e.common.issues.push(a)}var se,ae,ne=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 ie;"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 ie;if("aborted"===n.status)return ie;"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}}},ie=Object.freeze({status:"aborted"}),re=e=>({status:"dirty",value:e}),oe=e=>({status:"valid",value:e}),de=e=>"aborted"===e.status,ce=e=>"dirty"===e.status,le=e=>"valid"===e.status,ue=e=>"undefined"!=typeof Promise&&e instanceof Promise;(ae=se||(se={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},ae.toString=e=>"string"==typeof e?e:e?.message;var pe=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}},he=(e,t)=>{if(le(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new J(e.common.issues);return this._error=t,this._error}}};function me(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 fe,ge=class{get description(){return this._def.description}_getType(e){return W(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:W(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ne,ctx:{common:e.parent.common,data:e.data,parsedType:W(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ue(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:W(e)},a=this._parseSync({data:e,path:s.path,parent:s});return he(s,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:W(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return le(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=>le(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:W(e)},a=this._parse({data:e,path:s.path,parent:s}),n=await(ue(a)?a:Promise.resolve(a));return he(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:B.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 ft({schema:this,typeName:It.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return gt.create(this,this._def)}nullable(){return yt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ye.create(this)}promise(){return mt.create(this,this._def)}or(e){return Xe.create([this,e],this._def)}and(e){return at.create(this,e,this._def)}transform(e){return new ft({...me(this._def),schema:this,typeName:It.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new vt({...me(this._def),innerType:this,defaultValue:t,typeName:It.ZodDefault})}brand(){return new xt({typeName:It.ZodBranded,type:this,...me(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new _t({...me(this._def),innerType:this,catchValue:t,typeName:It.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return kt.create(this,e)}readonly(){return Ct.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ye=/^c[^\s-]{8,}$/i,ve=/^[0-9a-z]+$/,_e=/^[0-9A-HJKMNP-TV-Z]{26}$/i,we=/^[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,be=/^[a-z0-9_-]{21}$/i,xe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ke=/^[-+]?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)?)??$/,Ce=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Te=/^(?:(?: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])$/,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])\/(3[0-2]|[12]?[0-9])$/,Ie=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Se=/^(([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])$/,Ne=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ae=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Oe="((\\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])))",Ee=new RegExp(`^${Oe}$`);function Le(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 Pe(e){let t=`${Oe}T${Le(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 Ze(e,t){if(!xe.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 je(e,t){return!("v4"!==t&&t||!Me.test(e))||!("v6"!==t&&t||!Se.test(e))}var Re=class e extends ge{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==V.string){const t=this._getOrReturnCtx(e);return te(t,{code:B.invalid_type,expected:V.string,received:t.parsedType}),ie}const t=new ne;let s;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),te(s,{code:B.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),te(s,{code:B.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?te(s,{code:B.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):n&&te(s,{code:B.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)Ce.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"email",code:B.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)fe||(fe=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),fe.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"emoji",code:B.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)we.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"uuid",code:B.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)be.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"nanoid",code:B.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)ye.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"cuid",code:B.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)ve.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"cuid2",code:B.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)_e.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"ulid",code:B.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),te(s,{validation:"url",code:B.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),te(s,{validation:"regex",code:B.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),te(s,{code:B.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),te(s,{code:B.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),te(s,{code:B.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){Pe(i).test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{code:B.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){Ee.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{code:B.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${Le(i)}$`).test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{code:B.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?ke.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"duration",code:B.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(a=e.data,("v4"!==(n=i.version)&&n||!Te.test(a))&&("v6"!==n&&n||!Ie.test(a))&&(s=this._getOrReturnCtx(e,s),te(s,{validation:"ip",code:B.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?Ze(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"jwt",code:B.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?je(e.data,i.version)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"cidr",code:B.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?Ne.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"base64",code:B.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?Ae.test(e.data)||(s=this._getOrReturnCtx(e,s),te(s,{validation:"base64url",code:B.invalid_string,message:i.message}),t.dirty()):x.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:B.invalid_string,...se.errToObj(s)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:"email",...se.errToObj(e)})}url(e){return this._addCheck({kind:"url",...se.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...se.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...se.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...se.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...se.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...se.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...se.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...se.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...se.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...se.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...se.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...se.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,...se.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,...se.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...se.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...se.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...se.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...se.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...se.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...se.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...se.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...se.errToObj(t)})}nonempty(e){return this.min(1,se.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 Fe(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}Re.create=e=>new Re({checks:[],typeName:It.ZodString,coerce:e?.coerce??!1,...me(e)});var qe=class e extends ge{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)!==V.number){const t=this._getOrReturnCtx(e);return te(t,{code:B.invalid_type,expected:V.number,received:t.parsedType}),ie}let t;const s=new ne;for(const a of this._def.checks)if("int"===a.kind)x.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),te(t,{code:B.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),te(t,{code:B.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),te(t,{code:B.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty())}else"multipleOf"===a.kind?0!==Fe(e.data,a.value)&&(t=this._getOrReturnCtx(e,t),te(t,{code:B.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),te(t,{code:B.not_finite,message:a.message}),s.dirty()):x.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,se.toString(t))}gt(e,t){return this.setLimit("min",e,!1,se.toString(t))}lte(e,t){return this.setLimit("max",e,!0,se.toString(t))}lt(e,t){return this.setLimit("max",e,!1,se.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:se.toString(n)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:"int",message:se.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:se.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:se.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:se.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:se.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:se.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&&x.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)}};qe.create=e=>new qe({checks:[],typeName:It.ZodNumber,coerce:e?.coerce||!1,...me(e)});var $e=class e extends ge{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)!==V.bigint)return this._getInvalidInput(e);let t;const s=new ne;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),te(t,{code:B.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),te(t,{code:B.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),te(t,{code:B.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):x.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return te(t,{code:B.invalid_type,expected:V.bigint,received:t.parsedType}),ie}gte(e,t){return this.setLimit("min",e,!0,se.toString(t))}gt(e,t){return this.setLimit("min",e,!1,se.toString(t))}lte(e,t){return this.setLimit("max",e,!0,se.toString(t))}lt(e,t){return this.setLimit("max",e,!1,se.toString(t))}setLimit(t,s,a,n){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:s,inclusive:a,message:se.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:se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:se.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:se.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}};$e.create=e=>new $e({checks:[],typeName:It.ZodBigInt,coerce:e?.coerce??!1,...me(e)});var ze=class extends ge{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==V.boolean){const t=this._getOrReturnCtx(e);return te(t,{code:B.invalid_type,expected:V.boolean,received:t.parsedType}),ie}return oe(e.data)}};ze.create=e=>new ze({typeName:It.ZodBoolean,coerce:e?.coerce||!1,...me(e)});var De=class e extends ge{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==V.date){const t=this._getOrReturnCtx(e);return te(t,{code:B.invalid_type,expected:V.date,received:t.parsedType}),ie}if(Number.isNaN(e.data.getTime())){return te(this._getOrReturnCtx(e),{code:B.invalid_date}),ie}const t=new ne;let s;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),te(s,{code:B.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),te(s,{code:B.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):x.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:se.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:se.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}};De.create=e=>new De({checks:[],coerce:e?.coerce||!1,typeName:It.ZodDate,...me(e)});var Ue=class extends ge{_parse(e){if(this._getType(e)!==V.symbol){const t=this._getOrReturnCtx(e);return te(t,{code:B.invalid_type,expected:V.symbol,received:t.parsedType}),ie}return oe(e.data)}};Ue.create=e=>new Ue({typeName:It.ZodSymbol,...me(e)});var Ve=class extends ge{_parse(e){if(this._getType(e)!==V.undefined){const t=this._getOrReturnCtx(e);return te(t,{code:B.invalid_type,expected:V.undefined,received:t.parsedType}),ie}return oe(e.data)}};Ve.create=e=>new Ve({typeName:It.ZodUndefined,...me(e)});var We=class extends ge{_parse(e){if(this._getType(e)!==V.null){const t=this._getOrReturnCtx(e);return te(t,{code:B.invalid_type,expected:V.null,received:t.parsedType}),ie}return oe(e.data)}};We.create=e=>new We({typeName:It.ZodNull,...me(e)});var Be=class extends ge{constructor(){super(...arguments),this._any=!0}_parse(e){return oe(e.data)}};Be.create=e=>new Be({typeName:It.ZodAny,...me(e)});var Ke=class extends ge{constructor(){super(...arguments),this._unknown=!0}_parse(e){return oe(e.data)}};Ke.create=e=>new Ke({typeName:It.ZodUnknown,...me(e)});var Je=class extends ge{_parse(e){const t=this._getOrReturnCtx(e);return te(t,{code:B.invalid_type,expected:V.never,received:t.parsedType}),ie}};Je.create=e=>new Je({typeName:It.ZodNever,...me(e)});var Ge=class extends ge{_parse(e){if(this._getType(e)!==V.undefined){const t=this._getOrReturnCtx(e);return te(t,{code:B.invalid_type,expected:V.void,received:t.parsedType}),ie}return oe(e.data)}};Ge.create=e=>new Ge({typeName:It.ZodVoid,...me(e)});var Ye=class e extends ge{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==V.array)return te(t,{code:B.invalid_type,expected:V.array,received:t.parsedType}),ie;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,n=t.data.length<a.exactLength.value;(e||n)&&(te(t,{code:e?B.too_big:B.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&&(te(t,{code:B.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&&(te(t,{code:B.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 pe(t,e,t.path,s))))).then((e=>ne.mergeArray(s,e)));const n=[...t.data].map(((e,s)=>a.type._parseSync(new pe(t,e,t.path,s))));return ne.mergeArray(s,n)}get element(){return this._def.type}min(t,s){return new e({...this._def,minLength:{value:t,message:se.toString(s)}})}max(t,s){return new e({...this._def,maxLength:{value:t,message:se.toString(s)}})}length(t,s){return new e({...this._def,exactLength:{value:t,message:se.toString(s)}})}nonempty(e){return this.min(1,e)}};function He(e){if(e instanceof Qe){const t={};for(const s in e.shape){const a=e.shape[s];t[s]=gt.create(He(a))}return new Qe({...e._def,shape:()=>t})}return e instanceof Ye?new Ye({...e._def,type:He(e.element)}):e instanceof gt?gt.create(He(e.unwrap())):e instanceof yt?yt.create(He(e.unwrap())):e instanceof nt?nt.create(e.items.map((e=>He(e)))):e}Ye.create=(e,t)=>new Ye({type:e,minLength:null,maxLength:null,exactLength:null,typeName:It.ZodArray,...me(t)});var Qe=class e extends ge{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=x.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==V.object){const t=this._getOrReturnCtx(e);return te(t,{code:B.invalid_type,expected:V.object,received:t.parsedType}),ie}const{status:t,ctx:s}=this._processInputParams(e),{shape:a,keys:n}=this._getCached(),i=[];if(!(this._def.catchall instanceof Je&&"strip"===this._def.unknownKeys))for(const e in s.data)n.includes(e)||i.push(e);const r=[];for(const e of n){const t=a[e],n=s.data[e];r.push({key:{status:"valid",value:e},value:t._parse(new pe(s,n,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof Je){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)r.push({key:{status:"valid",value:e},value:{status:"valid",value:s.data[e]}});else if("strict"===e)i.length>0&&(te(s,{code:B.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 pe(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=>ne.mergeObjectSync(t,e))):ne.mergeObjectSync(t,r)}get shape(){return this._def.shape()}strict(t){return se.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:se.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:It.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 x.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 x.objectKeys(this.shape))t[e]||(s[e]=this.shape[e]);return new e({...this._def,shape:()=>s})}deepPartial(){return He(this)}partial(t){const s={};for(const e of x.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 x.objectKeys(this.shape))if(t&&!t[e])s[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof gt;)t=t._def.innerType;s[e]=t}return new e({...this._def,shape:()=>s})}keyof(){return ut(x.objectKeys(this.shape))}};Qe.create=(e,t)=>new Qe({shape:()=>e,unknownKeys:"strip",catchall:Je.create(),typeName:It.ZodObject,...me(t)}),Qe.strictCreate=(e,t)=>new Qe({shape:()=>e,unknownKeys:"strict",catchall:Je.create(),typeName:It.ZodObject,...me(t)}),Qe.lazycreate=(e,t)=>new Qe({shape:e,unknownKeys:"strip",catchall:Je.create(),typeName:It.ZodObject,...me(t)});var Xe=class extends ge{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;if(t.common.async)return Promise.all(s.map((async e=>{const s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const s of e)if("dirty"===s.result.status)return t.common.issues.push(...s.ctx.common.issues),s.result;const s=e.map((e=>new J(e.ctx.common.issues)));return te(t,{code:B.invalid_union,unionErrors:s}),ie}));{let e;const a=[];for(const n of s){const s={...t,common:{...t.common,issues:[]},parent:null},i=n._parseSync({data:t.data,path:t.path,parent:s});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:s}),s.common.issues.length&&a.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=a.map((e=>new J(e)));return te(t,{code:B.invalid_union,unionErrors:n}),ie}}get options(){return this._def.options}};Xe.create=(e,t)=>new Xe({options:e,typeName:It.ZodUnion,...me(t)});var et=e=>e instanceof ct?et(e.schema):e instanceof ft?et(e.innerType()):e instanceof lt?[e.value]:e instanceof pt?e.options:e instanceof ht?x.objectValues(e.enum):e instanceof vt?et(e._def.innerType):e instanceof Ve?[void 0]:e instanceof We?[null]:e instanceof gt?[void 0,...et(e.unwrap())]:e instanceof yt?[null,...et(e.unwrap())]:e instanceof xt||e instanceof Ct?et(e.unwrap()):e instanceof _t?et(e._def.innerType):[],tt=class e extends ge{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==V.object)return te(t,{code:B.invalid_type,expected:V.object,received:t.parsedType}),ie;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}):(te(t,{code:B.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),ie)}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=et(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:It.ZodDiscriminatedUnion,discriminator:t,options:s,optionsMap:n,...me(a)})}};function st(e,t){const s=W(e),a=W(t);if(e===t)return{valid:!0,data:e};if(s===V.object&&a===V.object){const s=x.objectKeys(t),a=x.objectKeys(e).filter((e=>-1!==s.indexOf(e))),n={...e,...t};for(const s of a){const a=st(e[s],t[s]);if(!a.valid)return{valid:!1};n[s]=a.data}return{valid:!0,data:n}}if(s===V.array&&a===V.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let a=0;a<e.length;a++){const n=st(e[a],t[a]);if(!n.valid)return{valid:!1};s.push(n.data)}return{valid:!0,data:s}}return s===V.date&&a===V.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}var at=class extends ge{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=(e,a)=>{if(de(e)||de(a))return ie;const n=st(e.value,a.value);return n.valid?((ce(e)||ce(a))&&t.dirty(),{status:t.value,value:n.data}):(te(s,{code:B.invalid_intersection_types}),ie)};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}))}};at.create=(e,t,s)=>new at({left:e,right:t,typeName:It.ZodIntersection,...me(s)});var nt=class e extends ge{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==V.array)return te(s,{code:B.invalid_type,expected:V.array,received:s.parsedType}),ie;if(s.data.length<this._def.items.length)return te(s,{code:B.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ie;!this._def.rest&&s.data.length>this._def.items.length&&(te(s,{code:B.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 pe(s,e,s.path,t)):null})).filter((e=>!!e));return s.common.async?Promise.all(a).then((e=>ne.mergeArray(t,e))):ne.mergeArray(t,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};nt.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new nt({items:e,typeName:It.ZodTuple,rest:null,...me(t)})};var it=class e extends ge{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!==V.object)return te(s,{code:B.invalid_type,expected:V.object,received:s.parsedType}),ie;const a=[],n=this._def.keyType,i=this._def.valueType;for(const e in s.data)a.push({key:n._parse(new pe(s,e,s.path,e)),value:i._parse(new pe(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?ne.mergeObjectAsync(t,a):ne.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(t,s,a){return new e(s instanceof ge?{keyType:t,valueType:s,typeName:It.ZodRecord,...me(a)}:{keyType:Re.create(),valueType:t,typeName:It.ZodRecord,...me(s)})}},rt=class extends ge{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!==V.map)return te(s,{code:B.invalid_type,expected:V.map,received:s.parsedType}),ie;const a=this._def.keyType,n=this._def.valueType,i=[...s.data.entries()].map((([e,t],i)=>({key:a._parse(new pe(s,e,s.path,[i,"key"])),value:n._parse(new pe(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 ie;"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 ie;"dirty"!==a.status&&"dirty"!==n.status||t.dirty(),e.set(a.value,n.value)}return{status:t.value,value:e}}}};rt.create=(e,t,s)=>new rt({valueType:t,keyType:e,typeName:It.ZodMap,...me(s)});var ot=class e extends ge{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==V.set)return te(s,{code:B.invalid_type,expected:V.set,received:s.parsedType}),ie;const a=this._def;null!==a.minSize&&s.data.size<a.minSize.value&&(te(s,{code:B.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&&(te(s,{code:B.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 ie;"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 pe(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:se.toString(s)}})}max(t,s){return new e({...this._def,maxSize:{value:t,message:se.toString(s)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ot.create=(e,t)=>new ot({valueType:e,minSize:null,maxSize:null,typeName:It.ZodSet,...me(t)});var dt=class e extends ge{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==V.function)return te(t,{code:B.invalid_type,expected:V.function,received:t.parsedType}),ie;function s(e,s){return X({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Q(),G].filter((e=>!!e)),issueData:{code:B.invalid_arguments,argumentsError:s}})}function a(e,s){return X({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Q(),G].filter((e=>!!e)),issueData:{code:B.invalid_return_type,returnTypeError:s}})}const n={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof mt){const e=this;return oe((async function(...t){const r=new J([]),o=await e._def.args.parseAsync(t,n).catch((e=>{throw r.addIssue(s(t,e)),r})),d=await Reflect.apply(i,this,o);return await e._def.returns._def.type.parseAsync(d,n).catch((e=>{throw r.addIssue(a(d,e)),r}))}))}{const e=this;return oe((function(...t){const r=e._def.args.safeParse(t,n);if(!r.success)throw new J([s(t,r.error)]);const o=Reflect.apply(i,this,r.data),d=e._def.returns.safeParse(o,n);if(!d.success)throw new J([a(o,d.error)]);return d.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:nt.create(t).rest(Ke.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||nt.create([]).rest(Ke.create()),returns:s||Ke.create(),typeName:It.ZodFunction,...me(a)})}},ct=class extends ge{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})}};ct.create=(e,t)=>new ct({getter:e,typeName:It.ZodLazy,...me(t)});var lt=class extends ge{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return te(t,{received:t.data,code:B.invalid_literal,expected:this._def.value}),ie}return{status:"valid",value:e.data}}get value(){return this._def.value}};function ut(e,t){return new pt({values:e,typeName:It.ZodEnum,...me(t)})}lt.create=(e,t)=>new lt({value:e,typeName:It.ZodLiteral,...me(t)});var pt=class e extends ge{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),s=this._def.values;return te(t,{expected:x.joinValues(s),received:t.parsedType,code:B.invalid_type}),ie}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 te(t,{received:t.data,code:B.invalid_enum_value,options:s}),ie}return oe(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})}};pt.create=ut;var ht=class extends ge{_parse(e){const t=x.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==V.string&&s.parsedType!==V.number){const e=x.objectValues(t);return te(s,{expected:x.joinValues(e),received:s.parsedType,code:B.invalid_type}),ie}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=x.objectValues(t);return te(s,{received:s.data,code:B.invalid_enum_value,options:e}),ie}return oe(e.data)}get enum(){return this._def.values}};ht.create=(e,t)=>new ht({values:e,typeName:It.ZodNativeEnum,...me(t)});var mt=class extends ge{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==V.promise&&!1===t.common.async)return te(t,{code:B.invalid_type,expected:V.promise,received:t.parsedType}),ie;const s=t.parsedType===V.promise?t.data:Promise.resolve(t.data);return oe(s.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}};mt.create=(e,t)=>new mt({type:e,typeName:It.ZodPromise,...me(t)});var ft=class extends ge{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===It.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=>{te(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 ie;const a=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===a.status?ie:"dirty"===a.status||"dirty"===t.value?re(a.value):a}));{if("aborted"===t.value)return ie;const a=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===a.status?ie:"dirty"===a.status||"dirty"===t.value?re(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?ie:("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?ie:("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(!le(e))return ie;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=>le(e)?Promise.resolve(a.transform(e.value,n)).then((e=>({status:t.value,value:e}))):ie))}x.assertNever(a)}};ft.create=(e,t,s)=>new ft({schema:e,typeName:It.ZodEffects,effect:t,...me(s)}),ft.createWithPreprocess=(e,t,s)=>new ft({schema:t,effect:{type:"preprocess",transform:e},typeName:It.ZodEffects,...me(s)});var gt=class extends ge{_parse(e){return this._getType(e)===V.undefined?oe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gt.create=(e,t)=>new gt({innerType:e,typeName:It.ZodOptional,...me(t)});var yt=class extends ge{_parse(e){return this._getType(e)===V.null?oe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};yt.create=(e,t)=>new yt({innerType:e,typeName:It.ZodNullable,...me(t)});var vt=class extends ge{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===V.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};vt.create=(e,t)=>new vt({innerType:e,typeName:It.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...me(t)});var _t=class extends ge{_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 ue(a)?a.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new J(s.common.issues)},input:s.data})}))):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new J(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}};_t.create=(e,t)=>new _t({innerType:e,typeName:It.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...me(t)});var wt=class extends ge{_parse(e){if(this._getType(e)!==V.nan){const t=this._getOrReturnCtx(e);return te(t,{code:B.invalid_type,expected:V.nan,received:t.parsedType}),ie}return{status:"valid",value:e.data}}};wt.create=e=>new wt({typeName:It.ZodNaN,...me(e)});var bt=Symbol("zod_brand"),xt=class extends ge{_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}},kt=class e extends ge{_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?ie:"dirty"===e.status?(t.dirty(),re(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?ie:"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:It.ZodPipeline})}},Ct=class extends ge{_parse(e){const t=this._def.innerType._parse(e),s=e=>(le(e)&&(e.value=Object.freeze(e.value)),e);return ue(t)?t.then((e=>s(e))):s(t)}unwrap(){return this._def.innerType}};function Tt(e,t){const s="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof s?{message:s}:s}function Mt(e,t={},s){return e?Be.create().superRefine(((a,n)=>{const i=e(a);if(i instanceof Promise)return i.then((e=>{if(!e){const e=Tt(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}}));if(!i){const e=Tt(t,a),i=e.fatal??s??!0;n.addIssue({code:"custom",...e,fatal:i})}})):Be.create()}Ct.create=(e,t)=>new Ct({innerType:e,typeName:It.ZodReadonly,...me(t)});var It,St,Nt={object:Qe.lazycreate};(St=It||(It={})).ZodString="ZodString",St.ZodNumber="ZodNumber",St.ZodNaN="ZodNaN",St.ZodBigInt="ZodBigInt",St.ZodBoolean="ZodBoolean",St.ZodDate="ZodDate",St.ZodSymbol="ZodSymbol",St.ZodUndefined="ZodUndefined",St.ZodNull="ZodNull",St.ZodAny="ZodAny",St.ZodUnknown="ZodUnknown",St.ZodNever="ZodNever",St.ZodVoid="ZodVoid",St.ZodArray="ZodArray",St.ZodObject="ZodObject",St.ZodUnion="ZodUnion",St.ZodDiscriminatedUnion="ZodDiscriminatedUnion",St.ZodIntersection="ZodIntersection",St.ZodTuple="ZodTuple",St.ZodRecord="ZodRecord",St.ZodMap="ZodMap",St.ZodSet="ZodSet",St.ZodFunction="ZodFunction",St.ZodLazy="ZodLazy",St.ZodLiteral="ZodLiteral",St.ZodEnum="ZodEnum",St.ZodEffects="ZodEffects",St.ZodNativeEnum="ZodNativeEnum",St.ZodOptional="ZodOptional",St.ZodNullable="ZodNullable",St.ZodDefault="ZodDefault",St.ZodCatch="ZodCatch",St.ZodPromise="ZodPromise",St.ZodBranded="ZodBranded",St.ZodPipeline="ZodPipeline",St.ZodReadonly="ZodReadonly";var At=(e,t={message:`Input not instance of ${e.name}`})=>Mt((t=>t instanceof e),t),Ot=Re.create,Et=qe.create,Lt=wt.create,Pt=$e.create,Zt=ze.create,jt=De.create,Rt=Ue.create,Ft=Ve.create,qt=We.create,$t=Be.create,zt=Ke.create,Dt=Je.create,Ut=Ge.create,Vt=Ye.create,Wt=Qe.create,Bt=Qe.strictCreate,Kt=Xe.create,Jt=tt.create,Gt=at.create,Yt=nt.create,Ht=it.create,Qt=rt.create,Xt=ot.create,es=dt.create,ts=ct.create,ss=lt.create,as=pt.create,ns=ht.create,is=mt.create,rs=ft.create,os=gt.create,ds=yt.create,cs=ft.createWithPreprocess,ls=kt.create,us=()=>Ot().optional(),ps=()=>Et().optional(),hs=()=>Zt().optional(),ms={string:e=>Re.create({...e,coerce:!0}),number:e=>qe.create({...e,coerce:!0}),boolean:e=>ze.create({...e,coerce:!0}),bigint:e=>$e.create({...e,coerce:!0}),date:e=>De.create({...e,coerce:!0})},fs=ie,gs={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"},ys={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"},vs=U.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"]),_s=U.enum(["unknown","android","ios","desktop","web"]),ws=U.object({chatId:U.string(),channelId:U.string(),uniqueId:U.string(),receiverId:U.string(),receiverName:U.string(),roomId:U.string(),roomName:U.string(),senderId:U.string(),senderName:U.string(),senderDevice:_s,chatType:vs,timestamp:U.number(),mentions:U.string().array(),text:U.string().nullable(),links:U.string().array(),isPrefix:U.boolean(),isSpam:U.boolean(),isFromMe:U.boolean(),isTagMe:U.boolean(),isGroup:U.boolean(),isStory:U.boolean(),isViewOnce:U.boolean(),isEdited:U.boolean(),isDeleted:U.boolean(),isPinned:U.boolean(),isUnPinned:U.boolean(),isChannel:U.boolean(),isBroadcast:U.boolean(),isEphemeral:U.boolean(),isForwarded:U.boolean(),citation:U.record(U.string(),U.boolean()).nullable(),media:U.object({buffer:U.function().returns(U.instanceof(Buffer)),stream:U.function().returns(U.instanceof(f.Readable))}).passthrough().nullable(),message:U.function().returns(U.record(U.string(),U.any()))}),bs=ws.extend({replied:ws.nullable()}),xs=new M.default({stdTTL:3600,checkperiod:600}),ks=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 console.log(),console.log(await E.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){const t=a?.error?.output?.statusCode,n=t===e.DisconnectReason.restartRequired||t===e.DisconnectReason.connectionLost;if(this.client.failSpinner("connection",`[Connection Closed] [${t}]\n${a?.error?.message}\n`),401===t||405===t||500===t)return void console.error("Invalid session, please delete manually");n&&"close"==s&&await this.client.initialize()}else"open"===s&&(this.client.stopSpinner("connection",!0,"Connected to WhatsApp\n"),this.client.emit("connection",{status:"open"}));this.client.stopSpinner("connection",!1)}async messages(t,s,a){if(t?.messageStubType||t?.messageStubParameters?.length||t?.message?.protocolMessage?.peerDataOperationRequestResponseMessage||t?.message?.botInvokeMessage||!t?.key?.id||!t?.message)return null;if(this.client.options?.ignoreMe&&t?.key?.fromMe&&!this.maxReplies&&!a&&"status@broadcast"!=t?.key?.remoteJid&&!t?.participant)return null;this.client.options?.autoRead&&await this.socket.readMessages([t?.key]);const n=t,i=t?.message?.pinInChatMessage?.key?.id,r=1==t?.message?.pinInChatMessage?.type,o=2==t?.message?.pinInChatMessage?.type;if(i){const e=await this.db.selectFrom("messages").select("value").where("id","=",i).executeTakeFirst(),s=F(e?.value);t=s}const d=!t?.message?.protocolMessage?.editedMessage&&t?.message?.protocolMessage?.key?.id,c=!!d;if(d){const e=await this.db.selectFrom("messages").select("value").where("id","=",d).executeTakeFirst(),s=F(e?.value);t=s}const l={},u=e.getContentType(t?.message?.protocolMessage?.editedMessage||t?.message);l.chatId=t?.message?.protocolMessage?.key?.id||t?.key?.id,l.channelId="",l.uniqueId="",l.receiverId=e.jidNormalizedUser(this.socket.user?.id),l.receiverName=this.socket.user?.name||this.socket.user?.verifiedName,l.roomId=e.jidNormalizedUser(t?.key?.remoteJid);const p=await this.db.selectFrom("chats").select("value").where("id","=",l.roomId).executeTakeFirst();l.roomName=F(p?.value)?.name,l.senderId=e.jidNormalizedUser(t?.participant||t?.key?.participant||t?.key?.remoteJid);const h=await this.db.selectFrom("chats").select("value").where("id","=",l.senderId).executeTakeFirst();if(l.senderName=t?.pushName||t?.verifiedBizName||F(h?.value)?.name||l.receiverName,l.roomName=l.roomName||l.senderName,l.senderDevice=e.getDevice(l.chatId),l.chatType=gs[u],l.timestamp=t?.messageTimestamp?.low||t?.messageTimestamp||0,l.mentions=[],l.text=null,l.links=[],l.isPrefix=!1,l.isSpam=!1,l.isFromMe=t?.key?.fromMe,l.isTagMe=!1,l.isGroup=l.roomId.includes("@g.us"),l.isStory=l.roomId.includes("@broadcast"),l.isViewOnce=!1,l.isEdited=!1,l.isDeleted=c,l.isPinned=r,l.isUnPinned=o,l.isChannel=l.roomId.includes("@newsletter"),l.isBroadcast=!!t?.broadcast,l.isEphemeral=!1,l.isForwarded=!1,!s&&!a){const e=await(async(e,t,s)=>{const a=new P.default({maxConcurrent:1,minTime:0,reservoir:t,reservoirRefreshAmount:t,reservoirRefreshInterval:s}),n=Date.now(),i=xs.get(e)||{count:0,last:0};n-i.last>s&&(i.count=0),i.count+=1,i.last=n,xs.set(e,i);try{return await a.schedule((async()=>i.count>t?(xs.set(e,{...i,blacklisted:n+s}),!0):await!1))}catch(e){return console.error("Error detecting spam:",e),!1}})(l.roomId,this.client.options.limiter?.maxMessages,this.client.options.limiter?.durationMs);l.isSpam=e}l.isFromMe&&(l.senderId=l.receiverId,l.senderName=l.receiverName),l.citation=null,l.media=null,l.replied=null,l.channelId=l.roomId.split("@")[0]+"-"+l.senderId.split("@")[0],l.uniqueId=l.channelId+"-"+l.chatId;const m=this.client.options?.citation;if(Object.keys(m).length){l.citation={};for(const e of Object.keys(m))l.citation[e]=m[e].includes(Number(l.senderId.split("@")[0]))||m[e].includes(Number(l.roomId.split("@")[0]))}const f=(t?.message?.protocolMessage?.editedMessage?.[u]||t?.message?.[u])?.message?.documentMessage||t?.message?.[u];"text"!=l.chatType&&(l.media={...z(f,["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 g=t?.message?.[u]?.contextInfo?.stanzaId;if(g&&this.maxReplies<1){this.maxReplies++;const s=await this.db.selectFrom("messages").select("value").where("id","=",g).executeTakeFirst(),a=F(s?.value);if(a)l.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,l.replied=await this.messages(s,!0)}this.maxReplies=0}const y="string"==typeof f?f:f?.text||f?.caption||f?.name||f?.displayName||"";l.text=((e="")=>e?e.replace(/\u202E([\s\S]*?)\u202C/g,((e,t)=>Array.from(t).reverse().join(""))).replace(/[\u202A-\u202E\u202C]/g,""):null)(y)||null,l.mentions=((e="")=>{if(!e)return[];const t=new Set;for(const s of e.matchAll(/@(\d+)/g))t.add(s[1]);return[...t]})(l.text),l.links=((e="")=>e&&e.match(/(?:https?:\/\/)?[^\s<>"']+\.[^\s<>"']+/g)||[])(l.text);const v=t?.message?.[u];return l.isPrefix=!!this.client.options?.prefix&&!!l.text?.startsWith(this.client.options?.prefix),l.isTagMe=l.mentions.includes(l.receiverId.split("@")[0]),l.isEdited=$(q(t),"editedMessage"),l.isEphemeral=$(q(v?.contextInfo),"ephemeralSettingTimestamp"),l.isForwarded=$(q(v?.contextInfo),"forwardingScore"),l.isViewOnce=!!v?.viewOnce,l.isPrefix&&(l.text=l.text.replace(new RegExp(`^${this.client.options?.prefix}`),"")),l.message=()=>n,s||this.client.emit("messages",l),l}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)}async webhooks(e){let t;const s=e.req.method,a=e.req.query(),n=e.req.header("content-type")||"",i={query:a,json:null,form:null,raw:null};"GET"!=s&&(n.includes("application/json")?(i.json=await e.req.json().catch((()=>null)),t=await e.req.text()):n.includes("application/x-www-form-urlencoded")||n.includes("multipart/form-data")?(i.form=await e.req.parseBody().catch((()=>null)),t=await e.req.text()):(t=await e.req.text().catch((()=>null)),i.raw=t));const r={};r.id=R(20),r.method=s,r.host=e.req.header("host"),r.referer=e.req.header("referer"),r.date=e.req.header("date")||(new Date).toISOString(),r.size=Number(e.req.header("content-length")||Buffer.byteLength(t||"","utf8")),r.data=i,this.client.emit("webhooks",r)}},Cs=!1,Ts=async(e,t)=>{const s=new y.Hono,a=(()=>{const e=L.default.networkInterfaces();for(const t of Object.values(e))for(const e of t)if("IPv4"===e.family&&!e.internal)return e.address;return"localhost"})();s.get("/webhooks",(async e=>(t?.ev.emit("idle-webhooks",e),e.text("OK")))),s.post("/webhooks",(async e=>(t?.ev.emit("idle-webhooks",e),e.text("OK")))),Cs||v.serve({fetch:s.fetch,port:4135},(()=>{e.stopSpinner("webhooks",!0,`Webhooks Access\n - URL : http://${a}:4135/webhooks\n - PORT : 4135\n - METHOD: GET, POST`),Cs=!0})),e.stopSpinner("webhooks",!0,`Webhooks Access\n - URL : http://${a}:4135/webhooks\n - PORT : 4135\n - METHOD: GET, POST`)},Ms=async(e,t)=>{(e||t)&&await fetch(e,{method:"POST",body:JSON.stringify(t)}).catch((()=>null))},Is=async(t,s,a)=>{const n="auth";await(async(e,t)=>{await e.transaction().execute((async e=>{await e.schema.createTable("auth").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("auth_session_id_unique",["session","id"]).execute(),await e.schema.createTable("chats").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("chats_session_id_unique",["session","id"]).execute(),await e.schema.createTable("contacts").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("contacts_session_id_unique",["session","id"]).execute(),await e.schema.createTable("messages").ifNotExists().addColumn("session","char(36)",(e=>e.notNull())).addColumn("id","char(36)",(e=>e.notNull().primaryKey())).addColumn("value","text").addUniqueConstraint("messages_session_id_unique",["session","id"]).execute(),t.loadLLMSchemas&&(await e.schema.createTable("llm_messages").ifNotExists().addColumn("uniqueId","char(36)",(e=>e.notNull().primaryKey())).addColumn("channelId","char(36)").addColumn("model","char(36)").addColumn("role","varchar(20)",(e=>e.notNull())).addColumn("content","text",(e=>e.notNull())).addColumn("additional","text").addUniqueConstraint("llm_messages_id_unique",["uniqueId"]).execute(),await e.schema.createTable("llm_personalization").ifNotExists().addColumn("uniqueId","char(36)",(e=>e.notNull().primaryKey())).addColumn("senderId","char(36)").addColumn("content","text",(e=>e.notNull())).addUniqueConstraint("llm_personalization_id_unique",["uniqueId"]).execute(),await e.schema.createTable("llm_rag").ifNotExists().addColumn("metadata.id","char(36)",(e=>e.notNull().primaryKey())).addColumn("pageContent","text",(e=>e.notNull())).addUniqueConstraint("llm_rag_id_unique",["metadata.id"]).execute(),await Promise.all([e.schema.createIndex("llm_messages_uniqueId_idx").ifNotExists().on("llm_messages").column("uniqueId").execute(),e.schema.createIndex("llm_messages_channelId_idx").ifNotExists().on("llm_messages").column("channelId").execute(),e.schema.createIndex("llm_messages_model_idx").ifNotExists().on("llm_messages").column("model").execute(),e.schema.createIndex("llm_messages_role_idx").ifNotExists().on("llm_messages").column("role").execute(),e.schema.createIndex("llm_personalization_uniqueId_idx").ifNotExists().on("llm_personalization").column("uniqueId").execute(),e.schema.createIndex("llm_personalization_senderId_idx").ifNotExists().on("llm_personalization").column("senderId").execute(),e.schema.createIndex("llm_rag_id_idx").ifNotExists().on("llm_rag").column("metadata.id").execute(),e.schema.createIndex("llm_rag_pageContent_idx").ifNotExists().on("llm_rag").column("pageContent").execute()])),await Promise.all([e.schema.createIndex("auth_session_id_idx").ifNotExists().on("auth").columns(["session","id"]).execute(),e.schema.createIndex("chats_session_id_idx").ifNotExists().on("chats").columns(["session","id"]).execute(),e.schema.createIndex("contacts_session_id_idx").ifNotExists().on("contacts").columns(["session","id"]).execute(),e.schema.createIndex("messages_session_id_idx").ifNotExists().on("messages").columns(["session","id"]).execute()])}))})(t,a);const i=async e=>{for(let t=0;t<10;t++)try{return await e()}catch(e){await new Promise((e=>setTimeout(e,200)))}throw new Error("Max retries reached")},r=async a=>{const r=await i((()=>t.selectFrom(n).select(["value"]).where("id","=",a).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)},o=async(a,r)=>{const o=JSON.stringify(r,e.BufferJSON.replacer);await i((()=>t.insertInto(n).values({session:s,id:a,value:o}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:o}))).execute()))},d=async e=>{await i((()=>t.deleteFrom(n).where("id","=",e).where("session","=",s).execute()))},c=await r("creds")||e.initAuthCreds();return{state:{creds:c,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=D(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 o(n,a):await d(n)}}}},saveCreds:async()=>{await o("creds",c)},clear:async()=>{await(async()=>{await i((()=>t.deleteFrom(n).where("session","=",s).where("id","!=","creds").execute()))})()},removeCreds:async()=>{await(async()=>{await i((()=>t.deleteFrom(n).where("session","=",s).execute()))})()}}},Ss=U.object({type:U.enum(["sqlite","postgresql","mysql"]).default("sqlite"),connection:U.object({url:U.string().default("./session/zaileys.db")}).optional().default({})}).optional().default({}),Ns=U.record(U.function().returns(U.union([U.number().array(),U.promise(U.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})),As=U.object({durationMs:U.number(),maxMessages:U.number()}).optional(),Os=U.object({url:U.string()}).optional(),Es=U.object({prefix:U.string().optional(),ignoreMe:U.boolean().optional().default(!0),showLogs:U.boolean().optional().default(!0),autoMentions:U.boolean().optional().default(!0),autoOnline:U.boolean().optional().default(!0),autoRead:U.boolean().optional().default(!0),autoPresence:U.boolean().optional().default(!0),autoRejectCall:U.boolean().optional().default(!0),loadLLMSchemas:U.boolean().optional().default(!1),webhooks:Os,limiter:As,database:Ss,citation:Ns}),Ls=U.object({authType:U.literal("pairing"),phoneNumber:U.number()}).extend(Es.shape),Ps=U.object({authType:U.literal("qr"),phoneNumber:U.undefined().optional()}).extend(Es.shape),Zs=U.discriminatedUnion("authType",[Ls,Ps]),js=U.object({channelId:U.string(),uniqueId:U.string(),model:U.string().min(2).max(100).optional().nullable(),role:U.string().min(2).max(100),content:U.string().min(1).max(65e3),additional:U.string().max(2e4).optional().nullable()}),Rs=U.object({uniqueId:U.string(),senderId:U.string(),content:U.string().min(1).max(5e3)}),Fs=U.object({metadata:U.object({id:U.string().default((()=>R(5)))}).default({}),pageContent:U.string().min(1).max(128e3)}),qs=Fs.pick({pageContent:!0}),$s=U.union([U.string().url(),U.instanceof(Buffer).or(U.instanceof(f.Readable))]),zs=U.union([U.string(),U.object({image:$s,text:U.string().optional()}).strict(),U.object({video:$s,text:U.string().optional()}).strict(),U.object({note:$s}).strict(),U.object({gif:$s,text:U.string().optional()}).strict(),U.object({audio:$s}).strict(),U.object({voice:$s}).strict(),U.object({sticker:$s}).strict()]),Ds=U.object({roomId:U.string(),asForwarded:U.boolean().optional(),asViewOnce:U.boolean().optional(),asAI:U.boolean().optional(),verifiedReply:U.enum(["whatsapp","meta","chatgpt","copilot","instagram","tiktok"]).optional(),quoted:U.function().returns(U.record(U.string(),U.any())).optional()}),Us=Ds,Vs=U.object({latitude:U.number(),longitude:U.number(),title:U.string().optional(),footer:U.string().optional()}),Ws=Ds,Bs=U.object({fullname:U.string(),nickname:U.string().optional(),organization:U.string().optional(),role:U.string().optional(),email:U.string().email().optional(),whatsAppNumber:U.number(),callNumber:U.number().optional(),voiceNumber:U.number().optional(),website:U.string().url().optional(),homeAddress:U.string().optional(),workAddress:U.string().optional(),avatar:U.string().url().optional()}),Ks=U.object({message:U.function().returns(U.record(U.string(),U.any()))}),Js=U.string(),Gs=U.object({message:U.function().returns(U.record(U.string(),U.any()))}),Ys=U.object({action:U.enum(["pin","unpin"]),expired:U.enum(["24h","7d","30d"])}),Hs=Ds.pick({roomId:!0}),Qs=U.object({name:U.string(),answers:U.string().array(),multipleAnswers:U.boolean().optional()}),Xs=U.object({message:U.function().returns(U.record(U.string(),U.any()))}),ea=U.string(),ta=U.object({message:U.function().returns(U.record(U.string(),U.any()))}),sa=U.object({callId:U.string(),callerId:U.string()}),aa=Ds.pick({roomId:!0}),na=U.object({expired:U.enum(["remove","8h","7d"])}),ia=U.string(),ra=U.object({type:U.enum(["group","user"]),id:U.string(),name:U.string(),bio:U.string(),avatar:U.string().url(),ephemeralDuration:U.number().optional(),isRestrict:U.boolean().optional(),isAnnounce:U.boolean().optional(),isCommunity:U.boolean().optional(),isCommunityAnnounce:U.boolean().optional(),isJoinApprovalMode:U.boolean().optional(),isMemberAddMode:U.boolean().optional(),owner:U.object({type:U.literal("user"),id:U.string()}).nullable(),roomCreatedAt:U.number().optional(),nameUpdatedAt:U.number().optional(),bioUpdatedAt:U.number().optional(),membersLength:U.number().optional(),members:U.object({type:U.enum(["user","admin","superadmin"]),id:U.string()}).array().optional()}),oa=Ds.pick({roomId:!0}),da=U.enum(["typing","recording","online","offline","paused"]),ca=class{constructor(e){this.wa=e,this.parser=new ks(e.socket,e.client,e.db)}parser;caching=new M.default({stdTTL:600,checkperiod:120,maxKeys:1e3});async sendMessage(t,s,a){let n=[];this.wa.client.options?.autoMentions&&(n=((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`]))})(s?.text||s?.caption)),this.wa.client.options?.autoPresence&&this.wa.socket?.sendPresenceUpdate("composing",t),this.wa.client.options?.autoPresence&&(s?.audio||s?.audioNote)&&this.wa.socket?.sendPresenceUpdate("recording",t);const i=s,r=[],o={contextInfo:{isForwarded:!!i?.asForwarded,mentionedJid:n}};if(t.match("@s.whatsapp.net")&&!!i?.asAI&&r.push({attrs:{biz_bot:"1"},tag:"bot"}),"function"==typeof i?.quoted){let e=i?.quoted();e.key.remoteJid=ys[i?.verifiedReply]||e.key.remoteJid,a={...a,quoted:e}}const d=await e.generateWAMessage(t,{...i,...o},{userJid:t,upload:async(e,t)=>await(this.wa?.socket?.waUploadToServer(e,t)),...a});return await(this.wa.socket?.relayMessage(t,d.message,{additionalNodes:r})),await this.parser.messages(d,!0,!0)}async text(e,t){const s=zs.parse(e),a=Ds.parse(t);if("string"==typeof s)return await this.sendMessage(a.roomId,{text:s,...a});const n={caption:s?.text,viewOnce:!!a.asViewOnce,...a},i={image:e=>({image:"string"==typeof e?{url:e}:e}),video:e=>({video:"string"==typeof e?{url:e}:e,ptv:!1}),note:e=>({video:"string"==typeof e?{url:e}:e,ptv:!0}),gif:e=>({video:"string"==typeof e?{url:e}:e,gifPlayback:!0}),audio:e=>({audio:"string"==typeof e?{url:e}:e}),voice:e=>({audio:"string"==typeof e?{url:e}:e,ptt:!0}),sticker:e=>({sticker:"string"==typeof e?{url:e}:e})};for(const[e,t]of Object.entries(i))if(e in s)return await this.sendMessage(a.roomId,{...n,...t(s[e])});throw new Error("Invalid media type")}async location(e,t){return e=Vs.parse(e),t=Us.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=Bs.parse(e),t=Ws.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=Js.parse(e),t=Ks.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{react:{text:e,key:t.message()?.key},...t})}async pin(e,t){e=Ys.parse(e),t=Gs.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=Qs.parse(e),t=Hs.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=ea.parse(e),t=Xs.parse(t),await this.sendMessage(t.message()?.key?.remoteJid,{text:e,edit:t.message()?.key,...t})}async delete(e){return e=ta.parse(e),await this.sendMessage(e.message()?.key?.remoteJid,{delete:e.message()?.key})}async rejectCall(e){return e=sa.parse(e),await(this.wa.socket?.rejectCall(e.callId,e.callerId))}async mute(e,t){e=na.parse(e),t=aa.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=ia.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=F(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=da.parse(e),t=oa.parse(t);return await(this.wa.socket?.sendPresenceUpdate({typing:"composing",recording:"recording",online:"available",offline:"unavailable",paused:"paused"}[e],t.roomId))}async addCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=js.parse(e);if(!await(this.wa.db?.insertInto("llm_messages").values(e).executeTakeFirst()))throw new Error("Failed to add completion");return e}async deleteCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_messages").where("uniqueId","=",e).executeTakeFirst()))throw new Error("Failed to delete completion");return!0}async updateCompletion(e,t){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const s=js.partial().parse(t),a=await(this.wa.db?.updateTable("llm_messages").set(s).where("uniqueId","=",e).returningAll().executeTakeFirst());if(!a)throw new Error("Failed to update completion");return js.parse(a)}async clearCompletions(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_messages").where("channelId","=",e).executeTakeFirst()))throw new Error("Failed to clear completions");return!0}async getCompletion(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_messages").selectAll().where("uniqueId","=",e).executeTakeFirst());return t?js.parse(t):null}async getCompletions(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_messages").selectAll().where("channelId","=",e).execute());return t?.map((e=>js.parse(e)))||[]}async addPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=Rs.parse(e);if(!await(this.wa.db?.insertInto("llm_personalization").values(e).executeTakeFirst()))throw new Error("Failed to add completion");return e}async deletePersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_personalization").where("uniqueId","=",e).executeTakeFirst()))throw new Error("Failed to delete completion");return!0}async clearPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_personalization").where("senderId","=",e).executeTakeFirst()))throw new Error("Failed to clear completions");return!0}async getPersonalization(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_personalization").selectAll().where("senderId","=",e).execute());return t?.map((e=>Rs.parse(e)))||[]}async addRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");e=Fs.parse(e);if(!await(this.wa.db?.insertInto("llm_rag").values({pageContent:e.pageContent.toLowerCase(),"metadata.id":e.metadata?.id}).executeTakeFirst()))throw new Error("Failed to add RAG");return e}async deleteRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_rag").where(d.sql`"metadata.id"`,"=",e).executeTakeFirst()))throw new Error("Failed to delete RAG");return!0}async updateRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.updateTable("llm_rag").set({metadata:{id:e}}).where(d.sql`"metadata.id"`,"=",e).returningAll().executeTakeFirst());if(!t)throw new Error("Failed to update RAG");return Fs.parse(t)}async clearRAGs(){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");if(!await(this.wa.db?.deleteFrom("llm_rag").executeTakeFirst()))throw new Error("Failed to clear RAGs");return!0}async getRAG(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=await(this.wa.db?.selectFrom("llm_rag").selectAll().where(d.sql`"metadata.id"`,"=",e).executeTakeFirst());return t?Fs.parse(t):null}async getRAGs(e){if(!this.wa.client.options?.loadLLMSchemas)throw new Error("LLM schemas are not loaded. Please enable loadLLMSchemas in Client options.");const t=e.toLowerCase().trim(),s=this.caching.get(t);if(s)return s;const a=t.split(/\s+/).filter((e=>e.length>0));if(!a.length)return[];const n=await(this.wa.db?.selectFrom("llm_rag").select([d.sql`"metadata.id"`.as("metadata.id"),"pageContent"]).where("pageContent","!=","").limit(1e4).execute().then((e=>e.map((e=>Fs.parse({...e,metadata:{id:e["metadata.id"]}}))))).then((e=>e.filter((e=>{const t=e.pageContent.toLowerCase().split(/\s+/);return a.some((e=>t.some((t=>Z.get(e,t)<=Math.max(1,Math.floor(e.length/4))))))})))));return this.caching.set(t,n),n||[]}async getMessage(e){const t=await(this.wa.db?.selectFrom("messages").selectAll().where("id","=",e).executeTakeFirst());return t&&t?await this.parser.messages(F(t.value),!0,!0):null}llms={addCompletion:this.addCompletion.bind(this),deleteCompletion:this.deleteCompletion.bind(this),updateCompletion:this.updateCompletion.bind(this),clearCompletions:this.clearCompletions.bind(this),getCompletion:this.getCompletion.bind(this),getCompletions:this.getCompletions.bind(this),addPersonalization:this.addPersonalization.bind(this),deletePersonalization:this.deletePersonalization.bind(this),clearPersonalization:this.clearPersonalization.bind(this),getPersonalization:this.getPersonalization.bind(this),addRAG:this.addRAG.bind(this),deleteRAG:this.deleteRAG.bind(this),updateRAG:this.updateRAG.bind(this),clearRAGs:this.clearRAGs.bind(this),getRAG:this.getRAG.bind(this),getRAGs:this.getRAGs.bind(this)};chats={getMessage:this.getMessage.bind(this)}},la=U.object({callId:U.string(),roomId:U.string(),callerId:U.string(),date:U.date(),offline:U.boolean(),status:U.enum(["accept","offer","reject","ringing","terminate","timeout"]),isVideo:U.boolean(),isGroup:U.boolean()});U.object({status:U.enum(["connecting","open","close"])}),U.enum(["connection","messages","calls","webhooks"]),exports.AdapterDatabaseType=Ss,exports.CallsParserBaseType=la,exports.CitationType=Ns,exports.Client=class{constructor(e){return this.props=e,this.initialize(),this.worker,new Proxy(this,{get:(e,t)=>t in e?e[t]:e.worker[t]})}options={};cache=new M.default({stdTTL:300,useClones:!1});chatId="zaileys-chats";logger=S.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=>{T.default(e,((e,s)=>{if(e)return t("");console.log(s),t(s||"")}))})))(),this.options=await Zs.parseAsync(this.props),this.startSpinner("db","Initializing database..."),this.db=await(e=>{const{type:t,connection:s}=e.database;if("sqlite"===t){const e=s.url||"./db/zaileys.db",t=O.default.resolve(e);return o.mkdirSync(O.default.dirname(t),{recursive:!0}),o.writeFileSync(t,"",{flag:"a"}),new d.Kysely({dialect:new d.SqliteDialect({database:new N.default(t)})})}const a=new p.URL(s.url),n=a.protocol.replace(":","");if("mysql"===t)return new d.Kysely({dialect:new d.MysqlDialect({pool:A.default.createPool({host:a.hostname,user:a.username,password:a.password,database:a.pathname.replace("/",""),port:parseInt(a.port||"3306",10)})})});if("postgresql"===t)return new d.Kysely({dialect:new d.PostgresDialect({pool:new u.Pool({host:a.hostname,user:a.username,password:a.password,database:a.pathname.replace("/",""),port:parseInt(a.port||"5432",10)})})});throw new Error(`Unsupported database protocol: ${n}`)})(this.options),this.stopSpinner("db",!0,"Database initialized"),this.startSpinner("auth","Setting up auth adapter...");const{state:t,saveCreds:s}=await Is(this.db,this.chatId,this.options);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 ks(a,e,t);a?.ev.on("connection.update",(async e=>{await n.connection(e)})),a?.ev.on("call",(async t=>{for(const s of t){const t=await n.calls(s);e.options.ignoreMe&&t&&await Ms(e.options.webhooks?.url,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:a})=>{for(const i of a){if(!i.message)return;if(i.message?.protocolMessage)return;const a=await n.messages(i);e.options.ignoreMe&&a&&await Ms(e.options.webhooks?.url,a),await t.insertInto("messages").values({session:s,id:i.key.id,value:JSON.stringify(i)}).onConflict((e=>e.columns(["session","id"]).doUpdateSet({value:JSON.stringify(i)}))).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)})),a?.ev.on("idle-webhooks",(async e=>{await n.webhooks(e)}))}}))(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 M.default,mediaCache:new M.default({stdTTL:60}),userDevicesCache:new M.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 F(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 ca({client:this,db:this.db,socket:this.socket}),this.socket?.ev.on("creds.update",s),a.bind(this.socket),this.startSpinner("webhooks","Starting webhooks server..."),Ts(this,this.socket)}startSpinner(e,t){let s=this.spinners.get(e);return s||(s=I.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.ClientClassesBaseType=Es,exports.ClientClassesType=Zs,exports.ContactWorkerBaseType=Bs,exports.ContactWorkerOptionsType=Ws,exports.DeleteWorkerBaseType=ta,exports.EditWorkerBaseType=ea,exports.EditWorkerOptionsType=Xs,exports.LocationWorkerBaseType=Vs,exports.LocationWorkerOptionsType=Us,exports.MediaInputWorkerType=$s,exports.MessagesDeviceEnumType=_s,exports.MessagesEnumType=vs,exports.MessagesMediaType=gs,exports.MessagesParserBaseType=ws,exports.MessagesParserType=bs,exports.MessagesVerifiedPlatformType=ys,exports.MuteWorkerBaseType=na,exports.MuteWorkerOptionsType=aa,exports.PinWorkerBaseType=Ys,exports.PinWorkerOptionsType=Gs,exports.PollWorkerBaseType=Qs,exports.PollWorkerOptionsType=Hs,exports.PresenceWorkerBaseType=da,exports.PresenceWorkerOptionsType=oa,exports.ProfileWorkerBaseOutputType=ra,exports.ProfileWorkerBaseType=ia,exports.ReactionWorkerBaseType=Js,exports.ReactionWorkerOptionsType=Ks,exports.RejectCallWorkerBaseType=sa,exports.TextWorkerBaseType=zs,exports.TextWorkerOptionsType=Ds,exports.addRAGType=qs,exports.llmMessagesTable=js,exports.llmPersonalizationTable=Rs,exports.llmRAGTable=Fs;
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var makeWASocket = require('baileys');
|
|
4
|
+
var EventEmitter = require('events');
|
|
5
|
+
var nanospinner = require('nanospinner');
|
|
6
|
+
var NodeCache2 = require('node-cache');
|
|
7
|
+
var pino = require('pino');
|
|
8
|
+
var fs = require('fs');
|
|
9
|
+
var lowdb = require('lowdb');
|
|
10
|
+
var FileSync = require('lowdb/adapters/FileSync');
|
|
11
|
+
var path = require('path');
|
|
12
|
+
var chalk = require('chalk');
|
|
13
|
+
var _2 = require('lodash');
|
|
14
|
+
var z2 = require('zod/v4');
|
|
15
|
+
var figlet = require('figlet');
|
|
16
|
+
var QRCode = require('qrcode');
|
|
17
|
+
var zod = require('zod');
|
|
18
|
+
|
|
19
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
20
|
+
|
|
21
|
+
var makeWASocket__default = /*#__PURE__*/_interopDefault(makeWASocket);
|
|
22
|
+
var EventEmitter__default = /*#__PURE__*/_interopDefault(EventEmitter);
|
|
23
|
+
var NodeCache2__default = /*#__PURE__*/_interopDefault(NodeCache2);
|
|
24
|
+
var pino__default = /*#__PURE__*/_interopDefault(pino);
|
|
25
|
+
var lowdb__default = /*#__PURE__*/_interopDefault(lowdb);
|
|
26
|
+
var FileSync__default = /*#__PURE__*/_interopDefault(FileSync);
|
|
27
|
+
var chalk__default = /*#__PURE__*/_interopDefault(chalk);
|
|
28
|
+
var _2__default = /*#__PURE__*/_interopDefault(_2);
|
|
29
|
+
var z2__default = /*#__PURE__*/_interopDefault(z2);
|
|
30
|
+
var figlet__default = /*#__PURE__*/_interopDefault(figlet);
|
|
31
|
+
var QRCode__default = /*#__PURE__*/_interopDefault(QRCode);
|
|
32
|
+
|
|
33
|
+
// src/classes/Client.ts
|
|
34
|
+
var sendError = (text) => new Error(chalk__default.default.red(text));
|
|
35
|
+
var toJson = (object) => {
|
|
36
|
+
try {
|
|
37
|
+
return JSON.parse(object);
|
|
38
|
+
} catch {
|
|
39
|
+
return _2__default.default.attempt(() => JSON.parse(JSON.stringify(object) || "{}"));
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
var toString = (object) => {
|
|
43
|
+
try {
|
|
44
|
+
return JSON.stringify(object);
|
|
45
|
+
} catch {
|
|
46
|
+
const result = _2__default.default.attempt(() => JSON.stringify(toJson(object) || "{}"));
|
|
47
|
+
return _2__default.default.isError(result) ? "{}" : result;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
var shuffleString = (str) => {
|
|
51
|
+
return _2__default.default.shuffle([...str]).join("");
|
|
52
|
+
};
|
|
53
|
+
var tryAgain = async (fn) => {
|
|
54
|
+
const RETRY_DELAY = 200;
|
|
55
|
+
const MAX_RETRIES = 10;
|
|
56
|
+
for (let x = 0; x < MAX_RETRIES; x++) {
|
|
57
|
+
try {
|
|
58
|
+
return await fn();
|
|
59
|
+
} catch (_e) {
|
|
60
|
+
await new Promise((r) => setTimeout(r, RETRY_DELAY));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
throw sendError("Max retries reached");
|
|
64
|
+
};
|
|
65
|
+
var findWord = (text = "", word = "") => {
|
|
66
|
+
if (!text) return null;
|
|
67
|
+
return _2__default.default.includes(text.toLowerCase(), word.toLowerCase());
|
|
68
|
+
};
|
|
69
|
+
var normalizeText = (text = "") => {
|
|
70
|
+
if (!text) return null;
|
|
71
|
+
return _2__default.default.replace(text, /\u202E([\s\S]*?)\u202C/g, (_e, segmen) => {
|
|
72
|
+
const arr = _2__default.default.toArray(segmen);
|
|
73
|
+
const reversed = _2__default.default.reverse(_2__default.default.clone(arr));
|
|
74
|
+
return _2__default.default.join(reversed, "");
|
|
75
|
+
}).replace(/[\u202A-\u202E\u202C]/g, "");
|
|
76
|
+
};
|
|
77
|
+
var extractJids = (text = "") => {
|
|
78
|
+
if (!text) return [];
|
|
79
|
+
const ids = /* @__PURE__ */ new Set();
|
|
80
|
+
for (const match of text.matchAll(/@(\d+)/g)) {
|
|
81
|
+
ids.add(match[1]);
|
|
82
|
+
}
|
|
83
|
+
return _2__default.default.flatMap([...ids], (id) => [`${id}@s.whatsapp.net`, `${id}@g.us`]);
|
|
84
|
+
};
|
|
85
|
+
var extractUrls = (text = "") => {
|
|
86
|
+
if (!text) return [];
|
|
87
|
+
const regex = /https?:\/\/(?:[-\w.])+(?:\.[a-zA-Z]{2,})+(?:\/[^\s<>"']*)?/g;
|
|
88
|
+
return _2__default.default.castArray(text.match(regex) || []);
|
|
89
|
+
};
|
|
90
|
+
var getMentions = (text = "") => {
|
|
91
|
+
if (!text) return [];
|
|
92
|
+
const ids = /* @__PURE__ */ new Set();
|
|
93
|
+
for (const match of text.matchAll(/@(\d+)/g)) {
|
|
94
|
+
ids.add(match[1]);
|
|
95
|
+
}
|
|
96
|
+
return _2__default.default.toArray(ids);
|
|
97
|
+
};
|
|
98
|
+
var CHUNK_SIZE = 1e3;
|
|
99
|
+
var JsonDB = class {
|
|
100
|
+
session = "zaileys-sessions";
|
|
101
|
+
db;
|
|
102
|
+
storeDir;
|
|
103
|
+
async initialize(session) {
|
|
104
|
+
this.session = session;
|
|
105
|
+
const authPath = `sessions/${this.session}/auth.json`;
|
|
106
|
+
this.storeDir = `sessions/${this.session}/stores`;
|
|
107
|
+
const dirAuth = path.dirname(authPath);
|
|
108
|
+
if (!fs.existsSync(dirAuth)) fs.mkdirSync(dirAuth, { recursive: true });
|
|
109
|
+
if (!fs.existsSync(this.storeDir)) fs.mkdirSync(this.storeDir, { recursive: true });
|
|
110
|
+
const adapter = new FileSync__default.default(authPath);
|
|
111
|
+
this.db = lowdb__default.default(adapter);
|
|
112
|
+
this.db.defaults([]).write();
|
|
113
|
+
}
|
|
114
|
+
tryRecoverRaw(raw) {
|
|
115
|
+
const s = raw.trim();
|
|
116
|
+
try {
|
|
117
|
+
return JSON.parse(s);
|
|
118
|
+
} catch (_error) {
|
|
119
|
+
try {
|
|
120
|
+
const a = s.indexOf("[");
|
|
121
|
+
const b = s.lastIndexOf("]");
|
|
122
|
+
if (a !== -1 && b !== -1 && b > a) {
|
|
123
|
+
const sub = s.slice(a, b + 1);
|
|
124
|
+
return JSON.parse(sub);
|
|
125
|
+
}
|
|
126
|
+
} catch (_error2) {
|
|
127
|
+
}
|
|
128
|
+
try {
|
|
129
|
+
const wrapped = `[${s.replace(/}\s*{/g, "},{")}]`;
|
|
130
|
+
return JSON.parse(wrapped);
|
|
131
|
+
} catch (_error2) {
|
|
132
|
+
}
|
|
133
|
+
try {
|
|
134
|
+
const lines = _2__default.default.filter(_2__default.default.map(s.split(/\\r?\\n/), (l) => l.trim()), Boolean);
|
|
135
|
+
const parsedResults = _2__default.default.map(lines, (l) => {
|
|
136
|
+
try {
|
|
137
|
+
return JSON.parse(l);
|
|
138
|
+
} catch (_error2) {
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
const parsed = _2__default.default.filter(parsedResults, (item) => item !== null);
|
|
143
|
+
if (parsed.length) return parsed;
|
|
144
|
+
} catch (_error2) {
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
async chunks(key) {
|
|
150
|
+
const files = _2__default.default.filter(fs.readdirSync(this.storeDir), (f) => _2__default.default.startsWith(f, `${key}-`) && _2__default.default.endsWith(f, ".json")).sort();
|
|
151
|
+
const result = [];
|
|
152
|
+
for (const file of files) {
|
|
153
|
+
const full = `${this.storeDir}/${file}`;
|
|
154
|
+
const adapter = new FileSync__default.default(full);
|
|
155
|
+
const db = lowdb__default.default(adapter);
|
|
156
|
+
try {
|
|
157
|
+
db.defaults([]).write();
|
|
158
|
+
result.push(...toJson(db.value()));
|
|
159
|
+
} catch {
|
|
160
|
+
let raw = "";
|
|
161
|
+
try {
|
|
162
|
+
raw = fs.readFileSync(full, "utf8");
|
|
163
|
+
} catch (_error) {
|
|
164
|
+
raw = "";
|
|
165
|
+
}
|
|
166
|
+
const recovered = raw ? this.tryRecoverRaw(raw) : null;
|
|
167
|
+
if (recovered) {
|
|
168
|
+
db.setState(Array.isArray(recovered) ? recovered : [recovered]).write();
|
|
169
|
+
result.push(...toJson(db.value()));
|
|
170
|
+
} else {
|
|
171
|
+
const corrupt = `${full}.corrupt.${Date.now()}`;
|
|
172
|
+
try {
|
|
173
|
+
fs.renameSync(full, corrupt);
|
|
174
|
+
} catch (_renameErr) {
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
fs.writeFileSync(full, "[]", "utf8");
|
|
178
|
+
} catch (_writeFileErr) {
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return result;
|
|
184
|
+
}
|
|
185
|
+
async writeChunks(key, items) {
|
|
186
|
+
_2__default.default.forEach(
|
|
187
|
+
_2__default.default.filter(fs.readdirSync(this.storeDir), (f) => _2__default.default.startsWith(f, `${key}-`) && _2__default.default.endsWith(f, ".json")),
|
|
188
|
+
(f) => fs.unlinkSync(`${this.storeDir}/${f}`)
|
|
189
|
+
);
|
|
190
|
+
let index = 0;
|
|
191
|
+
for (let i = 0; i < items.length; i += CHUNK_SIZE) {
|
|
192
|
+
const chunk = items.slice(i, i + CHUNK_SIZE);
|
|
193
|
+
const file = `${this.storeDir}/${key}-${index}.json`;
|
|
194
|
+
const adapter = new FileSync__default.default(file);
|
|
195
|
+
const db = lowdb__default.default(adapter);
|
|
196
|
+
db.setState(chunk).write();
|
|
197
|
+
try {
|
|
198
|
+
db.write();
|
|
199
|
+
} catch (err) {
|
|
200
|
+
if (err?.code === "ENOENT") {
|
|
201
|
+
try {
|
|
202
|
+
fs.renameSync(`${file}.tmp`, file);
|
|
203
|
+
} catch (_renameErr) {
|
|
204
|
+
try {
|
|
205
|
+
db.write();
|
|
206
|
+
} catch (_writeErr) {
|
|
207
|
+
try {
|
|
208
|
+
fs.writeFileSync(file, JSON.stringify(chunk), "utf8");
|
|
209
|
+
} catch (_writeFileErr) {
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
} else {
|
|
214
|
+
throw err;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
index++;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
store(key) {
|
|
221
|
+
return {
|
|
222
|
+
read: async (id) => {
|
|
223
|
+
const list = await this.chunks(key);
|
|
224
|
+
const row = _2__default.default.find(list, (i) => i.id === id);
|
|
225
|
+
return row ? JSON.parse(row.value) : null;
|
|
226
|
+
},
|
|
227
|
+
write: async (obj) => {
|
|
228
|
+
const list = await this.chunks(key);
|
|
229
|
+
const id = obj.key && typeof obj.key === "object" && "id" in obj.key ? obj.key.id : obj.id;
|
|
230
|
+
const serialized = JSON.stringify(obj);
|
|
231
|
+
const idx = list.findIndex((i) => i.id === id);
|
|
232
|
+
if (idx !== -1) list[idx].value = serialized;
|
|
233
|
+
else list.push({ id, value: serialized });
|
|
234
|
+
await this.writeChunks(key, list);
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
async upsert(id, value) {
|
|
239
|
+
const replacer = JSON.stringify(value, makeWASocket.BufferJSON.replacer);
|
|
240
|
+
const dbValue = this.db.value();
|
|
241
|
+
const data = Array.isArray(dbValue) ? dbValue : [];
|
|
242
|
+
const idx = _2__default.default.findIndex(data, (i) => i.id === id);
|
|
243
|
+
if (idx !== -1) {
|
|
244
|
+
data[idx].value = replacer;
|
|
245
|
+
} else {
|
|
246
|
+
data.push({ id, value: replacer });
|
|
247
|
+
}
|
|
248
|
+
this.db.setState(data).write();
|
|
249
|
+
}
|
|
250
|
+
async read(id) {
|
|
251
|
+
const dbValue = this.db.value();
|
|
252
|
+
const data = Array.isArray(dbValue) ? dbValue : [];
|
|
253
|
+
const row = _2__default.default.find(data, (i) => i.id === id);
|
|
254
|
+
if (!row || !row.value) return null;
|
|
255
|
+
const creds = typeof row.value === "object" ? toString(row.value) : row.value;
|
|
256
|
+
return JSON.parse(creds, makeWASocket.BufferJSON.reviver);
|
|
257
|
+
}
|
|
258
|
+
async remove(id) {
|
|
259
|
+
const dbValue = this.db.value();
|
|
260
|
+
const data = Array.isArray(dbValue) ? dbValue : [];
|
|
261
|
+
const filtered = _2__default.default.filter(data, (i) => i.id !== id);
|
|
262
|
+
this.db.setState(filtered).write();
|
|
263
|
+
}
|
|
264
|
+
async clear() {
|
|
265
|
+
const dbValue = this.db.value();
|
|
266
|
+
const data = Array.isArray(dbValue) ? dbValue : [];
|
|
267
|
+
const filtered = _2__default.default.filter(data, (i) => i.id === "creds");
|
|
268
|
+
this.db.setState(filtered).write();
|
|
269
|
+
}
|
|
270
|
+
async delete() {
|
|
271
|
+
this.db.setState([]);
|
|
272
|
+
await this.db.write();
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
// src/utils/decrypt.ts
|
|
277
|
+
var allocate = (str) => {
|
|
278
|
+
let n = 0;
|
|
279
|
+
let p = str.length;
|
|
280
|
+
if (!p) return new Uint8Array(1);
|
|
281
|
+
while (--p % 4 > 1 && str.charAt(p) === "=") ++n;
|
|
282
|
+
return new Uint8Array(Math.ceil(str.length * 3) / 4 - n).fill(0);
|
|
283
|
+
};
|
|
284
|
+
var parseTimestamp = (timestamp) => {
|
|
285
|
+
if (typeof timestamp === "string") return parseInt(timestamp, 10);
|
|
286
|
+
if (typeof timestamp === "number") return timestamp;
|
|
287
|
+
return timestamp;
|
|
288
|
+
};
|
|
289
|
+
var fromObject = (args) => {
|
|
290
|
+
const fingerprint = args.fingerprint || {};
|
|
291
|
+
const f = {
|
|
292
|
+
...fingerprint,
|
|
293
|
+
deviceIndexes: Array.isArray(fingerprint.deviceIndexes) ? fingerprint.deviceIndexes : []
|
|
294
|
+
};
|
|
295
|
+
const message = {
|
|
296
|
+
keyData: Array.isArray(args.keyData) ? args.keyData : new Uint8Array(),
|
|
297
|
+
fingerprint: {
|
|
298
|
+
rawId: fingerprint.rawId || 0,
|
|
299
|
+
currentIndex: fingerprint.rawId || 0,
|
|
300
|
+
deviceIndexes: f.deviceIndexes
|
|
301
|
+
},
|
|
302
|
+
timestamp: parseTimestamp(args.timestamp)
|
|
303
|
+
};
|
|
304
|
+
if (typeof args.keyData === "string") {
|
|
305
|
+
message.keyData = allocate(args.keyData);
|
|
306
|
+
}
|
|
307
|
+
return message;
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
// src/modules/store.ts
|
|
311
|
+
var StoreHandler = async (db) => {
|
|
312
|
+
return {
|
|
313
|
+
bind: (client) => {
|
|
314
|
+
client?.socket?.ev.on("messaging-history.set", async (update) => {
|
|
315
|
+
const { chats, contacts, messages } = update;
|
|
316
|
+
for (const chat of chats) {
|
|
317
|
+
await db.store("chats").write(chat);
|
|
318
|
+
}
|
|
319
|
+
for (const contact of contacts) {
|
|
320
|
+
await db.store("contacts").write(contact);
|
|
321
|
+
}
|
|
322
|
+
for (const message of messages) {
|
|
323
|
+
if (!message.message) return;
|
|
324
|
+
if (message.message?.protocolMessage) return;
|
|
325
|
+
await db.store("messages").write(message);
|
|
326
|
+
}
|
|
327
|
+
});
|
|
328
|
+
client?.socket?.ev.on("messages.upsert", async ({ messages }) => {
|
|
329
|
+
for (const message of messages) {
|
|
330
|
+
await db.store("messages").write(message);
|
|
331
|
+
}
|
|
332
|
+
});
|
|
333
|
+
client?.socket?.ev.on("chats.upsert", async (chats) => {
|
|
334
|
+
for (const chat of chats) {
|
|
335
|
+
await db.store("chats").write(chat);
|
|
336
|
+
}
|
|
337
|
+
});
|
|
338
|
+
client?.socket?.ev.on("contacts.upsert", async (contacts) => {
|
|
339
|
+
for (const contact of contacts) {
|
|
340
|
+
await db.store("contacts").write(contact);
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
client?.socket?.ev.on("groups.update", async ([event]) => {
|
|
344
|
+
if (event.id) {
|
|
345
|
+
const metadata = await client?.socket?.groupMetadata(event.id);
|
|
346
|
+
client.cache.set(event.id, metadata);
|
|
347
|
+
}
|
|
348
|
+
});
|
|
349
|
+
client?.socket?.ev.on("group-participants.update", async (event) => {
|
|
350
|
+
const metadata = await client?.socket?.groupMetadata(event.id);
|
|
351
|
+
client.cache.set(event.id, metadata);
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
};
|
|
356
|
+
|
|
357
|
+
// src/modules/auth.ts
|
|
358
|
+
var AuthHandler = async (db) => {
|
|
359
|
+
const creds = await tryAgain(() => db.read("creds")) || makeWASocket.initAuthCreds();
|
|
360
|
+
const store = await StoreHandler(db);
|
|
361
|
+
return {
|
|
362
|
+
db,
|
|
363
|
+
store,
|
|
364
|
+
state: {
|
|
365
|
+
creds,
|
|
366
|
+
keys: {
|
|
367
|
+
get: async (type, ids) => {
|
|
368
|
+
const data = {};
|
|
369
|
+
for (const id of ids) {
|
|
370
|
+
let value = await tryAgain(() => db.read(`${type}-${id}`));
|
|
371
|
+
if (type === "app-state-sync-key" && value) {
|
|
372
|
+
value = fromObject(value);
|
|
373
|
+
}
|
|
374
|
+
if (value !== null && value !== void 0) {
|
|
375
|
+
data[id] = value;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
return data;
|
|
379
|
+
},
|
|
380
|
+
set: async (data) => {
|
|
381
|
+
for (const category in data) {
|
|
382
|
+
for (const id in data[category]) {
|
|
383
|
+
const value = data[category][id];
|
|
384
|
+
const name = `${category}-${id}`;
|
|
385
|
+
if (value) {
|
|
386
|
+
await tryAgain(() => db.upsert(name, value));
|
|
387
|
+
} else {
|
|
388
|
+
await tryAgain(() => db.remove(name));
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
},
|
|
395
|
+
clear: async () => {
|
|
396
|
+
await tryAgain(() => db.clear());
|
|
397
|
+
},
|
|
398
|
+
saveCreds: async () => {
|
|
399
|
+
await tryAgain(() => db.upsert("creds", creds));
|
|
400
|
+
},
|
|
401
|
+
removeCreds: async () => {
|
|
402
|
+
await tryAgain(() => db.delete());
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
};
|
|
406
|
+
var PluginsHandler = (necessary, props) => {
|
|
407
|
+
const plugins = _2__default.default.find(props.plugins, (x) => x?.necessary == necessary);
|
|
408
|
+
return plugins;
|
|
409
|
+
};
|
|
410
|
+
|
|
411
|
+
// src/modules/database.ts
|
|
412
|
+
var CredsHandler = async (props) => {
|
|
413
|
+
const db = PluginsHandler("database", props) || new JsonDB();
|
|
414
|
+
await db.initialize(props.session || "default");
|
|
415
|
+
return await AuthHandler(db);
|
|
416
|
+
};
|
|
417
|
+
var defaultBoolean = (state) => z2.z.boolean().default(state).optional();
|
|
418
|
+
var AdsReplyType = z2.z.custom();
|
|
419
|
+
|
|
420
|
+
// src/types/classes/Client.ts
|
|
421
|
+
var PluginsType = z2__default.default.array(
|
|
422
|
+
z2__default.default.object({
|
|
423
|
+
necessary: z2__default.default.string()
|
|
424
|
+
}).passthrough()
|
|
425
|
+
).optional();
|
|
426
|
+
var LimiterType = z2__default.default.object({
|
|
427
|
+
durationMs: z2__default.default.number(),
|
|
428
|
+
maxMessages: z2__default.default.number()
|
|
429
|
+
}).optional();
|
|
430
|
+
var CitationType = z2__default.default.partialRecord(z2__default.default.string(), z2__default.default.number().array()).optional();
|
|
431
|
+
var FakeReplyType = z2__default.default.object({
|
|
432
|
+
provider: z2__default.default.enum(["whatsapp", "meta", "chatgpt", "copilot", "instagram", "tiktok"])
|
|
433
|
+
}).optional();
|
|
434
|
+
var ClientBaseType = z2__default.default.object({
|
|
435
|
+
session: z2__default.default.string().default("zaileys-sessions").optional(),
|
|
436
|
+
prefix: z2__default.default.string().optional(),
|
|
437
|
+
ignoreMe: defaultBoolean(true),
|
|
438
|
+
showLogs: defaultBoolean(true),
|
|
439
|
+
autoMentions: defaultBoolean(true),
|
|
440
|
+
autoOnline: defaultBoolean(true),
|
|
441
|
+
autoRead: defaultBoolean(true),
|
|
442
|
+
autoPresence: defaultBoolean(true),
|
|
443
|
+
autoRejectCall: defaultBoolean(true),
|
|
444
|
+
plugins: PluginsType,
|
|
445
|
+
limiter: LimiterType,
|
|
446
|
+
citation: CitationType,
|
|
447
|
+
fakeReply: FakeReplyType
|
|
448
|
+
});
|
|
449
|
+
var ClientAuthPairingType = z2__default.default.object({
|
|
450
|
+
authType: z2__default.default.literal("pairing"),
|
|
451
|
+
phoneNumber: z2__default.default.number()
|
|
452
|
+
});
|
|
453
|
+
var ClientAuthQRType = z2__default.default.object({
|
|
454
|
+
authType: z2__default.default.literal("qr")
|
|
455
|
+
});
|
|
456
|
+
var ClientOptionsType = z2__default.default.discriminatedUnion("authType", [ClientAuthPairingType.extend(ClientBaseType.shape), ClientAuthQRType.extend(ClientBaseType.shape)]);
|
|
457
|
+
var EventEnumType = z2__default.default.enum(["connection", "messages", "calls", "webhooks"]);
|
|
458
|
+
var displayBanner = async (text = "ZAILEYS") => {
|
|
459
|
+
figlet__default.default(text, async (err, data) => {
|
|
460
|
+
if (err) return;
|
|
461
|
+
console.log(chalk__default.default.gray.italic(data));
|
|
462
|
+
});
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
// src/extractor/calls.ts
|
|
466
|
+
var CallsExtractor = async (client, caller) => {
|
|
467
|
+
const payload = {};
|
|
468
|
+
payload.callId = caller.id;
|
|
469
|
+
payload.roomId = caller.chatId;
|
|
470
|
+
payload.callerId = caller.from;
|
|
471
|
+
payload.date = caller.date;
|
|
472
|
+
payload.offline = caller.offline;
|
|
473
|
+
payload.status = caller.status;
|
|
474
|
+
payload.isVideo = !!caller.isVideo;
|
|
475
|
+
payload.isGroup = !!caller.isGroup;
|
|
476
|
+
return payload;
|
|
477
|
+
};
|
|
478
|
+
var MessagesMediaType = {
|
|
479
|
+
text: "text",
|
|
480
|
+
conversation: "text",
|
|
481
|
+
imageMessage: "image",
|
|
482
|
+
contactMessage: "contact",
|
|
483
|
+
locationMessage: "location",
|
|
484
|
+
documentMessage: "document",
|
|
485
|
+
audioMessage: "audio",
|
|
486
|
+
videoMessage: "video",
|
|
487
|
+
protocolMessage: "protocol",
|
|
488
|
+
contactsArrayMessage: "contacts",
|
|
489
|
+
highlyStructuredMessage: "highlyStructured",
|
|
490
|
+
sendPaymentMessage: "sendPayment",
|
|
491
|
+
liveLocationMessage: "location",
|
|
492
|
+
requestPaymentMessage: "requestPayment",
|
|
493
|
+
declinePaymentRequestMessage: "declinePaymentRequest",
|
|
494
|
+
cancelPaymentRequestMessage: "cancelPaymentRequest",
|
|
495
|
+
templateMessage: "template",
|
|
496
|
+
stickerMessage: "sticker",
|
|
497
|
+
groupInviteMessage: "groupInvite",
|
|
498
|
+
templateButtonReplyMessage: "buttons",
|
|
499
|
+
productMessage: "product",
|
|
500
|
+
deviceSentMessage: "deviceSent",
|
|
501
|
+
listMessage: "list",
|
|
502
|
+
viewOnceMessage: "viewOnce",
|
|
503
|
+
orderMessage: "order",
|
|
504
|
+
listResponseMessage: "list",
|
|
505
|
+
ephemeralMessage: "ephemeral",
|
|
506
|
+
invoiceMessage: "invoice",
|
|
507
|
+
buttonsMessage: "buttons",
|
|
508
|
+
buttonsResponseMessage: "buttons",
|
|
509
|
+
paymentInviteMessage: "paymentInvite",
|
|
510
|
+
interactiveMessage: "interactive",
|
|
511
|
+
reactionMessage: "reaction",
|
|
512
|
+
stickerSyncRmrMessage: "sticker",
|
|
513
|
+
interactiveResponseMessage: "interactiveResponse",
|
|
514
|
+
pollCreationMessage: "pollCreation",
|
|
515
|
+
pollUpdateMessage: "pollUpdate",
|
|
516
|
+
keepInChatMessage: "keepInChat",
|
|
517
|
+
documentWithCaptionMessage: "document",
|
|
518
|
+
requestPhoneNumberMessage: "requestPhoneNumber",
|
|
519
|
+
viewOnceMessageV2: "viewOnce",
|
|
520
|
+
encReactionMessage: "reaction",
|
|
521
|
+
editedMessage: "text",
|
|
522
|
+
viewOnceMessageV2Extension: "viewOnce",
|
|
523
|
+
pollCreationMessageV2: "pollCreation",
|
|
524
|
+
scheduledCallCreationMessage: "scheduledCallCreation",
|
|
525
|
+
groupMentionedMessage: "groupMentioned",
|
|
526
|
+
pinInChatMessage: "pinInChat",
|
|
527
|
+
pollCreationMessageV3: "pollCreation",
|
|
528
|
+
scheduledCallEditMessage: "scheduledCallEdit",
|
|
529
|
+
ptvMessage: "ptv",
|
|
530
|
+
botInvokeMessage: "botInvoke",
|
|
531
|
+
callLogMesssage: "callLog",
|
|
532
|
+
encCommentMessage: "encComment",
|
|
533
|
+
bcallMessage: "bcall",
|
|
534
|
+
lottieStickerMessage: "lottieSticker",
|
|
535
|
+
eventMessage: "event",
|
|
536
|
+
commentMessage: "comment",
|
|
537
|
+
newsletterAdminInviteMessage: "text",
|
|
538
|
+
extendedTextMessageWithParentKey: "text",
|
|
539
|
+
extendedTextMessage: "text",
|
|
540
|
+
placeholderMessage: "placeholder",
|
|
541
|
+
encEventUpdateMessage: "encEventUpdate"
|
|
542
|
+
};
|
|
543
|
+
var MessagesVerifiedPlatformType = {
|
|
544
|
+
whatsapp: "0@s.whatsapp.net",
|
|
545
|
+
meta: "13135550002@s.whatsapp.net",
|
|
546
|
+
chatgpt: "18002428478@s.whatsapp.net",
|
|
547
|
+
copilot: "18772241042@s.whatsapp.net",
|
|
548
|
+
instagram: "447723442971@s.whatsapp.net",
|
|
549
|
+
tiktok: "6285574670498@s.whatsapp.net"
|
|
550
|
+
};
|
|
551
|
+
var MessagesEnumType = zod.z.enum([
|
|
552
|
+
"text",
|
|
553
|
+
"image",
|
|
554
|
+
"contact",
|
|
555
|
+
"location",
|
|
556
|
+
"document",
|
|
557
|
+
"audio",
|
|
558
|
+
"video",
|
|
559
|
+
"protocol",
|
|
560
|
+
"contacts",
|
|
561
|
+
"highlyStructured",
|
|
562
|
+
"sendPayment",
|
|
563
|
+
"requestPayment",
|
|
564
|
+
"declinePaymentRequest",
|
|
565
|
+
"cancelPaymentRequest",
|
|
566
|
+
"template",
|
|
567
|
+
"sticker",
|
|
568
|
+
"groupInvite",
|
|
569
|
+
"product",
|
|
570
|
+
"deviceSent",
|
|
571
|
+
"list",
|
|
572
|
+
"viewOnce",
|
|
573
|
+
"order",
|
|
574
|
+
"ephemeral",
|
|
575
|
+
"invoice",
|
|
576
|
+
"buttons",
|
|
577
|
+
"paymentInvite",
|
|
578
|
+
"interactive",
|
|
579
|
+
"reaction",
|
|
580
|
+
"sticker",
|
|
581
|
+
"interactiveResponse",
|
|
582
|
+
"pollCreation",
|
|
583
|
+
"pollUpdate",
|
|
584
|
+
"keepInChat",
|
|
585
|
+
"document",
|
|
586
|
+
"requestPhoneNumber",
|
|
587
|
+
"viewOnce",
|
|
588
|
+
"reaction",
|
|
589
|
+
"text",
|
|
590
|
+
"viewOnce",
|
|
591
|
+
"pollCreation",
|
|
592
|
+
"scheduledCallCreation",
|
|
593
|
+
"groupMentioned",
|
|
594
|
+
"pinInChat",
|
|
595
|
+
"pollCreation",
|
|
596
|
+
"scheduledCallEdit",
|
|
597
|
+
"ptv",
|
|
598
|
+
"botInvoke",
|
|
599
|
+
"callLog",
|
|
600
|
+
"encComment",
|
|
601
|
+
"bcall",
|
|
602
|
+
"lottieSticker",
|
|
603
|
+
"event",
|
|
604
|
+
"comment",
|
|
605
|
+
"placeholder",
|
|
606
|
+
"encEventUpdate"
|
|
607
|
+
]);
|
|
608
|
+
var MessagesDeviceEnumType = zod.z.enum([
|
|
609
|
+
"unknown",
|
|
610
|
+
"android",
|
|
611
|
+
"ios",
|
|
612
|
+
"desktop",
|
|
613
|
+
"web"
|
|
614
|
+
]);
|
|
615
|
+
var ExtractorMessagesType = zod.z.object({
|
|
616
|
+
chatId: zod.z.string(),
|
|
617
|
+
channelId: zod.z.string(),
|
|
618
|
+
uniqueId: zod.z.string(),
|
|
619
|
+
receiverId: zod.z.string(),
|
|
620
|
+
receiverName: zod.z.string(),
|
|
621
|
+
roomId: zod.z.string(),
|
|
622
|
+
roomName: zod.z.string(),
|
|
623
|
+
senderLid: zod.z.string(),
|
|
624
|
+
senderId: zod.z.string(),
|
|
625
|
+
senderName: zod.z.string(),
|
|
626
|
+
senderDevice: MessagesDeviceEnumType,
|
|
627
|
+
chatType: MessagesEnumType,
|
|
628
|
+
timestamp: zod.z.number(),
|
|
629
|
+
text: zod.z.string().nullable(),
|
|
630
|
+
mentions: zod.z.string().array(),
|
|
631
|
+
links: zod.z.string().array(),
|
|
632
|
+
isPrefix: zod.z.boolean(),
|
|
633
|
+
isSpam: zod.z.boolean(),
|
|
634
|
+
isFromMe: zod.z.boolean(),
|
|
635
|
+
isTagMe: zod.z.boolean(),
|
|
636
|
+
isGroup: zod.z.boolean(),
|
|
637
|
+
isStory: zod.z.boolean(),
|
|
638
|
+
isViewOnce: zod.z.boolean(),
|
|
639
|
+
isEdited: zod.z.boolean(),
|
|
640
|
+
isDeleted: zod.z.boolean(),
|
|
641
|
+
isPinned: zod.z.boolean(),
|
|
642
|
+
isUnPinned: zod.z.boolean(),
|
|
643
|
+
isChannel: zod.z.boolean(),
|
|
644
|
+
isBroadcast: zod.z.boolean(),
|
|
645
|
+
isEphemeral: zod.z.boolean(),
|
|
646
|
+
isForwarded: zod.z.boolean(),
|
|
647
|
+
citation: zod.z.record(zod.z.string(), zod.z.boolean()).nullable(),
|
|
648
|
+
media: zod.z.object({
|
|
649
|
+
buffer: zod.z.function(),
|
|
650
|
+
stream: zod.z.function()
|
|
651
|
+
}).loose().nullable(),
|
|
652
|
+
message: zod.z.function({
|
|
653
|
+
input: [],
|
|
654
|
+
output: zod.z.record(zod.z.string(), zod.z.any())
|
|
655
|
+
}),
|
|
656
|
+
get replied() {
|
|
657
|
+
return ExtractorMessagesType.nullable();
|
|
658
|
+
}
|
|
659
|
+
});
|
|
660
|
+
var limiterCache = new NodeCache2__default.default({ stdTTL: 60 * 60 });
|
|
661
|
+
var LimiterHandler = async (key, max, ms) => {
|
|
662
|
+
try {
|
|
663
|
+
if (max <= 0) {
|
|
664
|
+
return false;
|
|
665
|
+
}
|
|
666
|
+
const state = limiterCache.get(key);
|
|
667
|
+
const now = Date.now();
|
|
668
|
+
if (!state || now - state.firstRequestTime > ms) {
|
|
669
|
+
const newState2 = {
|
|
670
|
+
count: 1,
|
|
671
|
+
firstRequestTime: now
|
|
672
|
+
};
|
|
673
|
+
limiterCache.set(key, newState2, Math.ceil(ms / 1e3) + 10);
|
|
674
|
+
return false;
|
|
675
|
+
}
|
|
676
|
+
const newState = {
|
|
677
|
+
count: state.count + 1,
|
|
678
|
+
firstRequestTime: state.firstRequestTime
|
|
679
|
+
};
|
|
680
|
+
limiterCache.set(key, newState, Math.ceil((ms - (now - state.firstRequestTime)) / 1e3) + 10);
|
|
681
|
+
if (newState.count > max) {
|
|
682
|
+
return true;
|
|
683
|
+
}
|
|
684
|
+
return false;
|
|
685
|
+
} catch (err) {
|
|
686
|
+
console.error("Error detecting spam:", err);
|
|
687
|
+
return false;
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
|
|
691
|
+
// src/extractor/messages.ts
|
|
692
|
+
var MessagesExtractor = async (client, message) => {
|
|
693
|
+
let MAX_REPLIES = 0;
|
|
694
|
+
const CLONE = message;
|
|
695
|
+
const extract = async (obj, isReplied, isExtract) => {
|
|
696
|
+
let msg = toJson(obj);
|
|
697
|
+
if (!msg.message || !msg?.key?.id) {
|
|
698
|
+
return null;
|
|
699
|
+
}
|
|
700
|
+
if (msg?.messageStubType || !!msg?.messageStubParameters || msg?.message?.botInvokeMessage || msg.message?.protocolMessage?.peerDataOperationRequestResponseMessage) {
|
|
701
|
+
return null;
|
|
702
|
+
}
|
|
703
|
+
if (msg?.key?.fromMe && !msg?.participant && msg?.key?.remoteJid != "status@broadcast" && client.props?.ignoreMe && !MAX_REPLIES && true) {
|
|
704
|
+
return null;
|
|
705
|
+
}
|
|
706
|
+
const pinId = msg?.message?.pinInChatMessage?.key?.id;
|
|
707
|
+
const isPinned = msg?.message?.pinInChatMessage?.type == 1;
|
|
708
|
+
const isUnPinned = msg?.message?.pinInChatMessage?.type == 2;
|
|
709
|
+
if (pinId && client.db) {
|
|
710
|
+
const read = await client.db.store("messages").read(pinId);
|
|
711
|
+
msg = read;
|
|
712
|
+
}
|
|
713
|
+
const protocolId = !msg?.message?.protocolMessage?.editedMessage && msg?.message?.protocolMessage?.key?.id;
|
|
714
|
+
const isDeleted = !!protocolId;
|
|
715
|
+
if (protocolId && client.db) {
|
|
716
|
+
const read = await client.db.store("messages").read(protocolId);
|
|
717
|
+
msg = read;
|
|
718
|
+
}
|
|
719
|
+
const edited = msg?.message?.protocolMessage?.editedMessage || msg?.message?.editedMessage;
|
|
720
|
+
if (edited) {
|
|
721
|
+
const id = edited?.message?.protocolMessage?.key?.id;
|
|
722
|
+
if (id && client.db) {
|
|
723
|
+
const read3 = await client.db.store("messages").read(id);
|
|
724
|
+
const editType = makeWASocket.getContentType(edited?.message?.protocolMessage?.editedMessage);
|
|
725
|
+
const readType = makeWASocket.getContentType(read3?.message);
|
|
726
|
+
let editing = void 0;
|
|
727
|
+
if (editType && edited?.message?.protocolMessage?.editedMessage) {
|
|
728
|
+
editing = edited.message.protocolMessage.editedMessage[editType];
|
|
729
|
+
if (readType && read3?.message) {
|
|
730
|
+
read3.message[readType] = _2__default.default.merge(read3.message[readType], editing);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
msg = read3 || msg;
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
const contentType = makeWASocket.getContentType(msg?.message?.protocolMessage?.editedMessage || msg?.message);
|
|
737
|
+
if (!contentType) return null;
|
|
738
|
+
const payload = {};
|
|
739
|
+
payload.chatId = msg?.message?.protocolMessage?.key?.id || msg?.key?.id || "";
|
|
740
|
+
payload.channelId = "";
|
|
741
|
+
payload.uniqueId = "";
|
|
742
|
+
payload.receiverId = makeWASocket.jidNormalizedUser(client.socket?.user?.id || "");
|
|
743
|
+
payload.receiverName = client.socket?.user?.name || client.socket?.user?.verifiedName || "";
|
|
744
|
+
payload.roomId = makeWASocket.jidNormalizedUser(message?.key?.remoteJid || "");
|
|
745
|
+
if (client.db) {
|
|
746
|
+
const roomName = await client.db.store("chats").read(payload.roomId);
|
|
747
|
+
payload.roomName = toJson(roomName)?.name || "";
|
|
748
|
+
}
|
|
749
|
+
payload.senderLid = msg?.message?.protocolMessage?.key?.senderLid || msg?.key?.senderLid || msg?.key?.participantLid || "";
|
|
750
|
+
payload.senderId = makeWASocket.jidNormalizedUser(msg?.participant || msg?.key?.participant || msg?.key?.remoteJid);
|
|
751
|
+
if (client.db) {
|
|
752
|
+
const senderName = await client.db.store("chats").read(payload.senderId);
|
|
753
|
+
payload.senderLid = payload.senderLid || toJson(senderName)?.lidJid || "";
|
|
754
|
+
payload.senderName = msg?.pushName || msg?.verifiedBizName || toJson(senderName)?.name || payload.receiverName;
|
|
755
|
+
}
|
|
756
|
+
payload.senderDevice = makeWASocket.getDevice(payload.chatId);
|
|
757
|
+
if (payload.senderId == payload.receiverId) {
|
|
758
|
+
payload.senderName = payload.receiverName;
|
|
759
|
+
}
|
|
760
|
+
payload.roomName = payload.roomName || payload.senderName || _2__default.default.split(payload.roomId || "", "@")[0];
|
|
761
|
+
payload.chatType = MessagesMediaType[contentType];
|
|
762
|
+
payload.timestamp = Number(msg?.messageTimestamp || 0);
|
|
763
|
+
payload.text = null;
|
|
764
|
+
payload.mentions = [];
|
|
765
|
+
payload.links = [];
|
|
766
|
+
payload.isPrefix = false;
|
|
767
|
+
payload.isSpam = false;
|
|
768
|
+
payload.isFromMe = message?.key?.fromMe || false;
|
|
769
|
+
payload.isTagMe = false;
|
|
770
|
+
payload.isGroup = _2__default.default.includes(payload.roomId, "@g.us");
|
|
771
|
+
payload.isStory = _2__default.default.includes(payload.roomId, "@broadcast");
|
|
772
|
+
payload.isViewOnce = false;
|
|
773
|
+
payload.isEdited = false;
|
|
774
|
+
payload.isDeleted = isDeleted;
|
|
775
|
+
payload.isPinned = isPinned;
|
|
776
|
+
payload.isUnPinned = isUnPinned;
|
|
777
|
+
payload.isChannel = _2__default.default.includes(payload.roomId, "@newsletter");
|
|
778
|
+
payload.isBroadcast = !!message?.broadcast;
|
|
779
|
+
payload.isEphemeral = false;
|
|
780
|
+
payload.isForwarded = false;
|
|
781
|
+
if (!isReplied && true) {
|
|
782
|
+
const limiter = await LimiterHandler(payload.roomId, client.props.limiter?.maxMessages || 3, client.props.limiter?.durationMs || 5e3);
|
|
783
|
+
payload.isSpam = limiter;
|
|
784
|
+
}
|
|
785
|
+
if (payload.isFromMe) {
|
|
786
|
+
payload.senderId = payload.receiverId;
|
|
787
|
+
payload.senderName = payload.receiverName;
|
|
788
|
+
}
|
|
789
|
+
payload.citation = null;
|
|
790
|
+
payload.media = null;
|
|
791
|
+
payload.replied = null;
|
|
792
|
+
payload.channelId = _2__default.default.join([_2__default.default.split(payload.roomId, "@")[0], _2__default.default.split(payload.senderId, "@")[0]], "-");
|
|
793
|
+
payload.uniqueId = _2__default.default.join([payload.channelId, payload.chatId], "-");
|
|
794
|
+
const citation = client.props?.citation || {};
|
|
795
|
+
if (Object.keys(citation).length) {
|
|
796
|
+
payload.citation = {};
|
|
797
|
+
for (const key of Object.keys(citation)) {
|
|
798
|
+
const slug = "is" + _2__default.default.upperFirst(_2__default.default.camelCase(key));
|
|
799
|
+
const citationEntry = citation[key];
|
|
800
|
+
if (citationEntry && Array.isArray(citationEntry)) {
|
|
801
|
+
const senderId = payload.senderId.split("@")[0];
|
|
802
|
+
const roomId = payload.roomId.split("@")[0];
|
|
803
|
+
const citationRecord = citation;
|
|
804
|
+
payload.citation[slug] = (senderId ? (citationRecord[key] || []).includes(Number(senderId)) : false) || (roomId ? (citationRecord[key] || []).includes(Number(roomId)) : false);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
const media = msg?.message?.editedMessage?.[contentType] || msg?.message?.protocolMessage?.editedMessage?.[contentType] || msg?.message?.[contentType]?.message?.documentMessage || msg?.message?.[contentType];
|
|
809
|
+
if (payload.chatType != "text") {
|
|
810
|
+
payload.media = {
|
|
811
|
+
..._2__default.default.omit(media, [
|
|
812
|
+
"url",
|
|
813
|
+
"contextInfo",
|
|
814
|
+
"fileSha256",
|
|
815
|
+
"fileEncSha256",
|
|
816
|
+
"mediaKey",
|
|
817
|
+
"directPath",
|
|
818
|
+
"waveform",
|
|
819
|
+
"thumbnail",
|
|
820
|
+
"jpegThumbnail",
|
|
821
|
+
"thumbnailEncSha256",
|
|
822
|
+
"thumbnailSha256",
|
|
823
|
+
"thumbnailDirectPath",
|
|
824
|
+
"firstFrameSidecar",
|
|
825
|
+
"streamingSidecar",
|
|
826
|
+
"scansSidecar",
|
|
827
|
+
"callKey",
|
|
828
|
+
"message",
|
|
829
|
+
"key",
|
|
830
|
+
"midQualityFileSha256"
|
|
831
|
+
]),
|
|
832
|
+
buffer: () => makeWASocket.downloadMediaMessage(message, "buffer", {}),
|
|
833
|
+
stream: () => makeWASocket.downloadMediaMessage(message, "stream", {})
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
const repliedId = toJson(msg?.message?.[contentType])?.contextInfo?.stanzaId;
|
|
837
|
+
if (repliedId && MAX_REPLIES < 1 && client.db) {
|
|
838
|
+
MAX_REPLIES++;
|
|
839
|
+
const replied = await client.db.store("messages").read(repliedId);
|
|
840
|
+
if (!replied) {
|
|
841
|
+
payload.replied = await extract(msg, true);
|
|
842
|
+
} else {
|
|
843
|
+
payload.replied = await extract(replied, true);
|
|
844
|
+
}
|
|
845
|
+
MAX_REPLIES = 0;
|
|
846
|
+
}
|
|
847
|
+
const text = typeof media == "string" ? media : media?.text || media?.caption || media?.name || media?.displayName || media?.conversation || media?.contentText || media?.selectedDisplayText || "";
|
|
848
|
+
payload.text = normalizeText(text) || "";
|
|
849
|
+
payload.mentions = getMentions(payload.text || "");
|
|
850
|
+
payload.links = extractUrls(payload.text || "");
|
|
851
|
+
const messaging = toJson(msg?.message?.[contentType]);
|
|
852
|
+
payload.isPrefix = !!(client.props?.prefix && _2__default.default.startsWith(payload.text, client.props?.prefix));
|
|
853
|
+
payload.isTagMe = _2__default.default.includes(payload.mentions, _2__default.default.split(payload.receiverId, "@")[0] || "");
|
|
854
|
+
payload.isEdited = !!edited;
|
|
855
|
+
payload.isEphemeral = !!findWord(toString(messaging?.contextInfo), "ephemeralSettingTimestamp");
|
|
856
|
+
payload.isForwarded = !!findWord(toString(messaging?.contextInfo), "forwardingScore");
|
|
857
|
+
payload.isViewOnce = !!messaging?.viewOnce;
|
|
858
|
+
if (payload.isPrefix) {
|
|
859
|
+
payload.text = _2__default.default.replace(payload.text, new RegExp(`^${client.props?.prefix}`), "");
|
|
860
|
+
}
|
|
861
|
+
payload.message = () => CLONE;
|
|
862
|
+
return payload;
|
|
863
|
+
};
|
|
864
|
+
return extract(message);
|
|
865
|
+
};
|
|
866
|
+
var Listener = class {
|
|
867
|
+
client;
|
|
868
|
+
async bind(client, db) {
|
|
869
|
+
this.client = client;
|
|
870
|
+
this.client.db = db;
|
|
871
|
+
this.client.socket?.ev.on("connection.update", async (update) => {
|
|
872
|
+
await this.connection(update);
|
|
873
|
+
});
|
|
874
|
+
this.client.socket?.ev.on("messages.upsert", async ({ messages }) => {
|
|
875
|
+
for (const message of messages) {
|
|
876
|
+
await this.messages(message);
|
|
877
|
+
}
|
|
878
|
+
});
|
|
879
|
+
this.client.socket?.ev.on("call", async (callers) => {
|
|
880
|
+
for (const caller of callers) {
|
|
881
|
+
await this.calls(caller);
|
|
882
|
+
}
|
|
883
|
+
});
|
|
884
|
+
this.client.socket?.ev.on("creds.update", () => {
|
|
885
|
+
});
|
|
886
|
+
if (this.client.socket?.ws) {
|
|
887
|
+
const originalEmit = this.client.socket.ws.emit.bind(this.client.socket.ws);
|
|
888
|
+
this.client.socket.ws.emit = (event, ...args) => {
|
|
889
|
+
if (event === "error" && args[0]) {
|
|
890
|
+
const errorMessage = args[0].message || args[0]?.toString();
|
|
891
|
+
if (_2__default.default.includes(errorMessage, "Closing open session in favor of incoming prekey bundle") || _2__default.default.includes(errorMessage, "Closing stale open session for new outgoing prekey bundle") || _2__default.default.includes(errorMessage, "Closing session: SessionEntry")) {
|
|
892
|
+
this.handleSessionClosing();
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
return originalEmit(event, ...args);
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
async handleSessionClosing() {
|
|
900
|
+
this.client.spinner.start("Processing session changes...");
|
|
901
|
+
await makeWASocket.delay(3e3);
|
|
902
|
+
this.client.spinner.success("Session processing completed");
|
|
903
|
+
}
|
|
904
|
+
async connection(update) {
|
|
905
|
+
const { connection, lastDisconnect, qr } = update;
|
|
906
|
+
this.client.emit("connection", { status: "connecting" });
|
|
907
|
+
if (this.client.props.authType === "qr" && qr) {
|
|
908
|
+
this.client.spinner.info(`Please scan the QR
|
|
909
|
+
|
|
910
|
+
${await QRCode__default.default.toString(qr, { type: "terminal", small: true })}`);
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
if (connection === "close") {
|
|
914
|
+
const code = toJson(lastDisconnect?.error)?.output?.statusCode;
|
|
915
|
+
const errorMessage = lastDisconnect?.error?.message || "";
|
|
916
|
+
const isReconnect = typeof code === "number" && code !== makeWASocket.DisconnectReason.loggedOut;
|
|
917
|
+
if (_2__default.default.includes(errorMessage, "Closing open session in favor of incoming prekey bundle") || _2__default.default.includes(errorMessage, "Closing stale open session for new outgoing prekey bundle") || _2__default.default.includes(errorMessage, "Closing session: SessionEntry")) {
|
|
918
|
+
this.client.spinner.start("Processing session changes...");
|
|
919
|
+
await new Promise((resolve) => setTimeout(resolve, 2e3));
|
|
920
|
+
this.client.spinner.success("Session processing completed");
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
923
|
+
this.client.spinner.error(`[Connection Closed] [${code}] ${errorMessage}`);
|
|
924
|
+
if (code === 401 || code === 405 || code === 500) {
|
|
925
|
+
this.client.spinner.error("Invalid session, please delete manually");
|
|
926
|
+
this.client.spinner.error(`Session "${this.client.props.session}" has not valid, please delete it`);
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
if (isReconnect) {
|
|
930
|
+
this.client.spinner.warn("Connection lost. Attempting auto-reload...");
|
|
931
|
+
const clientRecord = this.client;
|
|
932
|
+
if (typeof clientRecord.autoReload === "function") {
|
|
933
|
+
await clientRecord.autoReload();
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
} else if (connection === "open") {
|
|
937
|
+
if (this.client.socket?.user) {
|
|
938
|
+
const id = makeWASocket.jidNormalizedUser(this.client.socket.user.id).split("@")[0];
|
|
939
|
+
const name = this.client.socket.user.name || this.client.socket.user.verifiedName;
|
|
940
|
+
const clientRecord = this.client;
|
|
941
|
+
if (typeof clientRecord.resetRetryCount === "function") {
|
|
942
|
+
clientRecord.resetRetryCount();
|
|
943
|
+
}
|
|
944
|
+
this.client.spinner.success(`Connected as ${chalk__default.default.green(name || id)}`);
|
|
945
|
+
this.client.emit("connection", { status: "open" });
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
async messages(message) {
|
|
950
|
+
if (this.client.props?.autoRead && this.client.socket) {
|
|
951
|
+
if (message?.key) {
|
|
952
|
+
await this.client.socket.readMessages([message.key]);
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
const extract = await MessagesExtractor(this.client, message);
|
|
956
|
+
if (extract) {
|
|
957
|
+
this.client.emit("messages", extract);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
async calls(caller) {
|
|
961
|
+
if (this.client.props?.autoRejectCall && this.client.socket) {
|
|
962
|
+
await this.client.socket.rejectCall(caller.id, caller.from);
|
|
963
|
+
}
|
|
964
|
+
const extract = await CallsExtractor(this.client, caller);
|
|
965
|
+
this.client.emit("calls", extract);
|
|
966
|
+
}
|
|
967
|
+
};
|
|
968
|
+
var RelayTextType = z2.z.string().or(z2.z.object({
|
|
969
|
+
text: z2.z.string(),
|
|
970
|
+
roomId: z2.z.string().optional(),
|
|
971
|
+
options: z2.z.custom().optional(),
|
|
972
|
+
externalAdReply: AdsReplyType.optional()
|
|
973
|
+
}));
|
|
974
|
+
var RelayReplyType = z2.z.string().or(
|
|
975
|
+
z2.z.object({
|
|
976
|
+
text: z2.z.string(),
|
|
977
|
+
roomId: z2.z.string().optional(),
|
|
978
|
+
options: z2.z.custom().optional(),
|
|
979
|
+
externalAdReply: AdsReplyType.optional()
|
|
980
|
+
})
|
|
981
|
+
);
|
|
982
|
+
var RelayForwardType = z2.z.string().or(
|
|
983
|
+
z2.z.object({
|
|
984
|
+
text: z2.z.string(),
|
|
985
|
+
isForwardMany: defaultBoolean(false),
|
|
986
|
+
roomId: z2.z.string().optional(),
|
|
987
|
+
options: z2.z.custom().optional(),
|
|
988
|
+
externalAdReply: AdsReplyType.optional()
|
|
989
|
+
})
|
|
990
|
+
);
|
|
991
|
+
var RelayImageEnumType = z2.z.enum(["text", "reply", "forward"]);
|
|
992
|
+
var RelayImageType = z2.z.object({
|
|
993
|
+
image: z2.z.url().or(z2.z.base64()).or(z2.z.instanceof(Buffer)),
|
|
994
|
+
text: z2.z.string().optional(),
|
|
995
|
+
viewOnce: defaultBoolean(false),
|
|
996
|
+
roomId: z2.z.string().optional(),
|
|
997
|
+
externalAdReply: AdsReplyType.optional()
|
|
998
|
+
});
|
|
999
|
+
var RelayVideoEnumType = z2.z.enum(["text", "reply", "forward"]);
|
|
1000
|
+
var RelayVideoType = z2.z.object({
|
|
1001
|
+
video: z2.z.url().or(z2.z.base64()).or(z2.z.instanceof(Buffer)),
|
|
1002
|
+
text: z2.z.string().optional(),
|
|
1003
|
+
viewOnce: defaultBoolean(false),
|
|
1004
|
+
roomId: z2.z.string().optional()
|
|
1005
|
+
});
|
|
1006
|
+
var RelayAudioEnumType = z2.z.enum(["text", "reply", "forward"]);
|
|
1007
|
+
var RelayAudioType = z2.z.object({
|
|
1008
|
+
audio: z2.z.url().or(z2.z.base64()).or(z2.z.instanceof(Buffer)),
|
|
1009
|
+
viewOnce: defaultBoolean(false),
|
|
1010
|
+
roomId: z2.z.string().optional(),
|
|
1011
|
+
externalAdReply: AdsReplyType.optional()
|
|
1012
|
+
});
|
|
1013
|
+
var RelayStickerEnumType = z2.z.enum(["text", "reply", "forward"]);
|
|
1014
|
+
var RelayStickerType = z2.z.object({
|
|
1015
|
+
sticker: z2.z.url().or(z2.z.base64()).or(z2.z.instanceof(Buffer)),
|
|
1016
|
+
roomId: z2.z.string().optional()
|
|
1017
|
+
});
|
|
1018
|
+
var RelayEditType = z2.z.object({
|
|
1019
|
+
text: z2.z.string(),
|
|
1020
|
+
message: z2.z.function({
|
|
1021
|
+
input: [],
|
|
1022
|
+
output: z2.z.any()
|
|
1023
|
+
}).optional()
|
|
1024
|
+
});
|
|
1025
|
+
var RelayDeleteType = z2.z.object({
|
|
1026
|
+
message: z2.z.function({
|
|
1027
|
+
input: [],
|
|
1028
|
+
output: z2.z.any()
|
|
1029
|
+
}).optional()
|
|
1030
|
+
});
|
|
1031
|
+
var ExtractorCallsType = z2.z.object({
|
|
1032
|
+
callId: z2.z.string(),
|
|
1033
|
+
roomId: z2.z.string(),
|
|
1034
|
+
callerId: z2.z.string(),
|
|
1035
|
+
date: z2.z.date(),
|
|
1036
|
+
offline: z2.z.boolean(),
|
|
1037
|
+
status: z2.z.enum(["accept", "offer", "reject", "ringing", "terminate", "timeout"]),
|
|
1038
|
+
isVideo: z2.z.boolean(),
|
|
1039
|
+
isGroup: z2.z.boolean()
|
|
1040
|
+
});
|
|
1041
|
+
|
|
1042
|
+
// src/types/relay/reject.ts
|
|
1043
|
+
var RelayRejectType = ExtractorCallsType.pick({
|
|
1044
|
+
callId: true,
|
|
1045
|
+
callerId: true
|
|
1046
|
+
});
|
|
1047
|
+
var RelayPresenceType = z2.z.enum(["typing", "recording", "online", "offline", "paused"]);
|
|
1048
|
+
var RelayReactionType = z2.z.emoji().or(
|
|
1049
|
+
z2.z.object({
|
|
1050
|
+
emoticon: z2.z.emoji(),
|
|
1051
|
+
message: z2.z.function({
|
|
1052
|
+
input: [],
|
|
1053
|
+
output: z2.z.any()
|
|
1054
|
+
}).optional()
|
|
1055
|
+
})
|
|
1056
|
+
);
|
|
1057
|
+
var RelayLocationEnumType = z2.z.enum(["text", "reply", "forward"]);
|
|
1058
|
+
var RelayLocationType = z2.z.object({
|
|
1059
|
+
latitude: z2.z.number(),
|
|
1060
|
+
longitude: z2.z.number(),
|
|
1061
|
+
title: z2.z.string().optional(),
|
|
1062
|
+
footer: z2.z.string().optional(),
|
|
1063
|
+
roomId: z2.z.string().optional(),
|
|
1064
|
+
externalAdReply: AdsReplyType.optional()
|
|
1065
|
+
});
|
|
1066
|
+
var RelayContactEnumType = z2.z.enum(["text", "reply", "forward"]);
|
|
1067
|
+
var RelayContactType = z2.z.object({
|
|
1068
|
+
title: z2.z.string().optional(),
|
|
1069
|
+
contacts: z2.z.object({
|
|
1070
|
+
fullname: z2.z.string(),
|
|
1071
|
+
nickname: z2.z.string().optional(),
|
|
1072
|
+
organization: z2.z.string().optional(),
|
|
1073
|
+
phoneNumber: z2.z.number(),
|
|
1074
|
+
website: z2.z.url().optional()
|
|
1075
|
+
}).array(),
|
|
1076
|
+
roomId: z2.z.string().optional()
|
|
1077
|
+
});
|
|
1078
|
+
var RelayPollEnumType = z2.z.enum(["text", "reply", "forward"]);
|
|
1079
|
+
var RelayPollCreateType = z2.z.object({
|
|
1080
|
+
action: z2.z.literal("create"),
|
|
1081
|
+
name: z2.z.string(),
|
|
1082
|
+
answers: z2.z.string().array(),
|
|
1083
|
+
isMultiple: defaultBoolean(false),
|
|
1084
|
+
roomId: z2.z.string().optional()
|
|
1085
|
+
});
|
|
1086
|
+
z2.z.object({
|
|
1087
|
+
action: z2.z.literal("result"),
|
|
1088
|
+
name: z2.z.string(),
|
|
1089
|
+
votes: z2.z.tuple([z2.z.string(), z2.z.number()]).array(),
|
|
1090
|
+
roomId: z2.z.string().optional()
|
|
1091
|
+
});
|
|
1092
|
+
var RelayPollType = z2.z.discriminatedUnion("action", [RelayPollCreateType]);
|
|
1093
|
+
var RelayDocumentEnumType = z2.z.enum(["text", "reply", "forward"]);
|
|
1094
|
+
var RelayDocumentType = z2.z.object({
|
|
1095
|
+
document: z2.z.url().or(z2.z.base64()).or(z2.z.instanceof(Buffer)),
|
|
1096
|
+
mimetype: z2.z.string(),
|
|
1097
|
+
text: z2.z.string().optional(),
|
|
1098
|
+
fileName: z2.z.string().optional(),
|
|
1099
|
+
roomId: z2.z.string().optional(),
|
|
1100
|
+
externalAdReply: AdsReplyType.optional()
|
|
1101
|
+
});
|
|
1102
|
+
var RelayButtonEnumType = z2.z.enum(["text", "reply", "forward"]);
|
|
1103
|
+
var RelayButtonSimpleType = z2.z.object({
|
|
1104
|
+
type: z2.z.literal("simple"),
|
|
1105
|
+
text: z2.z.string(),
|
|
1106
|
+
footer: z2.z.string().optional(),
|
|
1107
|
+
buttons: z2.z.object({
|
|
1108
|
+
id: z2.z.string(),
|
|
1109
|
+
text: z2.z.string()
|
|
1110
|
+
}).array(),
|
|
1111
|
+
roomId: z2.z.string().optional()
|
|
1112
|
+
});
|
|
1113
|
+
var RelayButtonInteractiveReplyType = z2.z.object({
|
|
1114
|
+
type: z2.z.literal("quick_reply"),
|
|
1115
|
+
id: z2.z.string(),
|
|
1116
|
+
text: z2.z.string()
|
|
1117
|
+
});
|
|
1118
|
+
var RelayButtonInteractiveUrlType = z2.z.object({
|
|
1119
|
+
type: z2.z.literal("cta_url"),
|
|
1120
|
+
id: z2.z.string(),
|
|
1121
|
+
url: z2.z.url(),
|
|
1122
|
+
text: z2.z.string()
|
|
1123
|
+
});
|
|
1124
|
+
var RelayButtonInteractiveCopyType = z2.z.object({
|
|
1125
|
+
type: z2.z.literal("cta_copy"),
|
|
1126
|
+
id: z2.z.string(),
|
|
1127
|
+
copy: z2.z.string(),
|
|
1128
|
+
text: z2.z.string()
|
|
1129
|
+
});
|
|
1130
|
+
var RelayButtonInteractiveCallType = z2.z.object({
|
|
1131
|
+
type: z2.z.literal("cta_call"),
|
|
1132
|
+
id: z2.z.string(),
|
|
1133
|
+
phoneNumber: z2.z.string(),
|
|
1134
|
+
text: z2.z.string()
|
|
1135
|
+
});
|
|
1136
|
+
var RelayButtonInteractiveType = z2.z.object({
|
|
1137
|
+
type: z2.z.literal("interactive"),
|
|
1138
|
+
text: z2.z.string(),
|
|
1139
|
+
footer: z2.z.string().optional(),
|
|
1140
|
+
buttons: z2.z.discriminatedUnion("type", [RelayButtonInteractiveReplyType, RelayButtonInteractiveUrlType, RelayButtonInteractiveCopyType, RelayButtonInteractiveCallType]).array(),
|
|
1141
|
+
roomId: z2.z.string().optional()
|
|
1142
|
+
});
|
|
1143
|
+
z2.z.object({
|
|
1144
|
+
type: z2.z.literal("list"),
|
|
1145
|
+
text: z2.z.string(),
|
|
1146
|
+
footer: z2.z.string(),
|
|
1147
|
+
roomId: z2.z.string().optional()
|
|
1148
|
+
});
|
|
1149
|
+
var RelayButtonType = z2.z.discriminatedUnion("type", [RelayButtonSimpleType, RelayButtonInteractiveType]);
|
|
1150
|
+
var RelayGroupCreateType = z2.z.object({
|
|
1151
|
+
title: z2.z.string(),
|
|
1152
|
+
members: z2.z.string().array()
|
|
1153
|
+
});
|
|
1154
|
+
var RelayGroupActionType = z2.z.object({
|
|
1155
|
+
roomId: z2.z.string(),
|
|
1156
|
+
action: z2.z.enum(["add", "kick", "promote", "demote"]),
|
|
1157
|
+
members: z2.z.string().array()
|
|
1158
|
+
});
|
|
1159
|
+
var RelayGroupUpdateType = z2.z.object({
|
|
1160
|
+
roomId: z2.z.string(),
|
|
1161
|
+
text: z2.z.string(),
|
|
1162
|
+
action: z2.z.enum(["subject", "description"])
|
|
1163
|
+
});
|
|
1164
|
+
var RelayGroupSettingsType = z2.z.object({
|
|
1165
|
+
roomId: z2.z.string(),
|
|
1166
|
+
action: z2.z.enum(["open", "close", "lock", "unlock"])
|
|
1167
|
+
});
|
|
1168
|
+
var RelayGroupLeaveType = z2.z.object({
|
|
1169
|
+
roomId: z2.z.string()
|
|
1170
|
+
});
|
|
1171
|
+
var RelayGroupLinksType = z2.z.object({
|
|
1172
|
+
roomId: z2.z.string(),
|
|
1173
|
+
action: z2.z.enum(["get", "revoke"])
|
|
1174
|
+
});
|
|
1175
|
+
var RelayGroupInviteType = z2.z.object({
|
|
1176
|
+
url: z2.z.url().regex(/^https:\/\/chat\.whatsapp\.com\/[A-Za-z0-9_-]{5,}$/),
|
|
1177
|
+
action: z2.z.enum(["join", "info"])
|
|
1178
|
+
});
|
|
1179
|
+
var RelayGroupRequestsListType = z2.z.object({
|
|
1180
|
+
roomId: z2.z.string()
|
|
1181
|
+
});
|
|
1182
|
+
var RelayGroupRequestsApproveType = z2.z.object({
|
|
1183
|
+
roomId: z2.z.string(),
|
|
1184
|
+
members: z2.z.string().array()
|
|
1185
|
+
});
|
|
1186
|
+
var RelayGroupRequestsRejectType = z2.z.object({
|
|
1187
|
+
roomId: z2.z.string(),
|
|
1188
|
+
members: z2.z.string().array()
|
|
1189
|
+
});
|
|
1190
|
+
var RelayGroupMetadataType = z2.z.object({
|
|
1191
|
+
roomId: z2.z.string()
|
|
1192
|
+
});
|
|
1193
|
+
var RelayPrivacyUpdateControlType = z2.z.object({
|
|
1194
|
+
action: z2.z.literal("control"),
|
|
1195
|
+
type: z2.z.enum(["block", "unblock"]),
|
|
1196
|
+
senderId: z2.z.string()
|
|
1197
|
+
});
|
|
1198
|
+
var RelayPrivacyUpdateLastSeenType = z2.z.object({
|
|
1199
|
+
action: z2.z.literal("lastSeen"),
|
|
1200
|
+
type: z2.z.enum(["all", "contacts", "contact_blacklist", "none"])
|
|
1201
|
+
});
|
|
1202
|
+
var RelayPrivacyUpdateOnlineType = z2.z.object({
|
|
1203
|
+
action: z2.z.literal("online"),
|
|
1204
|
+
type: z2.z.enum(["all", "match_last_seen"])
|
|
1205
|
+
});
|
|
1206
|
+
var RelayPrivacyUpdateAvatarType = z2.z.object({
|
|
1207
|
+
action: z2.z.literal("avatar"),
|
|
1208
|
+
type: z2.z.enum(["all", "contacts", "contact_blacklist", "none"])
|
|
1209
|
+
});
|
|
1210
|
+
var RelayPrivacyUpdateStoryType = z2.z.object({
|
|
1211
|
+
action: z2.z.literal("story"),
|
|
1212
|
+
type: z2.z.enum(["all", "contacts", "contact_blacklist", "none"])
|
|
1213
|
+
});
|
|
1214
|
+
var RelayPrivacyUpdateReadType = z2.z.object({
|
|
1215
|
+
action: z2.z.literal("read"),
|
|
1216
|
+
type: z2.z.enum(["all", "none"])
|
|
1217
|
+
});
|
|
1218
|
+
var RelayPrivacyGroupsAddType = z2.z.object({
|
|
1219
|
+
action: z2.z.literal("groupsAdd"),
|
|
1220
|
+
type: z2.z.enum(["all", "contacts", "contact_blacklist"])
|
|
1221
|
+
});
|
|
1222
|
+
var RelayPrivacyEphemeralType = z2.z.object({
|
|
1223
|
+
action: z2.z.literal("ephemeral"),
|
|
1224
|
+
type: z2.z.enum(["remove", "24h", "7d", "90d"])
|
|
1225
|
+
});
|
|
1226
|
+
var RelayPrivacyUpdateType = z2.z.discriminatedUnion("action", [
|
|
1227
|
+
RelayPrivacyUpdateControlType,
|
|
1228
|
+
RelayPrivacyUpdateLastSeenType,
|
|
1229
|
+
RelayPrivacyUpdateOnlineType,
|
|
1230
|
+
RelayPrivacyUpdateAvatarType,
|
|
1231
|
+
RelayPrivacyUpdateStoryType,
|
|
1232
|
+
RelayPrivacyUpdateReadType,
|
|
1233
|
+
RelayPrivacyGroupsAddType,
|
|
1234
|
+
RelayPrivacyEphemeralType
|
|
1235
|
+
]);
|
|
1236
|
+
var RelayProfileBioType = z2.z.object({
|
|
1237
|
+
senderId: z2.z.string()
|
|
1238
|
+
});
|
|
1239
|
+
var RelayProfileUpdateType = z2.z.object({
|
|
1240
|
+
type: z2.z.enum(["name", "bio", "avatar"]),
|
|
1241
|
+
text: z2.z.string().optional(),
|
|
1242
|
+
roomId: z2.z.string().optional(),
|
|
1243
|
+
avatar: z2.z.url().or(z2.z.base64()).or(z2.z.instanceof(Buffer)).or(z2.z.literal("remove"))
|
|
1244
|
+
});
|
|
1245
|
+
var RelayProfileCheckType = z2.z.object({
|
|
1246
|
+
senderId: z2.z.string()
|
|
1247
|
+
});
|
|
1248
|
+
|
|
1249
|
+
// src/classes/Relay.ts
|
|
1250
|
+
var Relay = class {
|
|
1251
|
+
client;
|
|
1252
|
+
message;
|
|
1253
|
+
db;
|
|
1254
|
+
ctx;
|
|
1255
|
+
bind(client, db) {
|
|
1256
|
+
this.client = client;
|
|
1257
|
+
this.db = db;
|
|
1258
|
+
this.ctx = client;
|
|
1259
|
+
this.ctx.db = db;
|
|
1260
|
+
this.client.on("messages", (ctx) => {
|
|
1261
|
+
this.message = ctx;
|
|
1262
|
+
});
|
|
1263
|
+
}
|
|
1264
|
+
async initial(props) {
|
|
1265
|
+
await makeWASocket.delay(0);
|
|
1266
|
+
if (!props?.disabledPresence) {
|
|
1267
|
+
if (this.client.props?.autoPresence && props?.isAudio) {
|
|
1268
|
+
this.client.socket?.sendPresenceUpdate("recording", this.message?.roomId);
|
|
1269
|
+
} else {
|
|
1270
|
+
this.client.socket?.sendPresenceUpdate("composing", this.message?.roomId);
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
// GENERAL RELAY
|
|
1275
|
+
async text(props) {
|
|
1276
|
+
await this.initial();
|
|
1277
|
+
const params = RelayTextType.parse(props);
|
|
1278
|
+
let extend = { contextInfo: {} };
|
|
1279
|
+
if (this.client.props.autoMentions) {
|
|
1280
|
+
extend.contextInfo.mentionedJid = extractJids(this.message.text);
|
|
1281
|
+
}
|
|
1282
|
+
if (typeof params == "string") {
|
|
1283
|
+
if (this.client.socket) {
|
|
1284
|
+
const res = await this.client.socket.sendMessage(this.message?.roomId, {
|
|
1285
|
+
text: params,
|
|
1286
|
+
...extend
|
|
1287
|
+
});
|
|
1288
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
if (typeof params == "object") {
|
|
1292
|
+
const obj = { ...extend, ...params.options };
|
|
1293
|
+
if (params.externalAdReply) {
|
|
1294
|
+
obj.contextInfo = { externalAdReply: params.externalAdReply };
|
|
1295
|
+
}
|
|
1296
|
+
if (this.client.socket) {
|
|
1297
|
+
if (params.text != "$$media$$") {
|
|
1298
|
+
obj.text = params?.text;
|
|
1299
|
+
}
|
|
1300
|
+
const res = await this.client.socket.sendMessage(params?.roomId || this.message?.roomId, obj);
|
|
1301
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
async reply(props) {
|
|
1306
|
+
await this.initial();
|
|
1307
|
+
const params = RelayReplyType.parse(props);
|
|
1308
|
+
const quoted = this.message?.message();
|
|
1309
|
+
let extend = { contextInfo: {} };
|
|
1310
|
+
if (this.client.props.autoMentions) {
|
|
1311
|
+
extend.contextInfo.mentionedJid = extractJids(this.message.text);
|
|
1312
|
+
}
|
|
1313
|
+
if (this.client.props?.fakeReply?.provider) {
|
|
1314
|
+
const provider = this.client.props.fakeReply.provider;
|
|
1315
|
+
if (quoted && quoted.key) {
|
|
1316
|
+
quoted.key.remoteJid = MessagesVerifiedPlatformType[provider];
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
const options = quoted ? { quoted } : void 0;
|
|
1320
|
+
if (typeof params == "string") {
|
|
1321
|
+
if (this.client.socket) {
|
|
1322
|
+
const res = await this.client.socket.sendMessage(this.message?.roomId, { text: params, ...extend }, options);
|
|
1323
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
if (typeof params == "object") {
|
|
1327
|
+
const obj = { ...extend, ...params.options };
|
|
1328
|
+
if (params.externalAdReply) {
|
|
1329
|
+
obj.contextInfo = { externalAdReply: params.externalAdReply };
|
|
1330
|
+
}
|
|
1331
|
+
if (this.client.socket) {
|
|
1332
|
+
if (params.text != "$$media$$") {
|
|
1333
|
+
obj.text = params?.text;
|
|
1334
|
+
}
|
|
1335
|
+
const res = await this.client.socket.sendMessage(params?.roomId || this.message?.roomId, obj, options);
|
|
1336
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
async forward(props) {
|
|
1341
|
+
await this.initial();
|
|
1342
|
+
const params = RelayForwardType.parse(props);
|
|
1343
|
+
const quoted = this.message?.message();
|
|
1344
|
+
let extend = { contextInfo: { isForwarded: true } };
|
|
1345
|
+
if (this.client.props.autoMentions) {
|
|
1346
|
+
extend.contextInfo.mentionedJid = extractJids(this.message.text);
|
|
1347
|
+
}
|
|
1348
|
+
if (this.client.props?.fakeReply?.provider) {
|
|
1349
|
+
const provider = this.client.props.fakeReply.provider;
|
|
1350
|
+
if (quoted && quoted.key) {
|
|
1351
|
+
quoted.key.remoteJid = MessagesVerifiedPlatformType[provider];
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
if (typeof params == "string") {
|
|
1355
|
+
if (this.client.socket) {
|
|
1356
|
+
const res = await this.client.socket.sendMessage(this.message?.roomId, { text: params, ...extend });
|
|
1357
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
if (typeof params == "object") {
|
|
1361
|
+
const obj = { ...extend, ...params.options };
|
|
1362
|
+
if (params.externalAdReply) {
|
|
1363
|
+
obj.contextInfo.externalAdReply = params.externalAdReply;
|
|
1364
|
+
}
|
|
1365
|
+
if (params.isForwardMany) {
|
|
1366
|
+
extend.contextInfo.forwardingScore = 999999;
|
|
1367
|
+
}
|
|
1368
|
+
if (this.client.socket) {
|
|
1369
|
+
if (params.text != "$$media$$") {
|
|
1370
|
+
obj.text = params?.text;
|
|
1371
|
+
}
|
|
1372
|
+
const res = await this.client.socket.sendMessage(params?.roomId || this.message?.roomId, obj);
|
|
1373
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
async edit(props) {
|
|
1378
|
+
await this.initial({ disabledPresence: true });
|
|
1379
|
+
const params = RelayEditType.parse(props);
|
|
1380
|
+
const message = params.message();
|
|
1381
|
+
const res = await this.client.socket.sendMessage(message?.key?.remoteJid, { text: params.text, edit: message?.key });
|
|
1382
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1383
|
+
}
|
|
1384
|
+
async delete(props) {
|
|
1385
|
+
await this.initial({ disabledPresence: true });
|
|
1386
|
+
const params = RelayDeleteType.parse(props);
|
|
1387
|
+
const message = params.message();
|
|
1388
|
+
const res = await this.client.socket.sendMessage(message?.key?.remoteJid, { delete: message?.key });
|
|
1389
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1390
|
+
}
|
|
1391
|
+
async reject(props) {
|
|
1392
|
+
const params = RelayRejectType.parse(props);
|
|
1393
|
+
return await this.client.socket.rejectCall(params.callId, params.callerId);
|
|
1394
|
+
}
|
|
1395
|
+
async presence(props) {
|
|
1396
|
+
await this.initial({ disabledPresence: true });
|
|
1397
|
+
const params = RelayPresenceType.parse(props);
|
|
1398
|
+
const opts = {
|
|
1399
|
+
typing: "composing",
|
|
1400
|
+
recording: "recording",
|
|
1401
|
+
online: "available",
|
|
1402
|
+
offline: "unavailable",
|
|
1403
|
+
paused: "paused"
|
|
1404
|
+
};
|
|
1405
|
+
return await this.client.socket.sendPresenceUpdate(opts[params], this.message.roomId);
|
|
1406
|
+
}
|
|
1407
|
+
async reaction(props) {
|
|
1408
|
+
await this.initial({ disabledPresence: true });
|
|
1409
|
+
const params = RelayReactionType.parse(props);
|
|
1410
|
+
const message = typeof params == "string" ? this.message.message() : params.message();
|
|
1411
|
+
const text = typeof params == "string" ? params : params.emoticon;
|
|
1412
|
+
const res = await this.client.socket.sendMessage(message?.key?.remoteJid, { react: { text, key: message?.key } });
|
|
1413
|
+
return await MessagesExtractor(this.ctx, res);
|
|
1414
|
+
}
|
|
1415
|
+
// MEDIA RELAY
|
|
1416
|
+
async document(type, props) {
|
|
1417
|
+
await this.initial();
|
|
1418
|
+
const enumType = RelayDocumentEnumType.parse(type);
|
|
1419
|
+
const params = RelayDocumentType.parse(props);
|
|
1420
|
+
const options = {
|
|
1421
|
+
document: typeof params.document === "string" ? { url: params.document } : params.document,
|
|
1422
|
+
caption: params.text,
|
|
1423
|
+
mimetype: params.mimetype,
|
|
1424
|
+
fileName: params.fileName,
|
|
1425
|
+
contextInfo: { externalAdReply: params.externalAdReply }
|
|
1426
|
+
};
|
|
1427
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1428
|
+
}
|
|
1429
|
+
async image(type, props) {
|
|
1430
|
+
await this.initial();
|
|
1431
|
+
const enumType = RelayImageEnumType.parse(type);
|
|
1432
|
+
const params = RelayImageType.parse(props);
|
|
1433
|
+
const options = {
|
|
1434
|
+
image: typeof params.image === "string" ? { url: params.image } : params.image,
|
|
1435
|
+
caption: params.text,
|
|
1436
|
+
viewOnce: params.viewOnce,
|
|
1437
|
+
contextInfo: { externalAdReply: params.externalAdReply, isQuestion: true }
|
|
1438
|
+
};
|
|
1439
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1440
|
+
}
|
|
1441
|
+
async sticker(type, props) {
|
|
1442
|
+
await this.initial();
|
|
1443
|
+
const enumType = RelayStickerEnumType.parse(type);
|
|
1444
|
+
const params = RelayStickerType.parse(props);
|
|
1445
|
+
const options = { sticker: typeof params.sticker === "string" ? { url: params.sticker } : params.sticker };
|
|
1446
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1447
|
+
}
|
|
1448
|
+
async video(type, props) {
|
|
1449
|
+
await this.initial();
|
|
1450
|
+
const enumType = RelayVideoEnumType.parse(type);
|
|
1451
|
+
const params = RelayVideoType.parse(props);
|
|
1452
|
+
const options = {
|
|
1453
|
+
video: typeof params.video === "string" ? { url: params.video } : params.video,
|
|
1454
|
+
caption: params.text,
|
|
1455
|
+
viewOnce: params.viewOnce
|
|
1456
|
+
};
|
|
1457
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1458
|
+
}
|
|
1459
|
+
async audio(type, props) {
|
|
1460
|
+
const enumType = RelayAudioEnumType.parse(type);
|
|
1461
|
+
const params = RelayAudioType.parse(props);
|
|
1462
|
+
const options = {
|
|
1463
|
+
audio: typeof params.audio === "string" ? { url: params.audio } : params.audio,
|
|
1464
|
+
viewOnce: params.viewOnce,
|
|
1465
|
+
contextInfo: { externalAdReply: params.externalAdReply }
|
|
1466
|
+
};
|
|
1467
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1468
|
+
}
|
|
1469
|
+
async voice(type, props) {
|
|
1470
|
+
const enumType = RelayAudioEnumType.parse(type);
|
|
1471
|
+
const params = RelayAudioType.parse(props);
|
|
1472
|
+
const options = {
|
|
1473
|
+
audio: typeof params.audio === "string" ? { url: params.audio } : params.audio,
|
|
1474
|
+
ptt: true,
|
|
1475
|
+
viewOnce: params.viewOnce,
|
|
1476
|
+
mimetype: "audio/ogg; codecs=opus",
|
|
1477
|
+
contextInfo: { externalAdReply: params.externalAdReply }
|
|
1478
|
+
};
|
|
1479
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1480
|
+
}
|
|
1481
|
+
async note(type, props) {
|
|
1482
|
+
await this.initial();
|
|
1483
|
+
const enumType = RelayVideoEnumType.parse(type);
|
|
1484
|
+
const params = RelayVideoType.parse(props);
|
|
1485
|
+
const options = { video: typeof params.video === "string" ? { url: params.video } : params.video, caption: params.text, ptv: true };
|
|
1486
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1487
|
+
}
|
|
1488
|
+
async gif(type, props) {
|
|
1489
|
+
await this.initial();
|
|
1490
|
+
const enumType = RelayVideoEnumType.parse(type);
|
|
1491
|
+
const params = RelayVideoType.parse(props);
|
|
1492
|
+
const options = { video: typeof params.video === "string" ? { url: params.video } : params.video, gifPlayback: true };
|
|
1493
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1494
|
+
}
|
|
1495
|
+
async location(type, props) {
|
|
1496
|
+
await this.initial();
|
|
1497
|
+
const enumType = RelayLocationEnumType.parse(type);
|
|
1498
|
+
const params = RelayLocationType.parse(props);
|
|
1499
|
+
const options = {
|
|
1500
|
+
location: {
|
|
1501
|
+
degreesLatitude: params.latitude,
|
|
1502
|
+
degreesLongitude: params.longitude,
|
|
1503
|
+
url: params.title,
|
|
1504
|
+
address: params.footer,
|
|
1505
|
+
name: params.title
|
|
1506
|
+
},
|
|
1507
|
+
contextInfo: { externalAdReply: params.externalAdReply }
|
|
1508
|
+
};
|
|
1509
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1510
|
+
}
|
|
1511
|
+
async contacts(type, props) {
|
|
1512
|
+
await this.initial();
|
|
1513
|
+
const enumType = RelayContactEnumType.parse(type);
|
|
1514
|
+
const params = RelayContactType.parse(props);
|
|
1515
|
+
const contacts = params.contacts.map((x) => {
|
|
1516
|
+
const vcard = [
|
|
1517
|
+
"BEGIN:VCARD",
|
|
1518
|
+
"VERSION:3.0",
|
|
1519
|
+
`FN:${x.fullname}`,
|
|
1520
|
+
`ORG:${x.organization || ""}`,
|
|
1521
|
+
`TEL;type=CELL;type=VOICE;waid=${x.phoneNumber}:${x.phoneNumber}`,
|
|
1522
|
+
"END:VCARD"
|
|
1523
|
+
].join("\n");
|
|
1524
|
+
return { displayName: x.fullname, vcard };
|
|
1525
|
+
});
|
|
1526
|
+
const options = {
|
|
1527
|
+
contacts: {
|
|
1528
|
+
displayName: params?.title,
|
|
1529
|
+
contacts
|
|
1530
|
+
}
|
|
1531
|
+
};
|
|
1532
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1533
|
+
}
|
|
1534
|
+
async poll(type, props) {
|
|
1535
|
+
await this.initial();
|
|
1536
|
+
const enumType = RelayPollEnumType.parse(type);
|
|
1537
|
+
const params = RelayPollType.parse(props);
|
|
1538
|
+
const options = {};
|
|
1539
|
+
if (params.action == "create") {
|
|
1540
|
+
options.poll = {
|
|
1541
|
+
name: params.name,
|
|
1542
|
+
values: params.answers,
|
|
1543
|
+
selectableCount: !!params.isMultiple ? 1 : 0,
|
|
1544
|
+
toAnnouncementGroup: true
|
|
1545
|
+
};
|
|
1546
|
+
}
|
|
1547
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1548
|
+
}
|
|
1549
|
+
async button(type, props) {
|
|
1550
|
+
await this.initial();
|
|
1551
|
+
const enumType = RelayButtonEnumType.parse(type);
|
|
1552
|
+
const params = RelayButtonType.parse(props);
|
|
1553
|
+
const options = {
|
|
1554
|
+
text: params.text,
|
|
1555
|
+
footer: params.footer
|
|
1556
|
+
};
|
|
1557
|
+
if (params.type == "simple") {
|
|
1558
|
+
options.buttons = params.buttons.map((x) => ({ buttonId: x.id, buttonText: { displayText: x.text } }));
|
|
1559
|
+
}
|
|
1560
|
+
if (params.type == "interactive") {
|
|
1561
|
+
options.interactiveButtons = params.buttons.map((x) => {
|
|
1562
|
+
let schema = { name: x.type };
|
|
1563
|
+
if (x.type == "quick_reply") {
|
|
1564
|
+
schema.buttonParamsJson = toString({
|
|
1565
|
+
id: x.id,
|
|
1566
|
+
display_text: x.text
|
|
1567
|
+
});
|
|
1568
|
+
}
|
|
1569
|
+
if (x.type == "cta_url") {
|
|
1570
|
+
schema.buttonParamsJson = toString({
|
|
1571
|
+
id: x.id,
|
|
1572
|
+
display_text: x.text,
|
|
1573
|
+
url: x.url,
|
|
1574
|
+
merchant_url: x.url
|
|
1575
|
+
});
|
|
1576
|
+
}
|
|
1577
|
+
if (x.type == "cta_copy") {
|
|
1578
|
+
schema.buttonParamsJson = toString({
|
|
1579
|
+
id: x.id,
|
|
1580
|
+
display_text: x.text,
|
|
1581
|
+
copy_code: x.copy
|
|
1582
|
+
});
|
|
1583
|
+
}
|
|
1584
|
+
if (x.type == "cta_call") {
|
|
1585
|
+
schema.buttonParamsJson = toString({
|
|
1586
|
+
id: x.id,
|
|
1587
|
+
display_text: x.text,
|
|
1588
|
+
phone_number: x.phoneNumber
|
|
1589
|
+
});
|
|
1590
|
+
}
|
|
1591
|
+
return schema;
|
|
1592
|
+
});
|
|
1593
|
+
}
|
|
1594
|
+
this[enumType]({ text: "$$media$$", roomId: params.roomId, options });
|
|
1595
|
+
}
|
|
1596
|
+
// GROUP RELAY
|
|
1597
|
+
group() {
|
|
1598
|
+
const client = this.ctx;
|
|
1599
|
+
const create = async (props) => {
|
|
1600
|
+
const params = RelayGroupCreateType.parse(props);
|
|
1601
|
+
try {
|
|
1602
|
+
return await client.socket.groupCreate(params.title, params.members);
|
|
1603
|
+
} catch (error) {
|
|
1604
|
+
client.spinner.error("Failed create group. Make sure members has valid number.\n\n" + error);
|
|
1605
|
+
return null;
|
|
1606
|
+
}
|
|
1607
|
+
};
|
|
1608
|
+
const action = async (props) => {
|
|
1609
|
+
const params = RelayGroupActionType.parse(props);
|
|
1610
|
+
const opts = {
|
|
1611
|
+
add: "add",
|
|
1612
|
+
kick: "remove",
|
|
1613
|
+
promote: "promote",
|
|
1614
|
+
demote: "demote"
|
|
1615
|
+
};
|
|
1616
|
+
try {
|
|
1617
|
+
return await client.socket.groupParticipantsUpdate(params.roomId, params.members, opts[params.action]);
|
|
1618
|
+
} catch (error) {
|
|
1619
|
+
client.spinner.error("Failed update user. Make sure this number is in the group and as admin.\n\n" + error);
|
|
1620
|
+
return null;
|
|
1621
|
+
}
|
|
1622
|
+
};
|
|
1623
|
+
const update = async (props) => {
|
|
1624
|
+
const params = RelayGroupUpdateType.parse(props);
|
|
1625
|
+
const opts = {
|
|
1626
|
+
subject: "groupUpdateSubject",
|
|
1627
|
+
description: "groupUpdateDescription"
|
|
1628
|
+
};
|
|
1629
|
+
try {
|
|
1630
|
+
return await client.socket[opts[props.action]](params.roomId, props.text);
|
|
1631
|
+
} catch (error) {
|
|
1632
|
+
client.spinner.error("Failed update group. Make sure this number is in the group and as admin.\n\n" + error);
|
|
1633
|
+
return null;
|
|
1634
|
+
}
|
|
1635
|
+
};
|
|
1636
|
+
const settings = async (props) => {
|
|
1637
|
+
const params = RelayGroupSettingsType.parse(props);
|
|
1638
|
+
const opts = {
|
|
1639
|
+
open: "not_announcement",
|
|
1640
|
+
close: "announcement",
|
|
1641
|
+
lock: "locked",
|
|
1642
|
+
unlock: "unlocked"
|
|
1643
|
+
};
|
|
1644
|
+
try {
|
|
1645
|
+
return await client.socket.groupSettingUpdate(params.roomId, opts[params.action]);
|
|
1646
|
+
} catch (error) {
|
|
1647
|
+
client.spinner.error("Failed settings group. Make sure this number is in the group and as admin.\n\n" + error);
|
|
1648
|
+
return null;
|
|
1649
|
+
}
|
|
1650
|
+
};
|
|
1651
|
+
const leave = async (props) => {
|
|
1652
|
+
const params = RelayGroupLeaveType.parse(props);
|
|
1653
|
+
try {
|
|
1654
|
+
return await client.socket.groupLeave(params.roomId);
|
|
1655
|
+
} catch (error) {
|
|
1656
|
+
client.spinner.error("Failed leave group. Make sure this number is in the group.\n\n" + error);
|
|
1657
|
+
return null;
|
|
1658
|
+
}
|
|
1659
|
+
};
|
|
1660
|
+
const links = async (props) => {
|
|
1661
|
+
const params = RelayGroupLinksType.parse(props);
|
|
1662
|
+
const opts = {
|
|
1663
|
+
get: "groupInviteCode",
|
|
1664
|
+
revoke: "groupRevokeInvite"
|
|
1665
|
+
};
|
|
1666
|
+
try {
|
|
1667
|
+
const code = await client.socket[opts[params.action]](params.roomId);
|
|
1668
|
+
return `https://chat.whatsapp.com/` + code;
|
|
1669
|
+
} catch (error) {
|
|
1670
|
+
client.spinner.error("Failed get group link. Make sure this number is in the group and as admin.\n\n" + error);
|
|
1671
|
+
return null;
|
|
1672
|
+
}
|
|
1673
|
+
};
|
|
1674
|
+
const invite = async (props) => {
|
|
1675
|
+
const params = RelayGroupInviteType.parse(props);
|
|
1676
|
+
const opts = {
|
|
1677
|
+
join: "groupAcceptInvite",
|
|
1678
|
+
info: "groupGetInviteInfo"
|
|
1679
|
+
};
|
|
1680
|
+
try {
|
|
1681
|
+
const code = params.url.split("https://chat.whatsapp.com/");
|
|
1682
|
+
return await client.socket[opts[params.action]](code[1]);
|
|
1683
|
+
} catch (error) {
|
|
1684
|
+
client.spinner.error("Failed get group link. Make sure this number is in the group and as admin.\n\n" + error);
|
|
1685
|
+
return null;
|
|
1686
|
+
}
|
|
1687
|
+
};
|
|
1688
|
+
const metadata = async (props) => {
|
|
1689
|
+
const params = RelayGroupMetadataType.parse(props);
|
|
1690
|
+
try {
|
|
1691
|
+
const meta = await client.socket.groupMetadata(params.roomId);
|
|
1692
|
+
return meta;
|
|
1693
|
+
} catch (error) {
|
|
1694
|
+
client.spinner.error("Failed get group metadata. Make sure this number is in the group and as admin.\n\n" + error);
|
|
1695
|
+
return null;
|
|
1696
|
+
}
|
|
1697
|
+
};
|
|
1698
|
+
const requests = {
|
|
1699
|
+
list: async (props) => {
|
|
1700
|
+
const params = RelayGroupRequestsListType.parse(props);
|
|
1701
|
+
return await client.socket.groupRequestParticipantsList(params.roomId);
|
|
1702
|
+
},
|
|
1703
|
+
approve: async (props) => {
|
|
1704
|
+
const params = RelayGroupRequestsApproveType.parse(props);
|
|
1705
|
+
return await client.socket.groupRequestParticipantsUpdate(params.roomId, params.members, "approve");
|
|
1706
|
+
},
|
|
1707
|
+
reject: async (props) => {
|
|
1708
|
+
const params = RelayGroupRequestsRejectType.parse(props);
|
|
1709
|
+
return await client.socket.groupRequestParticipantsUpdate(params.roomId, params.members, "reject");
|
|
1710
|
+
}
|
|
1711
|
+
};
|
|
1712
|
+
return {
|
|
1713
|
+
create,
|
|
1714
|
+
action,
|
|
1715
|
+
update,
|
|
1716
|
+
settings,
|
|
1717
|
+
leave,
|
|
1718
|
+
links,
|
|
1719
|
+
invite,
|
|
1720
|
+
metadata,
|
|
1721
|
+
requests
|
|
1722
|
+
};
|
|
1723
|
+
}
|
|
1724
|
+
// PRIVACY RELAY
|
|
1725
|
+
privacy() {
|
|
1726
|
+
const client = this.ctx;
|
|
1727
|
+
const update = async (props) => {
|
|
1728
|
+
const params = RelayPrivacyUpdateType.parse(props);
|
|
1729
|
+
try {
|
|
1730
|
+
if (params.action == "control") {
|
|
1731
|
+
return await client.socket.updateBlockStatus(params.senderId, params.type);
|
|
1732
|
+
}
|
|
1733
|
+
if (params.action == "lastSeen") {
|
|
1734
|
+
return await client.socket.updateLastSeenPrivacy(params.type);
|
|
1735
|
+
}
|
|
1736
|
+
if (params.action == "online") {
|
|
1737
|
+
return await client.socket.updateOnlinePrivacy(params.type);
|
|
1738
|
+
}
|
|
1739
|
+
if (params.action == "avatar") {
|
|
1740
|
+
return await client.socket.updateProfilePicturePrivacy(params.type);
|
|
1741
|
+
}
|
|
1742
|
+
if (params.action == "story") {
|
|
1743
|
+
return await client.socket.updateStatusPrivacy(params.type);
|
|
1744
|
+
}
|
|
1745
|
+
if (params.action == "read") {
|
|
1746
|
+
return await client.socket.updateReadReceiptsPrivacy(params.type);
|
|
1747
|
+
}
|
|
1748
|
+
if (params.action == "groupsAdd") {
|
|
1749
|
+
return await client.socket.updateGroupsAddPrivacy(params.type);
|
|
1750
|
+
}
|
|
1751
|
+
if (params.action == "ephemeral") {
|
|
1752
|
+
const opts = { remove: 0, "24h": 86400, "7d": 604800, "90d": 7776e3 };
|
|
1753
|
+
return await client.socket.updateDefaultDisappearingMode(opts[params.type]);
|
|
1754
|
+
}
|
|
1755
|
+
} catch (error) {
|
|
1756
|
+
client.spinner.error("Failed update privacy, please try again.\n\n" + error);
|
|
1757
|
+
return null;
|
|
1758
|
+
}
|
|
1759
|
+
};
|
|
1760
|
+
const fetch = {
|
|
1761
|
+
settings: async () => {
|
|
1762
|
+
return await client.socket.fetchPrivacySettings(true);
|
|
1763
|
+
},
|
|
1764
|
+
blocklists: async () => {
|
|
1765
|
+
return await client.socket.fetchBlocklist();
|
|
1766
|
+
}
|
|
1767
|
+
};
|
|
1768
|
+
return {
|
|
1769
|
+
update,
|
|
1770
|
+
fetch
|
|
1771
|
+
};
|
|
1772
|
+
}
|
|
1773
|
+
// PROFILE RELAY
|
|
1774
|
+
profile() {
|
|
1775
|
+
const client = this.ctx;
|
|
1776
|
+
const bio = async (props) => {
|
|
1777
|
+
const params = RelayProfileBioType.parse(props);
|
|
1778
|
+
try {
|
|
1779
|
+
return await client.socket.fetchStatus(params.senderId);
|
|
1780
|
+
} catch (error) {
|
|
1781
|
+
client.spinner.error("Failed fetch profile bio. Make sure senderId is valid.\n\n" + error);
|
|
1782
|
+
return null;
|
|
1783
|
+
}
|
|
1784
|
+
};
|
|
1785
|
+
const avatar = async (props) => {
|
|
1786
|
+
const params = RelayProfileBioType.parse(props);
|
|
1787
|
+
try {
|
|
1788
|
+
return await client.socket.profilePictureUrl(params.senderId);
|
|
1789
|
+
} catch (error) {
|
|
1790
|
+
client.spinner.error("Failed fetch profile avatar. Make sure senderId is valid.\n\n" + error);
|
|
1791
|
+
return null;
|
|
1792
|
+
}
|
|
1793
|
+
};
|
|
1794
|
+
const business = async (props) => {
|
|
1795
|
+
const params = RelayProfileBioType.parse(props);
|
|
1796
|
+
try {
|
|
1797
|
+
return await client.socket.getBusinessProfile(params.senderId);
|
|
1798
|
+
} catch (error) {
|
|
1799
|
+
client.spinner.error("Failed fetch profile business. Make sure senderId is valid.\n\n" + error);
|
|
1800
|
+
return null;
|
|
1801
|
+
}
|
|
1802
|
+
};
|
|
1803
|
+
const update = async (props) => {
|
|
1804
|
+
const params = RelayProfileUpdateType.parse(props);
|
|
1805
|
+
try {
|
|
1806
|
+
if (params.type == "name") {
|
|
1807
|
+
return await client.socket.updateProfileName(params.text);
|
|
1808
|
+
}
|
|
1809
|
+
if (params.type == "bio") {
|
|
1810
|
+
return await client.socket.updateProfileStatus(params.text);
|
|
1811
|
+
}
|
|
1812
|
+
if (params.type == "avatar") {
|
|
1813
|
+
if (params.avatar == "remove") {
|
|
1814
|
+
return await client.socket.removeProfilePicture(params.roomId);
|
|
1815
|
+
}
|
|
1816
|
+
const avatar2 = typeof params.avatar == "string" ? { url: params.avatar } : params.avatar;
|
|
1817
|
+
return await client.socket.updateProfilePicture(params.roomId, avatar2);
|
|
1818
|
+
}
|
|
1819
|
+
} catch (error) {
|
|
1820
|
+
client.spinner.error("Failed update profile. Make sure senderId is valid.\n\n" + error);
|
|
1821
|
+
return null;
|
|
1822
|
+
}
|
|
1823
|
+
};
|
|
1824
|
+
const check = async (props) => {
|
|
1825
|
+
const params = RelayProfileCheckType.parse(props);
|
|
1826
|
+
try {
|
|
1827
|
+
const [wa] = await client.socket.onWhatsApp(params.senderId);
|
|
1828
|
+
if (!wa) return { isOnWhatsApp: false };
|
|
1829
|
+
const pic = await avatar({ senderId: wa.jid });
|
|
1830
|
+
const status = await bio({ senderId: wa.jid });
|
|
1831
|
+
const obj = {
|
|
1832
|
+
isOnWhatsApp: true,
|
|
1833
|
+
avatar: pic,
|
|
1834
|
+
bio: status,
|
|
1835
|
+
...wa
|
|
1836
|
+
};
|
|
1837
|
+
return obj;
|
|
1838
|
+
} catch (error) {
|
|
1839
|
+
client.spinner.error("Failed check profile. Make sure senderId is valid.\n\n" + error);
|
|
1840
|
+
return null;
|
|
1841
|
+
}
|
|
1842
|
+
};
|
|
1843
|
+
return {
|
|
1844
|
+
bio,
|
|
1845
|
+
avatar,
|
|
1846
|
+
business,
|
|
1847
|
+
update,
|
|
1848
|
+
check
|
|
1849
|
+
};
|
|
1850
|
+
}
|
|
1851
|
+
};
|
|
1852
|
+
var Client = class {
|
|
1853
|
+
props;
|
|
1854
|
+
db;
|
|
1855
|
+
logger = pino__default.default({ level: "silent", enabled: false });
|
|
1856
|
+
events = new EventEmitter__default.default();
|
|
1857
|
+
relay;
|
|
1858
|
+
retryCount = 0;
|
|
1859
|
+
maxRetries = 10;
|
|
1860
|
+
connectionTimeout;
|
|
1861
|
+
spinner = nanospinner.createSpinner("", { color: "green" });
|
|
1862
|
+
socket;
|
|
1863
|
+
cache = new NodeCache2__default.default({ stdTTL: 5 * 60, useClones: false });
|
|
1864
|
+
constructor(props) {
|
|
1865
|
+
this.props = ClientOptionsType.parse(props);
|
|
1866
|
+
this.initialize();
|
|
1867
|
+
return new Proxy(this, {
|
|
1868
|
+
get(target, prop) {
|
|
1869
|
+
if (typeof prop === "string" && (prop in target || _2__default.default.includes(["on", "emit"], prop))) return target[prop];
|
|
1870
|
+
if (typeof prop === "string") return target.relay[prop];
|
|
1871
|
+
return void 0;
|
|
1872
|
+
}
|
|
1873
|
+
});
|
|
1874
|
+
}
|
|
1875
|
+
async initialize() {
|
|
1876
|
+
console.clear();
|
|
1877
|
+
await displayBanner();
|
|
1878
|
+
await makeWASocket.delay(1e3);
|
|
1879
|
+
await this.spinner.start("Initializing database...");
|
|
1880
|
+
const { db, state, store, saveCreds } = await CredsHandler(this.props);
|
|
1881
|
+
await this.spinner.start("Fetching newest version...");
|
|
1882
|
+
const { version } = await makeWASocket.fetchLatestBaileysVersion();
|
|
1883
|
+
this.socket = makeWASocket__default.default({
|
|
1884
|
+
version,
|
|
1885
|
+
logger: this.logger,
|
|
1886
|
+
markOnlineOnConnect: this.props.autoOnline,
|
|
1887
|
+
syncFullHistory: true,
|
|
1888
|
+
printQRInTerminal: false,
|
|
1889
|
+
defaultQueryTimeoutMs: void 0,
|
|
1890
|
+
msgRetryCounterCache: new NodeCache2__default.default(),
|
|
1891
|
+
mediaCache: new NodeCache2__default.default({ stdTTL: 60 }),
|
|
1892
|
+
userDevicesCache: new NodeCache2__default.default(),
|
|
1893
|
+
cachedGroupMetadata: async (jid) => this.cache.get(jid),
|
|
1894
|
+
auth: {
|
|
1895
|
+
creds: state.creds,
|
|
1896
|
+
keys: makeWASocket.makeCacheableSignalKeyStore(state.keys, this.logger)
|
|
1897
|
+
},
|
|
1898
|
+
getMessage: async (key) => {
|
|
1899
|
+
if (!key?.id) return void 0;
|
|
1900
|
+
const message = await db.store("messages").read(key.id);
|
|
1901
|
+
return message;
|
|
1902
|
+
}
|
|
1903
|
+
});
|
|
1904
|
+
await this.socket?.ev.on("creds.update", saveCreds);
|
|
1905
|
+
if (this.props.authType === "pairing" && this.props.phoneNumber && !this.socket?.authState.creds.registered) {
|
|
1906
|
+
this.spinner.start("Generating pairing code...");
|
|
1907
|
+
setTimeout(async () => {
|
|
1908
|
+
try {
|
|
1909
|
+
if (this.props?.authType === "pairing") {
|
|
1910
|
+
const code = await this.socket?.requestPairingCode(this.props.phoneNumber.toString(), shuffleString("Z4D3V0FC"));
|
|
1911
|
+
this.spinner.info(`Pairing code: ${code}`);
|
|
1912
|
+
}
|
|
1913
|
+
} catch {
|
|
1914
|
+
this.spinner.error(`Session "${this.props.session}" has not valid, please delete it`);
|
|
1915
|
+
process.exit(0);
|
|
1916
|
+
}
|
|
1917
|
+
}, 5e3);
|
|
1918
|
+
}
|
|
1919
|
+
const listener = new Listener();
|
|
1920
|
+
this.relay = new Relay();
|
|
1921
|
+
this.spinner.success("Initialize Successfully");
|
|
1922
|
+
await store.bind(this);
|
|
1923
|
+
await listener.bind(this, db);
|
|
1924
|
+
await this.relay.bind(this, db);
|
|
1925
|
+
this.spinner.start("Connecting to WhatsApp...");
|
|
1926
|
+
this.startConnectionTimeout();
|
|
1927
|
+
}
|
|
1928
|
+
startConnectionTimeout() {
|
|
1929
|
+
if (this.connectionTimeout) {
|
|
1930
|
+
clearTimeout(this.connectionTimeout);
|
|
1931
|
+
}
|
|
1932
|
+
this.connectionTimeout = setTimeout(() => {
|
|
1933
|
+
this.handleConnectionTimeout();
|
|
1934
|
+
}, 6e4);
|
|
1935
|
+
}
|
|
1936
|
+
handleConnectionTimeout() {
|
|
1937
|
+
if (this.retryCount < this.maxRetries) {
|
|
1938
|
+
this.retryCount++;
|
|
1939
|
+
this.spinner.warn(`Connection timeout. Retrying... (${this.retryCount}/${this.maxRetries})`);
|
|
1940
|
+
this.autoReload();
|
|
1941
|
+
} else {
|
|
1942
|
+
this.spinner.error(`Max retries reached (${this.maxRetries}). Connection failed.`);
|
|
1943
|
+
process.exit(1);
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
async autoReload() {
|
|
1947
|
+
try {
|
|
1948
|
+
if (this.connectionTimeout) {
|
|
1949
|
+
clearTimeout(this.connectionTimeout);
|
|
1950
|
+
}
|
|
1951
|
+
if (this.socket) {
|
|
1952
|
+
this.socket.end?.(void 0);
|
|
1953
|
+
this.socket = void 0;
|
|
1954
|
+
}
|
|
1955
|
+
await makeWASocket.delay(2e3);
|
|
1956
|
+
await this.initialize();
|
|
1957
|
+
} catch (error) {
|
|
1958
|
+
this.spinner.error(`Auto-reload failed: ${error.message}`);
|
|
1959
|
+
this.handleConnectionTimeout();
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
resetRetryCount() {
|
|
1963
|
+
this.retryCount = 0;
|
|
1964
|
+
if (this.connectionTimeout) {
|
|
1965
|
+
clearTimeout(this.connectionTimeout);
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
on(event, handler) {
|
|
1969
|
+
this.events.on(event, handler);
|
|
1970
|
+
}
|
|
1971
|
+
emit(event, ...args) {
|
|
1972
|
+
this.events.emit(event, ...args);
|
|
1973
|
+
}
|
|
1974
|
+
};
|
|
1975
|
+
|
|
1976
|
+
exports.CitationType = CitationType;
|
|
1977
|
+
exports.Client = Client;
|
|
1978
|
+
exports.ClientAuthPairingType = ClientAuthPairingType;
|
|
1979
|
+
exports.ClientAuthQRType = ClientAuthQRType;
|
|
1980
|
+
exports.ClientBaseType = ClientBaseType;
|
|
1981
|
+
exports.ClientOptionsType = ClientOptionsType;
|
|
1982
|
+
exports.EventEnumType = EventEnumType;
|
|
1983
|
+
exports.FakeReplyType = FakeReplyType;
|
|
1984
|
+
exports.JsonDB = JsonDB;
|
|
1985
|
+
exports.LimiterType = LimiterType;
|
|
1986
|
+
exports.PluginsType = PluginsType;
|