zaileys 4.8.8 → 4.8.9

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.
@@ -19,15 +19,11 @@ export interface MediaAttachment {
19
19
  fileName: string | null;
20
20
  fileSize: number | null;
21
21
  ptt: boolean;
22
- /** Playback length in seconds, for audio and video. */
22
+ isAnimated: boolean;
23
23
  duration: number | null;
24
24
  width: number | null;
25
25
  height: number | null;
26
- /** Page count, for documents. */
27
26
  pages: number | null;
28
- /** `true` for an animated sticker or a GIF-playback video. */
29
- isAnimated: boolean;
30
- /** Inline JPEG preview, when WhatsApp sent one. Lets you show a thumbnail without downloading. */
31
27
  thumbnail: Buffer | null;
32
28
  buffer(): Promise<Buffer>;
33
29
  stream(): Promise<Readable>;
@@ -187,7 +183,6 @@ export interface MessageContext {
187
183
  senderId: string;
188
184
  senderLid: string | null;
189
185
  senderName: string | null;
190
- /** WhatsApp username (the `@handle`), without the `@`. Only sent for accounts that set one. */
191
186
  senderUsername: string | null;
192
187
  senderDevice: SenderDevice;
193
188
  timestamp: number;
@@ -201,20 +196,7 @@ export interface MessageContext {
201
196
  isViewOnce: boolean;
202
197
  isEphemeral: boolean;
203
198
  isForwarded: boolean;
204
- /** `true` for a backlog message replayed after a reconnect. Skip these to avoid answering twice. */
205
- isOffline: boolean;
206
- /** How many hops this message has been forwarded. `>= 5` is WhatsApp's "forwarded many times". */
207
- forwardCount: number;
208
- /** The chat's disappearing timer in seconds, or `null` when messages are kept. */
209
- ephemeralDuration: number | null;
210
- /** Whether WhatsApp addressed this message by phone number or by LID. */
211
- addressingMode: 'pn' | 'lid';
212
- /** JIDs of groups tagged in the message (community `@group` mentions). */
213
- mentionedGroups: string[];
214
- /** Present only on the first message of a chat opened from a Meta ad. */
215
- ad?: AdAttribution;
216
- /** Present only when the sender is a verified WhatsApp Business account. */
217
- business?: BusinessInfo;
199
+ isOld: boolean;
218
200
  isQuestion: boolean;
219
201
  isPrefix: boolean;
220
202
  isTagMe: boolean;
@@ -229,6 +211,12 @@ export interface MessageContext {
229
211
  isGroupStatusMention: boolean;
230
212
  isGroupStatus: boolean;
231
213
  isStory: boolean;
214
+ forwardCount: number;
215
+ ephemeralDuration: number | null;
216
+ addressingMode: 'pn' | 'lid';
217
+ mentionedGroups: string[];
218
+ ad?: AdAttribution;
219
+ business?: BusinessInfo;
232
220
  roomName(): Promise<string | null>;
233
221
  receiverName(): Promise<string | null>;
234
222
  media?: ContextMedia;
@@ -262,7 +250,7 @@ export interface BuildContextInput {
262
250
  isForwarded: boolean;
263
251
  isBroadcast: boolean;
264
252
  isNewsletter: boolean;
265
- isOffline?: boolean;
253
+ isOld?: boolean;
266
254
  forwardCount?: number;
267
255
  ephemeralDuration?: number | null;
268
256
  addressingMode?: 'pn' | 'lid';
@@ -8,7 +8,7 @@ export interface DecodeContext {
8
8
  selfName?: string;
9
9
  lidMap?: Map<string, string>;
10
10
  /** WhatsApp replays a reconnect's backlog as `append`; live traffic arrives as `notify`. */
11
- isOffline?: boolean;
11
+ isOld?: boolean;
12
12
  logger?: DownloadLogger;
13
13
  channelId?: string;
14
14
  receiverId?: string;
package/dist/index.cjs CHANGED
@@ -10,9 +10,9 @@
10
10
  `:""}${n.body}`};return n.footer!==void 0&&(t.footer=n.footer),vt(n.buttons,t)};var bt=n=>{if(typeof n!="string"||n.trim().length===0)throw new p("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var Wr=(n,e,t)=>({recipient:n,...e?{resolveRecipient:e}:{},...t?{recordSent:t}:{}});var pn=new WeakSet,Fr=n=>{pn.add(n);},jr=n=>{if(!pn.has(n))return n;pn.delete(n);let e=crypto.randomBytes(32),t={...n,messageContextInfo:{messageSecret:e}};return {messageContextInfo:{messageSecret:e},groupStatusMessageV2:{message:t}}};var At="status@broadcast",Fo=[{tag:"biz",attrs:{},content:[{tag:"interactive",attrs:{type:"native_flow",v:"1"},content:[{tag:"native_flow",attrs:{v:"9",name:"mixed"}}]}]}],Y=class n{socket;internal;constructor(e,t){this.socket=e,this.internal=t;}static create(e,t,r,s){return new n(e,Wr(t,r,s))}to(e){return this.internal.recipient=e,delete this.internal.resolveRecipient,this}text(e,t){return t?.rich===true?this.internal.content=lr(fr(e),t):this.internal.content=bt(e),this}image(e,t){return this.internal.pendingContent=ge(e,t),this}videoNote(e,t){return this.internal.pendingContent=ne(e,{...t,ptv:true}),this}video(e,t){return this.internal.pendingContent=ne(e,t),this}audio(e,t){return this.internal.pendingContent=or(e,t),this}document(e,t){return this.internal.pendingContent=yr(e,t),this}sticker(e,t){return this.internal.pendingContent=Nr(e,t),this}buttons(e,t){return this.internal.content=vt(e,t),this}carousel(e,t){return this.internal.content=dr(e,t),this}list(e){return this.internal.content=Ir(e),this}poll(e,t,r){return this.internal.content=_r(e,t,r),this}location(e,t,r){return this.internal.content=xr(e,t,r),this}contact(e){return this.internal.content=hr(e),this}template(e){return this.internal.content=Br(e),this}event(e){return this.internal.content=vr(e),this}groupInvite(e){return this.internal.content=Mr(e),this}groupStatus(e,t){return typeof e=="string"?this.internal.content=Pr(e,t):this.internal.pendingContent=Er(e,t),this}product(e){return this.internal.pendingContent=Lr(e),this}requestPhoneNumber(){return this.internal.content={requestPhoneNumber:{}},this}sharePhoneNumber(){return this.internal.content={sharePhoneNumber:{}},this}limitSharing(e=true){return this.internal.content={limitSharing:e},this}album(e){return this.internal.albumItems=e,this}reply(e){if(e==null)throw new p("INVALID_OPTIONS","reply() requires a quoted message or key");let t="key"in e&&e.key!=null;return this.internal.quoted=t?e:{key:e},this}mentions(e){if(e.length===0)throw new p("INVALID_OPTIONS","mentions() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new p("INVALID_OPTIONS",`invalid jid: ${String(r)}`);let t=new Set([...this.internal.mentions??[],...e]);return this.internal.mentions=[...t],this}mentionAll(){return this.internal.mentionAll=true,this}audience(e){if(e.length===0)throw new p("INVALID_OPTIONS","audience() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new p("INVALID_OPTIONS",`invalid jid: ${String(r)}`);let t=new Set([...this.internal.statusJidList??[],...e]);return this.internal.statusJidList=[...t],this}disappearing(e){if(!Number.isInteger(e)||e<=0)throw new p("INVALID_OPTIONS","disappearing() requires a positive integer duration");return this.internal.disappearingSeconds=e,this}then(e,t){return (async()=>{if(this.internal.resolveRecipient&&(this.internal.recipient=await this.internal.resolveRecipient(this.internal.recipient),delete this.internal.resolveRecipient),this.internal.statusJidList!==void 0&&this.internal.recipient!==At)throw new p("INVALID_RECIPIENT",`audience() only applies to ${At}, not ${this.internal.recipient}`);if(this.internal.albumItems){let d={recipient:this.internal.recipient};return this.internal.quoted!==void 0&&(d.quoted=this.internal.quoted),this.internal.mentions!==void 0&&(d.mentions=this.internal.mentions),this.internal.mentionAll!==void 0&&(d.mentionAll=this.internal.mentionAll),this.internal.disappearingSeconds!==void 0&&(d.disappearingSeconds=this.internal.disappearingSeconds),nr(this.socket,this.internal.recipient,this.internal.albumItems,d)}if(this.internal.pendingContent&&(this.internal.content=await this.internal.pendingContent),!this.internal.content)throw new p("EMPTY_CONTENT","no content set");let s=this.internal.content,i=s[R];if(i!==void 0){let d=s[Re];if(typeof d=="string"&&!this.internal.recipient.endsWith("@g.us"))throw new p("INVALID_RECIPIENT",`${d} can only be sent to a group jid ending in @g.us`);let l=s[wt],u=l!==void 0?await this.buildStatusMedia(l):i,w=s[cn],M=s[ln];return this.sendRelay(u,w,M,l!==void 0)}let o=this.internal.content;if(this.internal.mentions&&this.internal.mentions.length>0&&(o.mentions=this.internal.mentions),this.internal.mentionAll&&(o.mentionAll=true),this.internal.recipient===At&&this.internal.statusJidList===void 0)throw new p("INVALID_OPTIONS",`a status sent to ${At} needs audience([...]); without it WhatsApp accepts the message but shows it to nobody`);let a={};this.internal.quoted&&(a.quoted=this.internal.quoted),this.internal.disappearingSeconds!==void 0&&(a.ephemeralExpiration=this.internal.disappearingSeconds),this.internal.statusJidList!==void 0&&(a.statusJidList=this.internal.statusJidList);let c;try{c=await this.socket.sendMessage(this.internal.recipient,o,a);}catch(d){throw new p("SEND_FAILED","socket sendMessage rejected",{cause:d})}if(!c?.key)throw new p("SEND_FAILED","socket returned no message key");return c.key})().then(e,t)}async uploadHeaderMedia(e,t){let{buffer:r}=await O(t.src),s=await Yc.prepareWAMessageMedia({[t.kind]:r},{upload:this.socket.waUploadToServer});e.hasMediaAttachment=true,t.kind==="image"&&s.imageMessage&&(e.imageMessage=s.imageMessage),t.kind==="video"&&s.videoMessage&&(e.videoMessage=s.videoMessage);}async buildStatusMedia(e){let t={[e.kind]:e.buffer};e.caption!==void 0&&(t.caption=e.caption),e.ptt===true&&(t.ptt=true);try{let r=await Yc.generateWAMessageContent(t,{upload:this.socket.waUploadToServer});return typeof r.toJSON=="function"?r.toJSON():r}catch(r){throw new p("MEDIA_LOAD_FAILED","groupStatus() media upload failed",{cause:r})}}applyRelayMentions(e){let t=this.internal.mentions,r=this.internal.mentionAll===true;if((t===void 0||t.length===0)&&!r)return;let s=Yc.normalizeMessageContent(e),i=s==null?void 0:Yc.getContentType(s);if(s==null||i===void 0)return;let o=s[i];if(o==null||typeof o!="object")return;let a=o.contextInfo??{};t!==void 0&&t.length>0&&(a.mentionedJid=t),r&&(a.nonJidMentions=1),o.contextInfo=a;}async sendRelay(e,t,r,s=false){let i=this.socket.relayMessage;if(typeof i!="function")throw new p("SEND_FAILED","socket does not support relayMessage (interactive content)");if(this.socket.waUploadToServer!==void 0)try{let M=e.interactiveMessage?.header;t!==void 0&&M&&await this.uploadHeaderMedia(M,t);let v=e.interactiveMessage?.carouselMessage?.cards;if(r!==void 0&&v)for(let P of r){let y=v[P.index]?.header;y&&await this.uploadHeaderMedia(y,P);}}catch(M){throw new p("SEND_FAILED","interactive media upload failed",{cause:M})}let o=e;!s&&o.messageContextInfo?.messageSecret==null&&(o.messageContextInfo={...o.messageContextInfo,messageSecret:crypto.randomBytes(32)}),this.applyRelayMentions(e);let c={userJid:this.socket.user?.id??""},d=this.internal.quoted;d!==void 0&&d.message!=null&&(c.quoted=d),this.internal.disappearingSeconds!==void 0&&(c.ephemeralExpiration=this.internal.disappearingSeconds);let l=Yc.generateWAMessageFromContent(this.internal.recipient,e,c);if(s&&l.message!=null&&Fr(l.message),typeof l.key?.id!="string")throw new p("SEND_FAILED","failed to generate relay message key");let w="interactiveMessage"in e&&e.interactiveMessage!=null?{messageId:l.key.id,additionalNodes:Fo}:{messageId:l.key.id};try{await i(this.internal.recipient,l.message,w);}catch(M){throw new p("SEND_FAILED","socket relayMessage rejected",{cause:M})}return this.internal.recordSent?.(l),l.key}};var _e=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=bt(e),this}image(e,t){return this.pendingContent=ge(e,t),this}video(e,t){return this.pendingContent=ne(e,t),this}then(e,t){return this.send().then(e,t)}async send(){let e=this.key.remoteJid;if(typeof e!="string"||e.length===0)throw new p("INVALID_OPTIONS","message key is missing remoteJid");if(this.pendingContent&&(this.content=await this.pendingContent),!this.content)throw new p("EMPTY_CONTENT","edit() requires a content method before await");let t={...this.content,edit:this.key},r;try{r=await this.socket.sendMessage(e,t);}catch(s){throw new p("SEND_FAILED","socket sendMessage rejected",{cause:s})}if(!r?.key)throw new p("SEND_FAILED","socket returned no message key");return r.key}};var mn=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new p("INVALID_OPTIONS","message key is missing remoteJid");return e},gn=n=>{if(!n?.key)throw new p("SEND_FAILED","socket returned no message key");return n.key},fn=async(n,e,t={})=>{let r=mn(e);if(t.forEveryone??true){await n.sendMessage(r,{delete:e});return}if(typeof n.chatModify!="function")throw new p("INVALID_OPTIONS","delete-for-me is not supported by this socket");await n.chatModify({deleteForMe:{deleteMedia:false,key:e,timestamp:Date.now()}},r);},hn=async(n,e,t)=>{let r=mn(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return gn(s)},yn=async(n,e,t,r)=>{let s=await e.getMessage(t);if(!s)throw new p("MESSAGE_NOT_FOUND","message not found in store for forward");let i=await n.sendMessage(r,{forward:s});return gn(i)},Ct=async(n,e,t,r={})=>{let s=mn(e),i={pin:e,type:t?1:2,time:r.duration??86400},o=await n.sendMessage(s,i);return gn(o)};var jo=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,Le=n=>jo.test(n),wn=async(n,e,t,r=Uo)=>{if(Le(e))return e;let s=t.get(e);if(s!==void 0)return s;let i=r.get(e);if(i!==void 0)return i;let o=(async()=>{let c=(await n.onWhatsApp(e))?.find(d=>d.exists&&d.jid);if(!c)throw new p("USERNAME_NOT_FOUND",`username "${e}" not found`);return t.set(e,c.jid),c.jid})();r.set(e,o);try{return await o}finally{r.delete(e);}},Uo=new Map;var I=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysDomainError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var Ne=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}mapParticipants(e){return e.map(t=>({jid:t.jid,status:t.status}))}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("group.create",()=>this.requireSocket().groupCreate(e,t))}async addMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"add"));return this.mapParticipants(r)}async removeMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"remove"));return this.mapParticipants(r)}async promote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"promote"));return this.mapParticipants(r)}async demote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"demote"));return this.mapParticipants(r)}async updateSubject(e,t){await this.requireSocket().groupUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().groupUpdateDescription(e,t);}async leave(e){await this.requireSocket().groupLeave(e);}async metadata(e){return this.requireSocket().groupMetadata(e)}async tagMember(e,t,r){await this.requireSocket().updateMemberLabel(e,r);}async inviteCode(e){let t=await this.requireSocket().groupInviteCode(e);if(!t)throw new I("OPERATION_FAILED","invite code unavailable");return t}async revokeInvite(e){let t=await this.requireSocket().groupRevokeInvite(e);if(!t)throw new I("OPERATION_FAILED","invite code unavailable");return t}async acceptInvite(e){let t=await this.run("group.join",()=>this.requireSocket().groupAcceptInvite(e));if(!t)throw new I("OPERATION_FAILED","invite acceptance failed");return t}async toggleEphemeral(e,t){await this.requireSocket().groupToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().groupSettingUpdate(e,t);}async list(){let e=await this.requireSocket().groupFetchAllParticipating();return Object.values(e)}async inviteInfo(e){return this.requireSocket().groupGetInviteInfo(e)}async joinRequests(e){return this.requireSocket().groupRequestParticipantsList(e)}async approveJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"approve"));return this.mapParticipants(r)}async rejectJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"reject"));return this.mapParticipants(r)}async joinApproval(e,t){await this.requireSocket().groupJoinApprovalMode(e,t?"on":"off");}async memberAddMode(e,t){await this.requireSocket().groupMemberAddMode(e,t?"admin_add":"all_member_add");}};var De=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}async set(e){let t=this.requireSocket();if(e.lastSeen!==void 0&&await t.updateLastSeenPrivacy(e.lastSeen),e.online!==void 0&&await t.updateOnlinePrivacy(e.online),e.profile!==void 0&&await t.updateProfilePicturePrivacy(e.profile),e.status!==void 0&&await t.updateStatusPrivacy(e.status),e.readReceipts!==void 0){let r=typeof e.readReceipts=="boolean"?e.readReceipts?"all":"none":e.readReceipts;await t.updateReadReceiptsPrivacy(r);}e.groupAdd!==void 0&&await t.updateGroupsAddPrivacy(e.groupAdd),e.call!==void 0&&await t.updateCallPrivacy(e.call);}async get(){return this.requireSocket().fetchPrivacySettings()}async block(e){await this.requireSocket().updateBlockStatus(e,"block");}async unblock(e){await this.requireSocket().updateBlockStatus(e,"unblock");}async blocklist(){return this.requireSocket().fetchBlocklist()}async disappearingMode(e){await this.requireSocket().updateDefaultDisappearingMode(e);}async call(e){await this.requireSocket().updateCallPrivacy(e);}};var Be=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("newsletter.create",async()=>{let r=this.requireSocket(),s=await r.newsletterCreate(e,t?.description);return t?.picture&&await r.newsletterUpdatePicture(s.id,t.picture),s})}async follow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterFollow(e));}async unfollow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterUnfollow(e));}async metadata(e){let r=await this.requireSocket().newsletterMetadata("jid",e);if(!r)throw new I("NEWSLETTER_NOT_FOUND",`newsletter ${e} not found`);return r}async updateName(e,t){await this.requireSocket().newsletterUpdateName(e,t);}async updateDescription(e,t){await this.requireSocket().newsletterUpdateDescription(e,t);}async updatePicture(e,t){await this.requireSocket().newsletterUpdatePicture(e,t);}async mute(e){await this.requireSocket().newsletterMute(e);}async unmute(e){await this.requireSocket().newsletterUnmute(e);}async delete(e){await this.requireSocket().newsletterDelete(e);}async removePicture(e){await this.requireSocket().newsletterRemovePicture(e);}async react(e,t,r){await this.requireSocket().newsletterReactMessage(e,t,r);}async unreact(e,t){await this.requireSocket().newsletterReactMessage(e,t);}async subscribers(e){return this.requireSocket().newsletterSubscribers(e)}async messages(e,t=50,r){return this.requireSocket().newsletterFetchMessages(e,t,r?.since,r?.after)}async adminCount(e){return this.requireSocket().newsletterAdminCount(e)}async changeOwner(e,t){await this.requireSocket().newsletterChangeOwner(e,t);}async demote(e,t){await this.requireSocket().newsletterDemote(e,t);}};var We=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("community.create",()=>this.requireSocket().communityCreate(e,t))}async createGroup(e,t,r){return this.run("community.create",()=>this.requireSocket().communityCreateGroup(e,t,r))}async linkGroup(e,t){await this.requireSocket().communityLinkGroup(t,e);}async unlinkGroup(e,t){await this.requireSocket().communityUnlinkGroup(t,e);}async subGroups(e){return (await this.requireSocket().communityFetchLinkedGroups(e)).linkedGroups}async leave(e){await this.requireSocket().communityLeave(e);}async updateSubject(e,t){await this.requireSocket().communityUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().communityUpdateDescription(e,t);}async inviteCode(e){return this.requireSocket().communityInviteCode(e)}async revokeInvite(e){return this.requireSocket().communityRevokeInvite(e)}async acceptInvite(e){return this.run("community.join",()=>this.requireSocket().communityAcceptInvite(e))}async metadata(e){return this.requireSocket().communityMetadata(e)}async list(){return Object.values(await this.requireSocket().communityFetchAllParticipating())}async inviteInfo(e){return this.requireSocket().communityGetInviteInfo(e)}async toggleEphemeral(e,t){await this.requireSocket().communityToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().communitySettingUpdate(e,t);}async memberAddMode(e,t){await this.requireSocket().communityMemberAddMode(e,t?"admin_add":"all_member_add");}async joinApproval(e,t){await this.requireSocket().communityJoinApprovalMode(e,t?"on":"off");}};var Fe=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}async setName(e){await this.requireSocket().updateProfileName(e);}async setStatus(e){await this.requireSocket().updateProfileStatus(e);}async setPicture(e,t){await this.requireSocket().updateProfilePicture(e,t);}async removePicture(e){await this.requireSocket().removeProfilePicture(e);}async getPicture(e,t=false){return await this.requireSocket().profilePictureUrl(e,t?"image":"preview")??null}async getStatus(e){return this.requireSocket().fetchStatus(e)}};var Ur=n=>{if(typeof n.remoteJid!="string"||n.remoteJid.length===0)throw new I("OPERATION_FAILED","message key is missing remoteJid");return n.remoteJid},je=class{constructor(e,t){this.getSocket=e;this.resolveLast=t;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}async last(e){return await this.resolveLast?.(e)??[]}async archive(e){await this.requireSocket().chatModify({archive:true,lastMessages:await this.last(e)},e);}async unarchive(e){await this.requireSocket().chatModify({archive:false,lastMessages:await this.last(e)},e);}async pin(e){await this.requireSocket().chatModify({pin:true},e);}async unpin(e){await this.requireSocket().chatModify({pin:false},e);}async mute(e,t){await this.requireSocket().chatModify({mute:t??Date.now()+365*24*60*60*1e3},e);}async unmute(e){await this.requireSocket().chatModify({mute:null},e);}async markRead(e){let t=await this.last(e);t.length!==0&&await this.requireSocket().chatModify({markRead:true,lastMessages:t},e);}async markUnread(e){let t=await this.last(e);t.length!==0&&await this.requireSocket().chatModify({markRead:false,lastMessages:t},e);}async star(e,t=true){let r=Ur(e);await this.requireSocket().chatModify({star:{messages:[{id:e.id??"",fromMe:e.fromMe===true}],star:t}},r);}async unstar(e){await this.star(e,false);}async fetchHistory(e,t,r){return Ur(t),this.requireSocket().fetchMessageHistory(e,t,r)}async delete(e){await this.requireSocket().chatModify({delete:true,lastMessages:await this.last(e)},e);}async clear(e){await this.requireSocket().chatModify({clear:true,lastMessages:await this.last(e)},e);}};var Ue=class{constructor(e,t){this.getSocket=e;this.normalize=t;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}async check(...e){return (await this.requireSocket().onWhatsApp(...e)??[]).map(r=>{let s={jid:r.jid,exists:r.exists};return r.lid!==void 0&&(s.lid=r.lid),s})}async exists(e){let[t]=await this.check(e);return t?.exists??false}async save(e,t){await this.requireSocket().addOrEditContact(this.normalize(e),t);}async remove(e){await this.requireSocket().removeContact(this.normalize(e));}};var qe=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}async profile(e){return this.requireSocket().getBusinessProfile(e)}async catalog(e={}){return this.requireSocket().getCatalog(e)}async collections(e,t){return this.requireSocket().getCollections(e,t)}async orderDetails(e,t){return this.requireSocket().getOrderDetails(e,t)}async createProduct(e){return this.requireSocket().productCreate(e)}async updateProduct(e,t){return this.requireSocket().productUpdate(e,t)}async deleteProduct(...e){return this.requireSocket().productDelete(e)}};var _=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysCommandError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var qo=n=>{let e=n[0];return e==="{"||e==="["},Ko=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},$o=n=>n===" "||n===" "||n===`
11
11
  `||n==="\r",Go=n=>{let e=[],t="",r=null,s=false,i=false,o=true;for(let a=0;a<n.length;a+=1){let c=n[a];if(s){t+=c,s=false,i=true,o=false;continue}if(c==="\\"&&r!==null){s=true;continue}if(r!==null){c===r?r=null:t+=c,o=false;continue}if((c==='"'||c==="'")&&o){r=c,i=true,o=false;continue}if($o(c)){i&&(e.push(t),t="",i=false),o=true;continue}t+=c,i=true,o=false;}return i&&e.push(t),e},Jo=(n,e)=>{for(let t of e)if(t.length>0&&n.startsWith(t))return t;return null},Vo=n=>({matched:false,args:[],flags:{},json:void 0,raw:n});function vn(n,e){let t=Jo(n,e);if(t===null)return Vo(n);let r=n.slice(t.length),s=Go(r),i={matched:true,args:[],flags:{},json:void 0,raw:n};if(s.length===0)return i.name="",i;i.name=(s[0]??"").toLowerCase();let o=false;for(let a=1;a<s.length;a+=1){let c=s[a];if(c!==void 0){if(c.startsWith("--")){let d=c.slice(2);if(d.length===0){i.args.push(c);continue}let l=d.indexOf("=");if(l!==-1){let w=d.slice(0,l),M=d.slice(l+1);i.flags[w]=M;continue}let u=s[a+1];u!==void 0&&!u.startsWith("--")?(i.flags[d]=u,a+=1):i.flags[d]=true;continue}if(!o&&qo(c)){let d=Ko(c);d.ok&&(i.json=d.value,o=true);}i.args.push(c);}}return i}var qr=n=>{let e=n.trim().split(/\s+/).filter(t=>t.length>0).map(t=>t.toLowerCase());if(e.length===0)throw new _("INVALID_COMMAND_NAME","empty command segment in spec");return e},we=n=>n.join(" "),Ke=class{paths=new Map;defs=[];maxDepth=1;register(e,t){if(e.trim().length===0)throw new _("INVALID_COMMAND_NAME","command spec must not be empty");let r=e.split("|").map(a=>qr(a)),s=r[0],i=r.slice(1).map(a=>we(a)),o={name:we(s),aliases:i,parts:s,handler:t};for(let a of r){let c=we(a);if(this.paths.has(c))throw new _("DUPLICATE_COMMAND",`command "${c}" is already registered`)}for(let a of r)this.paths.set(we(a),o),a.length>this.maxDepth&&(this.maxDepth=a.length);this.defs.push(o);}resolve(e){if(!e.matched||e.name===void 0||e.name.length===0)return;let t=[e.name.toLowerCase(),...e.args.map(s=>s.toLowerCase())],r=Math.min(this.maxDepth,t.length);for(let s=r;s>=1;s-=1){let i=t.slice(0,s).join(" "),o=this.paths.get(i);if(o!==void 0)return {def:o,args:e.args.slice(s-1)}}}unregister(e){let t=e.split("|").map(o=>qr(o)),r=we(t[0]),s=this.paths.get(r);if(s===void 0)return;for(let o of [s.parts,...s.aliases.map(a=>a.split(" "))])this.paths.delete(we(o));let i=this.defs.indexOf(s);i>=0&&this.defs.splice(i,1),this.maxDepth=this.defs.reduce((o,a)=>Math.max(o,a.parts.length),1);}list(){return [...this.defs]}};async function Mn(n,e,t){let r=-1,s={error:void 0,thrown:false},i=async o=>{if(o<=r)throw new _("MIDDLEWARE_ERROR","next() called multiple times");if(r=o,o===n.length){try{await t();}catch(c){throw s.error=c,s.thrown=true,c}return}let a=n[o];try{await a(e,()=>i(o+1));}catch(c){throw s.thrown||c instanceof _?c:new _("MIDDLEWARE_ERROR","middleware threw during execution",{cause:c})}};await i(0);}function Sn(n){if(n.prefixes.length===0)return {detach(){}};let e=s=>{let i=vn(s.text,n.prefixes);if(!i.matched)return;let o=n.registry.resolve(i);if(o===void 0)return;let a={command:o.def.name,args:o.args,flags:i.flags,json:i.json,raw:i.raw},c=n.buildContext(a,s);Promise.resolve(Mn(n.middleware,c,()=>o.def.handler(c))).catch(d=>{let l=d instanceof _?d:new _("HANDLER_ERROR","command handler failed",{cause:d});n.logger.error(l,"command dispatch failed");});},t=n.onText(e),r=false;return {detach(){r||(r=true,t());}}}var Me=new Map,$r=n=>n!=null&&typeof n=="object"?n:null,Gr=n=>Array.isArray(n.content)?n.content.map($r).filter(e=>e!==null):[],Kr=(n,e)=>Gr(n).find(t=>t.tag===e),ve=n=>typeof n=="string"&&n.length>0?n:void 0,bn=n=>{if(n===void 0)return;let e=Number.parseInt(n,10);return Number.isFinite(e)?e:void 0},Ho=(n,e)=>{if(Object.keys(e).length!==0){if(Me.size>=64){let t=Me.keys().next().value;t!==void 0&&Me.delete(t);}Me.set(n,e);}},Jr=n=>{let e=$r(n);if(e===null||e.tag!=="call")return false;let t=Gr(e).find(v=>v.tag==="offer"),r=ve(t?.attrs?.["call-id"]);if(t===void 0||r===void 0)return false;let s={},i=ve(e.attrs?.platform),o=ve(e.attrs?.version),a=ve(e.attrs?.notify),c=ve(t.attrs?.caller_country_code),d=ve(t.attrs?.caller_pn);i!==void 0&&(s.platform=i),o!==void 0&&(s.appVersion=o),a!==void 0&&(s.name=a),c!==void 0&&(s.countryCode=c),d!==void 0&&(s.phoneJid=d);let l=bn(Kr(t,"net")?.attrs?.medium);l!==void 0&&(s.networkMedium=l);let u=Kr(t,"video"),w=bn(u?.attrs?.screen_width),M=bn(u?.attrs?.screen_height);return w!==void 0&&M!==void 0&&(s.screen={width:w,height:M}),Ho(r,s),true},Vr=n=>{let e=Me.get(n);return e!==void 0&&Me.delete(n),e};var Hr=n=>n;var $e=class{host;logger;plugins=new Map;constructor(e){this.host=e.client,this.logger=e.logger??e.client.logger;}has(e){return this.plugins.has(e)}list(){return [...this.plugins.keys()]}async loadPlugin(e,t){if(typeof e?.name!="string"||typeof e?.setup!="function"){this.logger?.warn({file:t},"plugin: invalid shape (need name + setup); skipped");return}if(this.plugins.has(e.name)){this.logger?.warn({name:e.name,file:t},"plugin: duplicate name; skipped");return}let r=[],s={client:this.host,logger:this.logger,pluginDir:Ze__default.default.dirname(t),command:(i,o)=>{this.host.command(i,o),r.push(()=>this.host.unregisterCommand(i));},use:i=>{this.host.use(i),r.push(()=>{this.host.unuse(i);});},on:(i,o)=>{let a=this.host.on(i,o);return r.push(a),a},once:(i,o)=>{let a=false,c=this.host.on(i,d=>{a||(a=true,c(),o(d));});return r.push(c),c}};try{let i=await e.setup(s);typeof i=="function"&&r.push(i);}catch(i){for(let o of [...r].reverse())try{await o();}catch{}this.logger?.error({err:i,name:e.name,file:t},"plugin: setup failed; skipped");return}this.plugins.set(e.name,{plugin:e,file:t,disposers:r});}async unload(e){let t=this.plugins.get(e);if(t){this.plugins.delete(e);for(let r of [...t.disposers].reverse())try{await r();}catch(s){this.logger?.warn({err:s,name:e},"plugin: disposer threw");}try{await t.plugin.onUnload?.();}catch(r){this.logger?.warn({err:r,name:e},"plugin: onUnload threw");}}}async unloadAll(){for(let e of this.list())await this.unload(e);}};var Qo=/\.(ts|js|mjs|cjs)$/,Xo=/(\.d\.ts$|^_|[/\\]_)/;async function Cn(n,e,t){let r;try{r=await fs$1.promises.readdir(n,{withFileTypes:!0});}catch{return []}let s=[];for(let i of r){let o=Ze__default.default.join(n,i.name);t.test(i.name)||t.test(o)||(i.isDirectory()?s.push(...await Cn(o,e,t)):e.test(i.name)&&s.push(o));}return s}async function Yr(n,e){try{let r=await import(url.pathToFileURL(n).href+(e!==void 0?`?t=${e}`:"")),s=r.default??r;return s&&typeof s.name=="string"&&typeof s.setup=="function"?s:void 0}catch{return}}var Ge=class{dir;pattern;ignore;watchEnabled;onError;registry;logger;watcher;fileToName=new Map;bust=0;debounce;pending=new Set;flushChain=Promise.resolve();constructor(e){this.registry=e.registry,this.logger=e.logger,this.dir=Ze__default.default.resolve(e.options.dir??"./plugins"),this.pattern=e.options.pattern??Qo,this.ignore=e.options.ignore??Xo,this.watchEnabled=e.options.watch!==false,this.onError=e.options.onError;}async start(){let e=await Cn(this.dir,this.pattern,this.ignore);for(let t of e)await this.loadFile(t);this.watchEnabled&&this.startWatch();}async stop(){this.debounce&&clearTimeout(this.debounce),this.watcher?.close(),this.watcher=void 0,await this.flushChain,await this.registry.unloadAll(),this.fileToName.clear();}async loadFile(e){let t=await Yr(e,this.bust);if(!t){let i=new Error(`failed to import plugin: ${e}`);this.onError?.(i,e),this.logger?.warn({file:e},"plugin: import failed; skipped");return}let r=this.registry.list();await this.registry.loadPlugin(t,e);let s=this.registry.list().find(i=>!r.includes(i));s&&this.fileToName.set(e,s);}startWatch(){try{this.watcher=fs$1.watch(this.dir,{recursive:!0},(e,t)=>{if(t==null)return;let r=Ze__default.default.join(this.dir,t.toString());this.ignore.test(t.toString())||!this.pattern.test(t.toString())||(this.pending.add(r),this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>{this.flushChain=this.flushChain.then(()=>this.flush());},150),this.debounce.unref?.());});}catch(e){this.logger?.warn({err:e,dir:this.dir},"plugin: watch unavailable; hot-reload disabled");}}async flush(){let e=[...this.pending];this.pending.clear(),this.bust+=1;for(let t of e){let r=this.fileToName.get(t);r&&(await this.registry.unload(r),this.fileToName.delete(t));let s=true;try{await fs$1.promises.access(t);}catch{s=false;}s&&await this.loadFile(t);}}};var x=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysAutomationError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var ea=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),oe=class{now;sleep;perJidRatePerMs;perJidCapacity;global;perJid=new Map;constructor(e,t={}){if(!(e.perSec>0))throw new x("RATE_LIMIT_INVALID","perSec must be greater than zero");if(e.perJidPerSec!==void 0&&!(e.perJidPerSec>0))throw new x("RATE_LIMIT_INVALID","perJidPerSec must be greater than zero");if(e.burst!==void 0&&!(e.burst>0))throw new x("RATE_LIMIT_INVALID","burst must be greater than zero");this.now=t.now??Date.now,this.sleep=t.sleep??ea;let r=e.burst??e.perSec;this.global={tokens:r,capacity:r,ratePerMs:e.perSec/1e3,last:this.now()},e.perJidPerSec!==void 0&&(this.perJidRatePerMs=e.perJidPerSec/1e3,this.perJidCapacity=e.perJidPerSec);}async acquire(e){await this.consume(this.global),e!==void 0&&this.perJidRatePerMs!==void 0&&await this.consume(this.bucketFor(e));}bucketFor(e){let t=this.perJid.get(e);if(t)return t;let r=this.perJidCapacity??1,s={tokens:r,capacity:r,ratePerMs:this.perJidRatePerMs??1,last:this.now()};return this.perJid.set(e,s),s}consume(e){if(this.refill(e),e.tokens>=1)return e.tokens-=1,Promise.resolve();let t=(1-e.tokens)/e.ratePerMs;return e.tokens-=1,this.sleep(t)}refill(e){let t=this.now(),r=t-e.last;r>0&&(e.tokens=Math.min(e.capacity,e.tokens+r*e.ratePerMs),e.last=t);}};var ta={"group.create":6e4,"group.join":3e4,"group.participants":1e4,"group.update":3e3,"community.create":12e4,"community.join":3e4,"community.update":3e3,"newsletter.create":12e4,"newsletter.follow":2e3,"newsletter.update":3e3},na=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n));function Pn(n={},e={}){let t=n.enabled??true,r=e.now??Date.now,s=e.sleep??na,i={...ta,...n.intervalsMs??{}},o=new Map,a=new Map,c=async(d,l)=>{let u=i[d]??0,w=o.get(d);if(w!==void 0&&u>0){let M=u-(r()-w);M>0&&await s(M);}return o.set(d,r()),l()};return {run(d,l){if(!t)return l();let w=(a.get(d)??Promise.resolve()).then(()=>c(d,l),()=>c(d,l));return a.set(d,w.then(()=>{},()=>{})),w}}}var ra={maxRetries:0,backoffMs:()=>0},sa=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),Je=class{concurrency;retry;sleep;pending=[];active=0;idleWaiters=[];constructor(e={},t={}){this.concurrency=e.concurrency??1,this.retry=e.retry??ra,this.sleep=t.sleep??sa;}add(e){return new Promise((t,r)=>{this.pending.push({run:()=>this.execute(e).then(t,r)}),this.pump();})}onIdle(){return this.active===0&&this.pending.length===0?Promise.resolve():new Promise(e=>{this.idleWaiters.push(e);})}pump(){for(;this.active<this.concurrency&&this.pending.length>0;){let e=this.pending.shift();if(!e)break;this.active++,e.run().finally(()=>{this.active--,this.pump(),this.settleIdle();});}}settleIdle(){if(this.active===0&&this.pending.length===0&&this.idleWaiters.length>0){let e=this.idleWaiters;this.idleWaiters=[];for(let t of e)t();}}async execute(e){let t=0;for(;;)try{return await e()}catch(r){if(t>=this.retry.maxRetries)throw r;t+=1,await this.sleep(this.retry.backoffMs(t));}}};var ia=n=>n instanceof Error?n:new Error(typeof n=="string"?n:String(n));async function kn(n,e,t,r={}){let s={sent:[],failed:[]};if(n.length===0)return s;let i=r.rateLimitPerSec??5,o={};t.now&&(o.now=t.now),t.sleep&&(o.sleep=t.sleep);let a=t.limiter??new oe({perSec:i},o),c=r.retry,d=t.sleep?{sleep:t.sleep}:{},l=c?new Je({concurrency:1,retry:c},d):void 0,u=n.length,w=0;for(let M of n){await a.acquire(M);let v=()=>e(t.sendTo(M)).then(()=>{});try{l?await l.add(v):await v(),s.sent.push(M),w+=1,r.onProgress?.(w,u,M,!0);}catch(P){s.failed.push({jid:M,error:ia(P)}),w+=1,r.onProgress?.(w,u,M,false);}}return s}var oa=1e3,Ve=class{constructor(e,t,r){this.getSocket=e;this.throttleEnabled=t?.enabled??true,this.minIntervalMs=t?.minIntervalMs??oa,this.now=r?.now??Date.now;}throttleEnabled;minIntervalMs;now;lastSent=new Map;requireSocket(){let e=this.getSocket();if(!e)throw new x("NOT_CONNECTED","client not connected");return e}throttled(e,t){if(!this.throttleEnabled||this.minIntervalMs<=0)return false;let r=`${e}:${t??"global"}`,s=this.lastSent.get(r),i=this.now();return s!==void 0&&i-s<this.minIntervalMs?true:(this.lastSent.set(r,i),false)}async update(e,t){let r=this.requireSocket();if(!this.throttled(e,t))try{await(t===void 0?r.sendPresenceUpdate(e):r.sendPresenceUpdate(e,t));}catch(s){throw new x("PRESENCE_FAILED",`presence update '${e}' failed`,{cause:s})}}scheduleClear(e,t){let r=this.getSocket();if(!r)return;let s=setTimeout(()=>{r.sendPresenceUpdate("paused",e).catch(()=>{});},t);typeof s.unref=="function"&&s.unref();}async online(){await this.update("available");}async offline(){await this.update("unavailable");}async typing(e,t){await this.update("composing",e),t!==void 0&&this.scheduleClear(e,t);}async recording(e,t){await this.update("recording",e),t!==void 0&&this.scheduleClear(e,t);}};var ca={set:(n,e)=>setTimeout(n,e),clear:n=>clearTimeout(n)},da=n=>typeof n=="object"&&n!==null&&typeof n.recipient=="string"&&typeof n.content=="object",He=class{store;sendSnapshot;now;timer;logger;acquire;memory=new Map;timers=new Map;constructor(e){this.store=e.store,this.sendSnapshot=e.sendSnapshot,this.now=e.now??(()=>Date.now()),this.timer=e.timer??ca,this.logger=e.logger,this.acquire=e.acquire;}async scheduleAt(e,t){let r=e.getTime();if(Number.isNaN(r))throw new x("SCHEDULE_INVALID","scheduleAt requires a valid Date");let s=await this.evaluate(t),i=crypto.randomUUID(),o={id:i,fireAt:r,recipient:s.recipient,payload:s};return await this.persist(o),this.arm(o),{id:i,cancel:()=>{this.cancel(i);}}}async loadPending(){let e=this.store.listScheduledJobs;if(!e){for(let r of this.memory.values())this.timers.has(r.id)||this.arm(r);return}let t;try{t=await e.call(this.store);}catch(r){this.logger?.warn(r,"scheduler loadPending failed");return}for(let r of t)this.timers.has(r.id)||(this.memory.set(r.id,r),this.arm(r));}dispose(){for(let e of this.timers.values())this.timer.clear(e);this.timers.clear();}cancel(e){let t=this.timers.get(e);t!==void 0&&(this.timer.clear(t),this.timers.delete(e)),this.memory.delete(e),this.remove(e);}arm(e){let t=Math.max(0,e.fireAt-this.now()),r=this.timer.set(()=>{this.fire(e);},t);this.timers.set(e.id,r);}async fire(e){if(this.timers.delete(e.id),da(e.payload))try{this.acquire&&await this.acquire(),await this.sendSnapshot(e.payload);}catch(t){this.logger?.warn(t,"scheduled send failed; retaining job for retry");return}this.memory.delete(e.id),await this.remove(e.id);}async persist(e){let t=this.store.saveScheduledJob;if(t){await t.call(this.store,e);return}this.memory.set(e.id,e);}async remove(e){let t=this.store.deleteScheduledJob;if(t)try{await t.call(this.store,e);}catch(r){this.logger?.warn(r,"scheduler deleteScheduledJob failed");}this.memory.delete(e);}async evaluate(e){let t,r=0,s={sendMessage:async(o,a,c)=>{if(r+=1,r>1)throw new x("SCHEDULE_INVALID","scheduling multi-part messages (e.g. album) is not supported; schedule a single message");return t=c?{recipient:o,content:a,options:c}:{recipient:o,content:a},{key:{remoteJid:o,id:"scheduled-snapshot",fromMe:true}}},relayMessage:async()=>{throw new x("SCHEDULE_INVALID","scheduling interactive/relayed content is not supported; schedule a text or media message")}},i=Y.create(s,"");try{await e(i);}catch(o){throw o instanceof x?o:new x("SCHEDULE_INVALID","scheduled builder evaluation failed",{cause:o})}if(!t)throw new x("SCHEDULE_INVALID","scheduled builder produced no content");return t}};async function Zr(n,e){if(typeof n.deleteMessage!="function"||typeof n.listChats!="function")return 0;let t=await n.listChats(),r=0;for(let s of t){let i=s.id??"";if(i.length===0||e.chatFilter&&!e.chatFilter(i))continue;let a=[...await n.listMessages(i)].sort((c,d)=>Number(d.messageTimestamp??0)-Number(c.messageTimestamp??0));for(let c=0;c<a.length;c+=1){let d=a[c],l=Number(d.messageTimestamp??0),u=e.olderThan!==void 0&&l<e.olderThan,w=e.maxPerChat!==void 0&&c>=e.maxPerChat;(u||w)&&(await n.deleteMessage(d.key),r+=1);}}return r}var ze=class{store;options;logger;now;timer;running=false;warnedUnsupported=false;disabled=false;constructor(e){this.store=e.store,this.options=e.options,this.logger=e.logger,this.now=e.now??Date.now;}get active(){return this.options.maxAgeMs!==void 0||this.options.maxPerChat!==void 0}buildPruneOptions(){let e={};return this.options.maxAgeMs!==void 0&&(e.olderThan=Math.floor((this.now()-this.options.maxAgeMs)/1e3)),this.options.maxPerChat!==void 0&&(e.maxPerChat=this.options.maxPerChat),typeof this.options.chats=="function"&&(e.chatFilter=this.options.chats),e}async runOnce(){if(!this.active||this.disabled)return 0;let e=this.buildPruneOptions();return typeof this.store.pruneMessages=="function"?this.store.pruneMessages(e):typeof this.store.deleteMessage=="function"?Zr(this.store,e):(this.disabled=true,this.warnedUnsupported||(this.warnedUnsupported=true,this.logger?.warn({code:"AUTO_DELETE_UNSUPPORTED"},"autoDelete: store implements neither pruneMessages nor deleteMessage; sweeper disabled")),0)}start(){if(!this.active||this.timer)return;let e=this.options.intervalMs??6e4;this.timer=setInterval(()=>{this.running||(this.running=true,this.runOnce().catch(t=>this.logger?.warn(t,"autoDelete sweep failed")).finally(()=>{this.running=false;}));},e),this.timer.unref?.();}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0);}};var Qr=n=>(n.split(/[:@]/)[0]??"").replace(/\D/g,""),Ye=class{getSocket;options;logger;constructor(e,t,r){this.getSocket=e,this.options=t,this.logger=r;}get enabled(){return this.options.enabled===true}async reject(e,t){let r=this.getSocket();if(!r)throw new x("NOT_CONNECTED","cannot reject a call: client not connected");await r.rejectCall(e,t);}async handle(e){if(this.enabled&&!await this.isAllowed(e.from)){try{await this.reject(e.callId,e.from);}catch(t){this.logger?.warn(t,"autoRejectCall: rejectCall failed");return}try{await this.options.onReject?.(e);}catch(t){this.logger?.warn(t,"autoRejectCall: onReject hook failed");}}}async isAllowed(e){let t=this.options.allow;if(t===void 0)return false;try{if(Array.isArray(t)){let r=Qr(e);return t.some(s=>s===e||Qr(s)===r)}return await t(e)===!0}catch(r){return this.logger?.warn(r,"autoRejectCall: allow predicate threw"),false}}};var la={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},ua=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[la[e]];if(r==null||typeof r!="object")return null;let s=r.mimetype;return typeof s=="string"&&s.length>0?s:null},Pt=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys'),s=await r(n,"buffer",{}),i=ua(n,e)??"application/octet-stream";return {buffer:s,mime:i,size:s.byteLength}}catch(r){throw t?.warn({error:r,kind:e,id:n.key?.id},"media download failed"),r instanceof Error?r:new Error("media download failed")}},Xr=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys');return await r(n,"stream",{})}catch(r){throw t?.warn({error:r,kind:e,id:n.key?.id},"media stream download failed"),r instanceof Error?r:new Error("media stream download failed")}};var ae="[zaileys]",pa="The saved session looks invalid or corrupted (connection keeps closing before it authenticates). Delete the auth folder (default: ./.zaileys) and run again to scan a fresh QR / request a new pairing code.";function ts(n){switch(n.kind){case "connecting":return `${ae} Connecting to WhatsApp (session: ${n.sessionId})...`;case "qr":return `${ae} Scan the QR code above with WhatsApp > Linked devices to authenticate.`;case "pairing-code":return `${ae} Pairing code: ${n.code} \u2014 enter it in WhatsApp > Linked devices > Link with phone number.`;case "connected":return `${ae} Connected as ${n.id}.`;case "reconnecting":{let e=(n.delayMs/1e3).toFixed(1),t=`${ae} Connection lost (${n.reason}). Reconnecting in ${e}s (attempt ${n.attempt})...`;return n.invalidCredsSuspected?`${t}
12
12
  ${ae} ${pa}`:t}case "disconnect":return n.willReconnect?null:`${ae} Disconnected (${n.reason}).`;default:return null}}var es=false,ma=["Closing session:","Closing open session","Closing stale open session","Opening session:","Removing old closed session","Migrating session to:","Session already closed","Decrypted message with closed session","Failed to decrypt message with any known session","Session error:"],ga=n=>typeof n[0]=="string"&&ma.some(e=>n[0].startsWith(e));function ns(){if(es)return;es=true;let n=e=>{let t=console[e].bind(console);console[e]=(...r)=>{ga(r)||t(...r);};};n("info"),n("warn"),n("error");}var h=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysStoreError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var ha="./.zaileys/auth",ya=n=>n.replace(/[^a-zA-Z0-9._-]/g,e=>`_${e.charCodeAt(0).toString(16)}`),Qe=n=>typeof n=="object"&&n!==null&&n.code==="ENOENT",Et=class{basePath;closed=false;constructor(e){this.basePath=e?.basePath??ha;}signal={read:async(e,t)=>{this.assertOpen();let r={};return await Promise.all(t.map(async s=>{let i=this.signalPath(e,s);try{let o=await fs$1.promises.readFile(i,"utf8");r[s]=JSON.parse(o,Yc.BufferJSON.reviver);}catch(o){if(Qe(o))return;throw new h("STORE_READ_FAILED",`failed to read ${i}`,{cause:o})}})),r},write:async e=>{this.assertOpen();let t=[];for(let r of Object.keys(e)){let s=e[r];if(!s)continue;let i=this.signalDir(r);await fs$1.promises.mkdir(i,{recursive:true});for(let o of Object.keys(s)){let a=s[o],c=this.signalPath(r,o);a===null?t.push(fs$1.promises.unlink(c).catch(d=>{if(!Qe(d))throw new h("STORE_WRITE_FAILED",`failed to unlink ${c}`,{cause:d})})):a!==void 0&&t.push(this.atomicWrite(c,JSON.stringify(a,Yc.BufferJSON.replacer)));}}await Promise.all(t);},delete:async(e,t)=>{this.assertOpen(),await Promise.all(t.map(async r=>{let s=this.signalPath(e,r);try{await fs$1.promises.unlink(s);}catch(i){if(!Qe(i))throw new h("STORE_WRITE_FAILED",`failed to unlink ${s}`,{cause:i})}}));},clear:async()=>{this.assertOpen(),await fs$1.promises.rm(this.basePath,{recursive:true,force:true});},close:async()=>{this.closed=true;}};creds={readCreds:async()=>{this.assertOpen();try{let e=await fs$1.promises.readFile(this.credsPath(),"utf8");return JSON.parse(e,Yc.BufferJSON.reviver)}catch(e){if(Qe(e))return;throw new h("STORE_READ_FAILED","failed to read creds.json",{cause:e})}},writeCreds:async e=>{this.assertOpen(),await fs$1.promises.mkdir(this.basePath,{recursive:true}),await this.atomicWrite(this.credsPath(),JSON.stringify(e,Yc.BufferJSON.replacer));},deleteCreds:async()=>{this.assertOpen();try{await fs$1.promises.unlink(this.credsPath());}catch(e){if(!Qe(e))throw new h("STORE_WRITE_FAILED","failed to delete creds.json",{cause:e})}}};credsPath(){return Ze__default.default.join(this.basePath,"creds.json")}signalDir(e){return Ze__default.default.join(this.basePath,"signal",String(e))}signalPath(e,t){return Ze__default.default.join(this.signalDir(e),`${ya(t)}.json`)}async atomicWrite(e,t){let r=Ze__default.default.join(Ze__default.default.dirname(e),`tmp-${crypto.randomBytes(8).toString("hex")}`);try{await fs$1.promises.writeFile(r,t,"utf8"),await fs$1.promises.rename(r,e);}catch(s){throw await fs$1.promises.unlink(r).catch(()=>{}),new h("STORE_WRITE_FAILED",`failed to write ${e}`,{cause:s})}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","FileAuthStore is closed")}};function rs(n,e){let t=n.signal,s=Yc.makeCacheableSignalKeyStore({get:(o,a)=>t.read(o,a),set:o=>t.write(o),clear:()=>t.clear()},e?.logger??void 0),i={read:async(o,a)=>await s.get(o,[...a]),write:async o=>{await s.set(o);},delete:async(o,a)=>{await t.delete(o,a);let c={},d={};for(let l of a)d[l]=null;c[o]=d,await s.set(c);},clear:async()=>{let o=s.clear;typeof o=="function"?await o.call(s):await t.clear();},close:()=>t.close()};return {creds:n.creds,signal:i}}function ss(n,e){return {get:async(t,r)=>await n.read(t,r),set:async t=>{await n.write(t);},clear:async()=>{await n.clear();}}}var va=429;function is(n){if(n===va)return "rate-limited";switch(n){case Yc.DisconnectReason.loggedOut:return "logged-out";case Yc.DisconnectReason.forbidden:return "forbidden";case Yc.DisconnectReason.connectionLost:return "connection-lost";case Yc.DisconnectReason.multideviceMismatch:return "multi-device-mismatch";case Yc.DisconnectReason.connectionClosed:return "connection-closed";case Yc.DisconnectReason.connectionReplaced:return "connection-replaced";case Yc.DisconnectReason.badSession:return "bad-session";case Yc.DisconnectReason.unavailableService:return "unavailable-service";case Yc.DisconnectReason.restartRequired:return "restart-required";default:return "unknown"}}function Xe(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"}function Tt(n){return n==="rate-limited"}function os(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"||n==="bad-session"}function ug(n){return !Xe(n)}var It={enabled:true,maxQrAttempts:5,maxPairingAttempts:3,pairingCooldownMs:6e4},Ma=3e5;function as(n={}){let e=n.enabled??It.enabled,t=n.maxQrAttempts??It.maxQrAttempts,r=n.maxPairingAttempts??It.maxPairingAttempts,s=n.pairingCooldownMs??It.pairingCooldownMs,i=0,o=0,a=0,c=w=>w<=0?0:Math.min(s*w,Ma);return {evaluate:(w,M)=>{if(!e)return {allowed:true,waitMs:0,attempts:w==="pairing"?o:i,max:Number.POSITIVE_INFINITY};if(w==="pairing"){if(o>=r)return {allowed:false,reason:"budget-exhausted",waitMs:0,attempts:o,max:r};let v=c(o),P=M-a;return o>0&&P<v?{allowed:false,reason:"cooldown",waitMs:v-P,attempts:o,max:r}:{allowed:true,waitMs:0,attempts:o,max:r}}return i>=t?{allowed:false,reason:"budget-exhausted",waitMs:0,attempts:i,max:t}:{allowed:true,waitMs:0,attempts:i,max:t}},record:(w,M)=>{w==="pairing"?(o+=1,a=M):i+=1;},reset:()=>{i=0,o=0,a=0;},get enabled(){return e},get qrAttempts(){return i},get pairingAttempts(){return o}}}var Sa=/[\s\-()+]/g;function ba(n){return typeof n!="string"?"":n.replace(Sa,"")}function Aa(n){if(!n||typeof n!="string"||!n.trim())throw new Error("phoneNumber is required");let e=ba(n);if(!/^\d+$/.test(e))throw new Error("phoneNumber must be E.164 with country code");if(e.length<8||e.length>15)throw new Error("phoneNumber must be E.164 with country code");return e}function cs(n){let e=Aa(n.phoneNumber),t=n.ttlMs??6e4;return {phoneNumber:e,async requestCode(r){let s;try{s=await r.requestPairingCode(e);}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`failed to request pairing code: ${o}`)}return {code:s,expiresAt:Date.now()+t}}}}function Pa(n){return !n||typeof n!="string"||!n.trim()?Promise.reject(new Error("qr string is required")):new Promise(e=>{Ca__default.default.generate(n,{small:true},t=>e(t));})}async function ds(n,e=t=>{process.stdout.write(t);}){let t=await Pa(n);e(t+`
13
- `);}var Se={enabled:true,maxAttempts:Number.POSITIVE_INFINITY,initialDelayMs:3e3,maxDelayMs:6e4,jitterFactor:.2,rateLimitedDelayMs:3e5};function ls(n,e){let t=n?.enabled??Se.enabled,r=n?.maxAttempts??Se.maxAttempts,s=n?.initialDelayMs??Se.initialDelayMs,i=n?.maxDelayMs??Se.maxDelayMs,o=n?.jitterFactor??Se.jitterFactor,a=n?.rateLimitedDelayMs??Se.rateLimitedDelayMs,c=e?.random??Math.random,d=0;return {next:w=>{if(!t||Xe(w))return null;let M=d+1;if(M>r)return null;if(d=M,Tt(w))return {attempt:M,delayMs:a};let v=Math.pow(2,M-1),P=Math.min(i,s*v),y=1+(c()*2-1)*o,m=P*y,f=Math.min(i,Math.max(0,m));return {attempt:M,delayMs:Math.round(f)}},reset:()=>{d=0;},get attempts(){return d}}}var ka={idle:["connecting"],connecting:["qr-pending","pairing-pending","connected","reconnecting","disconnecting","disconnected"],"qr-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],"pairing-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],connected:["disconnecting","reconnecting","disconnected"],reconnecting:["connecting","disconnecting","disconnected"],disconnecting:["disconnected"],disconnected:["idle","connecting","reconnecting"]};function us(n="idle"){let e=n,t=new Set,r=s=>ka[e].includes(s);return {get state(){return e},canTransition:r,transition(s){if(!r(s))throw new Error(`invalid state transition: ${e} -> ${s}`);let i=e;e=s;for(let o of t)try{o(i,s);}catch{}},onChange(s){return t.add(s),()=>{t.delete(s);}}}}var xt=n=>`${n.remoteJid??""}|${n.id??""}|${n.fromMe?1:0}`,Ot=class{messages=new Map;messagesByJid=new Map;chats=new Map;contacts=new Map;presence=new Map;boundSocket;listeners=new Map;closed=false;async saveMessage(e){this.assertOpen();let t=xt(e.key);this.messages.set(t,structuredClone(e));let r=e.key.remoteJid??"",s=this.messagesByJid.get(r);s||(s=new Set,this.messagesByJid.set(r,s)),s.add(t);}async getMessage(e){this.assertOpen();let t=this.messages.get(xt(e));return t?structuredClone(t):void 0}async listMessages(e,t){this.assertOpen();let r=this.messagesByJid.get(e);if(!r)return [];let s=[];for(let o of r){let a=this.messages.get(o);a&&s.push(a);}s.sort((o,a)=>Number(a.messageTimestamp)-Number(o.messageTimestamp));let i=s;if(typeof t?.before=="number"){let o=t.before;i=i.filter(a=>Number(a.messageTimestamp)<o);}return typeof t?.limit=="number"&&(i=i.slice(0,t.limit)),i.map(o=>structuredClone(o))}async saveChat(e){this.assertOpen();let t=e.id;t&&this.chats.set(t,structuredClone(e));}async getChat(e){this.assertOpen();let t=this.chats.get(e);return t?structuredClone(t):void 0}async listChats(e){this.assertOpen();let t=[];for(let r of this.chats.values())e?.archived===true&&r.archived!==true||t.push(structuredClone(r));return t}async saveContact(e){this.assertOpen(),this.contacts.set(e.id,structuredClone(e));}async getContact(e){this.assertOpen();let t=this.contacts.get(e);return t?structuredClone(t):void 0}async listContacts(){return this.assertOpen(),Array.from(this.contacts.values(),e=>structuredClone(e))}async savePresence(e,t){this.assertOpen(),this.presence.set(e,structuredClone(t));}async getPresence(e){this.assertOpen();let t=this.presence.get(e);return t?structuredClone(t):void 0}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...c)=>{let l=c[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let u=this.messages.get(xt(l.key));if(u){let w={...u,...l.update};this.saveMessage(w).catch(()=>{});}}},s=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveChat(l).catch(()=>{});},i=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let w={...this.chats.get(l.id)??{},...l};this.saveChat(w).catch(()=>{});}},o=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveContact(l).catch(()=>{});},a=(...c)=>{let d=c[0];if(d?.presences)for(let l of Object.keys(d.presences)){let u=d.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[c,d]of this.listeners)e.ev.on(c,d);}async deleteMessage(e){this.assertOpen();let t=xt(e);this.messages.delete(t);let r=e.remoteJid??"",s=this.messagesByJid.get(r);s&&(s.delete(t),s.size===0&&this.messagesByJid.delete(r));}async pruneMessages(e){this.assertOpen();let t=0;for(let[r,s]of [...this.messagesByJid.entries()]){if(e.chatFilter&&!e.chatFilter(r))continue;let i=[];for(let a of s){let c=this.messages.get(a);c&&i.push(c);}i.sort((a,c)=>Number(c.messageTimestamp??0)-Number(a.messageTimestamp??0));let o=i.filter((a,c)=>{let d=Number(a.messageTimestamp??0);return e.olderThan!==void 0&&d<e.olderThan||e.maxPerChat!==void 0&&c>=e.maxPerChat});for(let a of o)await this.deleteMessage(a.key),t+=1;}return t}async clear(){this.assertOpen(),this.messages.clear(),this.messagesByJid.clear(),this.chats.clear(),this.contacts.clear(),this.presence.clear();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);return this.listeners.clear(),this.boundSocket=void 0,Promise.resolve()}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","MemoryMessageStore is closed")}};var Ta=["silent","fatal","error","warn","info","debug","trace"];function Ia(n){if(n)return n;let e=process.env.ZAILEYS_DEBUG;return e===void 0?"silent":e==="1"?"info":Ta.includes(e)?e:"silent"}function xa(n={}){let e=Ia(n.level),t=Ea__default.default({level:e});return n.sessionId!==void 0?t.child({sessionId:n.sessionId}):t}var ps=["debug","info","warn","error","fatal"];function Oa(n){if(n===null||typeof n!="object")return false;for(let e of ps)if(typeof n[e]!="function")return false;return true}function et(){}function Ra(n){let e={debug:et,info:et,warn:et,error:et,fatal:et};for(let t of ps){let r=n[t];typeof r=="function"&&(e[t]=r.bind(n));}return e}function En(n,e){return n===void 0?e??xa():Oa(n)?n:Ra(n)}var Cg=Object.freeze(["HISTORY_SYNC_NOTIFICATION","APP_STATE_SYNC_KEY_SHARE","LID_MIGRATION_MAPPING_SYNC","PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]),ms=n=>{let e=n.requestId!=null,t=n.messages.filter(r=>{if(e)return false;let s=r.messageStubParameters;if(Array.isArray(s)){for(let i of s)if(typeof i=="string"&&i.startsWith("requestId:"))return false}return true});return {...n,messages:t}};var _a=new Set(["offer","ringing"]),La=new Set(["timeout","reject","accept","terminate"]),gs=n=>{let e=n instanceof Date?n.getTime():Date.parse(String(n));return Number.isFinite(e)?e:0},fs=n=>{if(typeof n.id!="string"||n.id.length===0||!_a.has(n.status))return null;let e=Vr(n.id),t={kind:"incoming",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:gs(n.date),status:n.status};return e!==void 0&&(t.caller=e),t},hs=n=>typeof n.id!="string"||n.id.length===0||!La.has(n.status)?null:{kind:"ended",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:gs(n.date),status:n.status};var B=n=>typeof n=="string"&&n.length>0,Na=n=>{let e={};return typeof n.subject=="string"&&(e.subject=n.subject),typeof n.desc=="string"&&(e.description=n.desc),typeof n.announce=="boolean"&&(e.announce=n.announce),typeof n.restrict=="boolean"&&(e.restrict=n.restrict),typeof n.ephemeralDuration=="number"&&(e.ephemeralDuration=n.ephemeralDuration),e},ys=(n,e,t)=>n.filter(r=>B(r?.id)).map(r=>{let s={jid:r.id},i=r.lid??r.pn??r.phoneNumber;return B(i)&&(s.participantAlt=i),B(e)&&(s.authorPn=e),B(t)&&(s.authorUsername=t),s.isAdmin=r.admin==="admin"||r.admin==="superadmin",s}),ws=n=>B(n?.id)?{groupId:n.id,update:Na(n),timestamp:Date.now()}:null,vs=n=>{if(!B(n?.groupId)||!B(n?.participant))return null;let e={groupId:n.groupId,participant:n.participant,label:typeof n.label=="string"?n.label:"",timestamp:typeof n.messageTimestamp=="number"?n.messageTimestamp:Date.now()};return B(n.participantAlt)&&(e.participantAlt=n.participantAlt),e},Da=new Set(["add","invite","invite-link"]),Ba=new Set(["remove","leave"]),Ms=n=>{if(!B(n?.id)||!Da.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=ys(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return B(n.author)&&(t.by=n.author),t},Ss=n=>{if(!B(n?.id)||!Ba.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=ys(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return B(n.author)&&(t.by=n.author),t};var be=n=>typeof n!="string"||n.length===0?null:Yc.jidNormalizedUser(n),Z=n=>typeof n=="string"&&n.length>0?n:void 0,ja=["@s.whatsapp.net","@c.us"],Rt=n=>n.endsWith("@lid"),bs=n=>ja.some(e=>n.endsWith(e)),$=(n,e)=>{if(!n)return null;let t=Z(n.participant)??n.remoteJid,r=be(t);if(r===null)return null;let s=Z(n.participantAlt)??Z(n.remoteJidAlt),i=s!=null?be(s):null,o=Z(n.participantUsername)??Z(n.remoteJidUsername),a={jid:r,isMe:n.fromMe===true};typeof t=="string"&&t.length>0&&(a.deviceJid=t);let c=i!==null?[r,i]:[r],d=c.find(Rt),l=c.find(bs);d!==void 0&&(a.lid=d),l!==void 0&&(a.pn=l),o!==void 0&&(a.username=o);let u=Z(e);return u!==void 0&&(a.pushName=u),a},As=n=>{if(!n)return null;let e=n.stanzaId;if(typeof e!="string"||e.length===0)return null;let t=Z(n.participant),r=Z(n.remoteJid)??t,s={id:e};typeof r=="string"&&(s.remoteJid=r),typeof t=="string"&&(s.participant=t);let i={key:s},o=$(s);return o&&(i.sender=o),i},tt=n=>{if(!n)return {mentionedJids:[],mentionAll:false};let e=n.mentionedJid,t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[],r=n.groupMentions,s=Array.isArray(r)&&r.length>0;return {mentionedJids:t,mentionAll:s}};var Ae=n=>Yc.isJidGroup(n)===true,Ce=n=>{if(n==null)return null;if(typeof n=="number")return Number.isFinite(n)?n:null;if(typeof n.toNumber=="function"){let e=n.toNumber();return Number.isFinite(e)?e:null}return null},g=n=>n!=null&&typeof n=="object"?n:null,Cs=["ephemeralMessage","viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension","documentWithCaptionMessage","editedMessage","lottieStickerMessage","groupStatusMessage","groupStatusMessageV2"],Ps=["groupStatusMessage","groupStatusMessageV2"],ks=(n,e)=>{let t=n;for(let r=0;r<5&&t!=null;r++){if(e.some(i=>t?.[i]!=null))return true;let s=null;for(let i of Cs){let o=g(g(t[i])?.message);if(o!=null){s=o;break}}t=s;}return false},Pe=n=>{let e=n;for(let t=0;t<5;t++){let r=null;for(let s of Cs){let i=g(g(e[s])?.message);if(i!=null){r=i;break}}if(r==null)break;e=r;}return e};var Ua=["quick_reply","cta_url","cta_call","button_click"],qa=["list_select","single_select"],J=n=>typeof n=="string"&&n.length>0,Ts=n=>{let e=typeof n.pushName=="string"?n.pushName:void 0;return $(n.key,e)},Is=n=>Ce(n.messageTimestamp)??0,xs=(n,e)=>{if(!J(n))return null;try{let t=JSON.parse(n);return t!==null&&typeof t=="object"?t:null}catch{return e?.debug({paramsJson:n},"interactive: failed to parse nativeFlow paramsJson"),null}},_t=(n,e)=>{for(let t of e){let r=n[t];if(J(r))return r}},Os=(n,e)=>{let t=n.message;if(!t)return null;let r=t.buttonsResponseMessage;if(r&&J(r.selectedButtonId))return Tn(n,r.selectedButtonId,r.selectedDisplayText);let s=t.templateButtonReplyMessage;if(s&&J(s.selectedId))return Tn(n,s.selectedId,s.selectedDisplayText);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&Ua.includes(i.name)){let o=xs(i.paramsJson,e.logger);if(!o)return null;let a=_t(o,["id","button_id"]);return a===void 0?null:Tn(n,a,_t(o,["display_text"])??null)}return null},Tn=(n,e,t)=>{let r=Ts(n);if(!r||!n.key)return null;let s={key:n.key,buttonId:e,sender:r,timestamp:Is(n)};return J(t)&&(s.buttonText=t),s},Rs=(n,e)=>{let t=n.message;if(!t)return null;let r=t.listResponseMessage,s=r?.singleSelectReply?.selectedRowId;if(J(s))return Es(n,s,r?.title);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&qa.includes(i.name)){let o=xs(i.paramsJson,e.logger);if(!o)return null;let a=_t(o,["row_id","id"]);return a===void 0?null:Es(n,a,_t(o,["title"])??null)}return null},Es=(n,e,t)=>{let r=Ts(n);if(!r||!n.key)return null;let s={key:n.key,rowId:e,sender:r,timestamp:Is(n)};return J(t)&&(s.title=t),s};var Ka=new Set(["available","unavailable","composing","recording","paused"]),$a=n=>n instanceof Date?n.getTime():typeof n=="number"&&Number.isFinite(n)?n:0,_s=n=>n.status!=="complete"&&n.status!=="paused"?null:{syncType:String(n.syncType),status:n.status,explicit:n.explicit===true},In=n=>{if(n.source==="connection-update"){let t=n.reachoutTimeLock;return t.isActive!==true?null:{reason:"reachout-timelock",retryAt:$a(t.timeEnforcementEnds)}}if(n.capInfo.capping_status!=="CAPPED")return null;let e={reason:"chat-limit-reached"};return typeof n.capInfo.used_quota=="number"&&(e.usedQuota=n.capInfo.used_quota),typeof n.capInfo.total_quota=="number"&&(e.totalQuota=n.capInfo.total_quota),e},Ls=n=>{if(typeof n.id!="string"||n.id.length===0)return [];let e=[];for(let[t,r]of Object.entries(n.presences??{})){let s=r?.lastKnownPresence;typeof s!="string"||!Ka.has(s)||e.push({jid:n.id,participant:t,status:s});}return e},nt=n=>{let e=n.payload.id;if(typeof e!="string"||e.length===0)return null;let t=Date.now();switch(n.source){case "reaction":{let r={action:"reaction",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.reaction?.code=="string"&&(r.emoji=n.payload.reaction.code),r}case "view":{let r={action:"view",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.count=="number"&&(r.count=n.payload.count),r}case "participants":return {action:"participants",newsletterId:e,timestamp:t};case "settings":{let r={action:"settings",newsletterId:e,timestamp:t};return n.payload.update&&(r.update=n.payload.update),r}}};var Ds=n=>{let e=n.match(/(https?:\/\/[^\s]+)/g);return e?e.map(t=>t.replace(/[.,;:!?]+$/,"")):[]},Ns=(n,e=2166136261)=>{let t=e>>>0;for(let r=0;r<n.length;r++)t^=n.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t>>>0},Bs=n=>(Ns(n).toString(16).padStart(8,"0")+Ns(n,2646966556).toString(16).padStart(8,"0")).toUpperCase(),Ws=n=>Bs(`${n.remoteJid??""}|${n.id??""}|${n.fromMe===true?"1":"0"}`),Fs=(n,e)=>Bs(`${n??""}|${e}`),js=n=>{let e=null;if(typeof n=="number")e=n;else if(typeof n=="bigint")e=Number(n);else if(typeof n=="string"){let t=Number.parseInt(n,10);e=Number.isFinite(t)?t:null;}else if(n!=null&&typeof n=="object"){let t=n;typeof t.toNumber=="function"?e=t.toNumber():typeof t.low=="number"&&(e=(typeof t.high=="number"?t.high:0)*4294967296+(t.low>>>0));}return e!=null&&Number.isFinite(e)&&e>0?e*1e3:0},Us=n=>{let e=Yc.jidDecode(n);if(!e)return "unknown";let t=e.device;return t===void 0||t===0?"android":t===2?"ios":t===3?"web":t===4?"desktop":"unknown"},Ja=n=>n.trim().endsWith("?"),Va=(n,e)=>e.length===0?false:e.some(t=>t.length>0&&n.startsWith(t)),Ha=(n,e)=>{if(e.length===0)return false;let t;try{t=Yc.jidNormalizedUser(n);}catch{t=n;}return e.some(r=>{try{return Yc.jidNormalizedUser(r)===t}catch{return r===n}})},za=(n,e)=>{let t=async r=>r===void 0?false:Array.isArray(r)?r.includes(e):r(e);return {authors:()=>t(n?.authors),banned:()=>t(n?.banned)}},Ya=0,Za=14,Qa=1,Xa=2,ec=n=>{let e=g(n.message);if(e==null)return {isEdited:false,isDeleted:false,isPinned:false,isUnPinned:false,isBot:false,isStatusMention:false,isGroupStatusMention:false,isGroupStatus:false};let t=g(e.protocolMessage),r=typeof t?.type=="number"?t.type:void 0,s=typeof g(e.pinInChatMessage)?.type=="number"?e.pinInChatMessage.type:void 0;return {isEdited:e.editedMessage!=null||r===Za,isDeleted:r===Ya,isPinned:s===Qa,isUnPinned:s===Xa,isBot:g(e.messageContextInfo)?.botMetadata!=null,isStatusMention:e.statusMentionMessage!=null,isGroupStatusMention:e.groupStatusMentionMessage!=null,isGroupStatus:ks(e,Ps)}},xn=n=>{let e=typeof n.key.remoteJid=="string"?n.key.remoteJid:null,t=e!==null&&Ae(e),r=ec(n.message),s=c=>n.lidMap!=null&&c.endsWith("@lid")?n.lidMap.get(c)??c:c,i=s(n.sender.pn??n.sender.jid),o=t?e?Yc.jidNormalizedUser(e):null:n.key.fromMe===true&&e?s(Yc.jidNormalizedUser(e)):i,a={uniqueId:Ws(n.key),staticId:Fs(o,i),channelId:n.channelId,chatId:n.key.id??"",chatType:n.chatType,receiverId:n.receiverId?s(Yc.jidNormalizedUser(n.receiverId)):n.receiverId,roomId:o,senderId:i,senderLid:n.sender.lid??null,senderName:n.sender.pushName??null,senderUsername:n.sender.username??null,senderDevice:Us(n.sender.deviceJid??n.sender.jid),timestamp:js(n.message.messageTimestamp),text:n.text,mentions:n.mentions,links:Ds(n.text),isFromMe:n.key.fromMe===true,isGroup:t,isNewsletter:n.isNewsletter,isBroadcast:n.isBroadcast,isViewOnce:n.isViewOnce,isEphemeral:n.isEphemeral,isForwarded:n.isForwarded,isOffline:n.isOffline===true,forwardCount:n.forwardCount??0,ephemeralDuration:n.ephemeralDuration??null,addressingMode:n.addressingMode??"pn",mentionedGroups:n.mentionedGroups??[],...n.ad!==void 0?{ad:n.ad}:{},...n.business!==void 0?{business:n.business}:{},isQuestion:Ja(n.text),isPrefix:Va(n.text,n.prefixes),isTagMe:Ha(n.selfJid,n.mentions),isEdited:r.isEdited,isDeleted:r.isDeleted,isPinned:r.isPinned,isUnPinned:r.isUnPinned,isBot:r.isBot,isSpam:false,isHideTags:n.mentions.length>0&&!/@\d/.test(n.text),isStatusMention:r.isStatusMention,isGroupStatusMention:r.isGroupStatusMention,isGroupStatus:r.isGroupStatus,isStory:e==="status@broadcast",roomName:n.resolveRoomName,receiverName:n.resolveReceiverName,replied:n.resolveReplied,reply:n.reply,react:n.react,message:()=>n.message,citation:za(n.citationConfig,n.sender.pn??n.sender.jid)};return n.media!==void 0&&(a.media=n.media),a};var Rn={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},$s=n=>{let e=n?.remoteJid;return typeof e=="string"&&e.length>0?e:""},S=n=>typeof n=="string"&&n.length>0?n:null,Q=(...n)=>{for(let e of n){let t=S(e);if(t!=null)return t}return null},Gs=n=>{let e=g(n.message);if(e==null)return n;let t=Pe(e);return t===e?n:{...n,message:t}},tc=n=>{let t=g(g(g(n.botForwardedMessage)?.message)?.richResponseMessage)??g(n.richResponseMessage);if(t==null)return null;let r=t.submessages;if(!Array.isArray(r))return null;let s=[];for(let o of r){let a=S(g(o)?.messageText);a!=null&&s.push(a);}let i=s.join(`
14
- `).trim();return i.length>0?i:null},nc=n=>{let e=g(n.templateMessage),t=g(e?.hydratedTemplate)??g(e?.hydratedFourRowTemplate);return S(t?.hydratedContentText)},rc=n=>Q(g(n.pollCreationMessage)?.name,g(n.pollCreationMessageV2)?.name,g(n.pollCreationMessageV3)?.name),sc=n=>{let e=g(n.locationMessage)??g(n.liveLocationMessage);if(e==null)return null;let t=Q(e.name,e.address);if(t!=null){let i=S(e.name),o=S(e.address);return i!=null&&o!=null&&i!==o?`${i} \u2014 ${o}`:t}let r=e.degreesLatitude,s=e.degreesLongitude;return typeof r=="number"&&typeof s=="number"?`${r}, ${s}`:null},ic=n=>{let e=S(g(n.contactMessage)?.displayName);if(e!=null)return e;let t=g(n.contactsArrayMessage),r=S(t?.displayName);if(r!=null)return r;let s=t?.contacts;if(Array.isArray(s)){let i=s.map(o=>S(g(o)?.displayName)).filter(o=>o!=null);if(i.length>0)return i.join(", ")}return null},Js=n=>Q(n.conversation,g(n.extendedTextMessage)?.text,tc(n),S(g(g(n.interactiveMessage)?.body)?.text),g(n.buttonsMessage)?.contentText,g(n.listMessage)?.description,nc(n),rc(n),sc(n),ic(n)),oc=n=>Q(g(n.buttonsResponseMessage)?.selectedDisplayText,g(n.buttonsResponseMessage)?.selectedButtonId,g(n.templateButtonReplyMessage)?.selectedDisplayText,g(n.templateButtonReplyMessage)?.selectedId,g(n.listResponseMessage)?.title,g(g(n.listResponseMessage)?.singleSelectReply)?.selectedRowId,g(g(n.interactiveResponseMessage)?.body)?.text),ac=n=>Q(g(n.imageMessage)?.caption,g(n.videoMessage)?.caption,g(n.documentMessage)?.caption,g(n.documentMessage)?.fileName),T=n=>{if(typeof n=="number")return n;let e=Ce(n);return typeof e=="number"?e:null},cc=[["pollCreationMessage","poll"],["pollCreationMessageV2","poll"],["pollCreationMessageV3","poll"],["contactMessage","contact"],["contactsArrayMessage","contact"],["locationMessage","location"],["liveLocationMessage","live-location"],["eventMessage","event"],["albumMessage","album"],["groupInviteMessage","group-invite"],["productMessage","product"],["orderMessage","order"],["requestPaymentMessage","payment"],["sendPaymentMessage","payment"],["paymentInviteMessage","payment"],["buttonsMessage","buttons"],["listMessage","list"],["interactiveMessage","interactive"],["templateMessage","template"]],Vs=n=>{let e=g(n.pollCreationMessage)??g(n.pollCreationMessageV2)??g(n.pollCreationMessageV3);if(e!=null){let m=Array.isArray(e.options)?e.options:[];return {type:"poll",name:S(e.name),options:m.map(f=>S(g(f)?.optionName)).filter(f=>f!=null),selectableCount:T(e.selectableOptionsCount)??0}}let t=g(n.contactMessage);if(t!=null)return {type:"contact",displayName:S(t.displayName),vcard:S(t.vcard),contacts:[{displayName:S(t.displayName),vcard:S(t.vcard)}]};let r=g(n.contactsArrayMessage);if(r!=null){let m=Array.isArray(r.contacts)?r.contacts:[];return {type:"contact",displayName:S(r.displayName),vcard:null,contacts:m.map(f=>({displayName:S(g(f)?.displayName),vcard:S(g(f)?.vcard)}))}}let s=g(n.locationMessage);if(s!=null)return {type:"location",latitude:T(s.degreesLatitude),longitude:T(s.degreesLongitude),name:S(s.name),address:S(s.address),accuracy:T(s.accuracyInMeters),speed:T(s.speedInMps),caption:S(s.comment)};let i=g(n.liveLocationMessage);if(i!=null)return {type:"live-location",latitude:T(i.degreesLatitude),longitude:T(i.degreesLongitude),name:null,address:null,accuracy:T(i.accuracyInMeters),speed:T(i.speedInMps),caption:S(i.caption)};let o=g(n.albumMessage);if(o!=null)return {type:"album",expectedImageCount:T(o.expectedImageCount),expectedVideoCount:T(o.expectedVideoCount)};let a=g(n.groupInviteMessage);if(a!=null)return {type:"group-invite",groupId:S(a.groupJid),groupName:S(a.groupName),inviteCode:S(a.inviteCode),caption:S(a.caption),expiresAt:T(a.inviteExpiration)};let c=g(g(n.productMessage)?.product);if(g(n.productMessage)!=null){let m=S(g(n.productMessage)?.businessOwnerJid),f=T(c?.priceAmount1000);return {type:"product",productId:S(c?.productId),title:S(c?.title),description:S(c?.description),price:f!=null?f/1e3:null,currency:S(c?.currencyCode),retailerId:S(c?.retailerId),url:S(c?.url),businessOwnerId:m}}let d=g(n.orderMessage);if(d!=null){let m=T(d.totalAmount1000),f={1:"inquiry",2:"accepted",3:"declined"},b=d.status;return {type:"order",orderId:S(d.orderId),title:S(d.orderTitle),itemCount:T(d.itemCount),total:m!=null?m/1e3:null,currency:S(d.totalCurrencyCode),status:typeof b=="number"?f[b]??null:S(b),message:S(d.message)}}let l=g(n.requestPaymentMessage)!=null&&{node:n.requestPaymentMessage,kind:"request"}||g(n.sendPaymentMessage)!=null&&{node:n.sendPaymentMessage,kind:"send"}||g(n.paymentInviteMessage)!=null&&{node:n.paymentInviteMessage,kind:"invite"};if(l!==false){let m=g(l.node),f=T(m?.amount1000),b=g(m?.noteMessage);return {type:"payment",kind:l.kind,amount:f!=null?f/1e3:null,currency:S(m?.currencyCodeIso4217),note:Q(b?.conversation,g(b?.extendedTextMessage)?.text),expiresAt:T(m?.expiryTimestamp)}}let u=g(n.eventMessage);if(u!=null){let m=g(u.location);return {type:"event",name:S(u.name),description:S(u.description),location:m!=null?Q(m.name,m.address):null,startTime:T(u.startTime),endTime:T(u.endTime),isCanceled:u.isCanceled===true}}let w=g(n.buttonsMessage);if(w!=null){let m=Array.isArray(w.buttons)?w.buttons:[];return {type:"buttons",contentText:S(w.contentText),footerText:S(w.footerText),buttons:m.map(f=>({id:S(g(f)?.buttonId),text:S(g(g(f)?.buttonText)?.displayText)}))}}let M=g(n.listMessage);if(M!=null){let m=Array.isArray(M.sections)?M.sections:[];return {type:"list",title:S(M.title),description:S(M.description),buttonText:S(M.buttonText),sections:m.map(f=>{let b=Array.isArray(g(f)?.rows)?g(f).rows:[];return {title:S(g(f)?.title),rows:b.map(k=>({id:S(g(k)?.rowId),title:S(g(k)?.title),description:S(g(k)?.description)}))}})}}let v=g(n.interactiveMessage);if(v!=null){let m=g(v.nativeFlowMessage),f=Array.isArray(m?.buttons)?m.buttons:[];return {type:"interactive",title:S(g(v.header)?.title),body:S(g(v.body)?.text),footer:S(g(v.footer)?.text),buttons:f.map(b=>({name:S(g(b)?.name),params:S(g(b)?.buttonParamsJson)}))}}let P=g(n.templateMessage);if(P!=null){let m=g(P.hydratedTemplate)??g(P.hydratedFourRowTemplate),f=Array.isArray(m?.hydratedButtons)?m.hydratedButtons:[];return {type:"template",text:S(m?.hydratedContentText),buttons:f.map(b=>{let k=g(b),F=g(k?.quickReplyButton)??g(k?.urlButton)??g(k?.callButton);return {id:S(F?.id),text:S(F?.displayText)}})}}let y=g(n.extendedTextMessage);if(y!=null){let m=Q(y.canonicalUrl,y.matchedText),f=S(y.title),b=S(y.description);if(m!=null&&(f!=null||b!=null))return {type:"link",url:m,title:f,description:b}}return null};var st=n=>{let e=g(n.message);if(e==null)return null;let t=Pe(e);return Js(t)??oc(t)??ac(t)},Nt=n=>{let e=g(Gs(n).message);if(e==null)return null;let t=g(e.extendedTextMessage)?.contextInfo;if(t!=null)return t;for(let r of Object.values(e)){if(r==null||typeof r!="object")continue;let s=r.contextInfo;if(s!=null)return s}return null},dc=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[Rn[e]];return r==null||typeof r!="object"?null:r},lc=n=>{let e=n.message;if(e==null)return false;if(e.viewOnceMessage!=null||e.viewOnceMessageV2!=null||e.viewOnceMessageV2Extension!=null)return true;for(let t of Object.values(Rn)){let r=e[t];if(r!=null&&typeof r=="object"&&r.viewOnce===true)return true}return false},uc=(n,e)=>n.message?.ephemeralMessage!=null?true:typeof e?.expiration=="number"&&e.expiration>0,pc=(n,e)=>typeof n=="number"&&Number.isFinite(n)?n:e,mc=(n,e)=>{let t=e?.expiration;if(typeof t=="number"&&t>0)return t;let r=g(g(n.message)?.ephemeralMessage),s=g(g(r?.message)?.extendedTextMessage)?.contextInfo,i=g(s)?.expiration;return typeof i=="number"&&i>0?i:null},gc=n=>{let e=n?.groupMentions;if(!Array.isArray(e))return [];let t=[];for(let r of e){let s=g(r)?.groupJid;typeof s=="string"&&s.length>0&&t.push(s);}return t},Hs=n=>typeof n=="string"&&n.length>0?n:void 0,fc=n=>{let e=g(n?.externalAdReply);if(e==null)return;let t={},r=[["clickId","ctwaClid"],["sourceId","sourceId"],["sourceUrl","sourceUrl"],["sourceApp","sourceApp"],["sourceType","sourceType"],["title","title"],["body","body"],["thumbnailUrl","thumbnailUrl"],["ref","ref"]];for(let[s,i]of r){let o=Hs(e[i]);o!==void 0&&(t[s]=o);}return Object.keys(t).length>0?t:void 0},hc=n=>{let e=Hs(g(n)?.verifiedBizName);return e!==void 0?{verifiedName:e}:void 0},ce=n=>{let e=g(n);if(e==null)return "text";let t=Pe(e);for(let r of Object.values(Rn))if(t[r]!=null)return r.replace("Message","");for(let[r,s]of cc)if(t[r]!=null)return s;return "text"},qs=(n,e)=>{if(n==null)return false;let t=[n.pn,n.lid,n.jid].filter(s=>typeof s=="string"&&s.length>0),r=[e.pn,e.lid,e.jid].filter(s=>typeof s=="string"&&s.length>0);return t.some(s=>r.includes(s))},yc=async(n,e,t,r,s,i)=>{try{if(n==null||n.quotedMessage==null)return null;let o=n.stanzaId;if(typeof o!="string"||o.length===0)return null;if(e.resolveQuoted!=null&&t.length>0){let v=await e.resolveQuoted(o,t);if(v!=null&&v.message!=null){let P=st(v)??"",y=de(v,e,ce(v.message),P,it(v,e),s);if(y!==null)return y}}let a=As(n);if(a===null||typeof a.key.id!="string"||a.key.id.length===0||(t.length>0&&(a.key.remoteJid=t),typeof a.key.remoteJid!="string"||a.key.remoteJid.length===0))return null;let c=a.key.participant,d=Ae(t),l=a.sender?.pushName;!d&&(c==null||c.length===0)?i===!0?(a.key.participant=t,l==null&&r!=null&&qs({jid:t},r)&&(l=r.pushName)):(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):typeof c=="string"&&(e.selfJid.length>0&&Lt(c,e.selfJid)||e.selfLid!=null&&Lt(c,e.selfLid))?(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):r!=null&&qs(a.sender,r)&&(r.pn!=null&&(a.key.participant=r.pn),r.lid!=null&&(a.key.participantAlt=r.lid),l==null&&(l=r.pushName));let u=n.quotedMessage,w=Object.assign({key:a.key,message:u??null},l!=null?{pushName:l}:{}),M=st(w)??"";return de(w,e,ce(u),M,it(w,e),s)}catch{return null}},zs=n=>tt(Nt(n)).mentionedJids,wc=n=>{try{return Yc.jidNormalizedUser(n)}catch{return n}},Ys=(n,e)=>n.map(t=>{let r=wc(t);return e.lidMap?.get(r)??r}),Ks=n=>(n.split("@")[0]??"").split(":")[0]??"",vc=(n,e)=>{if(e==null||e.size===0||n.length===0)return n;let t=[...e].map(([s,i])=>[Ks(s),Ks(i)]).filter(([s,i])=>s.length>0&&i.length>0&&s!==i).sort((s,i)=>i[0].length-s[0].length),r=n;for(let[s,i]of t)r=r.split(`@${s}`).join(`@${i}`);return r},de=(n,e,t,r,s,i)=>{let o=n.key;if(o==null)return null;let a=$(o,n.pushName??void 0);if(a===null)return null;let c=$s(o);if(c.length===0)return null;let d=Nt(n),l=Ae(c),u=c.endsWith("@broadcast"),w=c.endsWith("@newsletter"),M=d?.isForwarded===true||(d?.forwardingScore??0)>0,v=lc(n),P=uc(n,d),y=e.channelId??"",m=e.receiverId??"",f=e.prefixes??[],b=i??(()=>l?e.resolveRoomName!=null?e.resolveRoomName(c):Promise.resolve(null):Promise.resolve(a.pushName??null)),k=e.resolveReceiverName??(()=>Promise.resolve(null)),F=()=>yc(d,e,c,a,b,o.fromMe===true),en=c.length>0?c:a.pn??a.jid,tn=(rn,Ki)=>e.reply==null?Promise.reject(new Error("zaileys: ctx.reply() requires a connected client")):e.reply(en,rn,Ki,n),nn=rn=>e.react==null?Promise.reject(new Error("zaileys: ctx.react() requires a connected client")):e.react(o,rn),Ui=Ys(tt(d).mentionedJids,e),qi=vc(r,e.lidMap),qn=fc(d),Kn=hc(n),$n={message:n,key:o,channelId:y,receiverId:m,selfJid:e.selfJid,text:qi,chatType:t,sender:a,mentions:Ui,isViewOnce:v,isEphemeral:P,isForwarded:M,isBroadcast:u,isNewsletter:w,isOffline:e.isOffline===true,forwardCount:pc(d?.forwardingScore,0),ephemeralDuration:mc(n,d),addressingMode:o.addressingMode==="lid"?"lid":"pn",mentionedGroups:gc(d),...qn!==void 0?{ad:qn}:{},...Kn!==void 0?{business:Kn}:{},prefixes:f,...e.lidMap!=null?{lidMap:e.lidMap}:{},resolveRoomName:b,resolveReceiverName:k,resolveReplied:F,reply:tn,react:nn},Gn=s!==void 0?{...$n,media:s}:$n;return xn(e.citationConfig!==void 0?{...Gn,citationConfig:e.citationConfig}:Gn)},Mc=["image","video","audio","document","sticker"],Zs=(n,e,t)=>{let r=Gs(n),s=dc(r,e);if(s===null)return null;let i=Pt(r,e,t.logger),o=Xr(r,e,t.logger);return {type:e,mimetype:typeof s.mimetype=="string"?s.mimetype:null,caption:typeof s.caption=="string"?s.caption:null,fileName:typeof s.fileName=="string"?s.fileName:null,fileSize:T(s.fileLength),ptt:s.ptt===true,duration:T(s.seconds),width:T(s.width),height:T(s.height),pages:T(s.pageCount),isAnimated:s.isAnimated===true||s.gifPlayback===true,thumbnail:s.jpegThumbnail!=null?Buffer.from(s.jpegThumbnail):null,buffer:async()=>(await i()).buffer,stream:o}},it=(n,e)=>{let t=g(n.message);if(t==null)return;let r=ce(n.message);return Mc.includes(r)?Zs(n,r,e)??void 0:Vs(Pe(t))??void 0},Qs=(n,e)=>{if(g(n.message)==null)return null;let r=ce(n.message),s=it(n,e),i=st(n)??"";return i===""&&s===void 0?null:de(n,e,r,i,s)},Xs=(n,e)=>{let t=g(n.message);if(t==null)return null;let r=Pe(t),s=Js(r),i=Vs(r)??void 0;return s===null&&i===void 0?null:de(n,e,ce(n.message),s??"",i)},ot=(n,e,t)=>{let r=Zs(e,n,t);return r===null?null:de(e,t,n,r.caption??"",r)},ei=(n,e)=>ot("image",n,e),ti=(n,e)=>ot("video",n,e),ni=(n,e)=>ot("audio",n,e),ri=(n,e)=>ot("document",n,e),si=(n,e)=>ot("sticker",n,e),Lt=(n,e)=>{try{return Yc.jidNormalizedUser(n)===Yc.jidNormalizedUser(e)}catch{return n===e}},ii=(n,e)=>{if(n.key==null)return null;let r=Nt(n),s=tt(r).mentionedJids;if(s.length===0)return null;let i=Ys(s,e);if(!(i.some(u=>Lt(u,e.selfJid))||e.selfLid!=null&&s.some(u=>Lt(u,e.selfLid)))||g(n.message)==null)return null;let c=st(n)??"",d=it(n,e),l=de(n,e,ce(n.message),c,d);return l===null?null:{...l,mentionedJids:i,selfJid:e.selfJid}},oi=(n,e)=>{let t=n.key;if(t==null)return null;let r=$s(t);if(r.length===0||!Ae(r))return null;let{mentionAll:s}=tt(Nt(n));if(!s||g(n.message)==null)return null;let o=st(n)??"",a=it(n,e),c=de(n,e,ce(n.message),o,a);return c===null?null:{...c,isMentionAll:true,selfJid:e.selfJid}};var le=(n,e)=>{let t=Ce(n);return t===null?e:t},bc=n=>{if(!n)return "";if(typeof n.conversation=="string")return n.conversation;let e=n.extendedTextMessage?.text;if(typeof e=="string")return e;let t=n.imageMessage?.caption;if(typeof t=="string")return t;let r=n.videoMessage?.caption;if(typeof r=="string")return r;let s=n.documentMessage?.caption;if(typeof s=="string")return s;let o=(n.botForwardedMessage?.message?.richResponseMessage??n.richResponseMessage)?.submessages;if(Array.isArray(o)){let a=o.map(c=>c?.messageText).filter(c=>typeof c=="string"&&c.length>0);if(a.length>0)return a.join(`
15
- `)}return ""},Ac=n=>Array.isArray(n)?n.map(e=>Buffer.from(e).toString("hex")):[],ci=(n,e)=>{let t=n?.reaction,r=t?.key;if(!r)return null;let s=$(n.key,e.pushName);if(s===null)return null;let i=t.text,o=typeof i=="string"&&i.length>0?i:null;return {key:r,emoji:o,sender:s,timestamp:le(t.senderTimestampMs,0)}},di=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==Yc.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT)return null;let r=t.key;if(!r)return null;let s=$(n.key,e.pushName);return s===null?null:{key:r,newContent:bc(t.editedMessage),editedAt:le(n.update.messageTimestamp,0),sender:s}},li=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==Yc.proto.Message.ProtocolMessage.Type.REVOKE)return null;let r=t.key;if(!r)return null;let s=$(n.key,e.pushName);if(s===null)return null;let i=be(n.key.remoteJid),o=be(e.selfJid);return {key:r,deletedFor:i!==null&&o!==null&&i===o?"me":"everyone",sender:s,timestamp:le(n.update.messageTimestamp,0)}},Cc=async(n,e,t)=>{if(e.length===0||t.resolvePoll==null)return [];let r=n.id,s=n.remoteJid;if(typeof r!="string"||typeof s!="string")return [];let o=(await t.resolvePoll(r,s))?.message,a=o?.pollCreationMessage?.options??o?.pollCreationMessageV2?.options??o?.pollCreationMessageV3?.options??[],c=new Map;for(let l of a){let u=l?.optionName??"";c.set(crypto.createHash("sha256").update(Buffer.from(u)).digest("hex").toUpperCase(),u);}let d=[];for(let l of e){let u=c.get(l.toUpperCase());u!==void 0&&d.push(u);}return d},ui=(n,e)=>{let t=n?.update?.pollUpdates?.[0],r=n?.update?.message?.pollUpdateMessage,s=$(n?.key,e.pushName);if(s===null)return null;if(t){let i=t.pollUpdateMessageKey;if(!i)return null;let o=Ac(t.vote?.selectedOptions);return {pollKey:i,selectedOptions:o,options:()=>Cc(i,o,e),voter:s,timestamp:le(t.senderTimestampMs,le(n.update.messageTimestamp,0))}}if(r){let i=r.pollCreationMessageKey;return i?{pollKey:i,selectedOptions:[],options:()=>Promise.resolve([]),voter:s,timestamp:le(r.senderTimestampMs,le(n.update.messageTimestamp,0))}:null}return null};var Dt=n=>Array.isArray(n)?n:[],Pc=3e3,kc=(n,e)=>new Promise(t=>{let r=setTimeout(()=>t(null),e);n.then(s=>{clearTimeout(r),t(s);},()=>{clearTimeout(r),t(null);});}),Ec=n=>{if(n==null||typeof n!="object")return null;let e=n.reachoutTimeLock;return e==null||typeof e!="object"?null:e};function _n(n,e,t){let r=[],s=new Map,i=t.groupMetadata!=null?y=>{let m=s.get(y);if(m!==void 0)return m;let f=t.groupMetadata;if(f==null)return Promise.resolve(null);let b=f(y).then(k=>k?.subject??null).catch(()=>null);return s.set(y,b),b}:void 0,o={selfJid:t.selfJid,...t.selfLid!=null?{selfLid:t.selfLid}:{},...t.selfName!=null?{selfName:t.selfName}:{},receiverId:t.receiverId??t.selfJid,...t.logger!=null?{logger:t.logger}:{},...t.channelId!=null?{channelId:t.channelId}:{},...t.prefixes!=null?{prefixes:t.prefixes}:{},...t.citationConfig!=null?{citationConfig:t.citationConfig}:{},...i!=null?{resolveRoomName:i}:{},...t.receiverName!=null?{resolveReceiverName:t.receiverName}:{},...t.resolveQuoted!=null?{resolveQuoted:t.resolveQuoted}:{},...t.sendReply!=null?{reply:t.sendReply}:{},...t.react!=null?{react:t.react}:{}},a=t.logger?{selfJid:t.selfJid,logger:t.logger}:{selfJid:t.selfJid},c={selfJid:t.selfJid,...t.resolveQuoted!=null?{resolvePoll:t.resolveQuoted}:{}},d=(y,m)=>{let f=(...b)=>{try{m(b[0]);}catch(k){t.logger?.warn(k,`inbound pipeline: handler for ${y} threw`);}};e.ev.on(y,f),r.push(()=>e.ev.off(y,f));},l=(y,m)=>{v(()=>Qs(y,m),f=>n.emit("message",f)),v(()=>Xs(y,m),f=>n.emit("text",f)),v(()=>ei(y,m),f=>n.emit("image",f)),v(()=>ti(y,m),f=>n.emit("video",f)),v(()=>ni(y,m),f=>n.emit("audio",f)),v(()=>ri(y,m),f=>n.emit("document",f)),v(()=>si(y,m),f=>n.emit("sticker",f)),v(()=>ii(y,m),f=>n.emit("mention",f)),v(()=>oi(y,m),f=>n.emit("mention-all",f)),v(()=>Os(y,a),f=>n.emit("button-click",f)),v(()=>Rs(y,a),f=>n.emit("list-select",f));},u=y=>{if(typeof y!="string"||y.length===0)return null;let m;try{m=Yc.jidNormalizedUser(y);}catch{m=y;}return Rt(m)?m:null},w=y=>{let m=new Set;for(let f of [y.key?.participant,y.key?.remoteJid,t.selfJid,...zs(y)]){let b=u(f);b!=null&&m.add(b);}return [...m]},M=async y=>{let m=t.resolveLidToPn;if(m==null||y.length===0)return;let f=new Map;return await Promise.all(y.map(async b=>{try{let k=await kc(Promise.resolve(m(b)),Pc);if(k!=null&&k.length>0)try{f.set(b,Yc.jidNormalizedUser(k));}catch{f.set(b,k);}}catch(k){t.logger?.warn(k,"inbound pipeline: lid->pn resolve threw");}})),f.size>0?f:void 0},v=(y,m)=>{let f;try{f=y();}catch(b){t.logger?.warn(b,"inbound pipeline: decoder threw");return}f!=null&&m(f);};d("messages.upsert",y=>{let m=ms(y),f=m.type==="append"?{...o,isOffline:!0}:o;for(let b of m.messages){if(t.ignoreMe===!0&&b.key?.fromMe===!0)continue;let k=t.resolveLidToPn!=null?w(b):[];if(k.length===0){l(b,f);continue}M(k).then(F=>l(b,F!=null?{...f,lidMap:F}:f)).catch(F=>{t.logger?.warn(F,"inbound pipeline: deferred lid resolve emit failed"),l(b,f);});}}),d("messages.update",y=>{for(let m of Dt(y))v(()=>di(m,c),f=>n.emit("edit",f)),v(()=>li(m,c),f=>n.emit("delete",f)),v(()=>ui(m,c),f=>n.emit("poll-vote",f));}),d("messages.reaction",y=>{for(let m of Dt(y))v(()=>ci(m,c),f=>n.emit("reaction",f));}),d("groups.update",y=>{for(let m of Dt(y))v(()=>ws(m),f=>n.emit("group-update",f));}),d("group-participants.update",y=>{let m=y;v(()=>Ms(m),f=>n.emit("group-join",f)),v(()=>Ss(m),f=>n.emit("group-leave",f));}),d("group.member-tag.update",y=>{v(()=>vs(y),m=>n.emit("member-tag",m));}),d("call",y=>{for(let m of Dt(y))v(()=>fs(m),f=>n.emit("call-incoming",f)),v(()=>hs(m),f=>n.emit("call-ended",f));}),d("messaging-history.status",y=>{v(()=>_s(y),m=>n.emit("history-sync",m));}),d("presence.update",y=>{let m=(()=>{try{return Ls(y)}catch(f){return t.logger?.warn(f,"inbound pipeline: decodePresence threw"),[]}})();for(let f of m)n.emit("presence",f);}),d("connection.update",y=>{let m=Ec(y);m!==null&&v(()=>In({source:"connection-update",reachoutTimeLock:m}),f=>n.emit("limited",f));}),d("message-capping.update",y=>{v(()=>In({source:"message-capping",capInfo:y}),m=>n.emit("limited",m));}),d("newsletter.reaction",y=>{v(()=>nt({source:"reaction",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter.view",y=>{v(()=>nt({source:"view",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter-participants.update",y=>{v(()=>nt({source:"participants",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter-settings.update",y=>{v(()=>nt({source:"settings",payload:y}),m=>n.emit("newsletter",m));});let P=false;return {detach(){if(!P){P=true;for(let y of r)y();r.length=0;}}}}var Bt=class{inner=new events.EventEmitter;emitterLogger;constructor(e){this.emitterLogger=e?.logger,this.inner.setMaxListeners(0);}on(e,t){let r=this.wrap(e,t);this.tag(t,e,r),this.inner.on(e,r);let s=false;return ()=>{s||(s=true,this.inner.off(e,r),this.untag(t,e));}}off(e,t){let r=this.lookup(t,e);r&&(this.inner.off(e,r),this.untag(t,e));}emit(e,t){let r=this.inner.listeners(e).slice();for(let s of r)try{s(t);}catch(i){this.emitterLogger?.error(i,"listener threw");}}removeAllListeners(e){e===void 0?this.inner.removeAllListeners():this.inner.removeAllListeners(e);}listenerCount(e){return this.inner.listenerCount(e)}wrap(e,t){return r=>{try{t(r);}catch(s){this.emitterLogger?.error(s,"listener threw");}}}tag(e,t,r){this.tagMap(e).set(t,r);}untag(e,t){this.tagMap(e).delete(t);}lookup(e,t){return this.tagMap(e).get(t)}tagMap(e){let t=Ic,r=e,s=r[t];return s||(s=new Map,r[t]=s),s}},Ic=Symbol("zaileys.typed-ee.tag");var at=class extends Error{code="UNSUPPORTED_ON_CLOUD";feature;constructor(e){super(`${e} is not supported by the official WhatsApp Cloud API \u2014 it only exists on the web (baileys) provider`),this.name="ZaileysProviderError",this.feature=e;}},A=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysCloudError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};function Ln(n){if(!n||typeof n.accessToken!="string"||n.accessToken.length===0)throw new A("CONFIG","provider 'cloud' requires cloud.accessToken");if(typeof n.phoneNumberId!="string"||n.phoneNumberId.length===0)throw new A("CONFIG","provider 'cloud' requires cloud.phoneNumberId");return n}var Wt="v23.0",Nn="https://graph.facebook.com",mi=3,xc=500,Oc=n=>new Promise(e=>setTimeout(e,n));function Ft(n,e){let t=n.baseUrl??Nn,r=n.apiVersion??Wt,s=Oc,i=a=>`${t}/${r}/${a}`,o=async(a,c)=>{let d;for(let l=1;l<=mi;l++){let u;try{u=await fetch(i(a),{...c,headers:{Authorization:`Bearer ${n.accessToken}`,...c.headers}});}catch(m){throw new A("REQUEST_FAILED","graph request failed (network)",{cause:m})}if(u.ok)return await u.json().catch(()=>({}));let w=await u.json().catch(()=>({})),M=w.error?.message??`http ${u.status}`,v=w.error?` (code ${w.error.code??"?"}${w.error.error_subcode?`/${w.error.error_subcode}`:""})`:"";if(u.status===401||u.status===403)throw new A("AUTH",`graph auth rejected: ${M}${v}`);let P=u.status===429||u.status>=500,y=u.status===429?"RATE_LIMITED":"REQUEST_FAILED";if(d=new A(y,`graph request failed: ${M}${v}`),!P)throw d;l<mi&&await s(xc*2**(l-1));}throw d??new A("REQUEST_FAILED","graph request failed")};return {url:i,get:a=>o(a,{method:"GET"}),post:(a,c)=>o(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),postForm:(a,c)=>o(a,{method:"POST",body:c}),delete:(a,c)=>o(a,{method:"DELETE",...c!==void 0?{headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}:{}})}}var gi=n=>n.split("@")[0]??n,X=n=>n.includes("@")?n:`${n}@s.whatsapp.net`,V=(n,e,t)=>{let r={messaging_product:"whatsapp",recipient_type:"individual",to:gi(n),type:e},s=t?.quoted?.key?.id;return s&&(r.context={message_id:s}),r};function fi(n,e,t){let r=e;if(typeof r.text=="string")return {...V(n,"text",t),text:{body:r.text}};let s=r.react;if(s&&typeof s=="object"&&typeof s.key?.id=="string")return {...V(n,"reaction",t),reaction:{message_id:s.key.id,emoji:s.text??""}};let i=r.location;if(i&&typeof i.degreesLatitude=="number"&&typeof i.degreesLongitude=="number")return {...V(n,"location",t),location:{latitude:i.degreesLatitude,longitude:i.degreesLongitude,...i.name!==void 0?{name:i.name}:{},...i.address!==void 0?{address:i.address}:{}}};let o=r.contacts;if(o?.contacts&&Array.isArray(o.contacts)){let a=o.contacts.map(c=>typeof c.vcard=="string"?Rc(c.vcard):null).filter(c=>c!==null);if(a.length>0)return {...V(n,"contacts",t),contacts:a}}return null}function Rc(n){let e=n.split(/\r?\n/),t="",r="",s="",i=[];for(let a of e){if(a.startsWith("FN:")&&(t=a.slice(3).trim()),a.startsWith("N:")){let c=a.slice(2).split(";");s=(c[0]??"").trim(),r=(c[1]??"").trim();}if(a.startsWith("TEL")){let c=a.indexOf(":");if(c>0){let d=a.slice(c+1).trim(),l=/waid=([0-9]+)/.exec(a);d.length>0&&i.push({phone:d,...l?.[1]?{wa_id:l[1]}:{}});}}}if(t.length===0&&i.length===0)return null;let o=t||i[0]?.phone||"Contact";if(r.length===0&&s.length===0){let a=o.split(/\s+/);r=a[0]??o,a.length>1&&(s=a.slice(1).join(" "));}return {name:{formatted_name:o,first_name:r||o,...s?{last_name:s}:{}},...i.length>0?{phones:i}:{}}}function ct(n,e,t,r){let s=t,i=typeof s.text=="string"?{conversation:s.text}:{};return {key:{id:n,remoteJid:X(gi(e)),fromMe:true},message:i,messageTimestamp:Math.floor(r/1e3)}}var _c=["image","video","audio","document","sticker"];function hi(n){let e=n;for(let t of _c){let r=e[t];if(Buffer.isBuffer(r))return {kind:t,buffer:r,...typeof e.caption=="string"?{caption:e.caption}:{},...typeof e.fileName=="string"?{fileName:e.fileName}:{},...typeof e.mimetype=="string"?{mimetype:e.mimetype}:{}}}return null}async function yi(n,e,t){let r=t.mimetype??await me(t.buffer),s=new FormData;s.set("messaging_product","whatsapp"),s.set("type",r),s.set("file",new Blob([new Uint8Array(t.buffer)],{type:r}),t.fileName??"file");let i=await n.postForm(`${e}/media`,s);if(!i.id)throw new A("REQUEST_FAILED","media upload returned no id");return i.id}function wi(n,e){return {id:e,...n.caption!==void 0&&n.kind!=="audio"&&n.kind!=="sticker"?{caption:n.caption}:{},...n.kind==="document"&&n.fileName!==void 0?{filename:n.fileName}:{}}}var Lc=["image","video","audio","document","sticker"],Nc=n=>{let e=n.event,t=n.message_template_name;return typeof e!="string"||typeof t!="string"?null:{event:e,id:String(n.message_template_id??""),name:t,...typeof n.message_template_language=="string"?{language:n.message_template_language}:{},...typeof n.reason=="string"?{reason:n.reason}:{}}},jt=(n,e)=>n.contacts?.find(t=>t.wa_id===e)?.profile?.name??n.contacts?.[0]?.profile?.name,Dc=n=>{for(let e of Lc){let t=n[e];if(n.type===e&&t&&typeof t=="object"){let r=t;return {[`${e}Message`]:{...r.mime_type?{mimetype:r.mime_type}:{},...r.caption?{caption:r.caption}:{},...r.filename?{fileName:r.filename}:{},...r.voice===true?{ptt:true}:{},...r.id?{cloudMediaId:r.id}:{}}}}}return null},Bc=n=>{let e=n.interactive;return n.type!=="interactive"||!e?null:e.type==="button_reply"&&e.button_reply?.id?{buttonsResponseMessage:{selectedButtonId:e.button_reply.id,selectedDisplayText:e.button_reply.title??""}}:e.type==="list_reply"&&e.list_reply?.id?{listResponseMessage:{singleSelectReply:{selectedRowId:e.list_reply.id},title:e.list_reply.title??""}}:null},Wc=n=>{let e=n.location;return n.type!=="location"||typeof e?.latitude!="number"||typeof e.longitude!="number"?null:{locationMessage:{degreesLatitude:e.latitude,degreesLongitude:e.longitude,...e.name?{name:e.name}:{},...e.address?{address:e.address}:{}}}},Fc=n=>{let e=n.contacts;if(n.type!=="contacts"||!Array.isArray(e)||e.length===0)return null;let t=e.map(s=>{let i=s.name?.formatted_name??"",o=(s.phones??[]).filter(a=>typeof a.phone=="string").map(a=>`TEL${a.wa_id?`;waid=${a.wa_id}`:""}:${a.phone}`).join(`
13
+ `);}var Se={enabled:true,maxAttempts:Number.POSITIVE_INFINITY,initialDelayMs:3e3,maxDelayMs:6e4,jitterFactor:.2,rateLimitedDelayMs:3e5};function ls(n,e){let t=n?.enabled??Se.enabled,r=n?.maxAttempts??Se.maxAttempts,s=n?.initialDelayMs??Se.initialDelayMs,i=n?.maxDelayMs??Se.maxDelayMs,o=n?.jitterFactor??Se.jitterFactor,a=n?.rateLimitedDelayMs??Se.rateLimitedDelayMs,c=e?.random??Math.random,d=0;return {next:w=>{if(!t||Xe(w))return null;let M=d+1;if(M>r)return null;if(d=M,Tt(w))return {attempt:M,delayMs:a};let v=Math.pow(2,M-1),P=Math.min(i,s*v),y=1+(c()*2-1)*o,m=P*y,f=Math.min(i,Math.max(0,m));return {attempt:M,delayMs:Math.round(f)}},reset:()=>{d=0;},get attempts(){return d}}}var ka={idle:["connecting"],connecting:["qr-pending","pairing-pending","connected","reconnecting","disconnecting","disconnected"],"qr-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],"pairing-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],connected:["disconnecting","reconnecting","disconnected"],reconnecting:["connecting","disconnecting","disconnected"],disconnecting:["disconnected"],disconnected:["idle","connecting","reconnecting"]};function us(n="idle"){let e=n,t=new Set,r=s=>ka[e].includes(s);return {get state(){return e},canTransition:r,transition(s){if(!r(s))throw new Error(`invalid state transition: ${e} -> ${s}`);let i=e;e=s;for(let o of t)try{o(i,s);}catch{}},onChange(s){return t.add(s),()=>{t.delete(s);}}}}var xt=n=>`${n.remoteJid??""}|${n.id??""}|${n.fromMe?1:0}`,Ot=class{messages=new Map;messagesByJid=new Map;chats=new Map;contacts=new Map;presence=new Map;boundSocket;listeners=new Map;closed=false;async saveMessage(e){this.assertOpen();let t=xt(e.key);this.messages.set(t,structuredClone(e));let r=e.key.remoteJid??"",s=this.messagesByJid.get(r);s||(s=new Set,this.messagesByJid.set(r,s)),s.add(t);}async getMessage(e){this.assertOpen();let t=this.messages.get(xt(e));return t?structuredClone(t):void 0}async listMessages(e,t){this.assertOpen();let r=this.messagesByJid.get(e);if(!r)return [];let s=[];for(let o of r){let a=this.messages.get(o);a&&s.push(a);}s.sort((o,a)=>Number(a.messageTimestamp)-Number(o.messageTimestamp));let i=s;if(typeof t?.before=="number"){let o=t.before;i=i.filter(a=>Number(a.messageTimestamp)<o);}return typeof t?.limit=="number"&&(i=i.slice(0,t.limit)),i.map(o=>structuredClone(o))}async saveChat(e){this.assertOpen();let t=e.id;t&&this.chats.set(t,structuredClone(e));}async getChat(e){this.assertOpen();let t=this.chats.get(e);return t?structuredClone(t):void 0}async listChats(e){this.assertOpen();let t=[];for(let r of this.chats.values())e?.archived===true&&r.archived!==true||t.push(structuredClone(r));return t}async saveContact(e){this.assertOpen(),this.contacts.set(e.id,structuredClone(e));}async getContact(e){this.assertOpen();let t=this.contacts.get(e);return t?structuredClone(t):void 0}async listContacts(){return this.assertOpen(),Array.from(this.contacts.values(),e=>structuredClone(e))}async savePresence(e,t){this.assertOpen(),this.presence.set(e,structuredClone(t));}async getPresence(e){this.assertOpen();let t=this.presence.get(e);return t?structuredClone(t):void 0}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...c)=>{let l=c[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let u=this.messages.get(xt(l.key));if(u){let w={...u,...l.update};this.saveMessage(w).catch(()=>{});}}},s=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveChat(l).catch(()=>{});},i=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let w={...this.chats.get(l.id)??{},...l};this.saveChat(w).catch(()=>{});}},o=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveContact(l).catch(()=>{});},a=(...c)=>{let d=c[0];if(d?.presences)for(let l of Object.keys(d.presences)){let u=d.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[c,d]of this.listeners)e.ev.on(c,d);}async deleteMessage(e){this.assertOpen();let t=xt(e);this.messages.delete(t);let r=e.remoteJid??"",s=this.messagesByJid.get(r);s&&(s.delete(t),s.size===0&&this.messagesByJid.delete(r));}async pruneMessages(e){this.assertOpen();let t=0;for(let[r,s]of [...this.messagesByJid.entries()]){if(e.chatFilter&&!e.chatFilter(r))continue;let i=[];for(let a of s){let c=this.messages.get(a);c&&i.push(c);}i.sort((a,c)=>Number(c.messageTimestamp??0)-Number(a.messageTimestamp??0));let o=i.filter((a,c)=>{let d=Number(a.messageTimestamp??0);return e.olderThan!==void 0&&d<e.olderThan||e.maxPerChat!==void 0&&c>=e.maxPerChat});for(let a of o)await this.deleteMessage(a.key),t+=1;}return t}async clear(){this.assertOpen(),this.messages.clear(),this.messagesByJid.clear(),this.chats.clear(),this.contacts.clear(),this.presence.clear();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);return this.listeners.clear(),this.boundSocket=void 0,Promise.resolve()}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","MemoryMessageStore is closed")}};var Ta=["silent","fatal","error","warn","info","debug","trace"];function Ia(n){if(n)return n;let e=process.env.ZAILEYS_DEBUG;return e===void 0?"silent":e==="1"?"info":Ta.includes(e)?e:"silent"}function xa(n={}){let e=Ia(n.level),t=Ea__default.default({level:e});return n.sessionId!==void 0?t.child({sessionId:n.sessionId}):t}var ps=["debug","info","warn","error","fatal"];function Oa(n){if(n===null||typeof n!="object")return false;for(let e of ps)if(typeof n[e]!="function")return false;return true}function et(){}function Ra(n){let e={debug:et,info:et,warn:et,error:et,fatal:et};for(let t of ps){let r=n[t];typeof r=="function"&&(e[t]=r.bind(n));}return e}function En(n,e){return n===void 0?e??xa():Oa(n)?n:Ra(n)}var Cg=Object.freeze(["HISTORY_SYNC_NOTIFICATION","APP_STATE_SYNC_KEY_SHARE","LID_MIGRATION_MAPPING_SYNC","PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]),ms=n=>{let e=n.requestId!=null,t=n.messages.filter(r=>{if(e)return false;let s=r.messageStubParameters;if(Array.isArray(s)){for(let i of s)if(typeof i=="string"&&i.startsWith("requestId:"))return false}return true});return {...n,messages:t}};var _a=new Set(["offer","ringing"]),La=new Set(["timeout","reject","accept","terminate"]),gs=n=>{let e=n instanceof Date?n.getTime():Date.parse(String(n));return Number.isFinite(e)?e:0},fs=n=>{if(typeof n.id!="string"||n.id.length===0||!_a.has(n.status))return null;let e=Vr(n.id),t={kind:"incoming",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:gs(n.date),status:n.status};return e!==void 0&&(t.caller=e),t},hs=n=>typeof n.id!="string"||n.id.length===0||!La.has(n.status)?null:{kind:"ended",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:gs(n.date),status:n.status};var B=n=>typeof n=="string"&&n.length>0,Na=n=>{let e={};return typeof n.subject=="string"&&(e.subject=n.subject),typeof n.desc=="string"&&(e.description=n.desc),typeof n.announce=="boolean"&&(e.announce=n.announce),typeof n.restrict=="boolean"&&(e.restrict=n.restrict),typeof n.ephemeralDuration=="number"&&(e.ephemeralDuration=n.ephemeralDuration),e},ys=(n,e,t)=>n.filter(r=>B(r?.id)).map(r=>{let s={jid:r.id},i=r.lid??r.pn??r.phoneNumber;return B(i)&&(s.participantAlt=i),B(e)&&(s.authorPn=e),B(t)&&(s.authorUsername=t),s.isAdmin=r.admin==="admin"||r.admin==="superadmin",s}),ws=n=>B(n?.id)?{groupId:n.id,update:Na(n),timestamp:Date.now()}:null,vs=n=>{if(!B(n?.groupId)||!B(n?.participant))return null;let e={groupId:n.groupId,participant:n.participant,label:typeof n.label=="string"?n.label:"",timestamp:typeof n.messageTimestamp=="number"?n.messageTimestamp:Date.now()};return B(n.participantAlt)&&(e.participantAlt=n.participantAlt),e},Da=new Set(["add","invite","invite-link"]),Ba=new Set(["remove","leave"]),Ms=n=>{if(!B(n?.id)||!Da.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=ys(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return B(n.author)&&(t.by=n.author),t},Ss=n=>{if(!B(n?.id)||!Ba.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=ys(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return B(n.author)&&(t.by=n.author),t};var be=n=>typeof n!="string"||n.length===0?null:Yc.jidNormalizedUser(n),Z=n=>typeof n=="string"&&n.length>0?n:void 0,ja=["@s.whatsapp.net","@c.us"],Rt=n=>n.endsWith("@lid"),bs=n=>ja.some(e=>n.endsWith(e)),$=(n,e)=>{if(!n)return null;let t=Z(n.participant)??n.remoteJid,r=be(t);if(r===null)return null;let s=Z(n.participantAlt)??Z(n.remoteJidAlt),i=s!=null?be(s):null,o=Z(n.participantUsername)??Z(n.remoteJidUsername),a={jid:r,isMe:n.fromMe===true};typeof t=="string"&&t.length>0&&(a.deviceJid=t);let c=i!==null?[r,i]:[r],d=c.find(Rt),l=c.find(bs);d!==void 0&&(a.lid=d),l!==void 0&&(a.pn=l),o!==void 0&&(a.username=o);let u=Z(e);return u!==void 0&&(a.pushName=u),a},As=n=>{if(!n)return null;let e=n.stanzaId;if(typeof e!="string"||e.length===0)return null;let t=Z(n.participant),r=Z(n.remoteJid)??t,s={id:e};typeof r=="string"&&(s.remoteJid=r),typeof t=="string"&&(s.participant=t);let i={key:s},o=$(s);return o&&(i.sender=o),i},tt=n=>{if(!n)return {mentionedJids:[],mentionAll:false};let e=n.mentionedJid,t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[],r=n.groupMentions,s=Array.isArray(r)&&r.length>0;return {mentionedJids:t,mentionAll:s}};var Ae=n=>Yc.isJidGroup(n)===true,Ce=n=>{if(n==null)return null;if(typeof n=="number")return Number.isFinite(n)?n:null;if(typeof n.toNumber=="function"){let e=n.toNumber();return Number.isFinite(e)?e:null}return null},g=n=>n!=null&&typeof n=="object"?n:null,Cs=["ephemeralMessage","viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension","documentWithCaptionMessage","editedMessage","lottieStickerMessage","groupStatusMessage","groupStatusMessageV2"],Ps=["groupStatusMessage","groupStatusMessageV2"],ks=(n,e)=>{let t=n;for(let r=0;r<5&&t!=null;r++){if(e.some(i=>t?.[i]!=null))return true;let s=null;for(let i of Cs){let o=g(g(t[i])?.message);if(o!=null){s=o;break}}t=s;}return false},Pe=n=>{let e=n;for(let t=0;t<5;t++){let r=null;for(let s of Cs){let i=g(g(e[s])?.message);if(i!=null){r=i;break}}if(r==null)break;e=r;}return e};var Ua=["quick_reply","cta_url","cta_call","button_click"],qa=["list_select","single_select"],J=n=>typeof n=="string"&&n.length>0,Ts=n=>{let e=typeof n.pushName=="string"?n.pushName:void 0;return $(n.key,e)},Is=n=>Ce(n.messageTimestamp)??0,xs=(n,e)=>{if(!J(n))return null;try{let t=JSON.parse(n);return t!==null&&typeof t=="object"?t:null}catch{return e?.debug({paramsJson:n},"interactive: failed to parse nativeFlow paramsJson"),null}},_t=(n,e)=>{for(let t of e){let r=n[t];if(J(r))return r}},Os=(n,e)=>{let t=n.message;if(!t)return null;let r=t.buttonsResponseMessage;if(r&&J(r.selectedButtonId))return Tn(n,r.selectedButtonId,r.selectedDisplayText);let s=t.templateButtonReplyMessage;if(s&&J(s.selectedId))return Tn(n,s.selectedId,s.selectedDisplayText);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&Ua.includes(i.name)){let o=xs(i.paramsJson,e.logger);if(!o)return null;let a=_t(o,["id","button_id"]);return a===void 0?null:Tn(n,a,_t(o,["display_text"])??null)}return null},Tn=(n,e,t)=>{let r=Ts(n);if(!r||!n.key)return null;let s={key:n.key,buttonId:e,sender:r,timestamp:Is(n)};return J(t)&&(s.buttonText=t),s},Rs=(n,e)=>{let t=n.message;if(!t)return null;let r=t.listResponseMessage,s=r?.singleSelectReply?.selectedRowId;if(J(s))return Es(n,s,r?.title);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&qa.includes(i.name)){let o=xs(i.paramsJson,e.logger);if(!o)return null;let a=_t(o,["row_id","id"]);return a===void 0?null:Es(n,a,_t(o,["title"])??null)}return null},Es=(n,e,t)=>{let r=Ts(n);if(!r||!n.key)return null;let s={key:n.key,rowId:e,sender:r,timestamp:Is(n)};return J(t)&&(s.title=t),s};var Ka=new Set(["available","unavailable","composing","recording","paused"]),$a=n=>n instanceof Date?n.getTime():typeof n=="number"&&Number.isFinite(n)?n:0,_s=n=>n.status!=="complete"&&n.status!=="paused"?null:{syncType:String(n.syncType),status:n.status,explicit:n.explicit===true},In=n=>{if(n.source==="connection-update"){let t=n.reachoutTimeLock;return t.isActive!==true?null:{reason:"reachout-timelock",retryAt:$a(t.timeEnforcementEnds)}}if(n.capInfo.capping_status!=="CAPPED")return null;let e={reason:"chat-limit-reached"};return typeof n.capInfo.used_quota=="number"&&(e.usedQuota=n.capInfo.used_quota),typeof n.capInfo.total_quota=="number"&&(e.totalQuota=n.capInfo.total_quota),e},Ls=n=>{if(typeof n.id!="string"||n.id.length===0)return [];let e=[];for(let[t,r]of Object.entries(n.presences??{})){let s=r?.lastKnownPresence;typeof s!="string"||!Ka.has(s)||e.push({jid:n.id,participant:t,status:s});}return e},nt=n=>{let e=n.payload.id;if(typeof e!="string"||e.length===0)return null;let t=Date.now();switch(n.source){case "reaction":{let r={action:"reaction",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.reaction?.code=="string"&&(r.emoji=n.payload.reaction.code),r}case "view":{let r={action:"view",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.count=="number"&&(r.count=n.payload.count),r}case "participants":return {action:"participants",newsletterId:e,timestamp:t};case "settings":{let r={action:"settings",newsletterId:e,timestamp:t};return n.payload.update&&(r.update=n.payload.update),r}}};var Ds=n=>{let e=n.match(/(https?:\/\/[^\s]+)/g);return e?e.map(t=>t.replace(/[.,;:!?]+$/,"")):[]},Ns=(n,e=2166136261)=>{let t=e>>>0;for(let r=0;r<n.length;r++)t^=n.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t>>>0},Bs=n=>(Ns(n).toString(16).padStart(8,"0")+Ns(n,2646966556).toString(16).padStart(8,"0")).toUpperCase(),Ws=n=>Bs(`${n.remoteJid??""}|${n.id??""}|${n.fromMe===true?"1":"0"}`),Fs=(n,e)=>Bs(`${n??""}|${e}`),js=n=>{let e=null;if(typeof n=="number")e=n;else if(typeof n=="bigint")e=Number(n);else if(typeof n=="string"){let t=Number.parseInt(n,10);e=Number.isFinite(t)?t:null;}else if(n!=null&&typeof n=="object"){let t=n;typeof t.toNumber=="function"?e=t.toNumber():typeof t.low=="number"&&(e=(typeof t.high=="number"?t.high:0)*4294967296+(t.low>>>0));}return e!=null&&Number.isFinite(e)&&e>0?e*1e3:0},Us=n=>{let e=Yc.jidDecode(n);if(!e)return "unknown";let t=e.device;return t===void 0||t===0?"android":t===2?"ios":t===3?"web":t===4?"desktop":"unknown"},Ja=n=>n.trim().endsWith("?"),Va=(n,e)=>e.length===0?false:e.some(t=>t.length>0&&n.startsWith(t)),Ha=(n,e)=>{if(e.length===0)return false;let t;try{t=Yc.jidNormalizedUser(n);}catch{t=n;}return e.some(r=>{try{return Yc.jidNormalizedUser(r)===t}catch{return r===n}})},za=(n,e)=>{let t=async r=>r===void 0?false:Array.isArray(r)?r.includes(e):r(e);return {authors:()=>t(n?.authors),banned:()=>t(n?.banned)}},Ya=0,Za=14,Qa=1,Xa=2,ec=n=>{let e=g(n.message);if(e==null)return {isEdited:false,isDeleted:false,isPinned:false,isUnPinned:false,isBot:false,isStatusMention:false,isGroupStatusMention:false,isGroupStatus:false};let t=g(e.protocolMessage),r=typeof t?.type=="number"?t.type:void 0,s=typeof g(e.pinInChatMessage)?.type=="number"?e.pinInChatMessage.type:void 0;return {isEdited:e.editedMessage!=null||r===Za,isDeleted:r===Ya,isPinned:s===Qa,isUnPinned:s===Xa,isBot:g(e.messageContextInfo)?.botMetadata!=null,isStatusMention:e.statusMentionMessage!=null,isGroupStatusMention:e.groupStatusMentionMessage!=null,isGroupStatus:ks(e,Ps)}},xn=n=>{let e=typeof n.key.remoteJid=="string"?n.key.remoteJid:null,t=e!==null&&Ae(e),r=ec(n.message),s=c=>n.lidMap!=null&&c.endsWith("@lid")?n.lidMap.get(c)??c:c,i=s(n.sender.pn??n.sender.jid),o=t?e?Yc.jidNormalizedUser(e):null:n.key.fromMe===true&&e?s(Yc.jidNormalizedUser(e)):i,a={uniqueId:Ws(n.key),staticId:Fs(o,i),channelId:n.channelId,chatId:n.key.id??"",chatType:n.chatType,receiverId:n.receiverId?s(Yc.jidNormalizedUser(n.receiverId)):n.receiverId,roomId:o,senderId:i,senderLid:n.sender.lid??null,senderName:n.sender.pushName??null,senderUsername:n.sender.username??null,senderDevice:Us(n.sender.deviceJid??n.sender.jid),timestamp:js(n.message.messageTimestamp),text:n.text,mentions:n.mentions,links:Ds(n.text),isFromMe:n.key.fromMe===true,isGroup:t,isNewsletter:n.isNewsletter,isBroadcast:n.isBroadcast,isViewOnce:n.isViewOnce,isEphemeral:n.isEphemeral,isForwarded:n.isForwarded,isOld:n.isOld===true,isQuestion:Ja(n.text),isPrefix:Va(n.text,n.prefixes),isTagMe:Ha(n.selfJid,n.mentions),isEdited:r.isEdited,isDeleted:r.isDeleted,isPinned:r.isPinned,isUnPinned:r.isUnPinned,isBot:r.isBot,isSpam:false,isHideTags:n.mentions.length>0&&!/@\d/.test(n.text),isStatusMention:r.isStatusMention,isGroupStatusMention:r.isGroupStatusMention,isGroupStatus:r.isGroupStatus,isStory:e==="status@broadcast",forwardCount:n.forwardCount??0,ephemeralDuration:n.ephemeralDuration??null,addressingMode:n.addressingMode??"pn",mentionedGroups:n.mentionedGroups??[],...n.ad!==void 0?{ad:n.ad}:{},...n.business!==void 0?{business:n.business}:{},roomName:n.resolveRoomName,receiverName:n.resolveReceiverName,replied:n.resolveReplied,reply:n.reply,react:n.react,message:()=>n.message,citation:za(n.citationConfig,n.sender.pn??n.sender.jid)};return n.media!==void 0&&(a.media=n.media),a};var Rn={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},$s=n=>{let e=n?.remoteJid;return typeof e=="string"&&e.length>0?e:""},S=n=>typeof n=="string"&&n.length>0?n:null,Q=(...n)=>{for(let e of n){let t=S(e);if(t!=null)return t}return null},Gs=n=>{let e=g(n.message);if(e==null)return n;let t=Pe(e);return t===e?n:{...n,message:t}},tc=n=>{let t=g(g(g(n.botForwardedMessage)?.message)?.richResponseMessage)??g(n.richResponseMessage);if(t==null)return null;let r=t.submessages;if(!Array.isArray(r))return null;let s=[];for(let o of r){let a=S(g(o)?.messageText);a!=null&&s.push(a);}let i=s.join(`
14
+ `).trim();return i.length>0?i:null},nc=n=>{let e=g(n.templateMessage),t=g(e?.hydratedTemplate)??g(e?.hydratedFourRowTemplate);return S(t?.hydratedContentText)},rc=n=>Q(g(n.pollCreationMessage)?.name,g(n.pollCreationMessageV2)?.name,g(n.pollCreationMessageV3)?.name),sc=n=>{let e=g(n.locationMessage)??g(n.liveLocationMessage);if(e==null)return null;let t=Q(e.name,e.address);if(t!=null){let i=S(e.name),o=S(e.address);return i!=null&&o!=null&&i!==o?`${i} \u2014 ${o}`:t}let r=e.degreesLatitude,s=e.degreesLongitude;return typeof r=="number"&&typeof s=="number"?`${r}, ${s}`:null},ic=n=>{let e=S(g(n.contactMessage)?.displayName);if(e!=null)return e;let t=g(n.contactsArrayMessage),r=S(t?.displayName);if(r!=null)return r;let s=t?.contacts;if(Array.isArray(s)){let i=s.map(o=>S(g(o)?.displayName)).filter(o=>o!=null);if(i.length>0)return i.join(", ")}return null},Js=n=>Q(n.conversation,g(n.extendedTextMessage)?.text,tc(n),S(g(g(n.interactiveMessage)?.body)?.text),g(n.buttonsMessage)?.contentText,g(n.listMessage)?.description,nc(n),rc(n),sc(n),ic(n)),oc=n=>Q(g(n.buttonsResponseMessage)?.selectedDisplayText,g(n.buttonsResponseMessage)?.selectedButtonId,g(n.templateButtonReplyMessage)?.selectedDisplayText,g(n.templateButtonReplyMessage)?.selectedId,g(n.listResponseMessage)?.title,g(g(n.listResponseMessage)?.singleSelectReply)?.selectedRowId,g(g(n.interactiveResponseMessage)?.body)?.text),ac=n=>Q(g(n.imageMessage)?.caption,g(n.videoMessage)?.caption,g(n.documentMessage)?.caption,g(n.documentMessage)?.fileName),T=n=>{if(typeof n=="number")return n;let e=Ce(n);return typeof e=="number"?e:null},cc=[["pollCreationMessage","poll"],["pollCreationMessageV2","poll"],["pollCreationMessageV3","poll"],["contactMessage","contact"],["contactsArrayMessage","contact"],["locationMessage","location"],["liveLocationMessage","live-location"],["eventMessage","event"],["albumMessage","album"],["groupInviteMessage","group-invite"],["productMessage","product"],["orderMessage","order"],["requestPaymentMessage","payment"],["sendPaymentMessage","payment"],["paymentInviteMessage","payment"],["buttonsMessage","buttons"],["listMessage","list"],["interactiveMessage","interactive"],["templateMessage","template"]],Vs=n=>{let e=g(n.pollCreationMessage)??g(n.pollCreationMessageV2)??g(n.pollCreationMessageV3);if(e!=null){let m=Array.isArray(e.options)?e.options:[];return {type:"poll",name:S(e.name),options:m.map(f=>S(g(f)?.optionName)).filter(f=>f!=null),selectableCount:T(e.selectableOptionsCount)??0}}let t=g(n.contactMessage);if(t!=null)return {type:"contact",displayName:S(t.displayName),vcard:S(t.vcard),contacts:[{displayName:S(t.displayName),vcard:S(t.vcard)}]};let r=g(n.contactsArrayMessage);if(r!=null){let m=Array.isArray(r.contacts)?r.contacts:[];return {type:"contact",displayName:S(r.displayName),vcard:null,contacts:m.map(f=>({displayName:S(g(f)?.displayName),vcard:S(g(f)?.vcard)}))}}let s=g(n.locationMessage);if(s!=null)return {type:"location",latitude:T(s.degreesLatitude),longitude:T(s.degreesLongitude),name:S(s.name),address:S(s.address),accuracy:T(s.accuracyInMeters),speed:T(s.speedInMps),caption:S(s.comment)};let i=g(n.liveLocationMessage);if(i!=null)return {type:"live-location",latitude:T(i.degreesLatitude),longitude:T(i.degreesLongitude),name:null,address:null,accuracy:T(i.accuracyInMeters),speed:T(i.speedInMps),caption:S(i.caption)};let o=g(n.albumMessage);if(o!=null)return {type:"album",expectedImageCount:T(o.expectedImageCount),expectedVideoCount:T(o.expectedVideoCount)};let a=g(n.groupInviteMessage);if(a!=null)return {type:"group-invite",groupId:S(a.groupJid),groupName:S(a.groupName),inviteCode:S(a.inviteCode),caption:S(a.caption),expiresAt:T(a.inviteExpiration)};let c=g(g(n.productMessage)?.product);if(g(n.productMessage)!=null){let m=S(g(n.productMessage)?.businessOwnerJid),f=T(c?.priceAmount1000);return {type:"product",productId:S(c?.productId),title:S(c?.title),description:S(c?.description),price:f!=null?f/1e3:null,currency:S(c?.currencyCode),retailerId:S(c?.retailerId),url:S(c?.url),businessOwnerId:m}}let d=g(n.orderMessage);if(d!=null){let m=T(d.totalAmount1000),f={1:"inquiry",2:"accepted",3:"declined"},b=d.status;return {type:"order",orderId:S(d.orderId),title:S(d.orderTitle),itemCount:T(d.itemCount),total:m!=null?m/1e3:null,currency:S(d.totalCurrencyCode),status:typeof b=="number"?f[b]??null:S(b),message:S(d.message)}}let l=g(n.requestPaymentMessage)!=null&&{node:n.requestPaymentMessage,kind:"request"}||g(n.sendPaymentMessage)!=null&&{node:n.sendPaymentMessage,kind:"send"}||g(n.paymentInviteMessage)!=null&&{node:n.paymentInviteMessage,kind:"invite"};if(l!==false){let m=g(l.node),f=T(m?.amount1000),b=g(m?.noteMessage);return {type:"payment",kind:l.kind,amount:f!=null?f/1e3:null,currency:S(m?.currencyCodeIso4217),note:Q(b?.conversation,g(b?.extendedTextMessage)?.text),expiresAt:T(m?.expiryTimestamp)}}let u=g(n.eventMessage);if(u!=null){let m=g(u.location);return {type:"event",name:S(u.name),description:S(u.description),location:m!=null?Q(m.name,m.address):null,startTime:T(u.startTime),endTime:T(u.endTime),isCanceled:u.isCanceled===true}}let w=g(n.buttonsMessage);if(w!=null){let m=Array.isArray(w.buttons)?w.buttons:[];return {type:"buttons",contentText:S(w.contentText),footerText:S(w.footerText),buttons:m.map(f=>({id:S(g(f)?.buttonId),text:S(g(g(f)?.buttonText)?.displayText)}))}}let M=g(n.listMessage);if(M!=null){let m=Array.isArray(M.sections)?M.sections:[];return {type:"list",title:S(M.title),description:S(M.description),buttonText:S(M.buttonText),sections:m.map(f=>{let b=Array.isArray(g(f)?.rows)?g(f).rows:[];return {title:S(g(f)?.title),rows:b.map(k=>({id:S(g(k)?.rowId),title:S(g(k)?.title),description:S(g(k)?.description)}))}})}}let v=g(n.interactiveMessage);if(v!=null){let m=g(v.nativeFlowMessage),f=Array.isArray(m?.buttons)?m.buttons:[];return {type:"interactive",title:S(g(v.header)?.title),body:S(g(v.body)?.text),footer:S(g(v.footer)?.text),buttons:f.map(b=>({name:S(g(b)?.name),params:S(g(b)?.buttonParamsJson)}))}}let P=g(n.templateMessage);if(P!=null){let m=g(P.hydratedTemplate)??g(P.hydratedFourRowTemplate),f=Array.isArray(m?.hydratedButtons)?m.hydratedButtons:[];return {type:"template",text:S(m?.hydratedContentText),buttons:f.map(b=>{let k=g(b),F=g(k?.quickReplyButton)??g(k?.urlButton)??g(k?.callButton);return {id:S(F?.id),text:S(F?.displayText)}})}}let y=g(n.extendedTextMessage);if(y!=null){let m=Q(y.canonicalUrl,y.matchedText),f=S(y.title),b=S(y.description);if(m!=null&&(f!=null||b!=null))return {type:"link",url:m,title:f,description:b}}return null};var st=n=>{let e=g(n.message);if(e==null)return null;let t=Pe(e);return Js(t)??oc(t)??ac(t)},Nt=n=>{let e=g(Gs(n).message);if(e==null)return null;let t=g(e.extendedTextMessage)?.contextInfo;if(t!=null)return t;for(let r of Object.values(e)){if(r==null||typeof r!="object")continue;let s=r.contextInfo;if(s!=null)return s}return null},dc=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[Rn[e]];return r==null||typeof r!="object"?null:r},lc=n=>{let e=n.message;if(e==null)return false;if(e.viewOnceMessage!=null||e.viewOnceMessageV2!=null||e.viewOnceMessageV2Extension!=null)return true;for(let t of Object.values(Rn)){let r=e[t];if(r!=null&&typeof r=="object"&&r.viewOnce===true)return true}return false},uc=(n,e)=>n.message?.ephemeralMessage!=null?true:typeof e?.expiration=="number"&&e.expiration>0,pc=(n,e)=>typeof n=="number"&&Number.isFinite(n)?n:e,mc=(n,e)=>{let t=e?.expiration;if(typeof t=="number"&&t>0)return t;let r=g(g(n.message)?.ephemeralMessage),s=g(g(r?.message)?.extendedTextMessage)?.contextInfo,i=g(s)?.expiration;return typeof i=="number"&&i>0?i:null},gc=n=>{let e=n?.groupMentions;if(!Array.isArray(e))return [];let t=[];for(let r of e){let s=g(r)?.groupJid;typeof s=="string"&&s.length>0&&t.push(s);}return t},Hs=n=>typeof n=="string"&&n.length>0?n:void 0,fc=n=>{let e=g(n?.externalAdReply);if(e==null)return;let t={},r=[["clickId","ctwaClid"],["sourceId","sourceId"],["sourceUrl","sourceUrl"],["sourceApp","sourceApp"],["sourceType","sourceType"],["title","title"],["body","body"],["thumbnailUrl","thumbnailUrl"],["ref","ref"]];for(let[s,i]of r){let o=Hs(e[i]);o!==void 0&&(t[s]=o);}return Object.keys(t).length>0?t:void 0},hc=n=>{let e=Hs(g(n)?.verifiedBizName);return e!==void 0?{verifiedName:e}:void 0},ce=n=>{let e=g(n);if(e==null)return "text";let t=Pe(e);for(let r of Object.values(Rn))if(t[r]!=null)return r.replace("Message","");for(let[r,s]of cc)if(t[r]!=null)return s;return "text"},qs=(n,e)=>{if(n==null)return false;let t=[n.pn,n.lid,n.jid].filter(s=>typeof s=="string"&&s.length>0),r=[e.pn,e.lid,e.jid].filter(s=>typeof s=="string"&&s.length>0);return t.some(s=>r.includes(s))},yc=async(n,e,t,r,s,i)=>{try{if(n==null||n.quotedMessage==null)return null;let o=n.stanzaId;if(typeof o!="string"||o.length===0)return null;if(e.resolveQuoted!=null&&t.length>0){let v=await e.resolveQuoted(o,t);if(v!=null&&v.message!=null){let P=st(v)??"",y=de(v,e,ce(v.message),P,it(v,e),s);if(y!==null)return y}}let a=As(n);if(a===null||typeof a.key.id!="string"||a.key.id.length===0||(t.length>0&&(a.key.remoteJid=t),typeof a.key.remoteJid!="string"||a.key.remoteJid.length===0))return null;let c=a.key.participant,d=Ae(t),l=a.sender?.pushName;!d&&(c==null||c.length===0)?i===!0?(a.key.participant=t,l==null&&r!=null&&qs({jid:t},r)&&(l=r.pushName)):(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):typeof c=="string"&&(e.selfJid.length>0&&Lt(c,e.selfJid)||e.selfLid!=null&&Lt(c,e.selfLid))?(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):r!=null&&qs(a.sender,r)&&(r.pn!=null&&(a.key.participant=r.pn),r.lid!=null&&(a.key.participantAlt=r.lid),l==null&&(l=r.pushName));let u=n.quotedMessage,w=Object.assign({key:a.key,message:u??null},l!=null?{pushName:l}:{}),M=st(w)??"";return de(w,e,ce(u),M,it(w,e),s)}catch{return null}},zs=n=>tt(Nt(n)).mentionedJids,wc=n=>{try{return Yc.jidNormalizedUser(n)}catch{return n}},Ys=(n,e)=>n.map(t=>{let r=wc(t);return e.lidMap?.get(r)??r}),Ks=n=>(n.split("@")[0]??"").split(":")[0]??"",vc=(n,e)=>{if(e==null||e.size===0||n.length===0)return n;let t=[...e].map(([s,i])=>[Ks(s),Ks(i)]).filter(([s,i])=>s.length>0&&i.length>0&&s!==i).sort((s,i)=>i[0].length-s[0].length),r=n;for(let[s,i]of t)r=r.split(`@${s}`).join(`@${i}`);return r},de=(n,e,t,r,s,i)=>{let o=n.key;if(o==null)return null;let a=$(o,n.pushName??void 0);if(a===null)return null;let c=$s(o);if(c.length===0)return null;let d=Nt(n),l=Ae(c),u=c.endsWith("@broadcast"),w=c.endsWith("@newsletter"),M=d?.isForwarded===true||(d?.forwardingScore??0)>0,v=lc(n),P=uc(n,d),y=e.channelId??"",m=e.receiverId??"",f=e.prefixes??[],b=i??(()=>l?e.resolveRoomName!=null?e.resolveRoomName(c):Promise.resolve(null):Promise.resolve(a.pushName??null)),k=e.resolveReceiverName??(()=>Promise.resolve(null)),F=()=>yc(d,e,c,a,b,o.fromMe===true),en=c.length>0?c:a.pn??a.jid,tn=(rn,Ki)=>e.reply==null?Promise.reject(new Error("zaileys: ctx.reply() requires a connected client")):e.reply(en,rn,Ki,n),nn=rn=>e.react==null?Promise.reject(new Error("zaileys: ctx.react() requires a connected client")):e.react(o,rn),Ui=Ys(tt(d).mentionedJids,e),qi=vc(r,e.lidMap),qn=fc(d),Kn=hc(n),$n={message:n,key:o,channelId:y,receiverId:m,selfJid:e.selfJid,text:qi,chatType:t,sender:a,mentions:Ui,isViewOnce:v,isEphemeral:P,isForwarded:M,isBroadcast:u,isNewsletter:w,isOld:e.isOld===true,prefixes:f,forwardCount:pc(d?.forwardingScore,0),ephemeralDuration:mc(n,d),addressingMode:o.addressingMode==="lid"?"lid":"pn",mentionedGroups:gc(d),...qn!==void 0?{ad:qn}:{},...Kn!==void 0?{business:Kn}:{},...e.lidMap!=null?{lidMap:e.lidMap}:{},resolveRoomName:b,resolveReceiverName:k,resolveReplied:F,reply:tn,react:nn},Gn=s!==void 0?{...$n,media:s}:$n;return xn(e.citationConfig!==void 0?{...Gn,citationConfig:e.citationConfig}:Gn)},Mc=["image","video","audio","document","sticker"],Zs=(n,e,t)=>{let r=Gs(n),s=dc(r,e);if(s===null)return null;let i=Pt(r,e,t.logger),o=Xr(r,e,t.logger);return {type:e,mimetype:typeof s.mimetype=="string"?s.mimetype:null,caption:typeof s.caption=="string"?s.caption:null,fileName:typeof s.fileName=="string"?s.fileName:null,fileSize:T(s.fileLength),ptt:s.ptt===true,isAnimated:s.isAnimated===true||s.gifPlayback===true,duration:T(s.seconds),width:T(s.width),height:T(s.height),pages:T(s.pageCount),thumbnail:s.jpegThumbnail!=null?Buffer.from(s.jpegThumbnail):null,buffer:async()=>(await i()).buffer,stream:o}},it=(n,e)=>{let t=g(n.message);if(t==null)return;let r=ce(n.message);return Mc.includes(r)?Zs(n,r,e)??void 0:Vs(Pe(t))??void 0},Qs=(n,e)=>{if(g(n.message)==null)return null;let r=ce(n.message),s=it(n,e),i=st(n)??"";return i===""&&s===void 0?null:de(n,e,r,i,s)},Xs=(n,e)=>{let t=g(n.message);if(t==null)return null;let r=Pe(t),s=Js(r),i=Vs(r)??void 0;return s===null&&i===void 0?null:de(n,e,ce(n.message),s??"",i)},ot=(n,e,t)=>{let r=Zs(e,n,t);return r===null?null:de(e,t,n,r.caption??"",r)},ei=(n,e)=>ot("image",n,e),ti=(n,e)=>ot("video",n,e),ni=(n,e)=>ot("audio",n,e),ri=(n,e)=>ot("document",n,e),si=(n,e)=>ot("sticker",n,e),Lt=(n,e)=>{try{return Yc.jidNormalizedUser(n)===Yc.jidNormalizedUser(e)}catch{return n===e}},ii=(n,e)=>{if(n.key==null)return null;let r=Nt(n),s=tt(r).mentionedJids;if(s.length===0)return null;let i=Ys(s,e);if(!(i.some(u=>Lt(u,e.selfJid))||e.selfLid!=null&&s.some(u=>Lt(u,e.selfLid)))||g(n.message)==null)return null;let c=st(n)??"",d=it(n,e),l=de(n,e,ce(n.message),c,d);return l===null?null:{...l,mentionedJids:i,selfJid:e.selfJid}},oi=(n,e)=>{let t=n.key;if(t==null)return null;let r=$s(t);if(r.length===0||!Ae(r))return null;let{mentionAll:s}=tt(Nt(n));if(!s||g(n.message)==null)return null;let o=st(n)??"",a=it(n,e),c=de(n,e,ce(n.message),o,a);return c===null?null:{...c,isMentionAll:true,selfJid:e.selfJid}};var le=(n,e)=>{let t=Ce(n);return t===null?e:t},bc=n=>{if(!n)return "";if(typeof n.conversation=="string")return n.conversation;let e=n.extendedTextMessage?.text;if(typeof e=="string")return e;let t=n.imageMessage?.caption;if(typeof t=="string")return t;let r=n.videoMessage?.caption;if(typeof r=="string")return r;let s=n.documentMessage?.caption;if(typeof s=="string")return s;let o=(n.botForwardedMessage?.message?.richResponseMessage??n.richResponseMessage)?.submessages;if(Array.isArray(o)){let a=o.map(c=>c?.messageText).filter(c=>typeof c=="string"&&c.length>0);if(a.length>0)return a.join(`
15
+ `)}return ""},Ac=n=>Array.isArray(n)?n.map(e=>Buffer.from(e).toString("hex")):[],ci=(n,e)=>{let t=n?.reaction,r=t?.key;if(!r)return null;let s=$(n.key,e.pushName);if(s===null)return null;let i=t.text,o=typeof i=="string"&&i.length>0?i:null;return {key:r,emoji:o,sender:s,timestamp:le(t.senderTimestampMs,0)}},di=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==Yc.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT)return null;let r=t.key;if(!r)return null;let s=$(n.key,e.pushName);return s===null?null:{key:r,newContent:bc(t.editedMessage),editedAt:le(n.update.messageTimestamp,0),sender:s}},li=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==Yc.proto.Message.ProtocolMessage.Type.REVOKE)return null;let r=t.key;if(!r)return null;let s=$(n.key,e.pushName);if(s===null)return null;let i=be(n.key.remoteJid),o=be(e.selfJid);return {key:r,deletedFor:i!==null&&o!==null&&i===o?"me":"everyone",sender:s,timestamp:le(n.update.messageTimestamp,0)}},Cc=async(n,e,t)=>{if(e.length===0||t.resolvePoll==null)return [];let r=n.id,s=n.remoteJid;if(typeof r!="string"||typeof s!="string")return [];let o=(await t.resolvePoll(r,s))?.message,a=o?.pollCreationMessage?.options??o?.pollCreationMessageV2?.options??o?.pollCreationMessageV3?.options??[],c=new Map;for(let l of a){let u=l?.optionName??"";c.set(crypto.createHash("sha256").update(Buffer.from(u)).digest("hex").toUpperCase(),u);}let d=[];for(let l of e){let u=c.get(l.toUpperCase());u!==void 0&&d.push(u);}return d},ui=(n,e)=>{let t=n?.update?.pollUpdates?.[0],r=n?.update?.message?.pollUpdateMessage,s=$(n?.key,e.pushName);if(s===null)return null;if(t){let i=t.pollUpdateMessageKey;if(!i)return null;let o=Ac(t.vote?.selectedOptions);return {pollKey:i,selectedOptions:o,options:()=>Cc(i,o,e),voter:s,timestamp:le(t.senderTimestampMs,le(n.update.messageTimestamp,0))}}if(r){let i=r.pollCreationMessageKey;return i?{pollKey:i,selectedOptions:[],options:()=>Promise.resolve([]),voter:s,timestamp:le(r.senderTimestampMs,le(n.update.messageTimestamp,0))}:null}return null};var Dt=n=>Array.isArray(n)?n:[],Pc=3e3,kc=(n,e)=>new Promise(t=>{let r=setTimeout(()=>t(null),e);n.then(s=>{clearTimeout(r),t(s);},()=>{clearTimeout(r),t(null);});}),Ec=n=>{if(n==null||typeof n!="object")return null;let e=n.reachoutTimeLock;return e==null||typeof e!="object"?null:e};function _n(n,e,t){let r=[],s=new Map,i=t.groupMetadata!=null?y=>{let m=s.get(y);if(m!==void 0)return m;let f=t.groupMetadata;if(f==null)return Promise.resolve(null);let b=f(y).then(k=>k?.subject??null).catch(()=>null);return s.set(y,b),b}:void 0,o={selfJid:t.selfJid,...t.selfLid!=null?{selfLid:t.selfLid}:{},...t.selfName!=null?{selfName:t.selfName}:{},receiverId:t.receiverId??t.selfJid,...t.logger!=null?{logger:t.logger}:{},...t.channelId!=null?{channelId:t.channelId}:{},...t.prefixes!=null?{prefixes:t.prefixes}:{},...t.citationConfig!=null?{citationConfig:t.citationConfig}:{},...i!=null?{resolveRoomName:i}:{},...t.receiverName!=null?{resolveReceiverName:t.receiverName}:{},...t.resolveQuoted!=null?{resolveQuoted:t.resolveQuoted}:{},...t.sendReply!=null?{reply:t.sendReply}:{},...t.react!=null?{react:t.react}:{}},a=t.logger?{selfJid:t.selfJid,logger:t.logger}:{selfJid:t.selfJid},c={selfJid:t.selfJid,...t.resolveQuoted!=null?{resolvePoll:t.resolveQuoted}:{}},d=(y,m)=>{let f=(...b)=>{try{m(b[0]);}catch(k){t.logger?.warn(k,`inbound pipeline: handler for ${y} threw`);}};e.ev.on(y,f),r.push(()=>e.ev.off(y,f));},l=(y,m)=>{v(()=>Qs(y,m),f=>n.emit("message",f)),v(()=>Xs(y,m),f=>n.emit("text",f)),v(()=>ei(y,m),f=>n.emit("image",f)),v(()=>ti(y,m),f=>n.emit("video",f)),v(()=>ni(y,m),f=>n.emit("audio",f)),v(()=>ri(y,m),f=>n.emit("document",f)),v(()=>si(y,m),f=>n.emit("sticker",f)),v(()=>ii(y,m),f=>n.emit("mention",f)),v(()=>oi(y,m),f=>n.emit("mention-all",f)),v(()=>Os(y,a),f=>n.emit("button-click",f)),v(()=>Rs(y,a),f=>n.emit("list-select",f));},u=y=>{if(typeof y!="string"||y.length===0)return null;let m;try{m=Yc.jidNormalizedUser(y);}catch{m=y;}return Rt(m)?m:null},w=y=>{let m=new Set;for(let f of [y.key?.participant,y.key?.remoteJid,t.selfJid,...zs(y)]){let b=u(f);b!=null&&m.add(b);}return [...m]},M=async y=>{let m=t.resolveLidToPn;if(m==null||y.length===0)return;let f=new Map;return await Promise.all(y.map(async b=>{try{let k=await kc(Promise.resolve(m(b)),Pc);if(k!=null&&k.length>0)try{f.set(b,Yc.jidNormalizedUser(k));}catch{f.set(b,k);}}catch(k){t.logger?.warn(k,"inbound pipeline: lid->pn resolve threw");}})),f.size>0?f:void 0},v=(y,m)=>{let f;try{f=y();}catch(b){t.logger?.warn(b,"inbound pipeline: decoder threw");return}f!=null&&m(f);};d("messages.upsert",y=>{let m=ms(y),f=m.type==="append"?{...o,isOld:!0}:o;for(let b of m.messages){if(t.ignoreMe===!0&&b.key?.fromMe===!0)continue;let k=t.resolveLidToPn!=null?w(b):[];if(k.length===0){l(b,f);continue}M(k).then(F=>l(b,F!=null?{...f,lidMap:F}:f)).catch(F=>{t.logger?.warn(F,"inbound pipeline: deferred lid resolve emit failed"),l(b,f);});}}),d("messages.update",y=>{for(let m of Dt(y))v(()=>di(m,c),f=>n.emit("edit",f)),v(()=>li(m,c),f=>n.emit("delete",f)),v(()=>ui(m,c),f=>n.emit("poll-vote",f));}),d("messages.reaction",y=>{for(let m of Dt(y))v(()=>ci(m,c),f=>n.emit("reaction",f));}),d("groups.update",y=>{for(let m of Dt(y))v(()=>ws(m),f=>n.emit("group-update",f));}),d("group-participants.update",y=>{let m=y;v(()=>Ms(m),f=>n.emit("group-join",f)),v(()=>Ss(m),f=>n.emit("group-leave",f));}),d("group.member-tag.update",y=>{v(()=>vs(y),m=>n.emit("member-tag",m));}),d("call",y=>{for(let m of Dt(y))v(()=>fs(m),f=>n.emit("call-incoming",f)),v(()=>hs(m),f=>n.emit("call-ended",f));}),d("messaging-history.status",y=>{v(()=>_s(y),m=>n.emit("history-sync",m));}),d("presence.update",y=>{let m=(()=>{try{return Ls(y)}catch(f){return t.logger?.warn(f,"inbound pipeline: decodePresence threw"),[]}})();for(let f of m)n.emit("presence",f);}),d("connection.update",y=>{let m=Ec(y);m!==null&&v(()=>In({source:"connection-update",reachoutTimeLock:m}),f=>n.emit("limited",f));}),d("message-capping.update",y=>{v(()=>In({source:"message-capping",capInfo:y}),m=>n.emit("limited",m));}),d("newsletter.reaction",y=>{v(()=>nt({source:"reaction",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter.view",y=>{v(()=>nt({source:"view",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter-participants.update",y=>{v(()=>nt({source:"participants",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter-settings.update",y=>{v(()=>nt({source:"settings",payload:y}),m=>n.emit("newsletter",m));});let P=false;return {detach(){if(!P){P=true;for(let y of r)y();r.length=0;}}}}var Bt=class{inner=new events.EventEmitter;emitterLogger;constructor(e){this.emitterLogger=e?.logger,this.inner.setMaxListeners(0);}on(e,t){let r=this.wrap(e,t);this.tag(t,e,r),this.inner.on(e,r);let s=false;return ()=>{s||(s=true,this.inner.off(e,r),this.untag(t,e));}}off(e,t){let r=this.lookup(t,e);r&&(this.inner.off(e,r),this.untag(t,e));}emit(e,t){let r=this.inner.listeners(e).slice();for(let s of r)try{s(t);}catch(i){this.emitterLogger?.error(i,"listener threw");}}removeAllListeners(e){e===void 0?this.inner.removeAllListeners():this.inner.removeAllListeners(e);}listenerCount(e){return this.inner.listenerCount(e)}wrap(e,t){return r=>{try{t(r);}catch(s){this.emitterLogger?.error(s,"listener threw");}}}tag(e,t,r){this.tagMap(e).set(t,r);}untag(e,t){this.tagMap(e).delete(t);}lookup(e,t){return this.tagMap(e).get(t)}tagMap(e){let t=Ic,r=e,s=r[t];return s||(s=new Map,r[t]=s),s}},Ic=Symbol("zaileys.typed-ee.tag");var at=class extends Error{code="UNSUPPORTED_ON_CLOUD";feature;constructor(e){super(`${e} is not supported by the official WhatsApp Cloud API \u2014 it only exists on the web (baileys) provider`),this.name="ZaileysProviderError",this.feature=e;}},A=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysCloudError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};function Ln(n){if(!n||typeof n.accessToken!="string"||n.accessToken.length===0)throw new A("CONFIG","provider 'cloud' requires cloud.accessToken");if(typeof n.phoneNumberId!="string"||n.phoneNumberId.length===0)throw new A("CONFIG","provider 'cloud' requires cloud.phoneNumberId");return n}var Wt="v23.0",Nn="https://graph.facebook.com",mi=3,xc=500,Oc=n=>new Promise(e=>setTimeout(e,n));function Ft(n,e){let t=n.baseUrl??Nn,r=n.apiVersion??Wt,s=Oc,i=a=>`${t}/${r}/${a}`,o=async(a,c)=>{let d;for(let l=1;l<=mi;l++){let u;try{u=await fetch(i(a),{...c,headers:{Authorization:`Bearer ${n.accessToken}`,...c.headers}});}catch(m){throw new A("REQUEST_FAILED","graph request failed (network)",{cause:m})}if(u.ok)return await u.json().catch(()=>({}));let w=await u.json().catch(()=>({})),M=w.error?.message??`http ${u.status}`,v=w.error?` (code ${w.error.code??"?"}${w.error.error_subcode?`/${w.error.error_subcode}`:""})`:"";if(u.status===401||u.status===403)throw new A("AUTH",`graph auth rejected: ${M}${v}`);let P=u.status===429||u.status>=500,y=u.status===429?"RATE_LIMITED":"REQUEST_FAILED";if(d=new A(y,`graph request failed: ${M}${v}`),!P)throw d;l<mi&&await s(xc*2**(l-1));}throw d??new A("REQUEST_FAILED","graph request failed")};return {url:i,get:a=>o(a,{method:"GET"}),post:(a,c)=>o(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),postForm:(a,c)=>o(a,{method:"POST",body:c}),delete:(a,c)=>o(a,{method:"DELETE",...c!==void 0?{headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}:{}})}}var gi=n=>n.split("@")[0]??n,X=n=>n.includes("@")?n:`${n}@s.whatsapp.net`,V=(n,e,t)=>{let r={messaging_product:"whatsapp",recipient_type:"individual",to:gi(n),type:e},s=t?.quoted?.key?.id;return s&&(r.context={message_id:s}),r};function fi(n,e,t){let r=e;if(typeof r.text=="string")return {...V(n,"text",t),text:{body:r.text}};let s=r.react;if(s&&typeof s=="object"&&typeof s.key?.id=="string")return {...V(n,"reaction",t),reaction:{message_id:s.key.id,emoji:s.text??""}};let i=r.location;if(i&&typeof i.degreesLatitude=="number"&&typeof i.degreesLongitude=="number")return {...V(n,"location",t),location:{latitude:i.degreesLatitude,longitude:i.degreesLongitude,...i.name!==void 0?{name:i.name}:{},...i.address!==void 0?{address:i.address}:{}}};let o=r.contacts;if(o?.contacts&&Array.isArray(o.contacts)){let a=o.contacts.map(c=>typeof c.vcard=="string"?Rc(c.vcard):null).filter(c=>c!==null);if(a.length>0)return {...V(n,"contacts",t),contacts:a}}return null}function Rc(n){let e=n.split(/\r?\n/),t="",r="",s="",i=[];for(let a of e){if(a.startsWith("FN:")&&(t=a.slice(3).trim()),a.startsWith("N:")){let c=a.slice(2).split(";");s=(c[0]??"").trim(),r=(c[1]??"").trim();}if(a.startsWith("TEL")){let c=a.indexOf(":");if(c>0){let d=a.slice(c+1).trim(),l=/waid=([0-9]+)/.exec(a);d.length>0&&i.push({phone:d,...l?.[1]?{wa_id:l[1]}:{}});}}}if(t.length===0&&i.length===0)return null;let o=t||i[0]?.phone||"Contact";if(r.length===0&&s.length===0){let a=o.split(/\s+/);r=a[0]??o,a.length>1&&(s=a.slice(1).join(" "));}return {name:{formatted_name:o,first_name:r||o,...s?{last_name:s}:{}},...i.length>0?{phones:i}:{}}}function ct(n,e,t,r){let s=t,i=typeof s.text=="string"?{conversation:s.text}:{};return {key:{id:n,remoteJid:X(gi(e)),fromMe:true},message:i,messageTimestamp:Math.floor(r/1e3)}}var _c=["image","video","audio","document","sticker"];function hi(n){let e=n;for(let t of _c){let r=e[t];if(Buffer.isBuffer(r))return {kind:t,buffer:r,...typeof e.caption=="string"?{caption:e.caption}:{},...typeof e.fileName=="string"?{fileName:e.fileName}:{},...typeof e.mimetype=="string"?{mimetype:e.mimetype}:{}}}return null}async function yi(n,e,t){let r=t.mimetype??await me(t.buffer),s=new FormData;s.set("messaging_product","whatsapp"),s.set("type",r),s.set("file",new Blob([new Uint8Array(t.buffer)],{type:r}),t.fileName??"file");let i=await n.postForm(`${e}/media`,s);if(!i.id)throw new A("REQUEST_FAILED","media upload returned no id");return i.id}function wi(n,e){return {id:e,...n.caption!==void 0&&n.kind!=="audio"&&n.kind!=="sticker"?{caption:n.caption}:{},...n.kind==="document"&&n.fileName!==void 0?{filename:n.fileName}:{}}}var Lc=["image","video","audio","document","sticker"],Nc=n=>{let e=n.event,t=n.message_template_name;return typeof e!="string"||typeof t!="string"?null:{event:e,id:String(n.message_template_id??""),name:t,...typeof n.message_template_language=="string"?{language:n.message_template_language}:{},...typeof n.reason=="string"?{reason:n.reason}:{}}},jt=(n,e)=>n.contacts?.find(t=>t.wa_id===e)?.profile?.name??n.contacts?.[0]?.profile?.name,Dc=n=>{for(let e of Lc){let t=n[e];if(n.type===e&&t&&typeof t=="object"){let r=t;return {[`${e}Message`]:{...r.mime_type?{mimetype:r.mime_type}:{},...r.caption?{caption:r.caption}:{},...r.filename?{fileName:r.filename}:{},...r.voice===true?{ptt:true}:{},...r.id?{cloudMediaId:r.id}:{}}}}}return null},Bc=n=>{let e=n.interactive;return n.type!=="interactive"||!e?null:e.type==="button_reply"&&e.button_reply?.id?{buttonsResponseMessage:{selectedButtonId:e.button_reply.id,selectedDisplayText:e.button_reply.title??""}}:e.type==="list_reply"&&e.list_reply?.id?{listResponseMessage:{singleSelectReply:{selectedRowId:e.list_reply.id},title:e.list_reply.title??""}}:null},Wc=n=>{let e=n.location;return n.type!=="location"||typeof e?.latitude!="number"||typeof e.longitude!="number"?null:{locationMessage:{degreesLatitude:e.latitude,degreesLongitude:e.longitude,...e.name?{name:e.name}:{},...e.address?{address:e.address}:{}}}},Fc=n=>{let e=n.contacts;if(n.type!=="contacts"||!Array.isArray(e)||e.length===0)return null;let t=e.map(s=>{let i=s.name?.formatted_name??"",o=(s.phones??[]).filter(a=>typeof a.phone=="string").map(a=>`TEL${a.wa_id?`;waid=${a.wa_id}`:""}:${a.phone}`).join(`
16
16
  `);return {displayName:i,vcard:`BEGIN:VCARD
17
17
  VERSION:3.0
18
18
  FN:${i}${o?`
package/dist/index.mjs CHANGED
@@ -10,9 +10,9 @@ import Yc,{prepareWAMessageMedia,generateWAMessageContent,normalizeMessageConten
10
10
  `:""}${n.body}`};return n.footer!==void 0&&(t.footer=n.footer),vt(n.buttons,t)};var bt=n=>{if(typeof n!="string"||n.trim().length===0)throw new p("EMPTY_CONTENT","text() requires a non-empty string");return {text:n}};var Wr=(n,e,t)=>({recipient:n,...e?{resolveRecipient:e}:{},...t?{recordSent:t}:{}});var pn=new WeakSet,Fr=n=>{pn.add(n);},jr=n=>{if(!pn.has(n))return n;pn.delete(n);let e=randomBytes(32),t={...n,messageContextInfo:{messageSecret:e}};return {messageContextInfo:{messageSecret:e},groupStatusMessageV2:{message:t}}};var At="status@broadcast",Fo=[{tag:"biz",attrs:{},content:[{tag:"interactive",attrs:{type:"native_flow",v:"1"},content:[{tag:"native_flow",attrs:{v:"9",name:"mixed"}}]}]}],Y=class n{socket;internal;constructor(e,t){this.socket=e,this.internal=t;}static create(e,t,r,s){return new n(e,Wr(t,r,s))}to(e){return this.internal.recipient=e,delete this.internal.resolveRecipient,this}text(e,t){return t?.rich===true?this.internal.content=lr(fr(e),t):this.internal.content=bt(e),this}image(e,t){return this.internal.pendingContent=ge(e,t),this}videoNote(e,t){return this.internal.pendingContent=ne(e,{...t,ptv:true}),this}video(e,t){return this.internal.pendingContent=ne(e,t),this}audio(e,t){return this.internal.pendingContent=or(e,t),this}document(e,t){return this.internal.pendingContent=yr(e,t),this}sticker(e,t){return this.internal.pendingContent=Nr(e,t),this}buttons(e,t){return this.internal.content=vt(e,t),this}carousel(e,t){return this.internal.content=dr(e,t),this}list(e){return this.internal.content=Ir(e),this}poll(e,t,r){return this.internal.content=_r(e,t,r),this}location(e,t,r){return this.internal.content=xr(e,t,r),this}contact(e){return this.internal.content=hr(e),this}template(e){return this.internal.content=Br(e),this}event(e){return this.internal.content=vr(e),this}groupInvite(e){return this.internal.content=Mr(e),this}groupStatus(e,t){return typeof e=="string"?this.internal.content=Pr(e,t):this.internal.pendingContent=Er(e,t),this}product(e){return this.internal.pendingContent=Lr(e),this}requestPhoneNumber(){return this.internal.content={requestPhoneNumber:{}},this}sharePhoneNumber(){return this.internal.content={sharePhoneNumber:{}},this}limitSharing(e=true){return this.internal.content={limitSharing:e},this}album(e){return this.internal.albumItems=e,this}reply(e){if(e==null)throw new p("INVALID_OPTIONS","reply() requires a quoted message or key");let t="key"in e&&e.key!=null;return this.internal.quoted=t?e:{key:e},this}mentions(e){if(e.length===0)throw new p("INVALID_OPTIONS","mentions() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new p("INVALID_OPTIONS",`invalid jid: ${String(r)}`);let t=new Set([...this.internal.mentions??[],...e]);return this.internal.mentions=[...t],this}mentionAll(){return this.internal.mentionAll=true,this}audience(e){if(e.length===0)throw new p("INVALID_OPTIONS","audience() requires at least one jid");for(let r of e)if(typeof r!="string"||!r.includes("@"))throw new p("INVALID_OPTIONS",`invalid jid: ${String(r)}`);let t=new Set([...this.internal.statusJidList??[],...e]);return this.internal.statusJidList=[...t],this}disappearing(e){if(!Number.isInteger(e)||e<=0)throw new p("INVALID_OPTIONS","disappearing() requires a positive integer duration");return this.internal.disappearingSeconds=e,this}then(e,t){return (async()=>{if(this.internal.resolveRecipient&&(this.internal.recipient=await this.internal.resolveRecipient(this.internal.recipient),delete this.internal.resolveRecipient),this.internal.statusJidList!==void 0&&this.internal.recipient!==At)throw new p("INVALID_RECIPIENT",`audience() only applies to ${At}, not ${this.internal.recipient}`);if(this.internal.albumItems){let d={recipient:this.internal.recipient};return this.internal.quoted!==void 0&&(d.quoted=this.internal.quoted),this.internal.mentions!==void 0&&(d.mentions=this.internal.mentions),this.internal.mentionAll!==void 0&&(d.mentionAll=this.internal.mentionAll),this.internal.disappearingSeconds!==void 0&&(d.disappearingSeconds=this.internal.disappearingSeconds),nr(this.socket,this.internal.recipient,this.internal.albumItems,d)}if(this.internal.pendingContent&&(this.internal.content=await this.internal.pendingContent),!this.internal.content)throw new p("EMPTY_CONTENT","no content set");let s=this.internal.content,i=s[R];if(i!==void 0){let d=s[Re];if(typeof d=="string"&&!this.internal.recipient.endsWith("@g.us"))throw new p("INVALID_RECIPIENT",`${d} can only be sent to a group jid ending in @g.us`);let l=s[wt],u=l!==void 0?await this.buildStatusMedia(l):i,w=s[cn],M=s[ln];return this.sendRelay(u,w,M,l!==void 0)}let o=this.internal.content;if(this.internal.mentions&&this.internal.mentions.length>0&&(o.mentions=this.internal.mentions),this.internal.mentionAll&&(o.mentionAll=true),this.internal.recipient===At&&this.internal.statusJidList===void 0)throw new p("INVALID_OPTIONS",`a status sent to ${At} needs audience([...]); without it WhatsApp accepts the message but shows it to nobody`);let a={};this.internal.quoted&&(a.quoted=this.internal.quoted),this.internal.disappearingSeconds!==void 0&&(a.ephemeralExpiration=this.internal.disappearingSeconds),this.internal.statusJidList!==void 0&&(a.statusJidList=this.internal.statusJidList);let c;try{c=await this.socket.sendMessage(this.internal.recipient,o,a);}catch(d){throw new p("SEND_FAILED","socket sendMessage rejected",{cause:d})}if(!c?.key)throw new p("SEND_FAILED","socket returned no message key");return c.key})().then(e,t)}async uploadHeaderMedia(e,t){let{buffer:r}=await O(t.src),s=await prepareWAMessageMedia({[t.kind]:r},{upload:this.socket.waUploadToServer});e.hasMediaAttachment=true,t.kind==="image"&&s.imageMessage&&(e.imageMessage=s.imageMessage),t.kind==="video"&&s.videoMessage&&(e.videoMessage=s.videoMessage);}async buildStatusMedia(e){let t={[e.kind]:e.buffer};e.caption!==void 0&&(t.caption=e.caption),e.ptt===true&&(t.ptt=true);try{let r=await generateWAMessageContent(t,{upload:this.socket.waUploadToServer});return typeof r.toJSON=="function"?r.toJSON():r}catch(r){throw new p("MEDIA_LOAD_FAILED","groupStatus() media upload failed",{cause:r})}}applyRelayMentions(e){let t=this.internal.mentions,r=this.internal.mentionAll===true;if((t===void 0||t.length===0)&&!r)return;let s=normalizeMessageContent(e),i=s==null?void 0:getContentType(s);if(s==null||i===void 0)return;let o=s[i];if(o==null||typeof o!="object")return;let a=o.contextInfo??{};t!==void 0&&t.length>0&&(a.mentionedJid=t),r&&(a.nonJidMentions=1),o.contextInfo=a;}async sendRelay(e,t,r,s=false){let i=this.socket.relayMessage;if(typeof i!="function")throw new p("SEND_FAILED","socket does not support relayMessage (interactive content)");if(this.socket.waUploadToServer!==void 0)try{let M=e.interactiveMessage?.header;t!==void 0&&M&&await this.uploadHeaderMedia(M,t);let v=e.interactiveMessage?.carouselMessage?.cards;if(r!==void 0&&v)for(let P of r){let y=v[P.index]?.header;y&&await this.uploadHeaderMedia(y,P);}}catch(M){throw new p("SEND_FAILED","interactive media upload failed",{cause:M})}let o=e;!s&&o.messageContextInfo?.messageSecret==null&&(o.messageContextInfo={...o.messageContextInfo,messageSecret:randomBytes(32)}),this.applyRelayMentions(e);let c={userJid:this.socket.user?.id??""},d=this.internal.quoted;d!==void 0&&d.message!=null&&(c.quoted=d),this.internal.disappearingSeconds!==void 0&&(c.ephemeralExpiration=this.internal.disappearingSeconds);let l=generateWAMessageFromContent(this.internal.recipient,e,c);if(s&&l.message!=null&&Fr(l.message),typeof l.key?.id!="string")throw new p("SEND_FAILED","failed to generate relay message key");let w="interactiveMessage"in e&&e.interactiveMessage!=null?{messageId:l.key.id,additionalNodes:Fo}:{messageId:l.key.id};try{await i(this.internal.recipient,l.message,w);}catch(M){throw new p("SEND_FAILED","socket relayMessage rejected",{cause:M})}return this.internal.recordSent?.(l),l.key}};var _e=class{socket;key;content;pendingContent;constructor(e,t){this.socket=e,this.key=t;}text(e){return this.content=bt(e),this}image(e,t){return this.pendingContent=ge(e,t),this}video(e,t){return this.pendingContent=ne(e,t),this}then(e,t){return this.send().then(e,t)}async send(){let e=this.key.remoteJid;if(typeof e!="string"||e.length===0)throw new p("INVALID_OPTIONS","message key is missing remoteJid");if(this.pendingContent&&(this.content=await this.pendingContent),!this.content)throw new p("EMPTY_CONTENT","edit() requires a content method before await");let t={...this.content,edit:this.key},r;try{r=await this.socket.sendMessage(e,t);}catch(s){throw new p("SEND_FAILED","socket sendMessage rejected",{cause:s})}if(!r?.key)throw new p("SEND_FAILED","socket returned no message key");return r.key}};var mn=n=>{let e=n.remoteJid;if(typeof e!="string"||e.length===0)throw new p("INVALID_OPTIONS","message key is missing remoteJid");return e},gn=n=>{if(!n?.key)throw new p("SEND_FAILED","socket returned no message key");return n.key},fn=async(n,e,t={})=>{let r=mn(e);if(t.forEveryone??true){await n.sendMessage(r,{delete:e});return}if(typeof n.chatModify!="function")throw new p("INVALID_OPTIONS","delete-for-me is not supported by this socket");await n.chatModify({deleteForMe:{deleteMedia:false,key:e,timestamp:Date.now()}},r);},hn=async(n,e,t)=>{let r=mn(e),s=await n.sendMessage(r,{react:{text:t,key:e}});return gn(s)},yn=async(n,e,t,r)=>{let s=await e.getMessage(t);if(!s)throw new p("MESSAGE_NOT_FOUND","message not found in store for forward");let i=await n.sendMessage(r,{forward:s});return gn(i)},Ct=async(n,e,t,r={})=>{let s=mn(e),i={pin:e,type:t?1:2,time:r.duration??86400},o=await n.sendMessage(s,i);return gn(o)};var jo=/@(s\.whatsapp\.net|g\.us|lid|newsletter|broadcast|c\.us)$/,Le=n=>jo.test(n),wn=async(n,e,t,r=Uo)=>{if(Le(e))return e;let s=t.get(e);if(s!==void 0)return s;let i=r.get(e);if(i!==void 0)return i;let o=(async()=>{let c=(await n.onWhatsApp(e))?.find(d=>d.exists&&d.jid);if(!c)throw new p("USERNAME_NOT_FOUND",`username "${e}" not found`);return t.set(e,c.jid),c.jid})();r.set(e,o);try{return await o}finally{r.delete(e);}},Uo=new Map;var I=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysDomainError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var Ne=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}mapParticipants(e){return e.map(t=>({jid:t.jid,status:t.status}))}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("group.create",()=>this.requireSocket().groupCreate(e,t))}async addMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"add"));return this.mapParticipants(r)}async removeMember(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"remove"));return this.mapParticipants(r)}async promote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"promote"));return this.mapParticipants(r)}async demote(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupParticipantsUpdate(e,t,"demote"));return this.mapParticipants(r)}async updateSubject(e,t){await this.requireSocket().groupUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().groupUpdateDescription(e,t);}async leave(e){await this.requireSocket().groupLeave(e);}async metadata(e){return this.requireSocket().groupMetadata(e)}async tagMember(e,t,r){await this.requireSocket().updateMemberLabel(e,r);}async inviteCode(e){let t=await this.requireSocket().groupInviteCode(e);if(!t)throw new I("OPERATION_FAILED","invite code unavailable");return t}async revokeInvite(e){let t=await this.requireSocket().groupRevokeInvite(e);if(!t)throw new I("OPERATION_FAILED","invite code unavailable");return t}async acceptInvite(e){let t=await this.run("group.join",()=>this.requireSocket().groupAcceptInvite(e));if(!t)throw new I("OPERATION_FAILED","invite acceptance failed");return t}async toggleEphemeral(e,t){await this.requireSocket().groupToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().groupSettingUpdate(e,t);}async list(){let e=await this.requireSocket().groupFetchAllParticipating();return Object.values(e)}async inviteInfo(e){return this.requireSocket().groupGetInviteInfo(e)}async joinRequests(e){return this.requireSocket().groupRequestParticipantsList(e)}async approveJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"approve"));return this.mapParticipants(r)}async rejectJoin(e,t){let r=await this.run("group.participants",()=>this.requireSocket().groupRequestParticipantsUpdate(e,t,"reject"));return this.mapParticipants(r)}async joinApproval(e,t){await this.requireSocket().groupJoinApprovalMode(e,t?"on":"off");}async memberAddMode(e,t){await this.requireSocket().groupMemberAddMode(e,t?"admin_add":"all_member_add");}};var De=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}async set(e){let t=this.requireSocket();if(e.lastSeen!==void 0&&await t.updateLastSeenPrivacy(e.lastSeen),e.online!==void 0&&await t.updateOnlinePrivacy(e.online),e.profile!==void 0&&await t.updateProfilePicturePrivacy(e.profile),e.status!==void 0&&await t.updateStatusPrivacy(e.status),e.readReceipts!==void 0){let r=typeof e.readReceipts=="boolean"?e.readReceipts?"all":"none":e.readReceipts;await t.updateReadReceiptsPrivacy(r);}e.groupAdd!==void 0&&await t.updateGroupsAddPrivacy(e.groupAdd),e.call!==void 0&&await t.updateCallPrivacy(e.call);}async get(){return this.requireSocket().fetchPrivacySettings()}async block(e){await this.requireSocket().updateBlockStatus(e,"block");}async unblock(e){await this.requireSocket().updateBlockStatus(e,"unblock");}async blocklist(){return this.requireSocket().fetchBlocklist()}async disappearingMode(e){await this.requireSocket().updateDefaultDisappearingMode(e);}async call(e){await this.requireSocket().updateCallPrivacy(e);}};var Be=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("newsletter.create",async()=>{let r=this.requireSocket(),s=await r.newsletterCreate(e,t?.description);return t?.picture&&await r.newsletterUpdatePicture(s.id,t.picture),s})}async follow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterFollow(e));}async unfollow(e){await this.run("newsletter.follow",()=>this.requireSocket().newsletterUnfollow(e));}async metadata(e){let r=await this.requireSocket().newsletterMetadata("jid",e);if(!r)throw new I("NEWSLETTER_NOT_FOUND",`newsletter ${e} not found`);return r}async updateName(e,t){await this.requireSocket().newsletterUpdateName(e,t);}async updateDescription(e,t){await this.requireSocket().newsletterUpdateDescription(e,t);}async updatePicture(e,t){await this.requireSocket().newsletterUpdatePicture(e,t);}async mute(e){await this.requireSocket().newsletterMute(e);}async unmute(e){await this.requireSocket().newsletterUnmute(e);}async delete(e){await this.requireSocket().newsletterDelete(e);}async removePicture(e){await this.requireSocket().newsletterRemovePicture(e);}async react(e,t,r){await this.requireSocket().newsletterReactMessage(e,t,r);}async unreact(e,t){await this.requireSocket().newsletterReactMessage(e,t);}async subscribers(e){return this.requireSocket().newsletterSubscribers(e)}async messages(e,t=50,r){return this.requireSocket().newsletterFetchMessages(e,t,r?.since,r?.after)}async adminCount(e){return this.requireSocket().newsletterAdminCount(e)}async changeOwner(e,t){await this.requireSocket().newsletterChangeOwner(e,t);}async demote(e,t){await this.requireSocket().newsletterDemote(e,t);}};var We=class{constructor(e,t){this.getSocket=e;this.guard=t;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}run(e,t){return this.guard?this.guard.run(e,t):t()}async create(e,t){return this.run("community.create",()=>this.requireSocket().communityCreate(e,t))}async createGroup(e,t,r){return this.run("community.create",()=>this.requireSocket().communityCreateGroup(e,t,r))}async linkGroup(e,t){await this.requireSocket().communityLinkGroup(t,e);}async unlinkGroup(e,t){await this.requireSocket().communityUnlinkGroup(t,e);}async subGroups(e){return (await this.requireSocket().communityFetchLinkedGroups(e)).linkedGroups}async leave(e){await this.requireSocket().communityLeave(e);}async updateSubject(e,t){await this.requireSocket().communityUpdateSubject(e,t);}async updateDescription(e,t){await this.requireSocket().communityUpdateDescription(e,t);}async inviteCode(e){return this.requireSocket().communityInviteCode(e)}async revokeInvite(e){return this.requireSocket().communityRevokeInvite(e)}async acceptInvite(e){return this.run("community.join",()=>this.requireSocket().communityAcceptInvite(e))}async metadata(e){return this.requireSocket().communityMetadata(e)}async list(){return Object.values(await this.requireSocket().communityFetchAllParticipating())}async inviteInfo(e){return this.requireSocket().communityGetInviteInfo(e)}async toggleEphemeral(e,t){await this.requireSocket().communityToggleEphemeral(e,t);}async setting(e,t){await this.requireSocket().communitySettingUpdate(e,t);}async memberAddMode(e,t){await this.requireSocket().communityMemberAddMode(e,t?"admin_add":"all_member_add");}async joinApproval(e,t){await this.requireSocket().communityJoinApprovalMode(e,t?"on":"off");}};var Fe=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}async setName(e){await this.requireSocket().updateProfileName(e);}async setStatus(e){await this.requireSocket().updateProfileStatus(e);}async setPicture(e,t){await this.requireSocket().updateProfilePicture(e,t);}async removePicture(e){await this.requireSocket().removeProfilePicture(e);}async getPicture(e,t=false){return await this.requireSocket().profilePictureUrl(e,t?"image":"preview")??null}async getStatus(e){return this.requireSocket().fetchStatus(e)}};var Ur=n=>{if(typeof n.remoteJid!="string"||n.remoteJid.length===0)throw new I("OPERATION_FAILED","message key is missing remoteJid");return n.remoteJid},je=class{constructor(e,t){this.getSocket=e;this.resolveLast=t;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}async last(e){return await this.resolveLast?.(e)??[]}async archive(e){await this.requireSocket().chatModify({archive:true,lastMessages:await this.last(e)},e);}async unarchive(e){await this.requireSocket().chatModify({archive:false,lastMessages:await this.last(e)},e);}async pin(e){await this.requireSocket().chatModify({pin:true},e);}async unpin(e){await this.requireSocket().chatModify({pin:false},e);}async mute(e,t){await this.requireSocket().chatModify({mute:t??Date.now()+365*24*60*60*1e3},e);}async unmute(e){await this.requireSocket().chatModify({mute:null},e);}async markRead(e){let t=await this.last(e);t.length!==0&&await this.requireSocket().chatModify({markRead:true,lastMessages:t},e);}async markUnread(e){let t=await this.last(e);t.length!==0&&await this.requireSocket().chatModify({markRead:false,lastMessages:t},e);}async star(e,t=true){let r=Ur(e);await this.requireSocket().chatModify({star:{messages:[{id:e.id??"",fromMe:e.fromMe===true}],star:t}},r);}async unstar(e){await this.star(e,false);}async fetchHistory(e,t,r){return Ur(t),this.requireSocket().fetchMessageHistory(e,t,r)}async delete(e){await this.requireSocket().chatModify({delete:true,lastMessages:await this.last(e)},e);}async clear(e){await this.requireSocket().chatModify({clear:true,lastMessages:await this.last(e)},e);}};var Ue=class{constructor(e,t){this.getSocket=e;this.normalize=t;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}async check(...e){return (await this.requireSocket().onWhatsApp(...e)??[]).map(r=>{let s={jid:r.jid,exists:r.exists};return r.lid!==void 0&&(s.lid=r.lid),s})}async exists(e){let[t]=await this.check(e);return t?.exists??false}async save(e,t){await this.requireSocket().addOrEditContact(this.normalize(e),t);}async remove(e){await this.requireSocket().removeContact(this.normalize(e));}};var qe=class{constructor(e){this.getSocket=e;}requireSocket(){let e=this.getSocket();if(!e)throw new I("NOT_CONNECTED","client not connected");return e}async profile(e){return this.requireSocket().getBusinessProfile(e)}async catalog(e={}){return this.requireSocket().getCatalog(e)}async collections(e,t){return this.requireSocket().getCollections(e,t)}async orderDetails(e,t){return this.requireSocket().getOrderDetails(e,t)}async createProduct(e){return this.requireSocket().productCreate(e)}async updateProduct(e,t){return this.requireSocket().productUpdate(e,t)}async deleteProduct(...e){return this.requireSocket().productDelete(e)}};var _=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysCommandError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var qo=n=>{let e=n[0];return e==="{"||e==="["},Ko=n=>{try{return {ok:!0,value:JSON.parse(n)}}catch{return {ok:false}}},$o=n=>n===" "||n===" "||n===`
11
11
  `||n==="\r",Go=n=>{let e=[],t="",r=null,s=false,i=false,o=true;for(let a=0;a<n.length;a+=1){let c=n[a];if(s){t+=c,s=false,i=true,o=false;continue}if(c==="\\"&&r!==null){s=true;continue}if(r!==null){c===r?r=null:t+=c,o=false;continue}if((c==='"'||c==="'")&&o){r=c,i=true,o=false;continue}if($o(c)){i&&(e.push(t),t="",i=false),o=true;continue}t+=c,i=true,o=false;}return i&&e.push(t),e},Jo=(n,e)=>{for(let t of e)if(t.length>0&&n.startsWith(t))return t;return null},Vo=n=>({matched:false,args:[],flags:{},json:void 0,raw:n});function vn(n,e){let t=Jo(n,e);if(t===null)return Vo(n);let r=n.slice(t.length),s=Go(r),i={matched:true,args:[],flags:{},json:void 0,raw:n};if(s.length===0)return i.name="",i;i.name=(s[0]??"").toLowerCase();let o=false;for(let a=1;a<s.length;a+=1){let c=s[a];if(c!==void 0){if(c.startsWith("--")){let d=c.slice(2);if(d.length===0){i.args.push(c);continue}let l=d.indexOf("=");if(l!==-1){let w=d.slice(0,l),M=d.slice(l+1);i.flags[w]=M;continue}let u=s[a+1];u!==void 0&&!u.startsWith("--")?(i.flags[d]=u,a+=1):i.flags[d]=true;continue}if(!o&&qo(c)){let d=Ko(c);d.ok&&(i.json=d.value,o=true);}i.args.push(c);}}return i}var qr=n=>{let e=n.trim().split(/\s+/).filter(t=>t.length>0).map(t=>t.toLowerCase());if(e.length===0)throw new _("INVALID_COMMAND_NAME","empty command segment in spec");return e},we=n=>n.join(" "),Ke=class{paths=new Map;defs=[];maxDepth=1;register(e,t){if(e.trim().length===0)throw new _("INVALID_COMMAND_NAME","command spec must not be empty");let r=e.split("|").map(a=>qr(a)),s=r[0],i=r.slice(1).map(a=>we(a)),o={name:we(s),aliases:i,parts:s,handler:t};for(let a of r){let c=we(a);if(this.paths.has(c))throw new _("DUPLICATE_COMMAND",`command "${c}" is already registered`)}for(let a of r)this.paths.set(we(a),o),a.length>this.maxDepth&&(this.maxDepth=a.length);this.defs.push(o);}resolve(e){if(!e.matched||e.name===void 0||e.name.length===0)return;let t=[e.name.toLowerCase(),...e.args.map(s=>s.toLowerCase())],r=Math.min(this.maxDepth,t.length);for(let s=r;s>=1;s-=1){let i=t.slice(0,s).join(" "),o=this.paths.get(i);if(o!==void 0)return {def:o,args:e.args.slice(s-1)}}}unregister(e){let t=e.split("|").map(o=>qr(o)),r=we(t[0]),s=this.paths.get(r);if(s===void 0)return;for(let o of [s.parts,...s.aliases.map(a=>a.split(" "))])this.paths.delete(we(o));let i=this.defs.indexOf(s);i>=0&&this.defs.splice(i,1),this.maxDepth=this.defs.reduce((o,a)=>Math.max(o,a.parts.length),1);}list(){return [...this.defs]}};async function Mn(n,e,t){let r=-1,s={error:void 0,thrown:false},i=async o=>{if(o<=r)throw new _("MIDDLEWARE_ERROR","next() called multiple times");if(r=o,o===n.length){try{await t();}catch(c){throw s.error=c,s.thrown=true,c}return}let a=n[o];try{await a(e,()=>i(o+1));}catch(c){throw s.thrown||c instanceof _?c:new _("MIDDLEWARE_ERROR","middleware threw during execution",{cause:c})}};await i(0);}function Sn(n){if(n.prefixes.length===0)return {detach(){}};let e=s=>{let i=vn(s.text,n.prefixes);if(!i.matched)return;let o=n.registry.resolve(i);if(o===void 0)return;let a={command:o.def.name,args:o.args,flags:i.flags,json:i.json,raw:i.raw},c=n.buildContext(a,s);Promise.resolve(Mn(n.middleware,c,()=>o.def.handler(c))).catch(d=>{let l=d instanceof _?d:new _("HANDLER_ERROR","command handler failed",{cause:d});n.logger.error(l,"command dispatch failed");});},t=n.onText(e),r=false;return {detach(){r||(r=true,t());}}}var Me=new Map,$r=n=>n!=null&&typeof n=="object"?n:null,Gr=n=>Array.isArray(n.content)?n.content.map($r).filter(e=>e!==null):[],Kr=(n,e)=>Gr(n).find(t=>t.tag===e),ve=n=>typeof n=="string"&&n.length>0?n:void 0,bn=n=>{if(n===void 0)return;let e=Number.parseInt(n,10);return Number.isFinite(e)?e:void 0},Ho=(n,e)=>{if(Object.keys(e).length!==0){if(Me.size>=64){let t=Me.keys().next().value;t!==void 0&&Me.delete(t);}Me.set(n,e);}},Jr=n=>{let e=$r(n);if(e===null||e.tag!=="call")return false;let t=Gr(e).find(v=>v.tag==="offer"),r=ve(t?.attrs?.["call-id"]);if(t===void 0||r===void 0)return false;let s={},i=ve(e.attrs?.platform),o=ve(e.attrs?.version),a=ve(e.attrs?.notify),c=ve(t.attrs?.caller_country_code),d=ve(t.attrs?.caller_pn);i!==void 0&&(s.platform=i),o!==void 0&&(s.appVersion=o),a!==void 0&&(s.name=a),c!==void 0&&(s.countryCode=c),d!==void 0&&(s.phoneJid=d);let l=bn(Kr(t,"net")?.attrs?.medium);l!==void 0&&(s.networkMedium=l);let u=Kr(t,"video"),w=bn(u?.attrs?.screen_width),M=bn(u?.attrs?.screen_height);return w!==void 0&&M!==void 0&&(s.screen={width:w,height:M}),Ho(r,s),true},Vr=n=>{let e=Me.get(n);return e!==void 0&&Me.delete(n),e};var Hr=n=>n;var $e=class{host;logger;plugins=new Map;constructor(e){this.host=e.client,this.logger=e.logger??e.client.logger;}has(e){return this.plugins.has(e)}list(){return [...this.plugins.keys()]}async loadPlugin(e,t){if(typeof e?.name!="string"||typeof e?.setup!="function"){this.logger?.warn({file:t},"plugin: invalid shape (need name + setup); skipped");return}if(this.plugins.has(e.name)){this.logger?.warn({name:e.name,file:t},"plugin: duplicate name; skipped");return}let r=[],s={client:this.host,logger:this.logger,pluginDir:Ze.dirname(t),command:(i,o)=>{this.host.command(i,o),r.push(()=>this.host.unregisterCommand(i));},use:i=>{this.host.use(i),r.push(()=>{this.host.unuse(i);});},on:(i,o)=>{let a=this.host.on(i,o);return r.push(a),a},once:(i,o)=>{let a=false,c=this.host.on(i,d=>{a||(a=true,c(),o(d));});return r.push(c),c}};try{let i=await e.setup(s);typeof i=="function"&&r.push(i);}catch(i){for(let o of [...r].reverse())try{await o();}catch{}this.logger?.error({err:i,name:e.name,file:t},"plugin: setup failed; skipped");return}this.plugins.set(e.name,{plugin:e,file:t,disposers:r});}async unload(e){let t=this.plugins.get(e);if(t){this.plugins.delete(e);for(let r of [...t.disposers].reverse())try{await r();}catch(s){this.logger?.warn({err:s,name:e},"plugin: disposer threw");}try{await t.plugin.onUnload?.();}catch(r){this.logger?.warn({err:r,name:e},"plugin: onUnload threw");}}}async unloadAll(){for(let e of this.list())await this.unload(e);}};var Qo=/\.(ts|js|mjs|cjs)$/,Xo=/(\.d\.ts$|^_|[/\\]_)/;async function Cn(n,e,t){let r;try{r=await promises.readdir(n,{withFileTypes:!0});}catch{return []}let s=[];for(let i of r){let o=Ze.join(n,i.name);t.test(i.name)||t.test(o)||(i.isDirectory()?s.push(...await Cn(o,e,t)):e.test(i.name)&&s.push(o));}return s}async function Yr(n,e){try{let r=await import(pathToFileURL(n).href+(e!==void 0?`?t=${e}`:"")),s=r.default??r;return s&&typeof s.name=="string"&&typeof s.setup=="function"?s:void 0}catch{return}}var Ge=class{dir;pattern;ignore;watchEnabled;onError;registry;logger;watcher;fileToName=new Map;bust=0;debounce;pending=new Set;flushChain=Promise.resolve();constructor(e){this.registry=e.registry,this.logger=e.logger,this.dir=Ze.resolve(e.options.dir??"./plugins"),this.pattern=e.options.pattern??Qo,this.ignore=e.options.ignore??Xo,this.watchEnabled=e.options.watch!==false,this.onError=e.options.onError;}async start(){let e=await Cn(this.dir,this.pattern,this.ignore);for(let t of e)await this.loadFile(t);this.watchEnabled&&this.startWatch();}async stop(){this.debounce&&clearTimeout(this.debounce),this.watcher?.close(),this.watcher=void 0,await this.flushChain,await this.registry.unloadAll(),this.fileToName.clear();}async loadFile(e){let t=await Yr(e,this.bust);if(!t){let i=new Error(`failed to import plugin: ${e}`);this.onError?.(i,e),this.logger?.warn({file:e},"plugin: import failed; skipped");return}let r=this.registry.list();await this.registry.loadPlugin(t,e);let s=this.registry.list().find(i=>!r.includes(i));s&&this.fileToName.set(e,s);}startWatch(){try{this.watcher=watch(this.dir,{recursive:!0},(e,t)=>{if(t==null)return;let r=Ze.join(this.dir,t.toString());this.ignore.test(t.toString())||!this.pattern.test(t.toString())||(this.pending.add(r),this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>{this.flushChain=this.flushChain.then(()=>this.flush());},150),this.debounce.unref?.());});}catch(e){this.logger?.warn({err:e,dir:this.dir},"plugin: watch unavailable; hot-reload disabled");}}async flush(){let e=[...this.pending];this.pending.clear(),this.bust+=1;for(let t of e){let r=this.fileToName.get(t);r&&(await this.registry.unload(r),this.fileToName.delete(t));let s=true;try{await promises.access(t);}catch{s=false;}s&&await this.loadFile(t);}}};var x=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysAutomationError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var ea=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),oe=class{now;sleep;perJidRatePerMs;perJidCapacity;global;perJid=new Map;constructor(e,t={}){if(!(e.perSec>0))throw new x("RATE_LIMIT_INVALID","perSec must be greater than zero");if(e.perJidPerSec!==void 0&&!(e.perJidPerSec>0))throw new x("RATE_LIMIT_INVALID","perJidPerSec must be greater than zero");if(e.burst!==void 0&&!(e.burst>0))throw new x("RATE_LIMIT_INVALID","burst must be greater than zero");this.now=t.now??Date.now,this.sleep=t.sleep??ea;let r=e.burst??e.perSec;this.global={tokens:r,capacity:r,ratePerMs:e.perSec/1e3,last:this.now()},e.perJidPerSec!==void 0&&(this.perJidRatePerMs=e.perJidPerSec/1e3,this.perJidCapacity=e.perJidPerSec);}async acquire(e){await this.consume(this.global),e!==void 0&&this.perJidRatePerMs!==void 0&&await this.consume(this.bucketFor(e));}bucketFor(e){let t=this.perJid.get(e);if(t)return t;let r=this.perJidCapacity??1,s={tokens:r,capacity:r,ratePerMs:this.perJidRatePerMs??1,last:this.now()};return this.perJid.set(e,s),s}consume(e){if(this.refill(e),e.tokens>=1)return e.tokens-=1,Promise.resolve();let t=(1-e.tokens)/e.ratePerMs;return e.tokens-=1,this.sleep(t)}refill(e){let t=this.now(),r=t-e.last;r>0&&(e.tokens=Math.min(e.capacity,e.tokens+r*e.ratePerMs),e.last=t);}};var ta={"group.create":6e4,"group.join":3e4,"group.participants":1e4,"group.update":3e3,"community.create":12e4,"community.join":3e4,"community.update":3e3,"newsletter.create":12e4,"newsletter.follow":2e3,"newsletter.update":3e3},na=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n));function Pn(n={},e={}){let t=n.enabled??true,r=e.now??Date.now,s=e.sleep??na,i={...ta,...n.intervalsMs??{}},o=new Map,a=new Map,c=async(d,l)=>{let u=i[d]??0,w=o.get(d);if(w!==void 0&&u>0){let M=u-(r()-w);M>0&&await s(M);}return o.set(d,r()),l()};return {run(d,l){if(!t)return l();let w=(a.get(d)??Promise.resolve()).then(()=>c(d,l),()=>c(d,l));return a.set(d,w.then(()=>{},()=>{})),w}}}var ra={maxRetries:0,backoffMs:()=>0},sa=n=>n<=0?Promise.resolve():new Promise(e=>setTimeout(e,n)),Je=class{concurrency;retry;sleep;pending=[];active=0;idleWaiters=[];constructor(e={},t={}){this.concurrency=e.concurrency??1,this.retry=e.retry??ra,this.sleep=t.sleep??sa;}add(e){return new Promise((t,r)=>{this.pending.push({run:()=>this.execute(e).then(t,r)}),this.pump();})}onIdle(){return this.active===0&&this.pending.length===0?Promise.resolve():new Promise(e=>{this.idleWaiters.push(e);})}pump(){for(;this.active<this.concurrency&&this.pending.length>0;){let e=this.pending.shift();if(!e)break;this.active++,e.run().finally(()=>{this.active--,this.pump(),this.settleIdle();});}}settleIdle(){if(this.active===0&&this.pending.length===0&&this.idleWaiters.length>0){let e=this.idleWaiters;this.idleWaiters=[];for(let t of e)t();}}async execute(e){let t=0;for(;;)try{return await e()}catch(r){if(t>=this.retry.maxRetries)throw r;t+=1,await this.sleep(this.retry.backoffMs(t));}}};var ia=n=>n instanceof Error?n:new Error(typeof n=="string"?n:String(n));async function kn(n,e,t,r={}){let s={sent:[],failed:[]};if(n.length===0)return s;let i=r.rateLimitPerSec??5,o={};t.now&&(o.now=t.now),t.sleep&&(o.sleep=t.sleep);let a=t.limiter??new oe({perSec:i},o),c=r.retry,d=t.sleep?{sleep:t.sleep}:{},l=c?new Je({concurrency:1,retry:c},d):void 0,u=n.length,w=0;for(let M of n){await a.acquire(M);let v=()=>e(t.sendTo(M)).then(()=>{});try{l?await l.add(v):await v(),s.sent.push(M),w+=1,r.onProgress?.(w,u,M,!0);}catch(P){s.failed.push({jid:M,error:ia(P)}),w+=1,r.onProgress?.(w,u,M,false);}}return s}var oa=1e3,Ve=class{constructor(e,t,r){this.getSocket=e;this.throttleEnabled=t?.enabled??true,this.minIntervalMs=t?.minIntervalMs??oa,this.now=r?.now??Date.now;}throttleEnabled;minIntervalMs;now;lastSent=new Map;requireSocket(){let e=this.getSocket();if(!e)throw new x("NOT_CONNECTED","client not connected");return e}throttled(e,t){if(!this.throttleEnabled||this.minIntervalMs<=0)return false;let r=`${e}:${t??"global"}`,s=this.lastSent.get(r),i=this.now();return s!==void 0&&i-s<this.minIntervalMs?true:(this.lastSent.set(r,i),false)}async update(e,t){let r=this.requireSocket();if(!this.throttled(e,t))try{await(t===void 0?r.sendPresenceUpdate(e):r.sendPresenceUpdate(e,t));}catch(s){throw new x("PRESENCE_FAILED",`presence update '${e}' failed`,{cause:s})}}scheduleClear(e,t){let r=this.getSocket();if(!r)return;let s=setTimeout(()=>{r.sendPresenceUpdate("paused",e).catch(()=>{});},t);typeof s.unref=="function"&&s.unref();}async online(){await this.update("available");}async offline(){await this.update("unavailable");}async typing(e,t){await this.update("composing",e),t!==void 0&&this.scheduleClear(e,t);}async recording(e,t){await this.update("recording",e),t!==void 0&&this.scheduleClear(e,t);}};var ca={set:(n,e)=>setTimeout(n,e),clear:n=>clearTimeout(n)},da=n=>typeof n=="object"&&n!==null&&typeof n.recipient=="string"&&typeof n.content=="object",He=class{store;sendSnapshot;now;timer;logger;acquire;memory=new Map;timers=new Map;constructor(e){this.store=e.store,this.sendSnapshot=e.sendSnapshot,this.now=e.now??(()=>Date.now()),this.timer=e.timer??ca,this.logger=e.logger,this.acquire=e.acquire;}async scheduleAt(e,t){let r=e.getTime();if(Number.isNaN(r))throw new x("SCHEDULE_INVALID","scheduleAt requires a valid Date");let s=await this.evaluate(t),i=randomUUID(),o={id:i,fireAt:r,recipient:s.recipient,payload:s};return await this.persist(o),this.arm(o),{id:i,cancel:()=>{this.cancel(i);}}}async loadPending(){let e=this.store.listScheduledJobs;if(!e){for(let r of this.memory.values())this.timers.has(r.id)||this.arm(r);return}let t;try{t=await e.call(this.store);}catch(r){this.logger?.warn(r,"scheduler loadPending failed");return}for(let r of t)this.timers.has(r.id)||(this.memory.set(r.id,r),this.arm(r));}dispose(){for(let e of this.timers.values())this.timer.clear(e);this.timers.clear();}cancel(e){let t=this.timers.get(e);t!==void 0&&(this.timer.clear(t),this.timers.delete(e)),this.memory.delete(e),this.remove(e);}arm(e){let t=Math.max(0,e.fireAt-this.now()),r=this.timer.set(()=>{this.fire(e);},t);this.timers.set(e.id,r);}async fire(e){if(this.timers.delete(e.id),da(e.payload))try{this.acquire&&await this.acquire(),await this.sendSnapshot(e.payload);}catch(t){this.logger?.warn(t,"scheduled send failed; retaining job for retry");return}this.memory.delete(e.id),await this.remove(e.id);}async persist(e){let t=this.store.saveScheduledJob;if(t){await t.call(this.store,e);return}this.memory.set(e.id,e);}async remove(e){let t=this.store.deleteScheduledJob;if(t)try{await t.call(this.store,e);}catch(r){this.logger?.warn(r,"scheduler deleteScheduledJob failed");}this.memory.delete(e);}async evaluate(e){let t,r=0,s={sendMessage:async(o,a,c)=>{if(r+=1,r>1)throw new x("SCHEDULE_INVALID","scheduling multi-part messages (e.g. album) is not supported; schedule a single message");return t=c?{recipient:o,content:a,options:c}:{recipient:o,content:a},{key:{remoteJid:o,id:"scheduled-snapshot",fromMe:true}}},relayMessage:async()=>{throw new x("SCHEDULE_INVALID","scheduling interactive/relayed content is not supported; schedule a text or media message")}},i=Y.create(s,"");try{await e(i);}catch(o){throw o instanceof x?o:new x("SCHEDULE_INVALID","scheduled builder evaluation failed",{cause:o})}if(!t)throw new x("SCHEDULE_INVALID","scheduled builder produced no content");return t}};async function Zr(n,e){if(typeof n.deleteMessage!="function"||typeof n.listChats!="function")return 0;let t=await n.listChats(),r=0;for(let s of t){let i=s.id??"";if(i.length===0||e.chatFilter&&!e.chatFilter(i))continue;let a=[...await n.listMessages(i)].sort((c,d)=>Number(d.messageTimestamp??0)-Number(c.messageTimestamp??0));for(let c=0;c<a.length;c+=1){let d=a[c],l=Number(d.messageTimestamp??0),u=e.olderThan!==void 0&&l<e.olderThan,w=e.maxPerChat!==void 0&&c>=e.maxPerChat;(u||w)&&(await n.deleteMessage(d.key),r+=1);}}return r}var ze=class{store;options;logger;now;timer;running=false;warnedUnsupported=false;disabled=false;constructor(e){this.store=e.store,this.options=e.options,this.logger=e.logger,this.now=e.now??Date.now;}get active(){return this.options.maxAgeMs!==void 0||this.options.maxPerChat!==void 0}buildPruneOptions(){let e={};return this.options.maxAgeMs!==void 0&&(e.olderThan=Math.floor((this.now()-this.options.maxAgeMs)/1e3)),this.options.maxPerChat!==void 0&&(e.maxPerChat=this.options.maxPerChat),typeof this.options.chats=="function"&&(e.chatFilter=this.options.chats),e}async runOnce(){if(!this.active||this.disabled)return 0;let e=this.buildPruneOptions();return typeof this.store.pruneMessages=="function"?this.store.pruneMessages(e):typeof this.store.deleteMessage=="function"?Zr(this.store,e):(this.disabled=true,this.warnedUnsupported||(this.warnedUnsupported=true,this.logger?.warn({code:"AUTO_DELETE_UNSUPPORTED"},"autoDelete: store implements neither pruneMessages nor deleteMessage; sweeper disabled")),0)}start(){if(!this.active||this.timer)return;let e=this.options.intervalMs??6e4;this.timer=setInterval(()=>{this.running||(this.running=true,this.runOnce().catch(t=>this.logger?.warn(t,"autoDelete sweep failed")).finally(()=>{this.running=false;}));},e),this.timer.unref?.();}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0);}};var Qr=n=>(n.split(/[:@]/)[0]??"").replace(/\D/g,""),Ye=class{getSocket;options;logger;constructor(e,t,r){this.getSocket=e,this.options=t,this.logger=r;}get enabled(){return this.options.enabled===true}async reject(e,t){let r=this.getSocket();if(!r)throw new x("NOT_CONNECTED","cannot reject a call: client not connected");await r.rejectCall(e,t);}async handle(e){if(this.enabled&&!await this.isAllowed(e.from)){try{await this.reject(e.callId,e.from);}catch(t){this.logger?.warn(t,"autoRejectCall: rejectCall failed");return}try{await this.options.onReject?.(e);}catch(t){this.logger?.warn(t,"autoRejectCall: onReject hook failed");}}}async isAllowed(e){let t=this.options.allow;if(t===void 0)return false;try{if(Array.isArray(t)){let r=Qr(e);return t.some(s=>s===e||Qr(s)===r)}return await t(e)===!0}catch(r){return this.logger?.warn(r,"autoRejectCall: allow predicate threw"),false}}};var la={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},ua=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[la[e]];if(r==null||typeof r!="object")return null;let s=r.mimetype;return typeof s=="string"&&s.length>0?s:null},Pt=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys'),s=await r(n,"buffer",{}),i=ua(n,e)??"application/octet-stream";return {buffer:s,mime:i,size:s.byteLength}}catch(r){throw t?.warn({error:r,kind:e,id:n.key?.id},"media download failed"),r instanceof Error?r:new Error("media download failed")}},Xr=(n,e,t)=>async()=>{try{let{downloadMediaMessage:r}=await import('baileys');return await r(n,"stream",{})}catch(r){throw t?.warn({error:r,kind:e,id:n.key?.id},"media stream download failed"),r instanceof Error?r:new Error("media stream download failed")}};var ae="[zaileys]",pa="The saved session looks invalid or corrupted (connection keeps closing before it authenticates). Delete the auth folder (default: ./.zaileys) and run again to scan a fresh QR / request a new pairing code.";function ts(n){switch(n.kind){case "connecting":return `${ae} Connecting to WhatsApp (session: ${n.sessionId})...`;case "qr":return `${ae} Scan the QR code above with WhatsApp > Linked devices to authenticate.`;case "pairing-code":return `${ae} Pairing code: ${n.code} \u2014 enter it in WhatsApp > Linked devices > Link with phone number.`;case "connected":return `${ae} Connected as ${n.id}.`;case "reconnecting":{let e=(n.delayMs/1e3).toFixed(1),t=`${ae} Connection lost (${n.reason}). Reconnecting in ${e}s (attempt ${n.attempt})...`;return n.invalidCredsSuspected?`${t}
12
12
  ${ae} ${pa}`:t}case "disconnect":return n.willReconnect?null:`${ae} Disconnected (${n.reason}).`;default:return null}}var es=false,ma=["Closing session:","Closing open session","Closing stale open session","Opening session:","Removing old closed session","Migrating session to:","Session already closed","Decrypted message with closed session","Failed to decrypt message with any known session","Session error:"],ga=n=>typeof n[0]=="string"&&ma.some(e=>n[0].startsWith(e));function ns(){if(es)return;es=true;let n=e=>{let t=console[e].bind(console);console[e]=(...r)=>{ga(r)||t(...r);};};n("info"),n("warn"),n("error");}var h=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysStoreError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};var ha="./.zaileys/auth",ya=n=>n.replace(/[^a-zA-Z0-9._-]/g,e=>`_${e.charCodeAt(0).toString(16)}`),Qe=n=>typeof n=="object"&&n!==null&&n.code==="ENOENT",Et=class{basePath;closed=false;constructor(e){this.basePath=e?.basePath??ha;}signal={read:async(e,t)=>{this.assertOpen();let r={};return await Promise.all(t.map(async s=>{let i=this.signalPath(e,s);try{let o=await promises.readFile(i,"utf8");r[s]=JSON.parse(o,BufferJSON.reviver);}catch(o){if(Qe(o))return;throw new h("STORE_READ_FAILED",`failed to read ${i}`,{cause:o})}})),r},write:async e=>{this.assertOpen();let t=[];for(let r of Object.keys(e)){let s=e[r];if(!s)continue;let i=this.signalDir(r);await promises.mkdir(i,{recursive:true});for(let o of Object.keys(s)){let a=s[o],c=this.signalPath(r,o);a===null?t.push(promises.unlink(c).catch(d=>{if(!Qe(d))throw new h("STORE_WRITE_FAILED",`failed to unlink ${c}`,{cause:d})})):a!==void 0&&t.push(this.atomicWrite(c,JSON.stringify(a,BufferJSON.replacer)));}}await Promise.all(t);},delete:async(e,t)=>{this.assertOpen(),await Promise.all(t.map(async r=>{let s=this.signalPath(e,r);try{await promises.unlink(s);}catch(i){if(!Qe(i))throw new h("STORE_WRITE_FAILED",`failed to unlink ${s}`,{cause:i})}}));},clear:async()=>{this.assertOpen(),await promises.rm(this.basePath,{recursive:true,force:true});},close:async()=>{this.closed=true;}};creds={readCreds:async()=>{this.assertOpen();try{let e=await promises.readFile(this.credsPath(),"utf8");return JSON.parse(e,BufferJSON.reviver)}catch(e){if(Qe(e))return;throw new h("STORE_READ_FAILED","failed to read creds.json",{cause:e})}},writeCreds:async e=>{this.assertOpen(),await promises.mkdir(this.basePath,{recursive:true}),await this.atomicWrite(this.credsPath(),JSON.stringify(e,BufferJSON.replacer));},deleteCreds:async()=>{this.assertOpen();try{await promises.unlink(this.credsPath());}catch(e){if(!Qe(e))throw new h("STORE_WRITE_FAILED","failed to delete creds.json",{cause:e})}}};credsPath(){return Ze.join(this.basePath,"creds.json")}signalDir(e){return Ze.join(this.basePath,"signal",String(e))}signalPath(e,t){return Ze.join(this.signalDir(e),`${ya(t)}.json`)}async atomicWrite(e,t){let r=Ze.join(Ze.dirname(e),`tmp-${randomBytes(8).toString("hex")}`);try{await promises.writeFile(r,t,"utf8"),await promises.rename(r,e);}catch(s){throw await promises.unlink(r).catch(()=>{}),new h("STORE_WRITE_FAILED",`failed to write ${e}`,{cause:s})}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","FileAuthStore is closed")}};function rs(n,e){let t=n.signal,s=makeCacheableSignalKeyStore({get:(o,a)=>t.read(o,a),set:o=>t.write(o),clear:()=>t.clear()},e?.logger??void 0),i={read:async(o,a)=>await s.get(o,[...a]),write:async o=>{await s.set(o);},delete:async(o,a)=>{await t.delete(o,a);let c={},d={};for(let l of a)d[l]=null;c[o]=d,await s.set(c);},clear:async()=>{let o=s.clear;typeof o=="function"?await o.call(s):await t.clear();},close:()=>t.close()};return {creds:n.creds,signal:i}}function ss(n,e){return {get:async(t,r)=>await n.read(t,r),set:async t=>{await n.write(t);},clear:async()=>{await n.clear();}}}var va=429;function is(n){if(n===va)return "rate-limited";switch(n){case DisconnectReason.loggedOut:return "logged-out";case DisconnectReason.forbidden:return "forbidden";case DisconnectReason.connectionLost:return "connection-lost";case DisconnectReason.multideviceMismatch:return "multi-device-mismatch";case DisconnectReason.connectionClosed:return "connection-closed";case DisconnectReason.connectionReplaced:return "connection-replaced";case DisconnectReason.badSession:return "bad-session";case DisconnectReason.unavailableService:return "unavailable-service";case DisconnectReason.restartRequired:return "restart-required";default:return "unknown"}}function Xe(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"}function Tt(n){return n==="rate-limited"}function os(n){return n==="logged-out"||n==="connection-replaced"||n==="forbidden"||n==="bad-session"}function ug(n){return !Xe(n)}var It={enabled:true,maxQrAttempts:5,maxPairingAttempts:3,pairingCooldownMs:6e4},Ma=3e5;function as(n={}){let e=n.enabled??It.enabled,t=n.maxQrAttempts??It.maxQrAttempts,r=n.maxPairingAttempts??It.maxPairingAttempts,s=n.pairingCooldownMs??It.pairingCooldownMs,i=0,o=0,a=0,c=w=>w<=0?0:Math.min(s*w,Ma);return {evaluate:(w,M)=>{if(!e)return {allowed:true,waitMs:0,attempts:w==="pairing"?o:i,max:Number.POSITIVE_INFINITY};if(w==="pairing"){if(o>=r)return {allowed:false,reason:"budget-exhausted",waitMs:0,attempts:o,max:r};let v=c(o),P=M-a;return o>0&&P<v?{allowed:false,reason:"cooldown",waitMs:v-P,attempts:o,max:r}:{allowed:true,waitMs:0,attempts:o,max:r}}return i>=t?{allowed:false,reason:"budget-exhausted",waitMs:0,attempts:i,max:t}:{allowed:true,waitMs:0,attempts:i,max:t}},record:(w,M)=>{w==="pairing"?(o+=1,a=M):i+=1;},reset:()=>{i=0,o=0,a=0;},get enabled(){return e},get qrAttempts(){return i},get pairingAttempts(){return o}}}var Sa=/[\s\-()+]/g;function ba(n){return typeof n!="string"?"":n.replace(Sa,"")}function Aa(n){if(!n||typeof n!="string"||!n.trim())throw new Error("phoneNumber is required");let e=ba(n);if(!/^\d+$/.test(e))throw new Error("phoneNumber must be E.164 with country code");if(e.length<8||e.length>15)throw new Error("phoneNumber must be E.164 with country code");return e}function cs(n){let e=Aa(n.phoneNumber),t=n.ttlMs??6e4;return {phoneNumber:e,async requestCode(r){let s;try{s=await r.requestPairingCode(e);}catch(i){let o=i instanceof Error?i.message:String(i);throw new Error(`failed to request pairing code: ${o}`)}return {code:s,expiresAt:Date.now()+t}}}}function Pa(n){return !n||typeof n!="string"||!n.trim()?Promise.reject(new Error("qr string is required")):new Promise(e=>{Ca.generate(n,{small:true},t=>e(t));})}async function ds(n,e=t=>{process.stdout.write(t);}){let t=await Pa(n);e(t+`
13
- `);}var Se={enabled:true,maxAttempts:Number.POSITIVE_INFINITY,initialDelayMs:3e3,maxDelayMs:6e4,jitterFactor:.2,rateLimitedDelayMs:3e5};function ls(n,e){let t=n?.enabled??Se.enabled,r=n?.maxAttempts??Se.maxAttempts,s=n?.initialDelayMs??Se.initialDelayMs,i=n?.maxDelayMs??Se.maxDelayMs,o=n?.jitterFactor??Se.jitterFactor,a=n?.rateLimitedDelayMs??Se.rateLimitedDelayMs,c=e?.random??Math.random,d=0;return {next:w=>{if(!t||Xe(w))return null;let M=d+1;if(M>r)return null;if(d=M,Tt(w))return {attempt:M,delayMs:a};let v=Math.pow(2,M-1),P=Math.min(i,s*v),y=1+(c()*2-1)*o,m=P*y,f=Math.min(i,Math.max(0,m));return {attempt:M,delayMs:Math.round(f)}},reset:()=>{d=0;},get attempts(){return d}}}var ka={idle:["connecting"],connecting:["qr-pending","pairing-pending","connected","reconnecting","disconnecting","disconnected"],"qr-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],"pairing-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],connected:["disconnecting","reconnecting","disconnected"],reconnecting:["connecting","disconnecting","disconnected"],disconnecting:["disconnected"],disconnected:["idle","connecting","reconnecting"]};function us(n="idle"){let e=n,t=new Set,r=s=>ka[e].includes(s);return {get state(){return e},canTransition:r,transition(s){if(!r(s))throw new Error(`invalid state transition: ${e} -> ${s}`);let i=e;e=s;for(let o of t)try{o(i,s);}catch{}},onChange(s){return t.add(s),()=>{t.delete(s);}}}}var xt=n=>`${n.remoteJid??""}|${n.id??""}|${n.fromMe?1:0}`,Ot=class{messages=new Map;messagesByJid=new Map;chats=new Map;contacts=new Map;presence=new Map;boundSocket;listeners=new Map;closed=false;async saveMessage(e){this.assertOpen();let t=xt(e.key);this.messages.set(t,structuredClone(e));let r=e.key.remoteJid??"",s=this.messagesByJid.get(r);s||(s=new Set,this.messagesByJid.set(r,s)),s.add(t);}async getMessage(e){this.assertOpen();let t=this.messages.get(xt(e));return t?structuredClone(t):void 0}async listMessages(e,t){this.assertOpen();let r=this.messagesByJid.get(e);if(!r)return [];let s=[];for(let o of r){let a=this.messages.get(o);a&&s.push(a);}s.sort((o,a)=>Number(a.messageTimestamp)-Number(o.messageTimestamp));let i=s;if(typeof t?.before=="number"){let o=t.before;i=i.filter(a=>Number(a.messageTimestamp)<o);}return typeof t?.limit=="number"&&(i=i.slice(0,t.limit)),i.map(o=>structuredClone(o))}async saveChat(e){this.assertOpen();let t=e.id;t&&this.chats.set(t,structuredClone(e));}async getChat(e){this.assertOpen();let t=this.chats.get(e);return t?structuredClone(t):void 0}async listChats(e){this.assertOpen();let t=[];for(let r of this.chats.values())e?.archived===true&&r.archived!==true||t.push(structuredClone(r));return t}async saveContact(e){this.assertOpen(),this.contacts.set(e.id,structuredClone(e));}async getContact(e){this.assertOpen();let t=this.contacts.get(e);return t?structuredClone(t):void 0}async listContacts(){return this.assertOpen(),Array.from(this.contacts.values(),e=>structuredClone(e))}async savePresence(e,t){this.assertOpen(),this.presence.set(e,structuredClone(t));}async getPresence(e){this.assertOpen();let t=this.presence.get(e);return t?structuredClone(t):void 0}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...c)=>{let l=c[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let u=this.messages.get(xt(l.key));if(u){let w={...u,...l.update};this.saveMessage(w).catch(()=>{});}}},s=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveChat(l).catch(()=>{});},i=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let w={...this.chats.get(l.id)??{},...l};this.saveChat(w).catch(()=>{});}},o=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveContact(l).catch(()=>{});},a=(...c)=>{let d=c[0];if(d?.presences)for(let l of Object.keys(d.presences)){let u=d.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[c,d]of this.listeners)e.ev.on(c,d);}async deleteMessage(e){this.assertOpen();let t=xt(e);this.messages.delete(t);let r=e.remoteJid??"",s=this.messagesByJid.get(r);s&&(s.delete(t),s.size===0&&this.messagesByJid.delete(r));}async pruneMessages(e){this.assertOpen();let t=0;for(let[r,s]of [...this.messagesByJid.entries()]){if(e.chatFilter&&!e.chatFilter(r))continue;let i=[];for(let a of s){let c=this.messages.get(a);c&&i.push(c);}i.sort((a,c)=>Number(c.messageTimestamp??0)-Number(a.messageTimestamp??0));let o=i.filter((a,c)=>{let d=Number(a.messageTimestamp??0);return e.olderThan!==void 0&&d<e.olderThan||e.maxPerChat!==void 0&&c>=e.maxPerChat});for(let a of o)await this.deleteMessage(a.key),t+=1;}return t}async clear(){this.assertOpen(),this.messages.clear(),this.messagesByJid.clear(),this.chats.clear(),this.contacts.clear(),this.presence.clear();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);return this.listeners.clear(),this.boundSocket=void 0,Promise.resolve()}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","MemoryMessageStore is closed")}};var Ta=["silent","fatal","error","warn","info","debug","trace"];function Ia(n){if(n)return n;let e=process.env.ZAILEYS_DEBUG;return e===void 0?"silent":e==="1"?"info":Ta.includes(e)?e:"silent"}function xa(n={}){let e=Ia(n.level),t=Ea({level:e});return n.sessionId!==void 0?t.child({sessionId:n.sessionId}):t}var ps=["debug","info","warn","error","fatal"];function Oa(n){if(n===null||typeof n!="object")return false;for(let e of ps)if(typeof n[e]!="function")return false;return true}function et(){}function Ra(n){let e={debug:et,info:et,warn:et,error:et,fatal:et};for(let t of ps){let r=n[t];typeof r=="function"&&(e[t]=r.bind(n));}return e}function En(n,e){return n===void 0?e??xa():Oa(n)?n:Ra(n)}var Cg=Object.freeze(["HISTORY_SYNC_NOTIFICATION","APP_STATE_SYNC_KEY_SHARE","LID_MIGRATION_MAPPING_SYNC","PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]),ms=n=>{let e=n.requestId!=null,t=n.messages.filter(r=>{if(e)return false;let s=r.messageStubParameters;if(Array.isArray(s)){for(let i of s)if(typeof i=="string"&&i.startsWith("requestId:"))return false}return true});return {...n,messages:t}};var _a=new Set(["offer","ringing"]),La=new Set(["timeout","reject","accept","terminate"]),gs=n=>{let e=n instanceof Date?n.getTime():Date.parse(String(n));return Number.isFinite(e)?e:0},fs=n=>{if(typeof n.id!="string"||n.id.length===0||!_a.has(n.status))return null;let e=Vr(n.id),t={kind:"incoming",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:gs(n.date),status:n.status};return e!==void 0&&(t.caller=e),t},hs=n=>typeof n.id!="string"||n.id.length===0||!La.has(n.status)?null:{kind:"ended",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:gs(n.date),status:n.status};var B=n=>typeof n=="string"&&n.length>0,Na=n=>{let e={};return typeof n.subject=="string"&&(e.subject=n.subject),typeof n.desc=="string"&&(e.description=n.desc),typeof n.announce=="boolean"&&(e.announce=n.announce),typeof n.restrict=="boolean"&&(e.restrict=n.restrict),typeof n.ephemeralDuration=="number"&&(e.ephemeralDuration=n.ephemeralDuration),e},ys=(n,e,t)=>n.filter(r=>B(r?.id)).map(r=>{let s={jid:r.id},i=r.lid??r.pn??r.phoneNumber;return B(i)&&(s.participantAlt=i),B(e)&&(s.authorPn=e),B(t)&&(s.authorUsername=t),s.isAdmin=r.admin==="admin"||r.admin==="superadmin",s}),ws=n=>B(n?.id)?{groupId:n.id,update:Na(n),timestamp:Date.now()}:null,vs=n=>{if(!B(n?.groupId)||!B(n?.participant))return null;let e={groupId:n.groupId,participant:n.participant,label:typeof n.label=="string"?n.label:"",timestamp:typeof n.messageTimestamp=="number"?n.messageTimestamp:Date.now()};return B(n.participantAlt)&&(e.participantAlt=n.participantAlt),e},Da=new Set(["add","invite","invite-link"]),Ba=new Set(["remove","leave"]),Ms=n=>{if(!B(n?.id)||!Da.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=ys(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return B(n.author)&&(t.by=n.author),t},Ss=n=>{if(!B(n?.id)||!Ba.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=ys(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return B(n.author)&&(t.by=n.author),t};var be=n=>typeof n!="string"||n.length===0?null:jidNormalizedUser(n),Z=n=>typeof n=="string"&&n.length>0?n:void 0,ja=["@s.whatsapp.net","@c.us"],Rt=n=>n.endsWith("@lid"),bs=n=>ja.some(e=>n.endsWith(e)),$=(n,e)=>{if(!n)return null;let t=Z(n.participant)??n.remoteJid,r=be(t);if(r===null)return null;let s=Z(n.participantAlt)??Z(n.remoteJidAlt),i=s!=null?be(s):null,o=Z(n.participantUsername)??Z(n.remoteJidUsername),a={jid:r,isMe:n.fromMe===true};typeof t=="string"&&t.length>0&&(a.deviceJid=t);let c=i!==null?[r,i]:[r],d=c.find(Rt),l=c.find(bs);d!==void 0&&(a.lid=d),l!==void 0&&(a.pn=l),o!==void 0&&(a.username=o);let u=Z(e);return u!==void 0&&(a.pushName=u),a},As=n=>{if(!n)return null;let e=n.stanzaId;if(typeof e!="string"||e.length===0)return null;let t=Z(n.participant),r=Z(n.remoteJid)??t,s={id:e};typeof r=="string"&&(s.remoteJid=r),typeof t=="string"&&(s.participant=t);let i={key:s},o=$(s);return o&&(i.sender=o),i},tt=n=>{if(!n)return {mentionedJids:[],mentionAll:false};let e=n.mentionedJid,t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[],r=n.groupMentions,s=Array.isArray(r)&&r.length>0;return {mentionedJids:t,mentionAll:s}};var Ae=n=>isJidGroup(n)===true,Ce=n=>{if(n==null)return null;if(typeof n=="number")return Number.isFinite(n)?n:null;if(typeof n.toNumber=="function"){let e=n.toNumber();return Number.isFinite(e)?e:null}return null},g=n=>n!=null&&typeof n=="object"?n:null,Cs=["ephemeralMessage","viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension","documentWithCaptionMessage","editedMessage","lottieStickerMessage","groupStatusMessage","groupStatusMessageV2"],Ps=["groupStatusMessage","groupStatusMessageV2"],ks=(n,e)=>{let t=n;for(let r=0;r<5&&t!=null;r++){if(e.some(i=>t?.[i]!=null))return true;let s=null;for(let i of Cs){let o=g(g(t[i])?.message);if(o!=null){s=o;break}}t=s;}return false},Pe=n=>{let e=n;for(let t=0;t<5;t++){let r=null;for(let s of Cs){let i=g(g(e[s])?.message);if(i!=null){r=i;break}}if(r==null)break;e=r;}return e};var Ua=["quick_reply","cta_url","cta_call","button_click"],qa=["list_select","single_select"],J=n=>typeof n=="string"&&n.length>0,Ts=n=>{let e=typeof n.pushName=="string"?n.pushName:void 0;return $(n.key,e)},Is=n=>Ce(n.messageTimestamp)??0,xs=(n,e)=>{if(!J(n))return null;try{let t=JSON.parse(n);return t!==null&&typeof t=="object"?t:null}catch{return e?.debug({paramsJson:n},"interactive: failed to parse nativeFlow paramsJson"),null}},_t=(n,e)=>{for(let t of e){let r=n[t];if(J(r))return r}},Os=(n,e)=>{let t=n.message;if(!t)return null;let r=t.buttonsResponseMessage;if(r&&J(r.selectedButtonId))return Tn(n,r.selectedButtonId,r.selectedDisplayText);let s=t.templateButtonReplyMessage;if(s&&J(s.selectedId))return Tn(n,s.selectedId,s.selectedDisplayText);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&Ua.includes(i.name)){let o=xs(i.paramsJson,e.logger);if(!o)return null;let a=_t(o,["id","button_id"]);return a===void 0?null:Tn(n,a,_t(o,["display_text"])??null)}return null},Tn=(n,e,t)=>{let r=Ts(n);if(!r||!n.key)return null;let s={key:n.key,buttonId:e,sender:r,timestamp:Is(n)};return J(t)&&(s.buttonText=t),s},Rs=(n,e)=>{let t=n.message;if(!t)return null;let r=t.listResponseMessage,s=r?.singleSelectReply?.selectedRowId;if(J(s))return Es(n,s,r?.title);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&qa.includes(i.name)){let o=xs(i.paramsJson,e.logger);if(!o)return null;let a=_t(o,["row_id","id"]);return a===void 0?null:Es(n,a,_t(o,["title"])??null)}return null},Es=(n,e,t)=>{let r=Ts(n);if(!r||!n.key)return null;let s={key:n.key,rowId:e,sender:r,timestamp:Is(n)};return J(t)&&(s.title=t),s};var Ka=new Set(["available","unavailable","composing","recording","paused"]),$a=n=>n instanceof Date?n.getTime():typeof n=="number"&&Number.isFinite(n)?n:0,_s=n=>n.status!=="complete"&&n.status!=="paused"?null:{syncType:String(n.syncType),status:n.status,explicit:n.explicit===true},In=n=>{if(n.source==="connection-update"){let t=n.reachoutTimeLock;return t.isActive!==true?null:{reason:"reachout-timelock",retryAt:$a(t.timeEnforcementEnds)}}if(n.capInfo.capping_status!=="CAPPED")return null;let e={reason:"chat-limit-reached"};return typeof n.capInfo.used_quota=="number"&&(e.usedQuota=n.capInfo.used_quota),typeof n.capInfo.total_quota=="number"&&(e.totalQuota=n.capInfo.total_quota),e},Ls=n=>{if(typeof n.id!="string"||n.id.length===0)return [];let e=[];for(let[t,r]of Object.entries(n.presences??{})){let s=r?.lastKnownPresence;typeof s!="string"||!Ka.has(s)||e.push({jid:n.id,participant:t,status:s});}return e},nt=n=>{let e=n.payload.id;if(typeof e!="string"||e.length===0)return null;let t=Date.now();switch(n.source){case "reaction":{let r={action:"reaction",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.reaction?.code=="string"&&(r.emoji=n.payload.reaction.code),r}case "view":{let r={action:"view",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.count=="number"&&(r.count=n.payload.count),r}case "participants":return {action:"participants",newsletterId:e,timestamp:t};case "settings":{let r={action:"settings",newsletterId:e,timestamp:t};return n.payload.update&&(r.update=n.payload.update),r}}};var Ds=n=>{let e=n.match(/(https?:\/\/[^\s]+)/g);return e?e.map(t=>t.replace(/[.,;:!?]+$/,"")):[]},Ns=(n,e=2166136261)=>{let t=e>>>0;for(let r=0;r<n.length;r++)t^=n.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t>>>0},Bs=n=>(Ns(n).toString(16).padStart(8,"0")+Ns(n,2646966556).toString(16).padStart(8,"0")).toUpperCase(),Ws=n=>Bs(`${n.remoteJid??""}|${n.id??""}|${n.fromMe===true?"1":"0"}`),Fs=(n,e)=>Bs(`${n??""}|${e}`),js=n=>{let e=null;if(typeof n=="number")e=n;else if(typeof n=="bigint")e=Number(n);else if(typeof n=="string"){let t=Number.parseInt(n,10);e=Number.isFinite(t)?t:null;}else if(n!=null&&typeof n=="object"){let t=n;typeof t.toNumber=="function"?e=t.toNumber():typeof t.low=="number"&&(e=(typeof t.high=="number"?t.high:0)*4294967296+(t.low>>>0));}return e!=null&&Number.isFinite(e)&&e>0?e*1e3:0},Us=n=>{let e=jidDecode(n);if(!e)return "unknown";let t=e.device;return t===void 0||t===0?"android":t===2?"ios":t===3?"web":t===4?"desktop":"unknown"},Ja=n=>n.trim().endsWith("?"),Va=(n,e)=>e.length===0?false:e.some(t=>t.length>0&&n.startsWith(t)),Ha=(n,e)=>{if(e.length===0)return false;let t;try{t=jidNormalizedUser(n);}catch{t=n;}return e.some(r=>{try{return jidNormalizedUser(r)===t}catch{return r===n}})},za=(n,e)=>{let t=async r=>r===void 0?false:Array.isArray(r)?r.includes(e):r(e);return {authors:()=>t(n?.authors),banned:()=>t(n?.banned)}},Ya=0,Za=14,Qa=1,Xa=2,ec=n=>{let e=g(n.message);if(e==null)return {isEdited:false,isDeleted:false,isPinned:false,isUnPinned:false,isBot:false,isStatusMention:false,isGroupStatusMention:false,isGroupStatus:false};let t=g(e.protocolMessage),r=typeof t?.type=="number"?t.type:void 0,s=typeof g(e.pinInChatMessage)?.type=="number"?e.pinInChatMessage.type:void 0;return {isEdited:e.editedMessage!=null||r===Za,isDeleted:r===Ya,isPinned:s===Qa,isUnPinned:s===Xa,isBot:g(e.messageContextInfo)?.botMetadata!=null,isStatusMention:e.statusMentionMessage!=null,isGroupStatusMention:e.groupStatusMentionMessage!=null,isGroupStatus:ks(e,Ps)}},xn=n=>{let e=typeof n.key.remoteJid=="string"?n.key.remoteJid:null,t=e!==null&&Ae(e),r=ec(n.message),s=c=>n.lidMap!=null&&c.endsWith("@lid")?n.lidMap.get(c)??c:c,i=s(n.sender.pn??n.sender.jid),o=t?e?jidNormalizedUser(e):null:n.key.fromMe===true&&e?s(jidNormalizedUser(e)):i,a={uniqueId:Ws(n.key),staticId:Fs(o,i),channelId:n.channelId,chatId:n.key.id??"",chatType:n.chatType,receiverId:n.receiverId?s(jidNormalizedUser(n.receiverId)):n.receiverId,roomId:o,senderId:i,senderLid:n.sender.lid??null,senderName:n.sender.pushName??null,senderUsername:n.sender.username??null,senderDevice:Us(n.sender.deviceJid??n.sender.jid),timestamp:js(n.message.messageTimestamp),text:n.text,mentions:n.mentions,links:Ds(n.text),isFromMe:n.key.fromMe===true,isGroup:t,isNewsletter:n.isNewsletter,isBroadcast:n.isBroadcast,isViewOnce:n.isViewOnce,isEphemeral:n.isEphemeral,isForwarded:n.isForwarded,isOffline:n.isOffline===true,forwardCount:n.forwardCount??0,ephemeralDuration:n.ephemeralDuration??null,addressingMode:n.addressingMode??"pn",mentionedGroups:n.mentionedGroups??[],...n.ad!==void 0?{ad:n.ad}:{},...n.business!==void 0?{business:n.business}:{},isQuestion:Ja(n.text),isPrefix:Va(n.text,n.prefixes),isTagMe:Ha(n.selfJid,n.mentions),isEdited:r.isEdited,isDeleted:r.isDeleted,isPinned:r.isPinned,isUnPinned:r.isUnPinned,isBot:r.isBot,isSpam:false,isHideTags:n.mentions.length>0&&!/@\d/.test(n.text),isStatusMention:r.isStatusMention,isGroupStatusMention:r.isGroupStatusMention,isGroupStatus:r.isGroupStatus,isStory:e==="status@broadcast",roomName:n.resolveRoomName,receiverName:n.resolveReceiverName,replied:n.resolveReplied,reply:n.reply,react:n.react,message:()=>n.message,citation:za(n.citationConfig,n.sender.pn??n.sender.jid)};return n.media!==void 0&&(a.media=n.media),a};var Rn={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},$s=n=>{let e=n?.remoteJid;return typeof e=="string"&&e.length>0?e:""},S=n=>typeof n=="string"&&n.length>0?n:null,Q=(...n)=>{for(let e of n){let t=S(e);if(t!=null)return t}return null},Gs=n=>{let e=g(n.message);if(e==null)return n;let t=Pe(e);return t===e?n:{...n,message:t}},tc=n=>{let t=g(g(g(n.botForwardedMessage)?.message)?.richResponseMessage)??g(n.richResponseMessage);if(t==null)return null;let r=t.submessages;if(!Array.isArray(r))return null;let s=[];for(let o of r){let a=S(g(o)?.messageText);a!=null&&s.push(a);}let i=s.join(`
14
- `).trim();return i.length>0?i:null},nc=n=>{let e=g(n.templateMessage),t=g(e?.hydratedTemplate)??g(e?.hydratedFourRowTemplate);return S(t?.hydratedContentText)},rc=n=>Q(g(n.pollCreationMessage)?.name,g(n.pollCreationMessageV2)?.name,g(n.pollCreationMessageV3)?.name),sc=n=>{let e=g(n.locationMessage)??g(n.liveLocationMessage);if(e==null)return null;let t=Q(e.name,e.address);if(t!=null){let i=S(e.name),o=S(e.address);return i!=null&&o!=null&&i!==o?`${i} \u2014 ${o}`:t}let r=e.degreesLatitude,s=e.degreesLongitude;return typeof r=="number"&&typeof s=="number"?`${r}, ${s}`:null},ic=n=>{let e=S(g(n.contactMessage)?.displayName);if(e!=null)return e;let t=g(n.contactsArrayMessage),r=S(t?.displayName);if(r!=null)return r;let s=t?.contacts;if(Array.isArray(s)){let i=s.map(o=>S(g(o)?.displayName)).filter(o=>o!=null);if(i.length>0)return i.join(", ")}return null},Js=n=>Q(n.conversation,g(n.extendedTextMessage)?.text,tc(n),S(g(g(n.interactiveMessage)?.body)?.text),g(n.buttonsMessage)?.contentText,g(n.listMessage)?.description,nc(n),rc(n),sc(n),ic(n)),oc=n=>Q(g(n.buttonsResponseMessage)?.selectedDisplayText,g(n.buttonsResponseMessage)?.selectedButtonId,g(n.templateButtonReplyMessage)?.selectedDisplayText,g(n.templateButtonReplyMessage)?.selectedId,g(n.listResponseMessage)?.title,g(g(n.listResponseMessage)?.singleSelectReply)?.selectedRowId,g(g(n.interactiveResponseMessage)?.body)?.text),ac=n=>Q(g(n.imageMessage)?.caption,g(n.videoMessage)?.caption,g(n.documentMessage)?.caption,g(n.documentMessage)?.fileName),T=n=>{if(typeof n=="number")return n;let e=Ce(n);return typeof e=="number"?e:null},cc=[["pollCreationMessage","poll"],["pollCreationMessageV2","poll"],["pollCreationMessageV3","poll"],["contactMessage","contact"],["contactsArrayMessage","contact"],["locationMessage","location"],["liveLocationMessage","live-location"],["eventMessage","event"],["albumMessage","album"],["groupInviteMessage","group-invite"],["productMessage","product"],["orderMessage","order"],["requestPaymentMessage","payment"],["sendPaymentMessage","payment"],["paymentInviteMessage","payment"],["buttonsMessage","buttons"],["listMessage","list"],["interactiveMessage","interactive"],["templateMessage","template"]],Vs=n=>{let e=g(n.pollCreationMessage)??g(n.pollCreationMessageV2)??g(n.pollCreationMessageV3);if(e!=null){let m=Array.isArray(e.options)?e.options:[];return {type:"poll",name:S(e.name),options:m.map(f=>S(g(f)?.optionName)).filter(f=>f!=null),selectableCount:T(e.selectableOptionsCount)??0}}let t=g(n.contactMessage);if(t!=null)return {type:"contact",displayName:S(t.displayName),vcard:S(t.vcard),contacts:[{displayName:S(t.displayName),vcard:S(t.vcard)}]};let r=g(n.contactsArrayMessage);if(r!=null){let m=Array.isArray(r.contacts)?r.contacts:[];return {type:"contact",displayName:S(r.displayName),vcard:null,contacts:m.map(f=>({displayName:S(g(f)?.displayName),vcard:S(g(f)?.vcard)}))}}let s=g(n.locationMessage);if(s!=null)return {type:"location",latitude:T(s.degreesLatitude),longitude:T(s.degreesLongitude),name:S(s.name),address:S(s.address),accuracy:T(s.accuracyInMeters),speed:T(s.speedInMps),caption:S(s.comment)};let i=g(n.liveLocationMessage);if(i!=null)return {type:"live-location",latitude:T(i.degreesLatitude),longitude:T(i.degreesLongitude),name:null,address:null,accuracy:T(i.accuracyInMeters),speed:T(i.speedInMps),caption:S(i.caption)};let o=g(n.albumMessage);if(o!=null)return {type:"album",expectedImageCount:T(o.expectedImageCount),expectedVideoCount:T(o.expectedVideoCount)};let a=g(n.groupInviteMessage);if(a!=null)return {type:"group-invite",groupId:S(a.groupJid),groupName:S(a.groupName),inviteCode:S(a.inviteCode),caption:S(a.caption),expiresAt:T(a.inviteExpiration)};let c=g(g(n.productMessage)?.product);if(g(n.productMessage)!=null){let m=S(g(n.productMessage)?.businessOwnerJid),f=T(c?.priceAmount1000);return {type:"product",productId:S(c?.productId),title:S(c?.title),description:S(c?.description),price:f!=null?f/1e3:null,currency:S(c?.currencyCode),retailerId:S(c?.retailerId),url:S(c?.url),businessOwnerId:m}}let d=g(n.orderMessage);if(d!=null){let m=T(d.totalAmount1000),f={1:"inquiry",2:"accepted",3:"declined"},b=d.status;return {type:"order",orderId:S(d.orderId),title:S(d.orderTitle),itemCount:T(d.itemCount),total:m!=null?m/1e3:null,currency:S(d.totalCurrencyCode),status:typeof b=="number"?f[b]??null:S(b),message:S(d.message)}}let l=g(n.requestPaymentMessage)!=null&&{node:n.requestPaymentMessage,kind:"request"}||g(n.sendPaymentMessage)!=null&&{node:n.sendPaymentMessage,kind:"send"}||g(n.paymentInviteMessage)!=null&&{node:n.paymentInviteMessage,kind:"invite"};if(l!==false){let m=g(l.node),f=T(m?.amount1000),b=g(m?.noteMessage);return {type:"payment",kind:l.kind,amount:f!=null?f/1e3:null,currency:S(m?.currencyCodeIso4217),note:Q(b?.conversation,g(b?.extendedTextMessage)?.text),expiresAt:T(m?.expiryTimestamp)}}let u=g(n.eventMessage);if(u!=null){let m=g(u.location);return {type:"event",name:S(u.name),description:S(u.description),location:m!=null?Q(m.name,m.address):null,startTime:T(u.startTime),endTime:T(u.endTime),isCanceled:u.isCanceled===true}}let w=g(n.buttonsMessage);if(w!=null){let m=Array.isArray(w.buttons)?w.buttons:[];return {type:"buttons",contentText:S(w.contentText),footerText:S(w.footerText),buttons:m.map(f=>({id:S(g(f)?.buttonId),text:S(g(g(f)?.buttonText)?.displayText)}))}}let M=g(n.listMessage);if(M!=null){let m=Array.isArray(M.sections)?M.sections:[];return {type:"list",title:S(M.title),description:S(M.description),buttonText:S(M.buttonText),sections:m.map(f=>{let b=Array.isArray(g(f)?.rows)?g(f).rows:[];return {title:S(g(f)?.title),rows:b.map(k=>({id:S(g(k)?.rowId),title:S(g(k)?.title),description:S(g(k)?.description)}))}})}}let v=g(n.interactiveMessage);if(v!=null){let m=g(v.nativeFlowMessage),f=Array.isArray(m?.buttons)?m.buttons:[];return {type:"interactive",title:S(g(v.header)?.title),body:S(g(v.body)?.text),footer:S(g(v.footer)?.text),buttons:f.map(b=>({name:S(g(b)?.name),params:S(g(b)?.buttonParamsJson)}))}}let P=g(n.templateMessage);if(P!=null){let m=g(P.hydratedTemplate)??g(P.hydratedFourRowTemplate),f=Array.isArray(m?.hydratedButtons)?m.hydratedButtons:[];return {type:"template",text:S(m?.hydratedContentText),buttons:f.map(b=>{let k=g(b),F=g(k?.quickReplyButton)??g(k?.urlButton)??g(k?.callButton);return {id:S(F?.id),text:S(F?.displayText)}})}}let y=g(n.extendedTextMessage);if(y!=null){let m=Q(y.canonicalUrl,y.matchedText),f=S(y.title),b=S(y.description);if(m!=null&&(f!=null||b!=null))return {type:"link",url:m,title:f,description:b}}return null};var st=n=>{let e=g(n.message);if(e==null)return null;let t=Pe(e);return Js(t)??oc(t)??ac(t)},Nt=n=>{let e=g(Gs(n).message);if(e==null)return null;let t=g(e.extendedTextMessage)?.contextInfo;if(t!=null)return t;for(let r of Object.values(e)){if(r==null||typeof r!="object")continue;let s=r.contextInfo;if(s!=null)return s}return null},dc=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[Rn[e]];return r==null||typeof r!="object"?null:r},lc=n=>{let e=n.message;if(e==null)return false;if(e.viewOnceMessage!=null||e.viewOnceMessageV2!=null||e.viewOnceMessageV2Extension!=null)return true;for(let t of Object.values(Rn)){let r=e[t];if(r!=null&&typeof r=="object"&&r.viewOnce===true)return true}return false},uc=(n,e)=>n.message?.ephemeralMessage!=null?true:typeof e?.expiration=="number"&&e.expiration>0,pc=(n,e)=>typeof n=="number"&&Number.isFinite(n)?n:e,mc=(n,e)=>{let t=e?.expiration;if(typeof t=="number"&&t>0)return t;let r=g(g(n.message)?.ephemeralMessage),s=g(g(r?.message)?.extendedTextMessage)?.contextInfo,i=g(s)?.expiration;return typeof i=="number"&&i>0?i:null},gc=n=>{let e=n?.groupMentions;if(!Array.isArray(e))return [];let t=[];for(let r of e){let s=g(r)?.groupJid;typeof s=="string"&&s.length>0&&t.push(s);}return t},Hs=n=>typeof n=="string"&&n.length>0?n:void 0,fc=n=>{let e=g(n?.externalAdReply);if(e==null)return;let t={},r=[["clickId","ctwaClid"],["sourceId","sourceId"],["sourceUrl","sourceUrl"],["sourceApp","sourceApp"],["sourceType","sourceType"],["title","title"],["body","body"],["thumbnailUrl","thumbnailUrl"],["ref","ref"]];for(let[s,i]of r){let o=Hs(e[i]);o!==void 0&&(t[s]=o);}return Object.keys(t).length>0?t:void 0},hc=n=>{let e=Hs(g(n)?.verifiedBizName);return e!==void 0?{verifiedName:e}:void 0},ce=n=>{let e=g(n);if(e==null)return "text";let t=Pe(e);for(let r of Object.values(Rn))if(t[r]!=null)return r.replace("Message","");for(let[r,s]of cc)if(t[r]!=null)return s;return "text"},qs=(n,e)=>{if(n==null)return false;let t=[n.pn,n.lid,n.jid].filter(s=>typeof s=="string"&&s.length>0),r=[e.pn,e.lid,e.jid].filter(s=>typeof s=="string"&&s.length>0);return t.some(s=>r.includes(s))},yc=async(n,e,t,r,s,i)=>{try{if(n==null||n.quotedMessage==null)return null;let o=n.stanzaId;if(typeof o!="string"||o.length===0)return null;if(e.resolveQuoted!=null&&t.length>0){let v=await e.resolveQuoted(o,t);if(v!=null&&v.message!=null){let P=st(v)??"",y=de(v,e,ce(v.message),P,it(v,e),s);if(y!==null)return y}}let a=As(n);if(a===null||typeof a.key.id!="string"||a.key.id.length===0||(t.length>0&&(a.key.remoteJid=t),typeof a.key.remoteJid!="string"||a.key.remoteJid.length===0))return null;let c=a.key.participant,d=Ae(t),l=a.sender?.pushName;!d&&(c==null||c.length===0)?i===!0?(a.key.participant=t,l==null&&r!=null&&qs({jid:t},r)&&(l=r.pushName)):(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):typeof c=="string"&&(e.selfJid.length>0&&Lt(c,e.selfJid)||e.selfLid!=null&&Lt(c,e.selfLid))?(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):r!=null&&qs(a.sender,r)&&(r.pn!=null&&(a.key.participant=r.pn),r.lid!=null&&(a.key.participantAlt=r.lid),l==null&&(l=r.pushName));let u=n.quotedMessage,w=Object.assign({key:a.key,message:u??null},l!=null?{pushName:l}:{}),M=st(w)??"";return de(w,e,ce(u),M,it(w,e),s)}catch{return null}},zs=n=>tt(Nt(n)).mentionedJids,wc=n=>{try{return jidNormalizedUser(n)}catch{return n}},Ys=(n,e)=>n.map(t=>{let r=wc(t);return e.lidMap?.get(r)??r}),Ks=n=>(n.split("@")[0]??"").split(":")[0]??"",vc=(n,e)=>{if(e==null||e.size===0||n.length===0)return n;let t=[...e].map(([s,i])=>[Ks(s),Ks(i)]).filter(([s,i])=>s.length>0&&i.length>0&&s!==i).sort((s,i)=>i[0].length-s[0].length),r=n;for(let[s,i]of t)r=r.split(`@${s}`).join(`@${i}`);return r},de=(n,e,t,r,s,i)=>{let o=n.key;if(o==null)return null;let a=$(o,n.pushName??void 0);if(a===null)return null;let c=$s(o);if(c.length===0)return null;let d=Nt(n),l=Ae(c),u=c.endsWith("@broadcast"),w=c.endsWith("@newsletter"),M=d?.isForwarded===true||(d?.forwardingScore??0)>0,v=lc(n),P=uc(n,d),y=e.channelId??"",m=e.receiverId??"",f=e.prefixes??[],b=i??(()=>l?e.resolveRoomName!=null?e.resolveRoomName(c):Promise.resolve(null):Promise.resolve(a.pushName??null)),k=e.resolveReceiverName??(()=>Promise.resolve(null)),F=()=>yc(d,e,c,a,b,o.fromMe===true),en=c.length>0?c:a.pn??a.jid,tn=(rn,Ki)=>e.reply==null?Promise.reject(new Error("zaileys: ctx.reply() requires a connected client")):e.reply(en,rn,Ki,n),nn=rn=>e.react==null?Promise.reject(new Error("zaileys: ctx.react() requires a connected client")):e.react(o,rn),Ui=Ys(tt(d).mentionedJids,e),qi=vc(r,e.lidMap),qn=fc(d),Kn=hc(n),$n={message:n,key:o,channelId:y,receiverId:m,selfJid:e.selfJid,text:qi,chatType:t,sender:a,mentions:Ui,isViewOnce:v,isEphemeral:P,isForwarded:M,isBroadcast:u,isNewsletter:w,isOffline:e.isOffline===true,forwardCount:pc(d?.forwardingScore,0),ephemeralDuration:mc(n,d),addressingMode:o.addressingMode==="lid"?"lid":"pn",mentionedGroups:gc(d),...qn!==void 0?{ad:qn}:{},...Kn!==void 0?{business:Kn}:{},prefixes:f,...e.lidMap!=null?{lidMap:e.lidMap}:{},resolveRoomName:b,resolveReceiverName:k,resolveReplied:F,reply:tn,react:nn},Gn=s!==void 0?{...$n,media:s}:$n;return xn(e.citationConfig!==void 0?{...Gn,citationConfig:e.citationConfig}:Gn)},Mc=["image","video","audio","document","sticker"],Zs=(n,e,t)=>{let r=Gs(n),s=dc(r,e);if(s===null)return null;let i=Pt(r,e,t.logger),o=Xr(r,e,t.logger);return {type:e,mimetype:typeof s.mimetype=="string"?s.mimetype:null,caption:typeof s.caption=="string"?s.caption:null,fileName:typeof s.fileName=="string"?s.fileName:null,fileSize:T(s.fileLength),ptt:s.ptt===true,duration:T(s.seconds),width:T(s.width),height:T(s.height),pages:T(s.pageCount),isAnimated:s.isAnimated===true||s.gifPlayback===true,thumbnail:s.jpegThumbnail!=null?Buffer.from(s.jpegThumbnail):null,buffer:async()=>(await i()).buffer,stream:o}},it=(n,e)=>{let t=g(n.message);if(t==null)return;let r=ce(n.message);return Mc.includes(r)?Zs(n,r,e)??void 0:Vs(Pe(t))??void 0},Qs=(n,e)=>{if(g(n.message)==null)return null;let r=ce(n.message),s=it(n,e),i=st(n)??"";return i===""&&s===void 0?null:de(n,e,r,i,s)},Xs=(n,e)=>{let t=g(n.message);if(t==null)return null;let r=Pe(t),s=Js(r),i=Vs(r)??void 0;return s===null&&i===void 0?null:de(n,e,ce(n.message),s??"",i)},ot=(n,e,t)=>{let r=Zs(e,n,t);return r===null?null:de(e,t,n,r.caption??"",r)},ei=(n,e)=>ot("image",n,e),ti=(n,e)=>ot("video",n,e),ni=(n,e)=>ot("audio",n,e),ri=(n,e)=>ot("document",n,e),si=(n,e)=>ot("sticker",n,e),Lt=(n,e)=>{try{return jidNormalizedUser(n)===jidNormalizedUser(e)}catch{return n===e}},ii=(n,e)=>{if(n.key==null)return null;let r=Nt(n),s=tt(r).mentionedJids;if(s.length===0)return null;let i=Ys(s,e);if(!(i.some(u=>Lt(u,e.selfJid))||e.selfLid!=null&&s.some(u=>Lt(u,e.selfLid)))||g(n.message)==null)return null;let c=st(n)??"",d=it(n,e),l=de(n,e,ce(n.message),c,d);return l===null?null:{...l,mentionedJids:i,selfJid:e.selfJid}},oi=(n,e)=>{let t=n.key;if(t==null)return null;let r=$s(t);if(r.length===0||!Ae(r))return null;let{mentionAll:s}=tt(Nt(n));if(!s||g(n.message)==null)return null;let o=st(n)??"",a=it(n,e),c=de(n,e,ce(n.message),o,a);return c===null?null:{...c,isMentionAll:true,selfJid:e.selfJid}};var le=(n,e)=>{let t=Ce(n);return t===null?e:t},bc=n=>{if(!n)return "";if(typeof n.conversation=="string")return n.conversation;let e=n.extendedTextMessage?.text;if(typeof e=="string")return e;let t=n.imageMessage?.caption;if(typeof t=="string")return t;let r=n.videoMessage?.caption;if(typeof r=="string")return r;let s=n.documentMessage?.caption;if(typeof s=="string")return s;let o=(n.botForwardedMessage?.message?.richResponseMessage??n.richResponseMessage)?.submessages;if(Array.isArray(o)){let a=o.map(c=>c?.messageText).filter(c=>typeof c=="string"&&c.length>0);if(a.length>0)return a.join(`
15
- `)}return ""},Ac=n=>Array.isArray(n)?n.map(e=>Buffer.from(e).toString("hex")):[],ci=(n,e)=>{let t=n?.reaction,r=t?.key;if(!r)return null;let s=$(n.key,e.pushName);if(s===null)return null;let i=t.text,o=typeof i=="string"&&i.length>0?i:null;return {key:r,emoji:o,sender:s,timestamp:le(t.senderTimestampMs,0)}},di=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==proto.Message.ProtocolMessage.Type.MESSAGE_EDIT)return null;let r=t.key;if(!r)return null;let s=$(n.key,e.pushName);return s===null?null:{key:r,newContent:bc(t.editedMessage),editedAt:le(n.update.messageTimestamp,0),sender:s}},li=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==proto.Message.ProtocolMessage.Type.REVOKE)return null;let r=t.key;if(!r)return null;let s=$(n.key,e.pushName);if(s===null)return null;let i=be(n.key.remoteJid),o=be(e.selfJid);return {key:r,deletedFor:i!==null&&o!==null&&i===o?"me":"everyone",sender:s,timestamp:le(n.update.messageTimestamp,0)}},Cc=async(n,e,t)=>{if(e.length===0||t.resolvePoll==null)return [];let r=n.id,s=n.remoteJid;if(typeof r!="string"||typeof s!="string")return [];let o=(await t.resolvePoll(r,s))?.message,a=o?.pollCreationMessage?.options??o?.pollCreationMessageV2?.options??o?.pollCreationMessageV3?.options??[],c=new Map;for(let l of a){let u=l?.optionName??"";c.set(createHash("sha256").update(Buffer.from(u)).digest("hex").toUpperCase(),u);}let d=[];for(let l of e){let u=c.get(l.toUpperCase());u!==void 0&&d.push(u);}return d},ui=(n,e)=>{let t=n?.update?.pollUpdates?.[0],r=n?.update?.message?.pollUpdateMessage,s=$(n?.key,e.pushName);if(s===null)return null;if(t){let i=t.pollUpdateMessageKey;if(!i)return null;let o=Ac(t.vote?.selectedOptions);return {pollKey:i,selectedOptions:o,options:()=>Cc(i,o,e),voter:s,timestamp:le(t.senderTimestampMs,le(n.update.messageTimestamp,0))}}if(r){let i=r.pollCreationMessageKey;return i?{pollKey:i,selectedOptions:[],options:()=>Promise.resolve([]),voter:s,timestamp:le(r.senderTimestampMs,le(n.update.messageTimestamp,0))}:null}return null};var Dt=n=>Array.isArray(n)?n:[],Pc=3e3,kc=(n,e)=>new Promise(t=>{let r=setTimeout(()=>t(null),e);n.then(s=>{clearTimeout(r),t(s);},()=>{clearTimeout(r),t(null);});}),Ec=n=>{if(n==null||typeof n!="object")return null;let e=n.reachoutTimeLock;return e==null||typeof e!="object"?null:e};function _n(n,e,t){let r=[],s=new Map,i=t.groupMetadata!=null?y=>{let m=s.get(y);if(m!==void 0)return m;let f=t.groupMetadata;if(f==null)return Promise.resolve(null);let b=f(y).then(k=>k?.subject??null).catch(()=>null);return s.set(y,b),b}:void 0,o={selfJid:t.selfJid,...t.selfLid!=null?{selfLid:t.selfLid}:{},...t.selfName!=null?{selfName:t.selfName}:{},receiverId:t.receiverId??t.selfJid,...t.logger!=null?{logger:t.logger}:{},...t.channelId!=null?{channelId:t.channelId}:{},...t.prefixes!=null?{prefixes:t.prefixes}:{},...t.citationConfig!=null?{citationConfig:t.citationConfig}:{},...i!=null?{resolveRoomName:i}:{},...t.receiverName!=null?{resolveReceiverName:t.receiverName}:{},...t.resolveQuoted!=null?{resolveQuoted:t.resolveQuoted}:{},...t.sendReply!=null?{reply:t.sendReply}:{},...t.react!=null?{react:t.react}:{}},a=t.logger?{selfJid:t.selfJid,logger:t.logger}:{selfJid:t.selfJid},c={selfJid:t.selfJid,...t.resolveQuoted!=null?{resolvePoll:t.resolveQuoted}:{}},d=(y,m)=>{let f=(...b)=>{try{m(b[0]);}catch(k){t.logger?.warn(k,`inbound pipeline: handler for ${y} threw`);}};e.ev.on(y,f),r.push(()=>e.ev.off(y,f));},l=(y,m)=>{v(()=>Qs(y,m),f=>n.emit("message",f)),v(()=>Xs(y,m),f=>n.emit("text",f)),v(()=>ei(y,m),f=>n.emit("image",f)),v(()=>ti(y,m),f=>n.emit("video",f)),v(()=>ni(y,m),f=>n.emit("audio",f)),v(()=>ri(y,m),f=>n.emit("document",f)),v(()=>si(y,m),f=>n.emit("sticker",f)),v(()=>ii(y,m),f=>n.emit("mention",f)),v(()=>oi(y,m),f=>n.emit("mention-all",f)),v(()=>Os(y,a),f=>n.emit("button-click",f)),v(()=>Rs(y,a),f=>n.emit("list-select",f));},u=y=>{if(typeof y!="string"||y.length===0)return null;let m;try{m=jidNormalizedUser(y);}catch{m=y;}return Rt(m)?m:null},w=y=>{let m=new Set;for(let f of [y.key?.participant,y.key?.remoteJid,t.selfJid,...zs(y)]){let b=u(f);b!=null&&m.add(b);}return [...m]},M=async y=>{let m=t.resolveLidToPn;if(m==null||y.length===0)return;let f=new Map;return await Promise.all(y.map(async b=>{try{let k=await kc(Promise.resolve(m(b)),Pc);if(k!=null&&k.length>0)try{f.set(b,jidNormalizedUser(k));}catch{f.set(b,k);}}catch(k){t.logger?.warn(k,"inbound pipeline: lid->pn resolve threw");}})),f.size>0?f:void 0},v=(y,m)=>{let f;try{f=y();}catch(b){t.logger?.warn(b,"inbound pipeline: decoder threw");return}f!=null&&m(f);};d("messages.upsert",y=>{let m=ms(y),f=m.type==="append"?{...o,isOffline:!0}:o;for(let b of m.messages){if(t.ignoreMe===!0&&b.key?.fromMe===!0)continue;let k=t.resolveLidToPn!=null?w(b):[];if(k.length===0){l(b,f);continue}M(k).then(F=>l(b,F!=null?{...f,lidMap:F}:f)).catch(F=>{t.logger?.warn(F,"inbound pipeline: deferred lid resolve emit failed"),l(b,f);});}}),d("messages.update",y=>{for(let m of Dt(y))v(()=>di(m,c),f=>n.emit("edit",f)),v(()=>li(m,c),f=>n.emit("delete",f)),v(()=>ui(m,c),f=>n.emit("poll-vote",f));}),d("messages.reaction",y=>{for(let m of Dt(y))v(()=>ci(m,c),f=>n.emit("reaction",f));}),d("groups.update",y=>{for(let m of Dt(y))v(()=>ws(m),f=>n.emit("group-update",f));}),d("group-participants.update",y=>{let m=y;v(()=>Ms(m),f=>n.emit("group-join",f)),v(()=>Ss(m),f=>n.emit("group-leave",f));}),d("group.member-tag.update",y=>{v(()=>vs(y),m=>n.emit("member-tag",m));}),d("call",y=>{for(let m of Dt(y))v(()=>fs(m),f=>n.emit("call-incoming",f)),v(()=>hs(m),f=>n.emit("call-ended",f));}),d("messaging-history.status",y=>{v(()=>_s(y),m=>n.emit("history-sync",m));}),d("presence.update",y=>{let m=(()=>{try{return Ls(y)}catch(f){return t.logger?.warn(f,"inbound pipeline: decodePresence threw"),[]}})();for(let f of m)n.emit("presence",f);}),d("connection.update",y=>{let m=Ec(y);m!==null&&v(()=>In({source:"connection-update",reachoutTimeLock:m}),f=>n.emit("limited",f));}),d("message-capping.update",y=>{v(()=>In({source:"message-capping",capInfo:y}),m=>n.emit("limited",m));}),d("newsletter.reaction",y=>{v(()=>nt({source:"reaction",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter.view",y=>{v(()=>nt({source:"view",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter-participants.update",y=>{v(()=>nt({source:"participants",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter-settings.update",y=>{v(()=>nt({source:"settings",payload:y}),m=>n.emit("newsletter",m));});let P=false;return {detach(){if(!P){P=true;for(let y of r)y();r.length=0;}}}}var Bt=class{inner=new EventEmitter;emitterLogger;constructor(e){this.emitterLogger=e?.logger,this.inner.setMaxListeners(0);}on(e,t){let r=this.wrap(e,t);this.tag(t,e,r),this.inner.on(e,r);let s=false;return ()=>{s||(s=true,this.inner.off(e,r),this.untag(t,e));}}off(e,t){let r=this.lookup(t,e);r&&(this.inner.off(e,r),this.untag(t,e));}emit(e,t){let r=this.inner.listeners(e).slice();for(let s of r)try{s(t);}catch(i){this.emitterLogger?.error(i,"listener threw");}}removeAllListeners(e){e===void 0?this.inner.removeAllListeners():this.inner.removeAllListeners(e);}listenerCount(e){return this.inner.listenerCount(e)}wrap(e,t){return r=>{try{t(r);}catch(s){this.emitterLogger?.error(s,"listener threw");}}}tag(e,t,r){this.tagMap(e).set(t,r);}untag(e,t){this.tagMap(e).delete(t);}lookup(e,t){return this.tagMap(e).get(t)}tagMap(e){let t=Ic,r=e,s=r[t];return s||(s=new Map,r[t]=s),s}},Ic=Symbol("zaileys.typed-ee.tag");var at=class extends Error{code="UNSUPPORTED_ON_CLOUD";feature;constructor(e){super(`${e} is not supported by the official WhatsApp Cloud API \u2014 it only exists on the web (baileys) provider`),this.name="ZaileysProviderError",this.feature=e;}},A=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysCloudError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};function Ln(n){if(!n||typeof n.accessToken!="string"||n.accessToken.length===0)throw new A("CONFIG","provider 'cloud' requires cloud.accessToken");if(typeof n.phoneNumberId!="string"||n.phoneNumberId.length===0)throw new A("CONFIG","provider 'cloud' requires cloud.phoneNumberId");return n}var Wt="v23.0",Nn="https://graph.facebook.com",mi=3,xc=500,Oc=n=>new Promise(e=>setTimeout(e,n));function Ft(n,e){let t=n.baseUrl??Nn,r=n.apiVersion??Wt,s=Oc,i=a=>`${t}/${r}/${a}`,o=async(a,c)=>{let d;for(let l=1;l<=mi;l++){let u;try{u=await fetch(i(a),{...c,headers:{Authorization:`Bearer ${n.accessToken}`,...c.headers}});}catch(m){throw new A("REQUEST_FAILED","graph request failed (network)",{cause:m})}if(u.ok)return await u.json().catch(()=>({}));let w=await u.json().catch(()=>({})),M=w.error?.message??`http ${u.status}`,v=w.error?` (code ${w.error.code??"?"}${w.error.error_subcode?`/${w.error.error_subcode}`:""})`:"";if(u.status===401||u.status===403)throw new A("AUTH",`graph auth rejected: ${M}${v}`);let P=u.status===429||u.status>=500,y=u.status===429?"RATE_LIMITED":"REQUEST_FAILED";if(d=new A(y,`graph request failed: ${M}${v}`),!P)throw d;l<mi&&await s(xc*2**(l-1));}throw d??new A("REQUEST_FAILED","graph request failed")};return {url:i,get:a=>o(a,{method:"GET"}),post:(a,c)=>o(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),postForm:(a,c)=>o(a,{method:"POST",body:c}),delete:(a,c)=>o(a,{method:"DELETE",...c!==void 0?{headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}:{}})}}var gi=n=>n.split("@")[0]??n,X=n=>n.includes("@")?n:`${n}@s.whatsapp.net`,V=(n,e,t)=>{let r={messaging_product:"whatsapp",recipient_type:"individual",to:gi(n),type:e},s=t?.quoted?.key?.id;return s&&(r.context={message_id:s}),r};function fi(n,e,t){let r=e;if(typeof r.text=="string")return {...V(n,"text",t),text:{body:r.text}};let s=r.react;if(s&&typeof s=="object"&&typeof s.key?.id=="string")return {...V(n,"reaction",t),reaction:{message_id:s.key.id,emoji:s.text??""}};let i=r.location;if(i&&typeof i.degreesLatitude=="number"&&typeof i.degreesLongitude=="number")return {...V(n,"location",t),location:{latitude:i.degreesLatitude,longitude:i.degreesLongitude,...i.name!==void 0?{name:i.name}:{},...i.address!==void 0?{address:i.address}:{}}};let o=r.contacts;if(o?.contacts&&Array.isArray(o.contacts)){let a=o.contacts.map(c=>typeof c.vcard=="string"?Rc(c.vcard):null).filter(c=>c!==null);if(a.length>0)return {...V(n,"contacts",t),contacts:a}}return null}function Rc(n){let e=n.split(/\r?\n/),t="",r="",s="",i=[];for(let a of e){if(a.startsWith("FN:")&&(t=a.slice(3).trim()),a.startsWith("N:")){let c=a.slice(2).split(";");s=(c[0]??"").trim(),r=(c[1]??"").trim();}if(a.startsWith("TEL")){let c=a.indexOf(":");if(c>0){let d=a.slice(c+1).trim(),l=/waid=([0-9]+)/.exec(a);d.length>0&&i.push({phone:d,...l?.[1]?{wa_id:l[1]}:{}});}}}if(t.length===0&&i.length===0)return null;let o=t||i[0]?.phone||"Contact";if(r.length===0&&s.length===0){let a=o.split(/\s+/);r=a[0]??o,a.length>1&&(s=a.slice(1).join(" "));}return {name:{formatted_name:o,first_name:r||o,...s?{last_name:s}:{}},...i.length>0?{phones:i}:{}}}function ct(n,e,t,r){let s=t,i=typeof s.text=="string"?{conversation:s.text}:{};return {key:{id:n,remoteJid:X(gi(e)),fromMe:true},message:i,messageTimestamp:Math.floor(r/1e3)}}var _c=["image","video","audio","document","sticker"];function hi(n){let e=n;for(let t of _c){let r=e[t];if(Buffer.isBuffer(r))return {kind:t,buffer:r,...typeof e.caption=="string"?{caption:e.caption}:{},...typeof e.fileName=="string"?{fileName:e.fileName}:{},...typeof e.mimetype=="string"?{mimetype:e.mimetype}:{}}}return null}async function yi(n,e,t){let r=t.mimetype??await me(t.buffer),s=new FormData;s.set("messaging_product","whatsapp"),s.set("type",r),s.set("file",new Blob([new Uint8Array(t.buffer)],{type:r}),t.fileName??"file");let i=await n.postForm(`${e}/media`,s);if(!i.id)throw new A("REQUEST_FAILED","media upload returned no id");return i.id}function wi(n,e){return {id:e,...n.caption!==void 0&&n.kind!=="audio"&&n.kind!=="sticker"?{caption:n.caption}:{},...n.kind==="document"&&n.fileName!==void 0?{filename:n.fileName}:{}}}var Lc=["image","video","audio","document","sticker"],Nc=n=>{let e=n.event,t=n.message_template_name;return typeof e!="string"||typeof t!="string"?null:{event:e,id:String(n.message_template_id??""),name:t,...typeof n.message_template_language=="string"?{language:n.message_template_language}:{},...typeof n.reason=="string"?{reason:n.reason}:{}}},jt=(n,e)=>n.contacts?.find(t=>t.wa_id===e)?.profile?.name??n.contacts?.[0]?.profile?.name,Dc=n=>{for(let e of Lc){let t=n[e];if(n.type===e&&t&&typeof t=="object"){let r=t;return {[`${e}Message`]:{...r.mime_type?{mimetype:r.mime_type}:{},...r.caption?{caption:r.caption}:{},...r.filename?{fileName:r.filename}:{},...r.voice===true?{ptt:true}:{},...r.id?{cloudMediaId:r.id}:{}}}}}return null},Bc=n=>{let e=n.interactive;return n.type!=="interactive"||!e?null:e.type==="button_reply"&&e.button_reply?.id?{buttonsResponseMessage:{selectedButtonId:e.button_reply.id,selectedDisplayText:e.button_reply.title??""}}:e.type==="list_reply"&&e.list_reply?.id?{listResponseMessage:{singleSelectReply:{selectedRowId:e.list_reply.id},title:e.list_reply.title??""}}:null},Wc=n=>{let e=n.location;return n.type!=="location"||typeof e?.latitude!="number"||typeof e.longitude!="number"?null:{locationMessage:{degreesLatitude:e.latitude,degreesLongitude:e.longitude,...e.name?{name:e.name}:{},...e.address?{address:e.address}:{}}}},Fc=n=>{let e=n.contacts;if(n.type!=="contacts"||!Array.isArray(e)||e.length===0)return null;let t=e.map(s=>{let i=s.name?.formatted_name??"",o=(s.phones??[]).filter(a=>typeof a.phone=="string").map(a=>`TEL${a.wa_id?`;waid=${a.wa_id}`:""}:${a.phone}`).join(`
13
+ `);}var Se={enabled:true,maxAttempts:Number.POSITIVE_INFINITY,initialDelayMs:3e3,maxDelayMs:6e4,jitterFactor:.2,rateLimitedDelayMs:3e5};function ls(n,e){let t=n?.enabled??Se.enabled,r=n?.maxAttempts??Se.maxAttempts,s=n?.initialDelayMs??Se.initialDelayMs,i=n?.maxDelayMs??Se.maxDelayMs,o=n?.jitterFactor??Se.jitterFactor,a=n?.rateLimitedDelayMs??Se.rateLimitedDelayMs,c=e?.random??Math.random,d=0;return {next:w=>{if(!t||Xe(w))return null;let M=d+1;if(M>r)return null;if(d=M,Tt(w))return {attempt:M,delayMs:a};let v=Math.pow(2,M-1),P=Math.min(i,s*v),y=1+(c()*2-1)*o,m=P*y,f=Math.min(i,Math.max(0,m));return {attempt:M,delayMs:Math.round(f)}},reset:()=>{d=0;},get attempts(){return d}}}var ka={idle:["connecting"],connecting:["qr-pending","pairing-pending","connected","reconnecting","disconnecting","disconnected"],"qr-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],"pairing-pending":["connecting","connected","reconnecting","disconnecting","disconnected"],connected:["disconnecting","reconnecting","disconnected"],reconnecting:["connecting","disconnecting","disconnected"],disconnecting:["disconnected"],disconnected:["idle","connecting","reconnecting"]};function us(n="idle"){let e=n,t=new Set,r=s=>ka[e].includes(s);return {get state(){return e},canTransition:r,transition(s){if(!r(s))throw new Error(`invalid state transition: ${e} -> ${s}`);let i=e;e=s;for(let o of t)try{o(i,s);}catch{}},onChange(s){return t.add(s),()=>{t.delete(s);}}}}var xt=n=>`${n.remoteJid??""}|${n.id??""}|${n.fromMe?1:0}`,Ot=class{messages=new Map;messagesByJid=new Map;chats=new Map;contacts=new Map;presence=new Map;boundSocket;listeners=new Map;closed=false;async saveMessage(e){this.assertOpen();let t=xt(e.key);this.messages.set(t,structuredClone(e));let r=e.key.remoteJid??"",s=this.messagesByJid.get(r);s||(s=new Set,this.messagesByJid.set(r,s)),s.add(t);}async getMessage(e){this.assertOpen();let t=this.messages.get(xt(e));return t?structuredClone(t):void 0}async listMessages(e,t){this.assertOpen();let r=this.messagesByJid.get(e);if(!r)return [];let s=[];for(let o of r){let a=this.messages.get(o);a&&s.push(a);}s.sort((o,a)=>Number(a.messageTimestamp)-Number(o.messageTimestamp));let i=s;if(typeof t?.before=="number"){let o=t.before;i=i.filter(a=>Number(a.messageTimestamp)<o);}return typeof t?.limit=="number"&&(i=i.slice(0,t.limit)),i.map(o=>structuredClone(o))}async saveChat(e){this.assertOpen();let t=e.id;t&&this.chats.set(t,structuredClone(e));}async getChat(e){this.assertOpen();let t=this.chats.get(e);return t?structuredClone(t):void 0}async listChats(e){this.assertOpen();let t=[];for(let r of this.chats.values())e?.archived===true&&r.archived!==true||t.push(structuredClone(r));return t}async saveContact(e){this.assertOpen(),this.contacts.set(e.id,structuredClone(e));}async getContact(e){this.assertOpen();let t=this.contacts.get(e);return t?structuredClone(t):void 0}async listContacts(){return this.assertOpen(),Array.from(this.contacts.values(),e=>structuredClone(e))}async savePresence(e,t){this.assertOpen(),this.presence.set(e,structuredClone(t));}async getPresence(e){this.assertOpen();let t=this.presence.get(e);return t?structuredClone(t):void 0}bind(e){this.assertOpen(),this.boundSocket=e;let t=(...c)=>{let l=c[0]?.messages;if(Array.isArray(l))for(let u of l)this.saveMessage(u).catch(()=>{});},r=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let u=this.messages.get(xt(l.key));if(u){let w={...u,...l.update};this.saveMessage(w).catch(()=>{});}}},s=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveChat(l).catch(()=>{});},i=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d){let w={...this.chats.get(l.id)??{},...l};this.saveChat(w).catch(()=>{});}},o=(...c)=>{let d=c[0];if(Array.isArray(d))for(let l of d)this.saveContact(l).catch(()=>{});},a=(...c)=>{let d=c[0];if(d?.presences)for(let l of Object.keys(d.presences)){let u=d.presences[l];u&&this.savePresence(l,u).catch(()=>{});}};this.listeners.set("messages.upsert",t),this.listeners.set("messages.update",r),this.listeners.set("chats.upsert",s),this.listeners.set("chats.update",i),this.listeners.set("contacts.upsert",o),this.listeners.set("presence.update",a);for(let[c,d]of this.listeners)e.ev.on(c,d);}async deleteMessage(e){this.assertOpen();let t=xt(e);this.messages.delete(t);let r=e.remoteJid??"",s=this.messagesByJid.get(r);s&&(s.delete(t),s.size===0&&this.messagesByJid.delete(r));}async pruneMessages(e){this.assertOpen();let t=0;for(let[r,s]of [...this.messagesByJid.entries()]){if(e.chatFilter&&!e.chatFilter(r))continue;let i=[];for(let a of s){let c=this.messages.get(a);c&&i.push(c);}i.sort((a,c)=>Number(c.messageTimestamp??0)-Number(a.messageTimestamp??0));let o=i.filter((a,c)=>{let d=Number(a.messageTimestamp??0);return e.olderThan!==void 0&&d<e.olderThan||e.maxPerChat!==void 0&&c>=e.maxPerChat});for(let a of o)await this.deleteMessage(a.key),t+=1;}return t}async clear(){this.assertOpen(),this.messages.clear(),this.messagesByJid.clear(),this.chats.clear(),this.contacts.clear(),this.presence.clear();}async close(){if(!this.closed){if(this.closed=true,this.boundSocket?.ev.off)for(let[e,t]of this.listeners)this.boundSocket.ev.off(e,t);return this.listeners.clear(),this.boundSocket=void 0,Promise.resolve()}}assertOpen(){if(this.closed)throw new h("STORE_CLOSED","MemoryMessageStore is closed")}};var Ta=["silent","fatal","error","warn","info","debug","trace"];function Ia(n){if(n)return n;let e=process.env.ZAILEYS_DEBUG;return e===void 0?"silent":e==="1"?"info":Ta.includes(e)?e:"silent"}function xa(n={}){let e=Ia(n.level),t=Ea({level:e});return n.sessionId!==void 0?t.child({sessionId:n.sessionId}):t}var ps=["debug","info","warn","error","fatal"];function Oa(n){if(n===null||typeof n!="object")return false;for(let e of ps)if(typeof n[e]!="function")return false;return true}function et(){}function Ra(n){let e={debug:et,info:et,warn:et,error:et,fatal:et};for(let t of ps){let r=n[t];typeof r=="function"&&(e[t]=r.bind(n));}return e}function En(n,e){return n===void 0?e??xa():Oa(n)?n:Ra(n)}var Cg=Object.freeze(["HISTORY_SYNC_NOTIFICATION","APP_STATE_SYNC_KEY_SHARE","LID_MIGRATION_MAPPING_SYNC","PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE"]),ms=n=>{let e=n.requestId!=null,t=n.messages.filter(r=>{if(e)return false;let s=r.messageStubParameters;if(Array.isArray(s)){for(let i of s)if(typeof i=="string"&&i.startsWith("requestId:"))return false}return true});return {...n,messages:t}};var _a=new Set(["offer","ringing"]),La=new Set(["timeout","reject","accept","terminate"]),gs=n=>{let e=n instanceof Date?n.getTime():Date.parse(String(n));return Number.isFinite(e)?e:0},fs=n=>{if(typeof n.id!="string"||n.id.length===0||!_a.has(n.status))return null;let e=Vr(n.id),t={kind:"incoming",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:gs(n.date),status:n.status};return e!==void 0&&(t.caller=e),t},hs=n=>typeof n.id!="string"||n.id.length===0||!La.has(n.status)?null:{kind:"ended",callId:n.id,from:n.from,isGroup:n.isGroup===true,isVideo:n.isVideo===true,timestamp:gs(n.date),status:n.status};var B=n=>typeof n=="string"&&n.length>0,Na=n=>{let e={};return typeof n.subject=="string"&&(e.subject=n.subject),typeof n.desc=="string"&&(e.description=n.desc),typeof n.announce=="boolean"&&(e.announce=n.announce),typeof n.restrict=="boolean"&&(e.restrict=n.restrict),typeof n.ephemeralDuration=="number"&&(e.ephemeralDuration=n.ephemeralDuration),e},ys=(n,e,t)=>n.filter(r=>B(r?.id)).map(r=>{let s={jid:r.id},i=r.lid??r.pn??r.phoneNumber;return B(i)&&(s.participantAlt=i),B(e)&&(s.authorPn=e),B(t)&&(s.authorUsername=t),s.isAdmin=r.admin==="admin"||r.admin==="superadmin",s}),ws=n=>B(n?.id)?{groupId:n.id,update:Na(n),timestamp:Date.now()}:null,vs=n=>{if(!B(n?.groupId)||!B(n?.participant))return null;let e={groupId:n.groupId,participant:n.participant,label:typeof n.label=="string"?n.label:"",timestamp:typeof n.messageTimestamp=="number"?n.messageTimestamp:Date.now()};return B(n.participantAlt)&&(e.participantAlt=n.participantAlt),e},Da=new Set(["add","invite","invite-link"]),Ba=new Set(["remove","leave"]),Ms=n=>{if(!B(n?.id)||!Da.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=ys(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return B(n.author)&&(t.by=n.author),t},Ss=n=>{if(!B(n?.id)||!Ba.has(n.action)||!Array.isArray(n.participants)||n.participants.length===0)return null;let e=ys(n.participants,n.authorPn,n.authorUsername);if(e.length===0)return null;let t={groupId:n.id,participants:e,action:n.action,timestamp:Date.now()};return B(n.author)&&(t.by=n.author),t};var be=n=>typeof n!="string"||n.length===0?null:jidNormalizedUser(n),Z=n=>typeof n=="string"&&n.length>0?n:void 0,ja=["@s.whatsapp.net","@c.us"],Rt=n=>n.endsWith("@lid"),bs=n=>ja.some(e=>n.endsWith(e)),$=(n,e)=>{if(!n)return null;let t=Z(n.participant)??n.remoteJid,r=be(t);if(r===null)return null;let s=Z(n.participantAlt)??Z(n.remoteJidAlt),i=s!=null?be(s):null,o=Z(n.participantUsername)??Z(n.remoteJidUsername),a={jid:r,isMe:n.fromMe===true};typeof t=="string"&&t.length>0&&(a.deviceJid=t);let c=i!==null?[r,i]:[r],d=c.find(Rt),l=c.find(bs);d!==void 0&&(a.lid=d),l!==void 0&&(a.pn=l),o!==void 0&&(a.username=o);let u=Z(e);return u!==void 0&&(a.pushName=u),a},As=n=>{if(!n)return null;let e=n.stanzaId;if(typeof e!="string"||e.length===0)return null;let t=Z(n.participant),r=Z(n.remoteJid)??t,s={id:e};typeof r=="string"&&(s.remoteJid=r),typeof t=="string"&&(s.participant=t);let i={key:s},o=$(s);return o&&(i.sender=o),i},tt=n=>{if(!n)return {mentionedJids:[],mentionAll:false};let e=n.mentionedJid,t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[],r=n.groupMentions,s=Array.isArray(r)&&r.length>0;return {mentionedJids:t,mentionAll:s}};var Ae=n=>isJidGroup(n)===true,Ce=n=>{if(n==null)return null;if(typeof n=="number")return Number.isFinite(n)?n:null;if(typeof n.toNumber=="function"){let e=n.toNumber();return Number.isFinite(e)?e:null}return null},g=n=>n!=null&&typeof n=="object"?n:null,Cs=["ephemeralMessage","viewOnceMessage","viewOnceMessageV2","viewOnceMessageV2Extension","documentWithCaptionMessage","editedMessage","lottieStickerMessage","groupStatusMessage","groupStatusMessageV2"],Ps=["groupStatusMessage","groupStatusMessageV2"],ks=(n,e)=>{let t=n;for(let r=0;r<5&&t!=null;r++){if(e.some(i=>t?.[i]!=null))return true;let s=null;for(let i of Cs){let o=g(g(t[i])?.message);if(o!=null){s=o;break}}t=s;}return false},Pe=n=>{let e=n;for(let t=0;t<5;t++){let r=null;for(let s of Cs){let i=g(g(e[s])?.message);if(i!=null){r=i;break}}if(r==null)break;e=r;}return e};var Ua=["quick_reply","cta_url","cta_call","button_click"],qa=["list_select","single_select"],J=n=>typeof n=="string"&&n.length>0,Ts=n=>{let e=typeof n.pushName=="string"?n.pushName:void 0;return $(n.key,e)},Is=n=>Ce(n.messageTimestamp)??0,xs=(n,e)=>{if(!J(n))return null;try{let t=JSON.parse(n);return t!==null&&typeof t=="object"?t:null}catch{return e?.debug({paramsJson:n},"interactive: failed to parse nativeFlow paramsJson"),null}},_t=(n,e)=>{for(let t of e){let r=n[t];if(J(r))return r}},Os=(n,e)=>{let t=n.message;if(!t)return null;let r=t.buttonsResponseMessage;if(r&&J(r.selectedButtonId))return Tn(n,r.selectedButtonId,r.selectedDisplayText);let s=t.templateButtonReplyMessage;if(s&&J(s.selectedId))return Tn(n,s.selectedId,s.selectedDisplayText);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&Ua.includes(i.name)){let o=xs(i.paramsJson,e.logger);if(!o)return null;let a=_t(o,["id","button_id"]);return a===void 0?null:Tn(n,a,_t(o,["display_text"])??null)}return null},Tn=(n,e,t)=>{let r=Ts(n);if(!r||!n.key)return null;let s={key:n.key,buttonId:e,sender:r,timestamp:Is(n)};return J(t)&&(s.buttonText=t),s},Rs=(n,e)=>{let t=n.message;if(!t)return null;let r=t.listResponseMessage,s=r?.singleSelectReply?.selectedRowId;if(J(s))return Es(n,s,r?.title);let i=t.interactiveResponseMessage?.nativeFlowResponseMessage;if(i&&J(i.name)&&qa.includes(i.name)){let o=xs(i.paramsJson,e.logger);if(!o)return null;let a=_t(o,["row_id","id"]);return a===void 0?null:Es(n,a,_t(o,["title"])??null)}return null},Es=(n,e,t)=>{let r=Ts(n);if(!r||!n.key)return null;let s={key:n.key,rowId:e,sender:r,timestamp:Is(n)};return J(t)&&(s.title=t),s};var Ka=new Set(["available","unavailable","composing","recording","paused"]),$a=n=>n instanceof Date?n.getTime():typeof n=="number"&&Number.isFinite(n)?n:0,_s=n=>n.status!=="complete"&&n.status!=="paused"?null:{syncType:String(n.syncType),status:n.status,explicit:n.explicit===true},In=n=>{if(n.source==="connection-update"){let t=n.reachoutTimeLock;return t.isActive!==true?null:{reason:"reachout-timelock",retryAt:$a(t.timeEnforcementEnds)}}if(n.capInfo.capping_status!=="CAPPED")return null;let e={reason:"chat-limit-reached"};return typeof n.capInfo.used_quota=="number"&&(e.usedQuota=n.capInfo.used_quota),typeof n.capInfo.total_quota=="number"&&(e.totalQuota=n.capInfo.total_quota),e},Ls=n=>{if(typeof n.id!="string"||n.id.length===0)return [];let e=[];for(let[t,r]of Object.entries(n.presences??{})){let s=r?.lastKnownPresence;typeof s!="string"||!Ka.has(s)||e.push({jid:n.id,participant:t,status:s});}return e},nt=n=>{let e=n.payload.id;if(typeof e!="string"||e.length===0)return null;let t=Date.now();switch(n.source){case "reaction":{let r={action:"reaction",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.reaction?.code=="string"&&(r.emoji=n.payload.reaction.code),r}case "view":{let r={action:"view",newsletterId:e,timestamp:t};return typeof n.payload.server_id=="string"&&(r.serverId=n.payload.server_id),typeof n.payload.count=="number"&&(r.count=n.payload.count),r}case "participants":return {action:"participants",newsletterId:e,timestamp:t};case "settings":{let r={action:"settings",newsletterId:e,timestamp:t};return n.payload.update&&(r.update=n.payload.update),r}}};var Ds=n=>{let e=n.match(/(https?:\/\/[^\s]+)/g);return e?e.map(t=>t.replace(/[.,;:!?]+$/,"")):[]},Ns=(n,e=2166136261)=>{let t=e>>>0;for(let r=0;r<n.length;r++)t^=n.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t>>>0},Bs=n=>(Ns(n).toString(16).padStart(8,"0")+Ns(n,2646966556).toString(16).padStart(8,"0")).toUpperCase(),Ws=n=>Bs(`${n.remoteJid??""}|${n.id??""}|${n.fromMe===true?"1":"0"}`),Fs=(n,e)=>Bs(`${n??""}|${e}`),js=n=>{let e=null;if(typeof n=="number")e=n;else if(typeof n=="bigint")e=Number(n);else if(typeof n=="string"){let t=Number.parseInt(n,10);e=Number.isFinite(t)?t:null;}else if(n!=null&&typeof n=="object"){let t=n;typeof t.toNumber=="function"?e=t.toNumber():typeof t.low=="number"&&(e=(typeof t.high=="number"?t.high:0)*4294967296+(t.low>>>0));}return e!=null&&Number.isFinite(e)&&e>0?e*1e3:0},Us=n=>{let e=jidDecode(n);if(!e)return "unknown";let t=e.device;return t===void 0||t===0?"android":t===2?"ios":t===3?"web":t===4?"desktop":"unknown"},Ja=n=>n.trim().endsWith("?"),Va=(n,e)=>e.length===0?false:e.some(t=>t.length>0&&n.startsWith(t)),Ha=(n,e)=>{if(e.length===0)return false;let t;try{t=jidNormalizedUser(n);}catch{t=n;}return e.some(r=>{try{return jidNormalizedUser(r)===t}catch{return r===n}})},za=(n,e)=>{let t=async r=>r===void 0?false:Array.isArray(r)?r.includes(e):r(e);return {authors:()=>t(n?.authors),banned:()=>t(n?.banned)}},Ya=0,Za=14,Qa=1,Xa=2,ec=n=>{let e=g(n.message);if(e==null)return {isEdited:false,isDeleted:false,isPinned:false,isUnPinned:false,isBot:false,isStatusMention:false,isGroupStatusMention:false,isGroupStatus:false};let t=g(e.protocolMessage),r=typeof t?.type=="number"?t.type:void 0,s=typeof g(e.pinInChatMessage)?.type=="number"?e.pinInChatMessage.type:void 0;return {isEdited:e.editedMessage!=null||r===Za,isDeleted:r===Ya,isPinned:s===Qa,isUnPinned:s===Xa,isBot:g(e.messageContextInfo)?.botMetadata!=null,isStatusMention:e.statusMentionMessage!=null,isGroupStatusMention:e.groupStatusMentionMessage!=null,isGroupStatus:ks(e,Ps)}},xn=n=>{let e=typeof n.key.remoteJid=="string"?n.key.remoteJid:null,t=e!==null&&Ae(e),r=ec(n.message),s=c=>n.lidMap!=null&&c.endsWith("@lid")?n.lidMap.get(c)??c:c,i=s(n.sender.pn??n.sender.jid),o=t?e?jidNormalizedUser(e):null:n.key.fromMe===true&&e?s(jidNormalizedUser(e)):i,a={uniqueId:Ws(n.key),staticId:Fs(o,i),channelId:n.channelId,chatId:n.key.id??"",chatType:n.chatType,receiverId:n.receiverId?s(jidNormalizedUser(n.receiverId)):n.receiverId,roomId:o,senderId:i,senderLid:n.sender.lid??null,senderName:n.sender.pushName??null,senderUsername:n.sender.username??null,senderDevice:Us(n.sender.deviceJid??n.sender.jid),timestamp:js(n.message.messageTimestamp),text:n.text,mentions:n.mentions,links:Ds(n.text),isFromMe:n.key.fromMe===true,isGroup:t,isNewsletter:n.isNewsletter,isBroadcast:n.isBroadcast,isViewOnce:n.isViewOnce,isEphemeral:n.isEphemeral,isForwarded:n.isForwarded,isOld:n.isOld===true,isQuestion:Ja(n.text),isPrefix:Va(n.text,n.prefixes),isTagMe:Ha(n.selfJid,n.mentions),isEdited:r.isEdited,isDeleted:r.isDeleted,isPinned:r.isPinned,isUnPinned:r.isUnPinned,isBot:r.isBot,isSpam:false,isHideTags:n.mentions.length>0&&!/@\d/.test(n.text),isStatusMention:r.isStatusMention,isGroupStatusMention:r.isGroupStatusMention,isGroupStatus:r.isGroupStatus,isStory:e==="status@broadcast",forwardCount:n.forwardCount??0,ephemeralDuration:n.ephemeralDuration??null,addressingMode:n.addressingMode??"pn",mentionedGroups:n.mentionedGroups??[],...n.ad!==void 0?{ad:n.ad}:{},...n.business!==void 0?{business:n.business}:{},roomName:n.resolveRoomName,receiverName:n.resolveReceiverName,replied:n.resolveReplied,reply:n.reply,react:n.react,message:()=>n.message,citation:za(n.citationConfig,n.sender.pn??n.sender.jid)};return n.media!==void 0&&(a.media=n.media),a};var Rn={image:"imageMessage",video:"videoMessage",audio:"audioMessage",document:"documentMessage",sticker:"stickerMessage"},$s=n=>{let e=n?.remoteJid;return typeof e=="string"&&e.length>0?e:""},S=n=>typeof n=="string"&&n.length>0?n:null,Q=(...n)=>{for(let e of n){let t=S(e);if(t!=null)return t}return null},Gs=n=>{let e=g(n.message);if(e==null)return n;let t=Pe(e);return t===e?n:{...n,message:t}},tc=n=>{let t=g(g(g(n.botForwardedMessage)?.message)?.richResponseMessage)??g(n.richResponseMessage);if(t==null)return null;let r=t.submessages;if(!Array.isArray(r))return null;let s=[];for(let o of r){let a=S(g(o)?.messageText);a!=null&&s.push(a);}let i=s.join(`
14
+ `).trim();return i.length>0?i:null},nc=n=>{let e=g(n.templateMessage),t=g(e?.hydratedTemplate)??g(e?.hydratedFourRowTemplate);return S(t?.hydratedContentText)},rc=n=>Q(g(n.pollCreationMessage)?.name,g(n.pollCreationMessageV2)?.name,g(n.pollCreationMessageV3)?.name),sc=n=>{let e=g(n.locationMessage)??g(n.liveLocationMessage);if(e==null)return null;let t=Q(e.name,e.address);if(t!=null){let i=S(e.name),o=S(e.address);return i!=null&&o!=null&&i!==o?`${i} \u2014 ${o}`:t}let r=e.degreesLatitude,s=e.degreesLongitude;return typeof r=="number"&&typeof s=="number"?`${r}, ${s}`:null},ic=n=>{let e=S(g(n.contactMessage)?.displayName);if(e!=null)return e;let t=g(n.contactsArrayMessage),r=S(t?.displayName);if(r!=null)return r;let s=t?.contacts;if(Array.isArray(s)){let i=s.map(o=>S(g(o)?.displayName)).filter(o=>o!=null);if(i.length>0)return i.join(", ")}return null},Js=n=>Q(n.conversation,g(n.extendedTextMessage)?.text,tc(n),S(g(g(n.interactiveMessage)?.body)?.text),g(n.buttonsMessage)?.contentText,g(n.listMessage)?.description,nc(n),rc(n),sc(n),ic(n)),oc=n=>Q(g(n.buttonsResponseMessage)?.selectedDisplayText,g(n.buttonsResponseMessage)?.selectedButtonId,g(n.templateButtonReplyMessage)?.selectedDisplayText,g(n.templateButtonReplyMessage)?.selectedId,g(n.listResponseMessage)?.title,g(g(n.listResponseMessage)?.singleSelectReply)?.selectedRowId,g(g(n.interactiveResponseMessage)?.body)?.text),ac=n=>Q(g(n.imageMessage)?.caption,g(n.videoMessage)?.caption,g(n.documentMessage)?.caption,g(n.documentMessage)?.fileName),T=n=>{if(typeof n=="number")return n;let e=Ce(n);return typeof e=="number"?e:null},cc=[["pollCreationMessage","poll"],["pollCreationMessageV2","poll"],["pollCreationMessageV3","poll"],["contactMessage","contact"],["contactsArrayMessage","contact"],["locationMessage","location"],["liveLocationMessage","live-location"],["eventMessage","event"],["albumMessage","album"],["groupInviteMessage","group-invite"],["productMessage","product"],["orderMessage","order"],["requestPaymentMessage","payment"],["sendPaymentMessage","payment"],["paymentInviteMessage","payment"],["buttonsMessage","buttons"],["listMessage","list"],["interactiveMessage","interactive"],["templateMessage","template"]],Vs=n=>{let e=g(n.pollCreationMessage)??g(n.pollCreationMessageV2)??g(n.pollCreationMessageV3);if(e!=null){let m=Array.isArray(e.options)?e.options:[];return {type:"poll",name:S(e.name),options:m.map(f=>S(g(f)?.optionName)).filter(f=>f!=null),selectableCount:T(e.selectableOptionsCount)??0}}let t=g(n.contactMessage);if(t!=null)return {type:"contact",displayName:S(t.displayName),vcard:S(t.vcard),contacts:[{displayName:S(t.displayName),vcard:S(t.vcard)}]};let r=g(n.contactsArrayMessage);if(r!=null){let m=Array.isArray(r.contacts)?r.contacts:[];return {type:"contact",displayName:S(r.displayName),vcard:null,contacts:m.map(f=>({displayName:S(g(f)?.displayName),vcard:S(g(f)?.vcard)}))}}let s=g(n.locationMessage);if(s!=null)return {type:"location",latitude:T(s.degreesLatitude),longitude:T(s.degreesLongitude),name:S(s.name),address:S(s.address),accuracy:T(s.accuracyInMeters),speed:T(s.speedInMps),caption:S(s.comment)};let i=g(n.liveLocationMessage);if(i!=null)return {type:"live-location",latitude:T(i.degreesLatitude),longitude:T(i.degreesLongitude),name:null,address:null,accuracy:T(i.accuracyInMeters),speed:T(i.speedInMps),caption:S(i.caption)};let o=g(n.albumMessage);if(o!=null)return {type:"album",expectedImageCount:T(o.expectedImageCount),expectedVideoCount:T(o.expectedVideoCount)};let a=g(n.groupInviteMessage);if(a!=null)return {type:"group-invite",groupId:S(a.groupJid),groupName:S(a.groupName),inviteCode:S(a.inviteCode),caption:S(a.caption),expiresAt:T(a.inviteExpiration)};let c=g(g(n.productMessage)?.product);if(g(n.productMessage)!=null){let m=S(g(n.productMessage)?.businessOwnerJid),f=T(c?.priceAmount1000);return {type:"product",productId:S(c?.productId),title:S(c?.title),description:S(c?.description),price:f!=null?f/1e3:null,currency:S(c?.currencyCode),retailerId:S(c?.retailerId),url:S(c?.url),businessOwnerId:m}}let d=g(n.orderMessage);if(d!=null){let m=T(d.totalAmount1000),f={1:"inquiry",2:"accepted",3:"declined"},b=d.status;return {type:"order",orderId:S(d.orderId),title:S(d.orderTitle),itemCount:T(d.itemCount),total:m!=null?m/1e3:null,currency:S(d.totalCurrencyCode),status:typeof b=="number"?f[b]??null:S(b),message:S(d.message)}}let l=g(n.requestPaymentMessage)!=null&&{node:n.requestPaymentMessage,kind:"request"}||g(n.sendPaymentMessage)!=null&&{node:n.sendPaymentMessage,kind:"send"}||g(n.paymentInviteMessage)!=null&&{node:n.paymentInviteMessage,kind:"invite"};if(l!==false){let m=g(l.node),f=T(m?.amount1000),b=g(m?.noteMessage);return {type:"payment",kind:l.kind,amount:f!=null?f/1e3:null,currency:S(m?.currencyCodeIso4217),note:Q(b?.conversation,g(b?.extendedTextMessage)?.text),expiresAt:T(m?.expiryTimestamp)}}let u=g(n.eventMessage);if(u!=null){let m=g(u.location);return {type:"event",name:S(u.name),description:S(u.description),location:m!=null?Q(m.name,m.address):null,startTime:T(u.startTime),endTime:T(u.endTime),isCanceled:u.isCanceled===true}}let w=g(n.buttonsMessage);if(w!=null){let m=Array.isArray(w.buttons)?w.buttons:[];return {type:"buttons",contentText:S(w.contentText),footerText:S(w.footerText),buttons:m.map(f=>({id:S(g(f)?.buttonId),text:S(g(g(f)?.buttonText)?.displayText)}))}}let M=g(n.listMessage);if(M!=null){let m=Array.isArray(M.sections)?M.sections:[];return {type:"list",title:S(M.title),description:S(M.description),buttonText:S(M.buttonText),sections:m.map(f=>{let b=Array.isArray(g(f)?.rows)?g(f).rows:[];return {title:S(g(f)?.title),rows:b.map(k=>({id:S(g(k)?.rowId),title:S(g(k)?.title),description:S(g(k)?.description)}))}})}}let v=g(n.interactiveMessage);if(v!=null){let m=g(v.nativeFlowMessage),f=Array.isArray(m?.buttons)?m.buttons:[];return {type:"interactive",title:S(g(v.header)?.title),body:S(g(v.body)?.text),footer:S(g(v.footer)?.text),buttons:f.map(b=>({name:S(g(b)?.name),params:S(g(b)?.buttonParamsJson)}))}}let P=g(n.templateMessage);if(P!=null){let m=g(P.hydratedTemplate)??g(P.hydratedFourRowTemplate),f=Array.isArray(m?.hydratedButtons)?m.hydratedButtons:[];return {type:"template",text:S(m?.hydratedContentText),buttons:f.map(b=>{let k=g(b),F=g(k?.quickReplyButton)??g(k?.urlButton)??g(k?.callButton);return {id:S(F?.id),text:S(F?.displayText)}})}}let y=g(n.extendedTextMessage);if(y!=null){let m=Q(y.canonicalUrl,y.matchedText),f=S(y.title),b=S(y.description);if(m!=null&&(f!=null||b!=null))return {type:"link",url:m,title:f,description:b}}return null};var st=n=>{let e=g(n.message);if(e==null)return null;let t=Pe(e);return Js(t)??oc(t)??ac(t)},Nt=n=>{let e=g(Gs(n).message);if(e==null)return null;let t=g(e.extendedTextMessage)?.contextInfo;if(t!=null)return t;for(let r of Object.values(e)){if(r==null||typeof r!="object")continue;let s=r.contextInfo;if(s!=null)return s}return null},dc=(n,e)=>{let t=n.message;if(t==null)return null;let r=t[Rn[e]];return r==null||typeof r!="object"?null:r},lc=n=>{let e=n.message;if(e==null)return false;if(e.viewOnceMessage!=null||e.viewOnceMessageV2!=null||e.viewOnceMessageV2Extension!=null)return true;for(let t of Object.values(Rn)){let r=e[t];if(r!=null&&typeof r=="object"&&r.viewOnce===true)return true}return false},uc=(n,e)=>n.message?.ephemeralMessage!=null?true:typeof e?.expiration=="number"&&e.expiration>0,pc=(n,e)=>typeof n=="number"&&Number.isFinite(n)?n:e,mc=(n,e)=>{let t=e?.expiration;if(typeof t=="number"&&t>0)return t;let r=g(g(n.message)?.ephemeralMessage),s=g(g(r?.message)?.extendedTextMessage)?.contextInfo,i=g(s)?.expiration;return typeof i=="number"&&i>0?i:null},gc=n=>{let e=n?.groupMentions;if(!Array.isArray(e))return [];let t=[];for(let r of e){let s=g(r)?.groupJid;typeof s=="string"&&s.length>0&&t.push(s);}return t},Hs=n=>typeof n=="string"&&n.length>0?n:void 0,fc=n=>{let e=g(n?.externalAdReply);if(e==null)return;let t={},r=[["clickId","ctwaClid"],["sourceId","sourceId"],["sourceUrl","sourceUrl"],["sourceApp","sourceApp"],["sourceType","sourceType"],["title","title"],["body","body"],["thumbnailUrl","thumbnailUrl"],["ref","ref"]];for(let[s,i]of r){let o=Hs(e[i]);o!==void 0&&(t[s]=o);}return Object.keys(t).length>0?t:void 0},hc=n=>{let e=Hs(g(n)?.verifiedBizName);return e!==void 0?{verifiedName:e}:void 0},ce=n=>{let e=g(n);if(e==null)return "text";let t=Pe(e);for(let r of Object.values(Rn))if(t[r]!=null)return r.replace("Message","");for(let[r,s]of cc)if(t[r]!=null)return s;return "text"},qs=(n,e)=>{if(n==null)return false;let t=[n.pn,n.lid,n.jid].filter(s=>typeof s=="string"&&s.length>0),r=[e.pn,e.lid,e.jid].filter(s=>typeof s=="string"&&s.length>0);return t.some(s=>r.includes(s))},yc=async(n,e,t,r,s,i)=>{try{if(n==null||n.quotedMessage==null)return null;let o=n.stanzaId;if(typeof o!="string"||o.length===0)return null;if(e.resolveQuoted!=null&&t.length>0){let v=await e.resolveQuoted(o,t);if(v!=null&&v.message!=null){let P=st(v)??"",y=de(v,e,ce(v.message),P,it(v,e),s);if(y!==null)return y}}let a=As(n);if(a===null||typeof a.key.id!="string"||a.key.id.length===0||(t.length>0&&(a.key.remoteJid=t),typeof a.key.remoteJid!="string"||a.key.remoteJid.length===0))return null;let c=a.key.participant,d=Ae(t),l=a.sender?.pushName;!d&&(c==null||c.length===0)?i===!0?(a.key.participant=t,l==null&&r!=null&&qs({jid:t},r)&&(l=r.pushName)):(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):typeof c=="string"&&(e.selfJid.length>0&&Lt(c,e.selfJid)||e.selfLid!=null&&Lt(c,e.selfLid))?(a.key.fromMe=!0,e.selfJid.length>0&&(a.key.participant=e.selfJid),e.selfLid!=null&&(a.key.participantAlt=e.selfLid),l==null&&(l=e.selfName)):r!=null&&qs(a.sender,r)&&(r.pn!=null&&(a.key.participant=r.pn),r.lid!=null&&(a.key.participantAlt=r.lid),l==null&&(l=r.pushName));let u=n.quotedMessage,w=Object.assign({key:a.key,message:u??null},l!=null?{pushName:l}:{}),M=st(w)??"";return de(w,e,ce(u),M,it(w,e),s)}catch{return null}},zs=n=>tt(Nt(n)).mentionedJids,wc=n=>{try{return jidNormalizedUser(n)}catch{return n}},Ys=(n,e)=>n.map(t=>{let r=wc(t);return e.lidMap?.get(r)??r}),Ks=n=>(n.split("@")[0]??"").split(":")[0]??"",vc=(n,e)=>{if(e==null||e.size===0||n.length===0)return n;let t=[...e].map(([s,i])=>[Ks(s),Ks(i)]).filter(([s,i])=>s.length>0&&i.length>0&&s!==i).sort((s,i)=>i[0].length-s[0].length),r=n;for(let[s,i]of t)r=r.split(`@${s}`).join(`@${i}`);return r},de=(n,e,t,r,s,i)=>{let o=n.key;if(o==null)return null;let a=$(o,n.pushName??void 0);if(a===null)return null;let c=$s(o);if(c.length===0)return null;let d=Nt(n),l=Ae(c),u=c.endsWith("@broadcast"),w=c.endsWith("@newsletter"),M=d?.isForwarded===true||(d?.forwardingScore??0)>0,v=lc(n),P=uc(n,d),y=e.channelId??"",m=e.receiverId??"",f=e.prefixes??[],b=i??(()=>l?e.resolveRoomName!=null?e.resolveRoomName(c):Promise.resolve(null):Promise.resolve(a.pushName??null)),k=e.resolveReceiverName??(()=>Promise.resolve(null)),F=()=>yc(d,e,c,a,b,o.fromMe===true),en=c.length>0?c:a.pn??a.jid,tn=(rn,Ki)=>e.reply==null?Promise.reject(new Error("zaileys: ctx.reply() requires a connected client")):e.reply(en,rn,Ki,n),nn=rn=>e.react==null?Promise.reject(new Error("zaileys: ctx.react() requires a connected client")):e.react(o,rn),Ui=Ys(tt(d).mentionedJids,e),qi=vc(r,e.lidMap),qn=fc(d),Kn=hc(n),$n={message:n,key:o,channelId:y,receiverId:m,selfJid:e.selfJid,text:qi,chatType:t,sender:a,mentions:Ui,isViewOnce:v,isEphemeral:P,isForwarded:M,isBroadcast:u,isNewsletter:w,isOld:e.isOld===true,prefixes:f,forwardCount:pc(d?.forwardingScore,0),ephemeralDuration:mc(n,d),addressingMode:o.addressingMode==="lid"?"lid":"pn",mentionedGroups:gc(d),...qn!==void 0?{ad:qn}:{},...Kn!==void 0?{business:Kn}:{},...e.lidMap!=null?{lidMap:e.lidMap}:{},resolveRoomName:b,resolveReceiverName:k,resolveReplied:F,reply:tn,react:nn},Gn=s!==void 0?{...$n,media:s}:$n;return xn(e.citationConfig!==void 0?{...Gn,citationConfig:e.citationConfig}:Gn)},Mc=["image","video","audio","document","sticker"],Zs=(n,e,t)=>{let r=Gs(n),s=dc(r,e);if(s===null)return null;let i=Pt(r,e,t.logger),o=Xr(r,e,t.logger);return {type:e,mimetype:typeof s.mimetype=="string"?s.mimetype:null,caption:typeof s.caption=="string"?s.caption:null,fileName:typeof s.fileName=="string"?s.fileName:null,fileSize:T(s.fileLength),ptt:s.ptt===true,isAnimated:s.isAnimated===true||s.gifPlayback===true,duration:T(s.seconds),width:T(s.width),height:T(s.height),pages:T(s.pageCount),thumbnail:s.jpegThumbnail!=null?Buffer.from(s.jpegThumbnail):null,buffer:async()=>(await i()).buffer,stream:o}},it=(n,e)=>{let t=g(n.message);if(t==null)return;let r=ce(n.message);return Mc.includes(r)?Zs(n,r,e)??void 0:Vs(Pe(t))??void 0},Qs=(n,e)=>{if(g(n.message)==null)return null;let r=ce(n.message),s=it(n,e),i=st(n)??"";return i===""&&s===void 0?null:de(n,e,r,i,s)},Xs=(n,e)=>{let t=g(n.message);if(t==null)return null;let r=Pe(t),s=Js(r),i=Vs(r)??void 0;return s===null&&i===void 0?null:de(n,e,ce(n.message),s??"",i)},ot=(n,e,t)=>{let r=Zs(e,n,t);return r===null?null:de(e,t,n,r.caption??"",r)},ei=(n,e)=>ot("image",n,e),ti=(n,e)=>ot("video",n,e),ni=(n,e)=>ot("audio",n,e),ri=(n,e)=>ot("document",n,e),si=(n,e)=>ot("sticker",n,e),Lt=(n,e)=>{try{return jidNormalizedUser(n)===jidNormalizedUser(e)}catch{return n===e}},ii=(n,e)=>{if(n.key==null)return null;let r=Nt(n),s=tt(r).mentionedJids;if(s.length===0)return null;let i=Ys(s,e);if(!(i.some(u=>Lt(u,e.selfJid))||e.selfLid!=null&&s.some(u=>Lt(u,e.selfLid)))||g(n.message)==null)return null;let c=st(n)??"",d=it(n,e),l=de(n,e,ce(n.message),c,d);return l===null?null:{...l,mentionedJids:i,selfJid:e.selfJid}},oi=(n,e)=>{let t=n.key;if(t==null)return null;let r=$s(t);if(r.length===0||!Ae(r))return null;let{mentionAll:s}=tt(Nt(n));if(!s||g(n.message)==null)return null;let o=st(n)??"",a=it(n,e),c=de(n,e,ce(n.message),o,a);return c===null?null:{...c,isMentionAll:true,selfJid:e.selfJid}};var le=(n,e)=>{let t=Ce(n);return t===null?e:t},bc=n=>{if(!n)return "";if(typeof n.conversation=="string")return n.conversation;let e=n.extendedTextMessage?.text;if(typeof e=="string")return e;let t=n.imageMessage?.caption;if(typeof t=="string")return t;let r=n.videoMessage?.caption;if(typeof r=="string")return r;let s=n.documentMessage?.caption;if(typeof s=="string")return s;let o=(n.botForwardedMessage?.message?.richResponseMessage??n.richResponseMessage)?.submessages;if(Array.isArray(o)){let a=o.map(c=>c?.messageText).filter(c=>typeof c=="string"&&c.length>0);if(a.length>0)return a.join(`
15
+ `)}return ""},Ac=n=>Array.isArray(n)?n.map(e=>Buffer.from(e).toString("hex")):[],ci=(n,e)=>{let t=n?.reaction,r=t?.key;if(!r)return null;let s=$(n.key,e.pushName);if(s===null)return null;let i=t.text,o=typeof i=="string"&&i.length>0?i:null;return {key:r,emoji:o,sender:s,timestamp:le(t.senderTimestampMs,0)}},di=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==proto.Message.ProtocolMessage.Type.MESSAGE_EDIT)return null;let r=t.key;if(!r)return null;let s=$(n.key,e.pushName);return s===null?null:{key:r,newContent:bc(t.editedMessage),editedAt:le(n.update.messageTimestamp,0),sender:s}},li=(n,e)=>{let t=n?.update?.message?.protocolMessage;if(!t||t.type!==proto.Message.ProtocolMessage.Type.REVOKE)return null;let r=t.key;if(!r)return null;let s=$(n.key,e.pushName);if(s===null)return null;let i=be(n.key.remoteJid),o=be(e.selfJid);return {key:r,deletedFor:i!==null&&o!==null&&i===o?"me":"everyone",sender:s,timestamp:le(n.update.messageTimestamp,0)}},Cc=async(n,e,t)=>{if(e.length===0||t.resolvePoll==null)return [];let r=n.id,s=n.remoteJid;if(typeof r!="string"||typeof s!="string")return [];let o=(await t.resolvePoll(r,s))?.message,a=o?.pollCreationMessage?.options??o?.pollCreationMessageV2?.options??o?.pollCreationMessageV3?.options??[],c=new Map;for(let l of a){let u=l?.optionName??"";c.set(createHash("sha256").update(Buffer.from(u)).digest("hex").toUpperCase(),u);}let d=[];for(let l of e){let u=c.get(l.toUpperCase());u!==void 0&&d.push(u);}return d},ui=(n,e)=>{let t=n?.update?.pollUpdates?.[0],r=n?.update?.message?.pollUpdateMessage,s=$(n?.key,e.pushName);if(s===null)return null;if(t){let i=t.pollUpdateMessageKey;if(!i)return null;let o=Ac(t.vote?.selectedOptions);return {pollKey:i,selectedOptions:o,options:()=>Cc(i,o,e),voter:s,timestamp:le(t.senderTimestampMs,le(n.update.messageTimestamp,0))}}if(r){let i=r.pollCreationMessageKey;return i?{pollKey:i,selectedOptions:[],options:()=>Promise.resolve([]),voter:s,timestamp:le(r.senderTimestampMs,le(n.update.messageTimestamp,0))}:null}return null};var Dt=n=>Array.isArray(n)?n:[],Pc=3e3,kc=(n,e)=>new Promise(t=>{let r=setTimeout(()=>t(null),e);n.then(s=>{clearTimeout(r),t(s);},()=>{clearTimeout(r),t(null);});}),Ec=n=>{if(n==null||typeof n!="object")return null;let e=n.reachoutTimeLock;return e==null||typeof e!="object"?null:e};function _n(n,e,t){let r=[],s=new Map,i=t.groupMetadata!=null?y=>{let m=s.get(y);if(m!==void 0)return m;let f=t.groupMetadata;if(f==null)return Promise.resolve(null);let b=f(y).then(k=>k?.subject??null).catch(()=>null);return s.set(y,b),b}:void 0,o={selfJid:t.selfJid,...t.selfLid!=null?{selfLid:t.selfLid}:{},...t.selfName!=null?{selfName:t.selfName}:{},receiverId:t.receiverId??t.selfJid,...t.logger!=null?{logger:t.logger}:{},...t.channelId!=null?{channelId:t.channelId}:{},...t.prefixes!=null?{prefixes:t.prefixes}:{},...t.citationConfig!=null?{citationConfig:t.citationConfig}:{},...i!=null?{resolveRoomName:i}:{},...t.receiverName!=null?{resolveReceiverName:t.receiverName}:{},...t.resolveQuoted!=null?{resolveQuoted:t.resolveQuoted}:{},...t.sendReply!=null?{reply:t.sendReply}:{},...t.react!=null?{react:t.react}:{}},a=t.logger?{selfJid:t.selfJid,logger:t.logger}:{selfJid:t.selfJid},c={selfJid:t.selfJid,...t.resolveQuoted!=null?{resolvePoll:t.resolveQuoted}:{}},d=(y,m)=>{let f=(...b)=>{try{m(b[0]);}catch(k){t.logger?.warn(k,`inbound pipeline: handler for ${y} threw`);}};e.ev.on(y,f),r.push(()=>e.ev.off(y,f));},l=(y,m)=>{v(()=>Qs(y,m),f=>n.emit("message",f)),v(()=>Xs(y,m),f=>n.emit("text",f)),v(()=>ei(y,m),f=>n.emit("image",f)),v(()=>ti(y,m),f=>n.emit("video",f)),v(()=>ni(y,m),f=>n.emit("audio",f)),v(()=>ri(y,m),f=>n.emit("document",f)),v(()=>si(y,m),f=>n.emit("sticker",f)),v(()=>ii(y,m),f=>n.emit("mention",f)),v(()=>oi(y,m),f=>n.emit("mention-all",f)),v(()=>Os(y,a),f=>n.emit("button-click",f)),v(()=>Rs(y,a),f=>n.emit("list-select",f));},u=y=>{if(typeof y!="string"||y.length===0)return null;let m;try{m=jidNormalizedUser(y);}catch{m=y;}return Rt(m)?m:null},w=y=>{let m=new Set;for(let f of [y.key?.participant,y.key?.remoteJid,t.selfJid,...zs(y)]){let b=u(f);b!=null&&m.add(b);}return [...m]},M=async y=>{let m=t.resolveLidToPn;if(m==null||y.length===0)return;let f=new Map;return await Promise.all(y.map(async b=>{try{let k=await kc(Promise.resolve(m(b)),Pc);if(k!=null&&k.length>0)try{f.set(b,jidNormalizedUser(k));}catch{f.set(b,k);}}catch(k){t.logger?.warn(k,"inbound pipeline: lid->pn resolve threw");}})),f.size>0?f:void 0},v=(y,m)=>{let f;try{f=y();}catch(b){t.logger?.warn(b,"inbound pipeline: decoder threw");return}f!=null&&m(f);};d("messages.upsert",y=>{let m=ms(y),f=m.type==="append"?{...o,isOld:!0}:o;for(let b of m.messages){if(t.ignoreMe===!0&&b.key?.fromMe===!0)continue;let k=t.resolveLidToPn!=null?w(b):[];if(k.length===0){l(b,f);continue}M(k).then(F=>l(b,F!=null?{...f,lidMap:F}:f)).catch(F=>{t.logger?.warn(F,"inbound pipeline: deferred lid resolve emit failed"),l(b,f);});}}),d("messages.update",y=>{for(let m of Dt(y))v(()=>di(m,c),f=>n.emit("edit",f)),v(()=>li(m,c),f=>n.emit("delete",f)),v(()=>ui(m,c),f=>n.emit("poll-vote",f));}),d("messages.reaction",y=>{for(let m of Dt(y))v(()=>ci(m,c),f=>n.emit("reaction",f));}),d("groups.update",y=>{for(let m of Dt(y))v(()=>ws(m),f=>n.emit("group-update",f));}),d("group-participants.update",y=>{let m=y;v(()=>Ms(m),f=>n.emit("group-join",f)),v(()=>Ss(m),f=>n.emit("group-leave",f));}),d("group.member-tag.update",y=>{v(()=>vs(y),m=>n.emit("member-tag",m));}),d("call",y=>{for(let m of Dt(y))v(()=>fs(m),f=>n.emit("call-incoming",f)),v(()=>hs(m),f=>n.emit("call-ended",f));}),d("messaging-history.status",y=>{v(()=>_s(y),m=>n.emit("history-sync",m));}),d("presence.update",y=>{let m=(()=>{try{return Ls(y)}catch(f){return t.logger?.warn(f,"inbound pipeline: decodePresence threw"),[]}})();for(let f of m)n.emit("presence",f);}),d("connection.update",y=>{let m=Ec(y);m!==null&&v(()=>In({source:"connection-update",reachoutTimeLock:m}),f=>n.emit("limited",f));}),d("message-capping.update",y=>{v(()=>In({source:"message-capping",capInfo:y}),m=>n.emit("limited",m));}),d("newsletter.reaction",y=>{v(()=>nt({source:"reaction",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter.view",y=>{v(()=>nt({source:"view",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter-participants.update",y=>{v(()=>nt({source:"participants",payload:y}),m=>n.emit("newsletter",m));}),d("newsletter-settings.update",y=>{v(()=>nt({source:"settings",payload:y}),m=>n.emit("newsletter",m));});let P=false;return {detach(){if(!P){P=true;for(let y of r)y();r.length=0;}}}}var Bt=class{inner=new EventEmitter;emitterLogger;constructor(e){this.emitterLogger=e?.logger,this.inner.setMaxListeners(0);}on(e,t){let r=this.wrap(e,t);this.tag(t,e,r),this.inner.on(e,r);let s=false;return ()=>{s||(s=true,this.inner.off(e,r),this.untag(t,e));}}off(e,t){let r=this.lookup(t,e);r&&(this.inner.off(e,r),this.untag(t,e));}emit(e,t){let r=this.inner.listeners(e).slice();for(let s of r)try{s(t);}catch(i){this.emitterLogger?.error(i,"listener threw");}}removeAllListeners(e){e===void 0?this.inner.removeAllListeners():this.inner.removeAllListeners(e);}listenerCount(e){return this.inner.listenerCount(e)}wrap(e,t){return r=>{try{t(r);}catch(s){this.emitterLogger?.error(s,"listener threw");}}}tag(e,t,r){this.tagMap(e).set(t,r);}untag(e,t){this.tagMap(e).delete(t);}lookup(e,t){return this.tagMap(e).get(t)}tagMap(e){let t=Ic,r=e,s=r[t];return s||(s=new Map,r[t]=s),s}},Ic=Symbol("zaileys.typed-ee.tag");var at=class extends Error{code="UNSUPPORTED_ON_CLOUD";feature;constructor(e){super(`${e} is not supported by the official WhatsApp Cloud API \u2014 it only exists on the web (baileys) provider`),this.name="ZaileysProviderError",this.feature=e;}},A=class n extends Error{code;cause;constructor(e,t,r){super(t),this.name="ZaileysCloudError",this.code=e,r&&"cause"in r&&(this.cause=r.cause),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n);}};function Ln(n){if(!n||typeof n.accessToken!="string"||n.accessToken.length===0)throw new A("CONFIG","provider 'cloud' requires cloud.accessToken");if(typeof n.phoneNumberId!="string"||n.phoneNumberId.length===0)throw new A("CONFIG","provider 'cloud' requires cloud.phoneNumberId");return n}var Wt="v23.0",Nn="https://graph.facebook.com",mi=3,xc=500,Oc=n=>new Promise(e=>setTimeout(e,n));function Ft(n,e){let t=n.baseUrl??Nn,r=n.apiVersion??Wt,s=Oc,i=a=>`${t}/${r}/${a}`,o=async(a,c)=>{let d;for(let l=1;l<=mi;l++){let u;try{u=await fetch(i(a),{...c,headers:{Authorization:`Bearer ${n.accessToken}`,...c.headers}});}catch(m){throw new A("REQUEST_FAILED","graph request failed (network)",{cause:m})}if(u.ok)return await u.json().catch(()=>({}));let w=await u.json().catch(()=>({})),M=w.error?.message??`http ${u.status}`,v=w.error?` (code ${w.error.code??"?"}${w.error.error_subcode?`/${w.error.error_subcode}`:""})`:"";if(u.status===401||u.status===403)throw new A("AUTH",`graph auth rejected: ${M}${v}`);let P=u.status===429||u.status>=500,y=u.status===429?"RATE_LIMITED":"REQUEST_FAILED";if(d=new A(y,`graph request failed: ${M}${v}`),!P)throw d;l<mi&&await s(xc*2**(l-1));}throw d??new A("REQUEST_FAILED","graph request failed")};return {url:i,get:a=>o(a,{method:"GET"}),post:(a,c)=>o(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),postForm:(a,c)=>o(a,{method:"POST",body:c}),delete:(a,c)=>o(a,{method:"DELETE",...c!==void 0?{headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}:{}})}}var gi=n=>n.split("@")[0]??n,X=n=>n.includes("@")?n:`${n}@s.whatsapp.net`,V=(n,e,t)=>{let r={messaging_product:"whatsapp",recipient_type:"individual",to:gi(n),type:e},s=t?.quoted?.key?.id;return s&&(r.context={message_id:s}),r};function fi(n,e,t){let r=e;if(typeof r.text=="string")return {...V(n,"text",t),text:{body:r.text}};let s=r.react;if(s&&typeof s=="object"&&typeof s.key?.id=="string")return {...V(n,"reaction",t),reaction:{message_id:s.key.id,emoji:s.text??""}};let i=r.location;if(i&&typeof i.degreesLatitude=="number"&&typeof i.degreesLongitude=="number")return {...V(n,"location",t),location:{latitude:i.degreesLatitude,longitude:i.degreesLongitude,...i.name!==void 0?{name:i.name}:{},...i.address!==void 0?{address:i.address}:{}}};let o=r.contacts;if(o?.contacts&&Array.isArray(o.contacts)){let a=o.contacts.map(c=>typeof c.vcard=="string"?Rc(c.vcard):null).filter(c=>c!==null);if(a.length>0)return {...V(n,"contacts",t),contacts:a}}return null}function Rc(n){let e=n.split(/\r?\n/),t="",r="",s="",i=[];for(let a of e){if(a.startsWith("FN:")&&(t=a.slice(3).trim()),a.startsWith("N:")){let c=a.slice(2).split(";");s=(c[0]??"").trim(),r=(c[1]??"").trim();}if(a.startsWith("TEL")){let c=a.indexOf(":");if(c>0){let d=a.slice(c+1).trim(),l=/waid=([0-9]+)/.exec(a);d.length>0&&i.push({phone:d,...l?.[1]?{wa_id:l[1]}:{}});}}}if(t.length===0&&i.length===0)return null;let o=t||i[0]?.phone||"Contact";if(r.length===0&&s.length===0){let a=o.split(/\s+/);r=a[0]??o,a.length>1&&(s=a.slice(1).join(" "));}return {name:{formatted_name:o,first_name:r||o,...s?{last_name:s}:{}},...i.length>0?{phones:i}:{}}}function ct(n,e,t,r){let s=t,i=typeof s.text=="string"?{conversation:s.text}:{};return {key:{id:n,remoteJid:X(gi(e)),fromMe:true},message:i,messageTimestamp:Math.floor(r/1e3)}}var _c=["image","video","audio","document","sticker"];function hi(n){let e=n;for(let t of _c){let r=e[t];if(Buffer.isBuffer(r))return {kind:t,buffer:r,...typeof e.caption=="string"?{caption:e.caption}:{},...typeof e.fileName=="string"?{fileName:e.fileName}:{},...typeof e.mimetype=="string"?{mimetype:e.mimetype}:{}}}return null}async function yi(n,e,t){let r=t.mimetype??await me(t.buffer),s=new FormData;s.set("messaging_product","whatsapp"),s.set("type",r),s.set("file",new Blob([new Uint8Array(t.buffer)],{type:r}),t.fileName??"file");let i=await n.postForm(`${e}/media`,s);if(!i.id)throw new A("REQUEST_FAILED","media upload returned no id");return i.id}function wi(n,e){return {id:e,...n.caption!==void 0&&n.kind!=="audio"&&n.kind!=="sticker"?{caption:n.caption}:{},...n.kind==="document"&&n.fileName!==void 0?{filename:n.fileName}:{}}}var Lc=["image","video","audio","document","sticker"],Nc=n=>{let e=n.event,t=n.message_template_name;return typeof e!="string"||typeof t!="string"?null:{event:e,id:String(n.message_template_id??""),name:t,...typeof n.message_template_language=="string"?{language:n.message_template_language}:{},...typeof n.reason=="string"?{reason:n.reason}:{}}},jt=(n,e)=>n.contacts?.find(t=>t.wa_id===e)?.profile?.name??n.contacts?.[0]?.profile?.name,Dc=n=>{for(let e of Lc){let t=n[e];if(n.type===e&&t&&typeof t=="object"){let r=t;return {[`${e}Message`]:{...r.mime_type?{mimetype:r.mime_type}:{},...r.caption?{caption:r.caption}:{},...r.filename?{fileName:r.filename}:{},...r.voice===true?{ptt:true}:{},...r.id?{cloudMediaId:r.id}:{}}}}}return null},Bc=n=>{let e=n.interactive;return n.type!=="interactive"||!e?null:e.type==="button_reply"&&e.button_reply?.id?{buttonsResponseMessage:{selectedButtonId:e.button_reply.id,selectedDisplayText:e.button_reply.title??""}}:e.type==="list_reply"&&e.list_reply?.id?{listResponseMessage:{singleSelectReply:{selectedRowId:e.list_reply.id},title:e.list_reply.title??""}}:null},Wc=n=>{let e=n.location;return n.type!=="location"||typeof e?.latitude!="number"||typeof e.longitude!="number"?null:{locationMessage:{degreesLatitude:e.latitude,degreesLongitude:e.longitude,...e.name?{name:e.name}:{},...e.address?{address:e.address}:{}}}},Fc=n=>{let e=n.contacts;if(n.type!=="contacts"||!Array.isArray(e)||e.length===0)return null;let t=e.map(s=>{let i=s.name?.formatted_name??"",o=(s.phones??[]).filter(a=>typeof a.phone=="string").map(a=>`TEL${a.wa_id?`;waid=${a.wa_id}`:""}:${a.phone}`).join(`
16
16
  `);return {displayName:i,vcard:`BEGIN:VCARD
17
17
  VERSION:3.0
18
18
  FN:${i}${o?`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "zaileys",
3
3
  "description": "Zaileys - Simplified WhatsApp Node.js TypeScript/JavaScript API",
4
- "version": "4.8.8",
4
+ "version": "4.8.9",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "./dist/index.cjs",